Quantcast
Channel: The Rust Programming Language Forum - Latest topics
Viewing all 50976 articles
Browse latest View live

PyO3 0.9.0 released

$
0
0

@kngwyu wrote:

Hi. I'm happy to announce the release of PyO3 0.9.0.
PyO3 is an FFI library that makes it easy to interact with Python interpreter, thanks to the flexibility of proc-macro and useful toolchains like maturin.

This version has some breaking changes, mainly for preventing undefined behaviors. Probably, the most notable one is PyCell, which a RefCell-like object wrapper for #[pyclass].
#[pyclass] attribute is one of our primary APIs for making Python extension, which generates all boilerplates you need to convert a struct to a Python object. You can use it like:

#[pyclass]
struct MyClass { ... }

#[pymethods]
impl MyClass {
    #[new]
    fn new() -> Self { ... }
    fn merge(&mut self, other: &mut Names) { ... }
}

And once a struct is declared with #[pyclass], you can use it from Python scripts:

from my_module import MyClass
m = MyClass()

Isn't it an easy API?

However, here comes a problem: basically we use Python objects as references, but they are not as smart as Rust's reference. They don't have mutability flags and are thus always mutable.
So not to violate the the rules of references, we wrap Rust's struct by PyCell and dynamically tracks references counts.

As a result, when trying to get an invalid reference, we can throw exceptions like this:


For other breaking changes, please see the migration guide.

PyCell is inspired by WasmRefCell. In addition to wasm-bindgen, I really appreciate all the community's efforts for making safe FFI-bindings. Actually, I learned a lot from reading stdweb and rlua.

And I also appreciate all contributors, issue reporters, and discussions on gitter, which helps us
to step forward to this safer direction.

Finally, I want to say thanks to the users. We know Rust is good, but also know it can be too difficult for non-programmers like Physics or Biology researchers. So it's my pleasure to see PyO3 is used for providing made in Rust software to broader areas, like Astronomy or Natural Language Processing.
Thank you.

Posts: 2

Participants: 2

Read full topic


Reusing a type as a Diesel expression

$
0
0

@matteosister wrote:

Hello everybody. Diesel question!

I'm trying to do something like this: I have a type:

pub struct TextFilter {
    is: Option<String>,
    contains: Option<String>,
}

I would like to use this type to filter any arbitrary column of type text.

Is there any way to do this? Many thanks!

Posts: 1

Participants: 1

Read full topic

Reading CSV data from uri and putting it in a struct

$
0
0

@hyousef wrote:

Trying to read COVID-19 data and putting it in a struct, the data is here:
https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv
showing cases recorded every day.

I tried the below:

[dependencies]
serde = { version = "1.0.105", features = ["derive"] }
reqwest = { version = "0.10", features = ["json"] }
tokio = { version = "0.2", features = ["full"] }
csv = "1.1.3"

And

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Record {
    Province: str,
    Country: str,
    Lat: f64,
    Long: f64,
    d001: i32,    d002: i32,    d003: i32,     d004: i32,     d005: i32,     d006: i32,     d007: i32,    d008: i32,    d009: i32,
    d010: i32,    d011: i32,    d012: i32,     d013: i32,     d014: i32,     d015: i32,     d016: i32,    d017: i32,    d018: i32,
    d019: i32,    d020: i32,    d021: i32,     d022: i32,     d023: i32,     d024: i32,     d025: i32,    d026: i32,    d027: i32,
    d028: i32,    d029: i32,    d030: i32,     d031: i32,     d032: i32,     d033: i32,     d034: i32,    d035: i32,    d036: i32,
    d037: i32,    d038: i32,    d039: i32,
    d040: i32,    d041: i32,    d042: i32,     d043: i32,     d044: i32,     d045: i32,    d046: i32,    d047: i32,    d048: i32,
    d049: i32,    d050: i32,    d051: i32,     d052: i32,     d053: i32,     d054: i32,    d055: i32,    d056: i32,    d057: i32,
    d058: i32,    d059: i32,    d060: i32,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    
    let res = reqwest::get("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv").await?;

    println!("Status: {}", res.status());

    let body = res.text().await?;
      //  println!("Body:\n\n{}", body);

    let mut reader = csv::Reader::from_reader(body.as_bytes());

    for result in reader.deserialize() {
        // The iterator yields Result<StringRecord, Error>, so we check the
        // error here.
        let record: Record = result?;
        println!("{:?}", record);
    }
    Ok(())
}

But when I compiled it, I got the below error:

error: There are multiple `csv` packages in your project, and the specification `csv` is ambiguous.
Please re-run this command with `-p <spec>` where `<spec>` is one of the following:
  csv:0.1.0
  csv:1.1.3

Process finished with exit code 101

Posts: 1

Participants: 1

Read full topic

What's the quickest way to get the length of an integer?

$
0
0

@thor314 wrote:

S'pose I have some integer type, T.
The obvious way would be to get the length of of the string of that integer:

fn get_len_of_int<T>(i: T) -> usize
    where T: std::string::ToString
{
    i.to_string().len()
}

But is that the fastest way?
playground

Meta-questions:

  1. There are methods in the std library for quickly getting the binary representation of the integer, but I see no obvious conversion from binary to base 10. I may simply be uncreative though.
  2. I wonder how fast converting things to strings really is. I could test this (am doing that now), but I could bother other smart people too. Could it be that for some small cases, that a looping mod 10 method is faster?

Posts: 4

Participants: 3

Read full topic

About the code review category

$
0
0

@mbrubeck wrote:

Want feedback on your Rust code or project? Post your short program here, or share a link to your complete repo. Large and small projects, beginners and advanced programmers, all are welcome here.

Providing feedback on other people's code? Remember to be nice, and focus on specific ways to make the code better.

This category is mainly for sharing working code and finding ways to improve it by making it more efficient, more idiomatic, etc. If your code is not working and you want to know how to fix it, use the Help category.

Posts: 1

Participants: 1

Read full topic

What's the fastest way to read a lot of files?

$
0
0

@jcubed wrote:

I'm looking for the best way to walk through a directory and perform operations on every file in the directory. In the best case, I'd like to be able to create a work queue and some kind of multithreaded stealing mechanisms that grab the content of the file once it becomes read.

What is the best way to approach this?

Posts: 11

Participants: 6

Read full topic

Link.exe not found - But community edition not an option

$
0
0

@DrYSG wrote:

I am working on a loaner laptop (windows) do to COVID-19. So I don't have my usual VS2019 tools.

We are not legally supposed to use VS Community edition on company equipment (we don't qualify as a 1000+ non-profit).

Just installed rust on the loaner, but I am getting this error on cargo build



error: could not compile `proc-macro2`.
warning: build failed, waiting for other jobs to finish...
error: linker `link.exe` not found
  |
  = note: The system cannot find the file specified. (os error 2)

note: the msvc targets depend on the msvc linker but `link.exe` was not found

note: please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 was installed with the Visual C++ option

error: aborting due to previous error

error: could not compile `winapi`.

Posts: 5

Participants: 4

Read full topic

Webassembly: Why so closely tide to Node?

$
0
0

@worik wrote:

Friends

I have been learning Rust in my spare time for a couple of years, and recently have been exploring webassembly to tie in Rust with PWAs, another technology I have been recently exploring.

tl;dr Rust is a carefully designed marvel of modern technology that builds on the lessons of the past. Node.js is not and does not. Why tie Webassembly so closely to Node.js?

I recently walked through the tutorial for which I installed the Node.js mess into a VM for that purpose. The resulting www/ heirachy had more than 7,000 files in it, all in my document root. The system was periodically polling my server for some unknown reason. I really do not trust it. AFAICT there is no straightforward path to serving with my favorite webserver. The turtorial leaves me high and dry in Node hell.

I have found this documentation and this code which looks like it will meet my needs. Thank you (again) to Rusticans beating a path for me, I really appreciate it.

I am interested in why the choice was made.

Posts: 7

Participants: 5

Read full topic


External state in an async hyper service_fn

$
0
0

@bocc wrote:

I want to propagate state to hyper's service_fn, which takes a single parameter, the request. As the example suggests, you can work around this by using a closure. But, I am going to need to concatenate the request body in order to parse it, and I have only seen it done asynchronously - which is currently not possible inside a closure on stable.

How do I work around this?

Posts: 2

Participants: 1

Read full topic

Update of HashMap stored in immutable struct doesn't persist

$
0
0

@AlienKevin wrote:

Hi, I'm working on a parser for a simple assembly language and struggled to update the symbol_table stored in a state that's passed throughout the parser. I tried implementing the symbol_table as HashMap<String, usize> and Box<HashMap<String, usize>> but updates in both are lost.

Here's the immutable State sturct:

#[derive(Clone)]
pub struct State {
  symbol_table: HashMap<String, usize>,
  instruction_index: usize,
  variable_index: usize,
}

Update logic:

update_state(move |label, state|
          if !state.symbol_table.contains_key::<str>(&label) {
            let mut new_symbol_table = state.symbol_table.clone();
            new_symbol_table.insert(label.clone(), state.instruction_index + 1);
            State {
              symbol_table: new_symbol_table,
              ..state
            }
          } else {
            state
          }
        )

Here's the link to the full assembler on github: https://github.com/AlienKevin/hack-assembler

Posts: 7

Participants: 3

Read full topic

Exit code: 0xc0000135, STATUS_DLL_NOT_FOUND

$
0
0

@hyousef wrote:

I'm at Win 10 Trying to work with PyO3 but got the mentioned error, by searching found something telling I've to:

Download vspkg and install vcpkg.exe install libusb:x64-windows-static . Set an environment variable LIBUSB_DIR that points to C:\vcpkg\installed\x64-windows-static and use the patched version of libusb-sys by putting this in your

So, i did so, but still getting the same error:

I tried testing the:

[dependencies]
libusb = "0.3"
libusb-sys = "0.2.3"

[patch.crates-io]
"libusb-sys" = { git = "https://github.com/cmsd2/libusb-sys" }

And got the below:

It looks like you're compiling for MSVC but we couldn't detect a libusb-1.0
installation.
', C:\Users\hasan.yousef\.cargo\git\checkouts\libusb-sys-5e09c578d58d3871\096f247\build.rs:89:5

Posts: 1

Participants: 1

Read full topic

How to make a struct field generic for Vec and array

$
0
0

@joseph.wakeling wrote:

Hello folks,

I have a struct (and associated methods) where one of the fields could in principle be implemented as a Vec<f64>, or as a fixed-length array [f64; D] for some const D. In other words, it's expected that the stored Vec/array will have fixed length for the entire lifetime of the (mutable) struct.

My first implementation used const generics to fix the number of dimensions D and used [f64; D] for data storage. However, that relies on a nightly-only feature, and there are some limits on what features are available for arrays longer than 32.

So, I decided to rewrite to use a Vec instead. This worked fine, but halved the speed of the code (not really a surprise, as particularly with smaller length I imagine fixed size arrays are much easier to optimize).

So, having thought this through, it occurred to me that the best implementation would be to make the struct generic over the storage type, with the only constraints being that (i) it must be either an array or Vec and (or perhaps, that it must allow array-like interaction), and (ii) it must have floating-point elements.

Ideally it would also be possible to denote other fields as having the same type as the array/Vec element type.

In other words, I want to be able to craft a struct of the form

struct MyStruct<T> {
    vec_or_arr: T,
    some_float: {element-type-of-T}
    other_float: {element-type-of-T}
}

where T is constrained to being array-like or Vec-like.

(An effect of this would be that the function which initializes such struct instances -- which takes a slice as input -- would need to either just copy from the slice, or use to_vec to clone its content, depending on whether the struct data type is a fixed-size array or vec. And yes, the struct needs to own its data, not just hold a slice itself.)

So the question here is: how would I go about implementing such a generic version of my struct? The Rust book generic chapter isn't really helpful in this respect, and nor is Rust By Example.

I assume I would have to specify traits for the array-like behaviour, but which? And I really have no idea how I might go about setting other field types according to the array/Vec element type.

Can anyone advise?

Thanks in advance for any help, and best wishes,

    -- Joe

Posts: 12

Participants: 5

Read full topic

"Ocean of Code [Captain Sonar]" - Codingame competitive contest is live

Is my understanding to lifetime constraint in generic function correct?

$
0
0

@astrojhgu wrote:

In the declaration of a generic function, after the where clause, we may write:

where T: SomeTrait + 'a

Previously I'm confused about how could a type be associated with some lifetime, while it is not a reference.

Then I guess that T it self could be a reference, for example, T is instantiated to be e.g., &u32, then its lifetime becomes relevant.

In another example:

where T: SomeTrait + 'static

implies that eityer T has to be a &'static U (where U is some other type) , or it cannot be a reference type.

Is that correct?

Posts: 3

Participants: 3

Read full topic

`T` cannot be known at compilation time with `Sized` bound

$
0
0

@nano wrote:

When I try to compile this code:

pub trait Bytes {
    type Type;
}

impl<T> Bytes for T
    where
        T: Sized,
{
    type Type = [u8; std::mem::size_of::<T>()];
}

The compiler takes me an error:

error[E0277]: the size for values of type `T` cannot be known at compilation time
   --> src\from_bytes.rs:16:42
    |
14  |         T: Sized,
    |                  - help: consider further restricting type parameter `T`: `, T: std::marker::Sized`
15  | {
16  |     type Type = [u8; std::mem::size_of::<T>()];
    |                                          ^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `T`
    = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>

But did I restrict the type T to be Sized? Right?
Then what does the compiler need?

Also, I tried to write like this. But that doesn't help either.

pub trait Bytes
    where
        Self: Sized,
{
    type Type;
}

Posts: 2

Participants: 2

Read full topic


Do two things in Result matching

$
0
0

@Narann wrote:

Hi Rust community, I’m learning rust and would love to have a review of this tiny code snippets.

My original hint is to parse a string value to a int. If parsing fail I do something (here, I'm simply printing a message), and put a default value.

This technically works, but it looks weird to me:

let res = foo_str.parse::<u8>();

if res.is_err() {
    println!("Taking default value: 30");  // do something
}

let foo = match res {
    Ok(v) => v,
    Err(e) => 30,
};

They are a lot of example on Result handling over the internet with either print things or return thing but nothing explaining how to do something then return something.

Is there any rustonic way to handle this?

Posts: 2

Participants: 2

Read full topic

BTreeMap::with_capacity

How to sleep in no_std?

Issues making web request with reqwest

$
0
0

@palahacker wrote:

Hi,

I am exploring "reqwest" library, I did some test with get method.

If I use "Blocking::get", it is working ok but if I try to use simple "Get", I don't get any compiling error but when I execute my code I get this error:

"thread 'main' panicked at 'not currently running on the Tokio runtime.', src/libcore/option.rs:1188:5".

Any clue?

async fn http_request_3(_site: String) -> Result<()>{

    let mut _result = reqwest::get(&_site).await?;
    let mut _status = String::new();
    _result.text();
    

    Ok(())

 }

Posts: 3

Participants: 2

Read full topic

Who owns the return value?

$
0
0

@niharrs wrote:

fn main () {
    println! ("{}", some_function(x));
}

fn some_function (y) -> i32 {
    y+32
}

Where is the return value from some_function stored? Who owns that?

Posts: 3

Participants: 3

Read full topic

Viewing all 50976 articles
Browse latest View live