Rust

6044 readers
2 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

[email protected]

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year ago
MODERATORS
76
10
This Week in Rust 560 (this-week-in-rust.org)
submitted 3 months ago by mac to c/rust
77
78
 
 

Planning to build a PC in couple of weeks.

What is the optimal number of cores to have without having diminishing returns?

79
80
31
submitted 3 months ago* (last edited 3 months ago) by abrahambelch to c/rust
 
 

Hey there, I'm currently learning Rust (coming from object-oriented and also to some degree functional languages like Kotlin) and have some trouble how to design my software in a Rust-like way. I'm hoping someone could help me out with an explanation here :-)

I just started reading the book in order to get an overview of the language as well.

In OOP languages, I frequently use design patterns such as the Strategy pattern to model interchangeable pieces of logic.

How do I model this in Rust?

My current approach would be to define a trait and write different implementations of it. I would then pass around a boxed trait object (Box<dyn MyTrait>). I often find myself trying to combine this with some poor man's manual dependency injection.

This approach feels very object oriented and not native to the language. Would this be the recommended way of doing things or is there a better approach to take in Rust?

Thanks in advance!

81
65
Rust Project goals for 2024 (blog.rust-lang.org)
submitted 3 months ago by mac to c/rust
82
26
Announcing Rust 1.80.1 (blog.rust-lang.org)
submitted 3 months ago by mac to c/rust
83
 
 

EventHelix writes:

This article will investigate how Rust handles dynamic dispatch using trait objects and vtables. We will also explore how the Rust compiler can sometimes optimize tail calls in the context of dynamic dispatch. Finally, we will examine how the vtable facilitates freeing memory when using trait objects wrapped in a Box.

84
 
 

Maybe a little weird question but do you maybe know a smart watch that can run rust? I got running Egui on my Galaxy Watch 4 with WearOS and I'm thinking if any other watch (other than Galaxy and Pixel) can do that?

85
86
87
 
 

Hi rustaceans! What are you working on this week? Did you discover something new, you want to share?

88
 
 

This feels like it should already be a feature in a terminal. But I didn't find anything that let me do this efficiently.

I had a rust library for converting list like 1-4,8-10 into vectors, but thought I'd expand it into a command line command as well, as it is really useful when I want to run batch commands in parallel using templates.

I wanted to share it since it might be a useful simple command for many people.

89
90
 
 

So, I'm basically trying to parse a string literal with nom. This is the code I've come up with:

use nom::{
    bytes::complete::{tag, take_until},
    sequence::delimited,
    IResult,
};

/// Parses string literals.
fn parse_literal<'a>(input: &'a str) -> IResult<&'a str, &'a str> {
    // escape tag identifier is the same as delimiter, obviously
    let escape_tag_identifier =
        input
            .chars()
            .nth(0)
            .ok_or(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Verify,
            )))?;

    let (remaining, value) = delimited(
        tag(escape_tag_identifier.to_string().as_str()),
        take_until(match escape_tag_identifier {
            '\'' => "'",
            '"' => "\"",
            _ => unreachable!("parse_literal>>take_until branched into unreachable."),
        }),
        tag(escape_tag_identifier.to_string().as_str()),
    )(input)?;

    Ok((remaining, value))
}

#[cfg(test)]
mod literal_tests {
    use super::*;

    #[rstest]
    #[case(r#""foo""#, "foo")]
    #[case(r#""foo bar""#, "foo bar")]
    #[case(r#""foo \" bar""#, r#"foo " bar"#)]
    fn test_dquotes(#[case] input: &str, #[case] expected_output: &str) {
        let result = parse_literal(input);
        assert_eq!(result, Ok(("", expected_output)));
    }

    #[rstest]
    #[case("'foo'", "foo")]
    #[case("'foo bar'", "foo bar")]
    #[case(r#"'foo \' bar'"#, "foo ' bar")]
    fn test_squotes(#[case] input: &str, #[case] expected_output: &str) {
        let result = parse_literal(input);
        assert_eq!(result, Ok(("", expected_output)));
    }

    #[rstest]
    #[case(r#""foo'"#, "foo'")]
    #[case(r#"'foo""#, r#"foo""#)]
    fn test_errs(#[case] input: &str, #[case] expected_err_input: &str) {
        let result = parse_literal(input);
        assert_eq!(
            result,
            Err(nom::Err::Error(nom::error::Error::new(
                expected_err_input,
                nom::error::ErrorKind::TakeUntil
            ))),
        );
    }
}

Note: The example uses rstest for tests.

Although it looks a little bit complex, actually, it is not. Basically, the parse function is parse_literal. The tests are separated for double quotes and single quotes and errors.,

When you run the tests, you will realize first and second cases for single and double quotes run successfully. The problem is with the third case of each: #[case(r#""foo \" bar""#, r#"foo " bar"#)] for test_dquotes and #[case(r#"'foo \' bar'"#, "foo ' bar")] for test_squotes.

Ideally, if a string literal is defined with single quotes and has single quotes in its content, the single quotes can be escaped with single quotes again. Same goes for double quotes as well. To demonstrate in a pseudocode:

"foo ' bar" // is ok
"foo \" bar" // is ok
"foo " bar" // is err
'foo " bar' // is ok
'foo \' bar' // is ok
'foo ' bar' // is err

Currently, in the code, I take characters until the delimiter with take_until, which reaches to the end of the input, which, let's say, in this case, is guaranteed to contain only and only the string literal as input. So it's kind of okay for first and second cases in the tests.

But, of course, this fails in the third cases of each test since the input has the delimiter character early on, finishes early and returns the remaining.

This is only for research purposes, so you do not need to give a fully-featured answer. A pathway is, as well, appreciated.

Thanks in advance.

91
 
 

cross-posted from: https://lemmy.world/post/17984566

Hi all,

mpv communities seem to be tiny in lemmy, so I'm sharing it here.

This is a program I made for music control from local network.

You can run it in a computer with some local media files, or youtube links or any other links yt-dlp supports. And then with the server, you can control the media player and the playlist from any devices in your local network. So that you can just show a QR code or something to house guests for parties, or have it bookmarked within family to control the music.

I wanted to make something similar to how youtube app let's you play in TV and such, but my skills were not enough to do that. So I tried a simple alternative that works with computers. In an ideal world, I could make "Play with local mpv server" option come while on other android apps, but I have zero experience in android app development and it looks complicated.

I know some other programs also give option to control media, but I wanted to give it a go with a simple implementation. Making the web-server was a tricky part. Only tutorial from the rust book was useful here as every other web server developement in rust seems to be async ones using libraries so I would have to make a complicated system to communicate with the mpv. Using the simple Tcp connection let me make a thread with mpv instance in the scope. I do need to support https and file uploads and other things, but I haven't had any luck finding a solution that works with simple Tcp connection like in the tutorial. Let me know if you know anything.

Github: https://github.com/Atreyagaurav/local-mpv

92
16
This Week in Rust 557 (this-week-in-rust.org)
submitted 4 months ago by mac to c/rust
93
 
 

Many devs dream of one day writing their own operating system. Ideally in their favorite language: Rust. For many of us, this dream remains just that: a dream.

Jeremy Soller from System76, however, didn't just contribute kernel code for Pop!_OS, but also started his own operating system, RedoxOS, which is completely written in Rust. One might get the impression that he likes to tinker with low-level code!

In this episode of Rust in Production, Jeremy talks about his journey. From getting hired as a kernel developer at Denver-based company System76 after looking at the job ad for 1 month and finally applying, to being the maintainer of not one but two operating systems, additional system tools, and the Rust-based Cosmic desktop. We'll talk about why it's hard to write correct C code even for exceptional developers like Jeremy and why Rust is so great for refactoring and sharing code across different levels of abstraction.

Listen to Rust in Production Podcast S02 E07

94
70
Announcing Rust 1.80.0 (blog.rust-lang.org)
submitted 4 months ago by mac to c/rust
95
96
 
 

Pretty much the title. For those who use LLMs for learning or writing rust code, claude is much better at it, based on my experience.

97
 
 

Hi friends, Not sure whether this little tool could be of use to anyone here, but I thought it might be interesting to share.

I was running into problems on my VPS due to high-memory usage, which led to my email server going down with all the consequences that come with it. I tried using Grafana Agent to monitor the server's state, but with 2GB memory, the tool's footprint was creating more problems than anything else, so I reinvented my own, square, low-memory footprint, wheels.

Cheers everyone.

98
 
 

cross-posted from: https://lemmy.ml/post/18162485

This would entail:

  • Pulling in the ClearUrls rules as a git submodule.
  • Reading / transforming the json there into Rust structs.
  • Creating a Rust crate that runs a .clean(input_url) -> String

Lemmy issue: https://github.com/LemmyNet/lemmy/issues/4905

99
19
submitted 4 months ago* (last edited 4 months ago) by [email protected] to c/rust
 
 
  • Added type diesel_async::pooled_connection::mobc::PooledConnection
  • MySQL/MariaDB now use CLIENT_FOUND_ROWS capability to allow consistent behaviour with PostgreSQL regarding return value of UPDATe commands.
  • The minimal supported rust version is now 1.78.0
  • Add a SyncConnectionWrapper type that turns a sync connection into an async one. This enables SQLite support for diesel-async
  • Add support for diesel::connection::Instrumentation to support logging and other instrumentation for any of the provided connection impls.
  • Bump minimal supported mysql_async version to 0.34

A special thanks goes to @momobel and Wattsense for contributing the SyncConnectionWrapper implementation.

To support future development efforts, please consider sponsoring me on GitHub.

Full Changelog: v0.4.0...v0.5.0

100
view more: ‹ prev next ›