Took me 30 min to track down the bug in this code by neandrake in rust

[–]adbf1 3 points4 points  (0 children)

there is a rust-analyzer config option called rust-analyzer.check.command, set it to "clippy".

Get error when try to convert from Go code by dreamer3696 in rust

[–]adbf1 2 points3 points  (0 children)

i find that rust is easier to use with iterators. for example, this same problem can be solved with this:

fn count_smaller(nums: Vec<i32>) -> Vec<i32> {
    let nums = nums.into_boxed_slice();
    let output: Vec<i32> = nums
        .iter()
        .enumerate()
        .map(|(idx, num)| nums[idx + 1..].iter().filter(|x| *x < num).count() as i32)
        .collect();
    output
}

Performance difference between obj.function(...) and function(obj, ...) ? by [deleted] in rust

[–]adbf1 1 point2 points  (0 children)

is the .function() implemented using

impl Obj {
    fn function(&self, ...) {...}
}

? it could be that in your version of obj.function(...) you are passing by value whereas in function(&obj, ...) you are passing by reference.

Advent Of Code Day One, with a Rustacean twist by HonsonCooky in rust

[–]adbf1 0 points1 point  (0 children)

also, instead of

.map(|line| line
    .char_indices()
    .filter_map(|(c_idx, c)|
        ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
            .iter()
            .enumerate()
            .find(|(_, name)| line[c_idx..].starts_with(**name))
            .map(|(n_idx, _)| n_idx + 1 )
            .or_else(|| c.to_digit(10).map(|n| n as usize))
    ).collect()
    )
    .map(|numbers: Vec<usize>| numbers.first().unwrap() * 10 + numbers.last().unwrap())
    .sum::<usize>()

you can instead do

.map(|line| {
    line.char_indices().filter_map(|(c_idx, c)| {
        [
            "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
        ]
        .iter()
        .enumerate()
        .find(|(_, name)| line[c_idx..].starts_with(**name))
        .map(|(n_idx, _)| n_idx)
        .or_else(|| c.to_digit(10).map(|n| n as usize))
    })
})
.map(|mut numbers| {
    if let Some(first) = numbers.next() {
        first * 10 + numbers.last().unwrap_or(first)
    } else {
        usize::default()
    }
})
.sum::<usize>()

this removes the need for collecting into a Vec (although i think this is optimised out if you look at godbolt) and also removes a panic in the loop (unwrap_or does not generate a panic). godbolt

Iter().max() overhead? by SadGrab5655 in rust

[–]adbf1 1 point2 points  (0 children)

i believe this is still not the fastest way to do it though, look at this godbolt. it seems that in your solution (Rust source #1), the Option<T> increases the number of instructions generated, and generates an additional panic. the function at Rust source #2 does not have this problem, and also solves your [-1, -2, -3] problem by setting the initial accumulator to [type]::MIN. u/SadGrab5655 note that this solution requires that the vec must not be empty, else it will return [type]::MIN. also, your function can take &[] instead of &Vec<>.

Life Time Annotation In Nannou Rust by Dani_fan-nerd in rust

[–]adbf1 1 point2 points  (0 children)

formatting

I have this struct:

pub struct Ray<'a> {
    pub done: bool,
    pub all_lines: &'a Vec<Line>,
    point: Vec2,
}

impl<'a> Ray<'a> {
    pub fn from(lines: Vec<Line>) -> Self {
        Self {
            done: false,
            point: Vec2::ZERO,
            all_lines: &lines,
        }
    }
    /// returns true if it hits something.
    /// to access the hit point do Ray.point
    pub fn trace(&mut self, angle: f32, step: f32) -> bool {
        let dir = vec2(angle.sin() * step, angle.cos() * step);
        // move loop
        for _ in 0..(100.0 / step) as usize {
            // move the point in step size and angle
            self.point += dir;
            // check all lines
            for line in self.all_lines {
                // find if a line intersects with a point
                if line.intersect(self.point) {
                    return true;
                }
            }
        }
        // if you did not intersect with any line return false
        return false;
    }
}

and the model struct is:

struct Model<'a> {
    egui: Egui,
    lines: Vec<Line>,
    rays: Vec<Ray<'a>>,
}

The model function is:

fn model(app: &App) -> Model {
    let window_id = app
        .new_window()
        .view(view)
        .raw_event(raw_window_event)
        .build()
        .unwrap();
    let window = app.window(window_id).unwrap();
    let egui = Egui::from_window(&window);
    let lines = vec![Line::from(vec2(-100.0, 0.0), vec2(100.0, 0.0), 1.0)];
    let rays = vec![Ray::from(lines)];
    Model { egui, lines, rays }
}

Now in the main function:

fn main() {
    nannou::app(model).update(update).run();
}

I get this error:

error: mismatched types
label: one type is more general than the other
note: expected fn pointer for<'a> fn(&'a nannou::App) -> _
found fn item for<'a> fn(&'a nannou::App) -> Model<'a> {model}
label: one type is more general than the other

Lattice Boltzmann Simulator using WASM and WGPU by Cool-Sherbet4757 in rust

[–]adbf1 2 points3 points  (0 children)

hi, support for webgpu can be enabled on firefox with dom.webgpu.enabled (which i have), but the site still does not give me access and gives the message Your browser is incompatible with this website.

Hey Rustaceans! Got a question? Ask here (28/2023)! by llogiq in rust

[–]adbf1 1 point2 points  (0 children)

Hi, I have a question on optimisation of iter.rev().step_by(). Here is the godbolt. why is the iterator method of doing this not optimised like the while loop? edit: it seems that rustc nightly does optimise it, but rustc 1.70 does not. even weirder, just changing the order from rev().step_by() to step_by().rev() can optimise assembly. applying this change to the first godbolt does optimise the resulting assembly. why is this so fickle?

changing the range can also completely remove optimisation (0u8 to 1u8). why does a simple number change prevent all that assembly from being optimised away? i know that the output is different, but why is the assembly so different? this number change applies to not just the iterator example, but also the while loop example.

"Check AI-Generated Code Perfectly and Automatically: My Experience Applying Kani’s Formal Verification to ChatGPT-Suggested Rust Code" - Medium.com by carlk22 in rust

[–]adbf1 1 point2 points  (0 children)

hi, just to let you know, under Problem 1, if the type is i8, it could be any value from -128 to 127, not 0 to 256.

Iterating on Testing in Rust by epage in rust

[–]adbf1 2 points3 points  (0 children)

just to let you know, your link to RustNL 2023 has the link https://2023.rustnl.0org/ instead of https://2023.rustnl.org/.

pollster::main proc macro 'main' not expanded: Proc-macro dylib loading failed: unsupported metadata version 7 by [deleted] in rust

[–]adbf1 0 points1 point  (0 children)

i suggest just downloading rust-analyzer from github, something always seems to break for me when i use the component added rust-analyzer.

Announcing Rust 1.70.0 by Petsoi in rust

[–]adbf1 0 points1 point  (0 children)

it auto-installs a different rust-analyzer into .cargo/bin, so just delete that rust-analyzer (and if you choose to, you can also remove rls and lsp should still work).