The Rust Programming Language

1 readers
0 users here now

A place for all things related to the Rust programming language—an open-source systems language that emphasizes performance, reliability, and...

founded 1 year ago
MODERATORS
1
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/saylol2some on 2023-08-11 19:40:45.


I'd like to have as many checks in pre-submit such that i can reduce time to review patches and keep the repo sane.

I can't rely on pre-commit hooks in an open source project.

2
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/allmudi on 2023-08-11 17:51:54.


rust-security-framework (wrapper of apple security in rust) is no longer actively maintained due to internal misunderstandings, for those who are interested I created a new wrapper from that (I tried to contact them but didn't get a response).

github.com/emanuele-em/apple-security

I already added additional functions and if you want to contribute or make suggestions you are welcome.

if you want to help with maintenance please contact me!

3
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/Al_Redditor on 2023-08-11 22:49:17.


I was recently able to convince our team to stand up a service using Rust and Axum. It was my first Rust project so it definitely took me a little while to get up to speed, but after learning some Rust basics I was able to TDD a working service that is about 4x faster than a currently struggling Java version.

(This service has to crunch a lot of image bytes so I think garbage collection is the main culprit)

But I digress!

My main point here is that using Rust is such a great developer experience! First of all, there's a crate called "Axum Test Helper" that made it dead simple to test the endpoints. Then more tests around the core business functions. Then a few more tests around IO errors and edge cases, and the service was done! But working with JavaScript, I'm really used to the next phase which entails lots of optimizations and debugging. But Rust isn't crashing. It's not running out of memory. It's running in an ECS container with 0.5 CPU assigned to it. I've run a dozen perf tests and it never tips over.

So now I'm going to have to call it done and move on to another task and I have the sads.

Hopefully you folks can relate.

4
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/openquery on 2023-08-11 19:24:07.

5
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/rustological on 2023-08-11 16:02:37.


One way to call methodA or methodB, if depending on different platforms, is via conditional compilation For example, compilation on Windows and Linux requires different handling of filenames/paths. Ok, makes sense, like with C.

However, how to implement a dynamic choice on startup? Say, I'm running Linux, and either in a terminal/TUI or under X/GUI. On startup I have to run some checking code first, and then I want to set "output a string so user surely sees it" needs to be either writeTUI(..) oder writeGUI(..), globally, throughout the rest of the program.

Trait of methods with variants, then specific trait object instance assigned to global accessible static after test at startup?

6
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/Velfke on 2023-08-11 14:58:26.


Hello, r/rust!

I've been following Rust on this subreddit for some time now. Finally, I decided to dive in, having had no prior experience with the language, and share my experiences here.

BLUF: Rust is amazing, and I'm excited to dive deeper.

1. Choice of Project

I chose to implement a topic close to my heart from university: functional data structures. Check out the library . It doesn't make use of unsafe or &mut self.

To briefly introduce, functional data structures are immutable by design. Once created, they remain unchanged. To modify them, you clone and then modify the cloned version. This ensures immutability and persistence (allowing retention of all versions of the data structure). The beauty lies in making the clone operation inexpensive by reusing most of the original data structure.

2. Rust's Strengths

2.1. Pattern Matching + Union Type

This combination greatly enhances the expressiveness and correctness of certain data structures. Consider:

pub enum AVL {
    Empty,
    Node {
        key: ...,
        value: ...,
        left: ...,
        right: ...,
    },
}

In many languages, the typical implementation might set "left" as a null pointer, introducing potential runtime bugs, or an Option::None, leading to cluttered conditionals. Rust allows the empty AVL tree to be a valid state, simplifying method implementations:

fn height(&self) -> i64 {
  match self {
      AVL::Empty => 0,
      AVL::Node { key: _, value: _, left, right } => 1 + max(&left.height(), &right.height()),
  }
}

Furthermore, this approach guarantees you consider all possible states for functions like find:

pub fn find(&self, target_value: &K) -> Option<&V> {
    match self {
        AVL::Empty => Option::None,
        AVL::Node { key, value, left, right } => 
            match target_value.cmp(key) {
                std::cmp::Ordering::Less => left.find(target_value),
                std::cmp::Ordering::Equal => Option::Some(value),
                std::cmp::Ordering::Greater => right.find(target_value),
            },
    }
}

2.2. Traits

The trait system truly endeared Rust to me. Having copy and clone disabled by default for user-defined types means you must opt into their implementation. This can guarantee, through the type system, that no unintended copies or clones are made. This pushed me to deeply reflect on my algorithmic assumptions: In a Trie storing [T], is T required to implement clone? Should T be Ord or is Eq sufficient?

3. Challenges Faced

3.1. Learning Curve

Grasping Rust felt like re-learning programming. Despite the exhaustive Rust Book and its top-notch compiler error messages and LSP, Rust is conceptually intense. It felt like simultaneously mastering a robust type system and the intricacies of systems programming, topics that could each demand an entire university course. I find it hard to envision Rust as a "black box" programming language.

My primary learning resource was the Crust of Rust YouTube series.

3.2. Nested Pattern Matching with Rc/Arc

Given the heavy reliance on sharing chunks of immutable data in these structures, there are many instances of Rc/Arc. This essentially obstructs nested pattern matching, especially when you're handling tree rotations and aiming to match specific scenarios. This challenge seems to be under active consideration.

4. Reflections

Going forward, I aim to expand this library and continue my Rust journey, with iterators on the horizon.

In hindsight, perhaps this project wasn't the most beginner-friendly choice; it thrust me into the depths of Rust's concepts like borrow checker, lifetimes, Rc/Arc, and generics. Regardless, I'm delighted with my experience. It confirmed that Rust isn't just hype—it genuinely enhanced my understanding of many systems programming nuances that I'd previously overlooked.

7
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/Effective_Key5402 on 2023-08-11 14:19:08.

8
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/ibraheemdev on 2023-08-11 14:55:45.

9
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/security-union on 2023-08-11 04:58:54.

10
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/everything-narrative on 2023-08-11 09:08:09.


Ordinary definition of crash-only software, here. However, I've come across an interesting variation, wherein a program has no 'graceful shutdown' procedure, and the startup procedure is an error-recovery step as a matter of course. This style of design imparts tremendous stability, since it forces robust error-recovery on startup.

Are there any guides or blog posts about how to write such crash-only software in Rust?

11
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/joshhansen on 2023-08-11 08:46:37.


Introducing Ghee 0.3, the newest release of the premier tool for manipulating Linux extended attributes!

Originally known as Hatter and then, regrettably, as Mattress, this tastiest of tools has been redubbed Ghee after the clarified butter popular in Indian cuisine, and as a reference to the Btrfs filesystem, which originally convinced me that much database functionality has now been subsumed by advanced filesystem features.

This new release adds SQL WHERE-style predicates to filter by, e.g. ghee get --where age >= 65 ./people, and makes get recursive by default (the old behavior is still available behind the --flat flag).

The idea is for Ghee to implement as much of a relational data model as possible using the filesystem itself as a substrate. Design principles:

  1. Folders are tables
  2. Files are records
  3. Relative paths are primary keys
  4. Extended attributes are non-primary-key columns
  5. Enforce schema only when present
  6. The file contents are user-controlled; only directory structure, filenames, and extended attributes are used by Ghee
  7. Use of filesystem features should be preferred over implementing features directly in Ghee, e.g. locking, Btrfs subvolumes, snapshots, incremental backup

Would love to hear any comments. Apologies for the name changes---third time's the charm, I think this one'll stick.

12
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/OS6aDohpegavod4 on 2023-08-11 04:20:18.


I couldn't find any formal definition of it, at least for Rust. The Book uses it to describe "not generic" types, but at some point I had just assumed that it meant "not polymorphic", since polymorphism is an abstraction and "concrete" (at least to me) very clearly means "not abstract". As in I can look at the type and know what it is (e.g. a struct, enum, u64).

If I see a generic, I don't know what it could be (it could be many things). The same goes for trait objects, though. Enums are also a kind of polymorphism, but I always thought of them as concrete since I can see it's an enum and can look at the variants.

Are trait objects concrete types? If so, then I guess concrete type literally just means "not generic"? Or is it something else?

13
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/Shivalicious on 2023-08-10 22:57:16.


I have a file on disk. I want to find a particular line (whitespace & case insignificant), skip blank lines after it, skip one non-blank line, skip blank lines, and get the first non-blank line. The file looks like this:

something

something else  

 things
 some pattern

ignore this line

return this line

other stuff
`I want `return this line`. I’ve implemented two ways of parsing it so far. With a loop:`rust
let file = File::open(text\_file)?;
let mut reader = BufReader::new(file);

let mut buf = String::new();
let mut expecting\_1 = false;
let mut expecting\_2 = false;

while reader.read\_line(&mut buf)? != 0 {
 buf = buf.trim().to\_string();

if buf.is_empty() { continue; }

if expecting_2 { return Ok(Some(buf)); } else if expecting_1 { expecting_2 = true; } else if buf.to_ascii_lowercase() == "some pattern" { expecting_1 = true; }

buf.clear();


}

Ok(None)
`And by abusing iterators:`rust
let file = File::open(text\_file)?;
let reader = BufReader::new(file);

let amount = reader
 .lines()
 .map\_while(|l| l.ok().map(|l| l.trim().to\_owned()))
 .skip\_while(|l| l.to\_ascii\_lowercase() != "some pattern")
 .skip(1)
 .skip\_while(|l| l.is\_empty())
 .skip(1)
 .find(|l| !l.is\_empty());

Ok(amount)

Both work—I haven’t tried very hard to shorten them—but they seem inelegant in concept. Is there a better way?

14
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/pietroalbini on 2023-08-11 09:40:42.

15
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/timClicks on 2023-08-11 05:38:33.

16
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/jorda_n on 2023-08-11 02:00:00.

17
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/passcod on 2023-08-11 01:46:41.

18
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/wojtek-graj on 2023-08-11 01:30:43.


While perusing Wikipedia I stumbled upon a short page on Oriel, a scripting language bundled with the Windows 3/3.1/NT Power Tools books, and decided to write an interpreter. Oriel is quite a unique language because, despite being similar to basic, its output is entirely graphical, and because it was designed with Windows 3 in mind, it can take input from the menubar, mouse, and keyboard.

Given that this is my first larger rust project I'm sure there are plenty of things to improve, so I'll gladly accept any and all feedback.

If by some miracle anyone happens to have a copy of Windows NT Power Tools lying around, please get in touch with me. I'd love to add support for the 1994 version of Oriel, but this book has effectively been lost to time.

Check it out here:

19
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/SaltManager on 2023-08-10 19:35:24.


So I have been messing around with proc macros for the last couple of days with the syn crate yet I cannot get my head around just yet when it comes to the parser functions in syn.

Here is an example of what the macro could be parsing:

macro_name!{
    foo: "Some string",
    bar: "Some other string",
    baz: variable_value,
    some_ident: {
        attr1: "Oh look another string",
        attr2: "Ok now this is getting boring.."
    }
}

The order of the Idents foo, bar, baz and so on should not be important and the value of these could be a string or a variable value but that is not important for now for parsing the TokenStream.

I read the syn documentation about making you own Parse implementation but I could not find anywhere on how to iterate over a TokenStream and parsing it with my custom parsing function.

Does anyone know a resource I could look into?

20
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/_cart on 2023-08-10 22:41:44.

21
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/scorpionCPP on 2023-08-10 20:05:43.


Hi, I am working with C library bindings and needed to make some workaround to share data pointer between threads in C way. I find out that Box needs to be feeded again with pointer or copy to still be valid. That's ok, but why after giving ownership to the raw pointer, Box is printing "old" data insead of simply panic. It seems would be hard to investigate on production.

Code:

 let data: Arc>>> = Arc::new(Mutex::new(Some(Box::new(42))));

{ let lock = data.lock().unwrap();

let data_ptr: *mut u8 = lock.clone()
    .map(|boxed_u8| Box::into_raw(boxed_u8))
    .unwrap_or(std::ptr::null_mut());

unsafe{
    let ptr_copy: *mut u8 = data_ptr;
    *ptr_copy = 54;
    println!("{}", *ptr_copy);
}

}

let lock = data.lock().unwrap(); println!("{}", *lock.as_ref().unwrap());


Output: 54 42

22
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/LucaCiucci on 2023-08-10 17:59:02.


This may not be very interesting, but I made an example project that shows how to call Rust from Fortran.

I hope this can be useful to someone, especially some students that want to take advantage of the tools and libraries provided by Rust.

23
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/DJ-BigFish on 2023-08-10 11:16:06.


I am writing this post to get further knowlage about this topic.

Rust-Cuda project is well designed, but I didn't manage to build the examples. The fact that you can write entire kernel in Rust is really good move for whole rust-gpu project.

ocl crate was one that I manage to run on any device. The only downside is, that the kernel is still written in OpenCL C language.

Has someone came across a compiler that can compile to opencl from rust, like the rust-cuda does?

Edit: I am planning to do just computing, not any visuals

24
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/xSUNiMODx on 2023-08-10 18:04:40.


Could someone clarify to me how the implementation of Vec::retain_mut works? Source code is here.

From what I understand we are doing two passes over the vector, but only the second pass actually does the moving around.

It looks like the first process_loop call only gets rid of 1 element and makes a "hole" there. We then move on to the second process_loop call and that uses the hole we made to copy whatever the next non-removable element is into the first available hole.

One point of confusion is why the comment here makes sense: // SAFETY: deleted_cnt > 0, so the hole slot must not overlap with current element. Why are we guaranteed that deleted_cnt > 0?

After all the moving around we call drop on the guard. The comment says that the whole ptr::copy gets optimized away by LLVM, which I don't understand, since deleted_cnt is likely to be greater than 0. I do understand the copying of the unchecked elements into the holes we just made though.

A final question is why we need two calls to process_loop over a const bool generic, since they seem pretty different.

25
 
 
This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/SirOgeon on 2023-08-10 14:17:16.

view more: next ›