RunAwayFrog

@RunAwayFrog@sh.itjust.works

This profile is from a federated server and may be incomplete. Browse more on the original instance.

I created rcp, an OSC52 copy tool for your remote server (codeberg.org)

I have been searching for a simple way to copy loads of text from remote servers for a while. This includes files, but is sometimes also only multiple lines from stdout of a program. Oftentimes this is kinda hard to do in terminal emulators, so I wrote a very small program to copy text via Operating System Commands....

RunAwayFrog,
  • Don’t use “*” dep version requirements.
  • Add Cargo.lock to version control.
  • Why read to string if you’re going to base64-encode and use Vec<u8> later anyway?
RunAwayFrog,

Regarding Cargo.lock, the recommendation always was to include it in version control for application/binary crates, but not library ones. But tendencies changed over time to include it even for libraries. If a rust-toolchain file is tracked by version control, and is pinned to a specific stable release, then Cargo.lock should definitely be tracked too [1][2].

It’s strictly more information tracked, so there is no logical reason not to include it. There was this concern about people not being aware of –locked not being the default behaviour of cargo install, giving a false sense of security/reliability/reproducibility. But “false sense” is never a good technical argument in my book.

Anyway, your crate is an application/binary one. And if you were to not change the “*” dependency version requirement, then it is almost guaranteed that building your crate will break in the future without tracking Cargo.lock ;)

RunAwayFrog, (edited )

Here is an originally random list (using cargo tree --prefix=depth) with some very loose logical grouping. Wide-scoped and well-known crates removed (some remaining are probably still known by most).


<span style="color:#323232;">mime data-encoding percent-encoding textwrap unescape unicode-width scraper
</span><span style="color:#323232;">arrayvec bimap bstr enum-iterator os_str_bytes pretty_assertions paste
</span><span style="color:#323232;">clap_complete console indicatif shlex
</span><span style="color:#323232;">lz4_flex mpeg2ts roxmltree speedy
</span><span style="color:#323232;">aes base64 hex cbc sha1 sha2 rsa
</span><span style="color:#323232;">reverse_geocoder trust-dns-resolver
</span><span style="color:#323232;">signal-hook signal-hook-tokio
</span><span style="color:#323232;">blocking
</span><span style="color:#323232;">fs2
</span><span style="color:#323232;">semver
</span><span style="color:#323232;">snmalloc-rs
</span>
RunAwayFrog,

My quick notes which are tailored to beginners:

Use Option::ok_or_else() and Result::map_err() instead of let … else.

  • let … else didn’t always exist. And you might find that some old timers are slightly triggered by it.
  • Functional style is generally preferred, as long as it doesn’t effectively become a code obfuscater, like over-using Options as iterators (yes Options are iterators).
  • Familiarize yourself with the https://doc.rust-lang.org/nightly/std/ops/trait.Try.html

Type inference and generic params


<span style="color:#323232;">let headers: HashMap = header_pairs
</span><span style="color:#323232;">        .iter()
</span><span style="color:#323232;">        .map(|line| line.split_once(":").unwrap())
</span><span style="color:#323232;">        .map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
</span><span style="color:#323232;">        .collect();
</span>

(Borken sanitization will probably butcher this code, good thing the problem will be gone in Lemmy 0.19)

Three tips here:

  1. You don’t need to annotate the type here because it can be inferred since headers will be returned as a struct field, the type of which is already known.
  2. In this pattern, you should know that you can provide the collected type as a generic param to collect() itself. That may prove useful in other scenarios.
  3. You should know that you can collect to a if the iterator items are Results/Options. So that .unwrap() is not an ergonomic necessity 😉

Minor point

  • Use .into() or .to_owned() for &amp;str => String conversions.
    • Again, some pre-specialization old timers may get slightly triggered by it.

make good use of the crate echo system

  • It’s important to make good use of the crate echo system, and talking to people is important in doing that correctly and efficiently.
    • This post is a good start.
    • More specifically, the http crate is the compatibility layer used HTTP rust implementations. Check it out and maybe incorporate it into your experimental/educational code.

Alright, I will stop myself here.

RunAwayFrog,

lemmy deleted everything between the “less than” character and “>”.

Lemmy also escaped the ampersands in their comment’s link 😉

Isn’t broken sanitization great!

RunAwayFrog, (edited )

Practically speaking, you don’t have to.

Your executor of choice should be doing tokio compat for you, one way or another, so you don’t have to worry about it (e.g. async-global-executor with the tokio feature).

async-std is dead.

RunAwayFrog, (edited )

Next Day Edit: Sorry. Forgot to use my Canadian Aboriginal syllabics again. Because apparently it’s too hard to admit HTML-sanitizing source markdown was wrong!

One thing that irks me in these articles is gauging the opinion of the “Rust community” through Reddit/HN/Lemmy😉/blogs… etc. I don’t think I’d be way off the mark when I say that these platforms mostly collectively reflect the thoughts of junior Rustaceans, or non-Rustaceans experimenting with Rust, with the latter being the loudest, especially if they are struggling with it!

And I disagree with the argument that poor standard library support is the major issue, although I myself had that thought before. It’s definitely current lack of language features that do introduce some annoyances. I do agree however that implicit coloring is not the answer (or an answer I want to ever see).

Take this simple code I was writing today. Ideally, I would have liked to write it in functional style:


<span style="color:#323232;">    async fn some_fn(&self) -> OptionᐸMyResᐸVecᐸu8ᐳᐳᐳ {
</span><span style="color:#323232;">        (bool_cond).then(|| async {
</span><span style="color:#323232;">            // ...
</span><span style="color:#323232;">            // res_op1().await?;
</span><span style="color:#323232;">            // res_op2().await?;
</span><span style="color:#323232;">            // ...
</span><span style="color:#323232;">            Ok(bytes)
</span><span style="color:#323232;">        })
</span><span style="color:#323232;">    }
</span>

But this of course doesn’t work because of the opaque type of the async block. Is that a serious hurdle? Obviously, it’s not:


<span style="color:#323232;">    async fn some_fn(&self) -> OptionᐸMyResᐸVecᐸu8ᐳᐳᐳ {
</span><span style="color:#323232;">        if !bool_cond {
</span><span style="color:#323232;">            return None;
</span><span style="color:#323232;">        }
</span><span style="color:#323232;">
</span><span style="color:#323232;">        let res = || async {
</span><span style="color:#323232;">            // ...
</span><span style="color:#323232;">            // res_op1()?;
</span><span style="color:#323232;">            // res_op2()?;
</span><span style="color:#323232;">            // ...
</span><span style="color:#323232;">            Ok(bytes)
</span><span style="color:#323232;">        };
</span><span style="color:#323232;">
</span><span style="color:#323232;">        Some(res().await)
</span><span style="color:#323232;">    }
</span>

And done. A productive Rustacean is hardly wasting time on this.

Okay, bool::then() is not the best example. I’m just show-casing that it’s current language limitations, not stdlib ones, that are behind the odd async annoyance encountered. And the solution, I would argue, does not have to come in the form of implicit coloring.

RunAwayFrog,

Opendoas has a significantly smaller codebase. It only has 4397 lines of code compared to Sudo-rs’s staggering 35990 lines.

Hmm.


<span style="color:#323232;">% tokei src | rg ' (Language|Total)'
</span><span style="color:#323232;"> Language            Files        Lines         Code     Comments       Blanks
</span><span style="color:#323232;"> Total                  76        16243        13468          682         2093
</span>

<span style="color:#323232;">% tokei src test-framework | rg ' (Language|Total)'
</span><span style="color:#323232;"> Language            Files        Lines         Code     Comments       Blanks
</span><span style="color:#323232;"> Total                 196        34274        27742         1072         5460
</span>

<span style="color:#323232;">% git grep '#[cfg(test)]' src |wc
</span><span style="color:#323232;">     40      44    1387
</span>

I too love making unaware “Tests Considered Harmful” arguments based on some blind analysis.

Funnily enough, one could easily do some actually potentially useful shallow analysis, instead of a completely blind one, simply by noticing the libc crate dependency, then running:


<span style="color:#323232;">git grep -Enp -e libc:: --and --not -e '(libc::(c_|LOG)|b(type|use)b)'
</span>

Ignoring the usage in test modules, use of raw libc appears to be more than you would think from the title. One can also argue that some of that usage would be better served by using rustix instead of raw libc.

Of course authors can counter with arguments why using rustix* is not feasible or would complicate things, and would argue that the use of unsafe+libc is required for this kind of project, and it’s still reasonably limited and contained.

And a little bit more informed back-and-forth discussion can go from there.

  • Searching for rustix in the sudo-rs repo returned this. So this predictably has been brought up before.
RunAwayFrog,

I do, however, hold to the fact that any sudo implementation will be more complicated than doas. Sudo, as a project, has more options and usecases than doas so it also has more posibilities for bugs or misconfiguration for the user.

Fair.

I’m unable to tell what codebase your are refering to with you’re grep arguments, sorry.

sudo-rs

RunAwayFrog,

exa (which OP’s readme says eza is built on) supports creation times. Actual creation time (the “Birth” line in stat output), not ctime.

RunAwayFrog,

I would bad mouth Axum and Actix just because of the overhype. But then, the latter is powering this very platform, and the former is used in the federation crate examples 😉

So let me just say that I tried poem and it got the job done for me. Rusty API. Decent documentation. And everything is in one crate. No books, extension crates, and towers of abstractions needed.

I try to avoid tokio stuff in general for the same reason, although a compatible executor is unfortunately often required.

RunAwayFrog,

Look into Arc, RwLock, and Mutex too.

Later, check out parking_lot and co. and maybe async stuff too.

RunAwayFrog,

From your list, I use bat, exa and rg.

delta (sometimes packaged as git-delta) deserves a mention. I use it with this git configuration:


<span style="color:#323232;">[core]
</span><span style="color:#323232;">  # --inspect-raw-lines=false fixes issue where some added lines appear in bold blue without green background
</span><span style="color:#323232;">  # default minus-style is 'normal auto'
</span><span style="color:#323232;">  pager = "delta --inspect-raw-lines=false --minus-style='syntax #400000' --plus-style='syntax #004000' --minus-emph-style='normal #a00000' --plus-emph-style='normal #00a000' --line-buffer-size=48 --max-line-distance=0.8"
</span><span style="color:#323232;">
</span><span style="color:#323232;">[interactive]
</span><span style="color:#323232;">  diffFilter = "delta --inspect-raw-lines=false --color-only --minus-style='syntax #400000' --plus-style='syntax #004000' --minus-emph-style='normal #a00000' --plus-emph-style='normal #00a000' --line-buffer-size=48 --max-line-distance=0.8"
</span><span style="color:#323232;">
</span><span style="color:#323232;">[delta]
</span><span style="color:#323232;">  navigate = true  # use n and N to move between diff sections
</span><span style="color:#323232;">  light = false    # set to true if you're in a terminal w/ a light background color (e.g. the default macOS terminal)
</span><span style="color:#323232;">
</span><span style="color:#323232;">[merge]
</span><span style="color:#323232;">  conflictstyle = diff3
</span>
RunAwayFrog,

I constantly seem to include something from the docs, only to be told by the compiler that it does not exist, and then I have to open the source for the create to figure out if it’s hidden behind a feature flag.

As others mentioned, the situation is not perfect. And you may need to check Cargo.toml. Maybe even the source.

But as for the quoted part above, the docs should definitely indicate if a part of the API is behind a feature. Let’s take rustix as an example.

Here is the module list:

https://sh.itjust.works/pictrs/image/06f9b6d2-b682-4c95-8bd3-33281d369b6e.webp

Here is the view from inside a module:

https://sh.itjust.works/pictrs/image/895cdff4-49ad-4cc3-83b5-ba8c8ae6ea3e.webp

Here is the view from a function page:

https://sh.itjust.works/pictrs/image/48258d4c-13fc-4d3f-a44a-1a08f2856aaf.webp

This is also true for platform support. Take this extension trait from std:

https://sh.itjust.works/pictrs/image/8e8c6506-918c-4945-be31-08e97e05c7c8.webp

Now, it’s true that one could be navigating to method docs in the middle of a long doc page, where those indicators at the top may be missed. But that’s a UI issue. And it could be argued that repeating those indicators over and over would introduce too much clutter.

RunAwayFrog,

So, this is being worked on. But for now, that crate needs this line in lib.rs


<span style="color:#323232;">#![cfg_attr(docsrs, feature(doc_auto_cfg))]
</span>

And this line in Cargo.toml’s [package.metadata.docs.rs] section:


<span style="color:#323232;">rustdoc-args = ["--cfg", "docsrs"]
</span>

With these changes, feature gating will be displayed in the docs.

To replicate this locally:


<span style="color:#323232;">RUSTDOCFLAGS='--cfg docsrs' cargo doc --features=nightly,defmt,pender-callback,arch-cortex-m,executor-thread,executor-interrupt
</span>
RunAwayFrog,

are there any hurdles or other good reasons to not just adding this to every create?

I’m no expert. But my guess would be that many crate authors may simply not be aware of this feature. It wasn’t always there, and it’s still unstable. You would have to reach the “Unstable features” page of the rustdoc book to know about it.

Or maybe some know about it, but don’t want to use an unstable feature, or are just waiting for it to possibly automatically work without any modifications.

Of course, I would assume none of this applies to the embassy devs. That Cargo.toml file has a flavors field, which is something I’ve never seen before 😉 So, I’m assuming they are way more knowledgable (and up-to-date) about the Rust ecosystem than me.

RunAwayFrog,

–all-features doesn’t work with that particular crate because two of the features conflict with each other. The features list in my command is the one used for docs.rs from the crate’s Cargo.toml.

RunAwayFrog,

Note: the ᐸᐳ characters used below are Canadian Aboriginal syllabics because Lemmy devs haven’t fixed broken input sanitization yet.


A vec and a string are basically the same thing (a series of bytes)

Everything is a series of bytes! I thought you were going to mention that both are fat pointers. But that “series of bytes” description is quite weird.

This makes handling it much easier because you can still iterate over it

This is not a valid consideration/objection, as Options are iterable and you can flatten them:


<span style="color:#323232;">fn main() {
</span><span style="color:#323232;">  let v = vec![1,2,3];
</span><span style="color:#323232;">  for n in Some(&amp;v).into_iter().flatten() {
</span><span style="color:#323232;">    eprintln!("{n}");
</span><span style="color:#323232;">  }
</span><span style="color:#323232;">  for n in None::ᐸ&amp;Vecᐸi32ᐳᐳ.into_iter().flatten() {
</span><span style="color:#323232;">    eprintln!("{n}");
</span><span style="color:#323232;">  }
</span><span style="color:#323232;">}
</span>

This might involve the compiler making an allocation of an empty array but most of them (gcc, ghc) will now what you are doing and optimize the null check on the empty array to a bool check

This paragraph appears to be out of place in the context of a Rust discussion.

RunAwayFrog,

Note: the ᐸᐳ characters used below are Canadian Aboriginal syllabics because Lemmy devs haven’t fixed broken input sanitization yet.


Well, getters are not an official concept in Rust. You can do whatever works best in your case.

Just worth pointing out that a method with a return value of OptionᐸVecᐸStringᐳᐳ wouldn’t be really a getter, as you must be constructing values, or moving ownership, or cloning. None of these actions conceptually belong to a getter.

Also, you should be clear on the what the Option abstraction means. Does it mean the vector is empty? Does it mean the vector does not exist or some sort of null (FFI ore serialization contexts)? And make sure the code does what you expect it to do.

crabnebula, to rust
@crabnebula@fosstodon.org avatar

if you've been following us for a while you know we're passionate about ! 🦀

We've already discussed how you can install Rust, and we talked about basic concepts like variables and types.

Today, let's talk about sequence types.

👇👇👇

Sequence types are types that store an ordered list of some other type.

Today we'll talk about the two main sequence types @rust:

1️⃣ Arrays
2️⃣ Vectors

⬇️

RunAwayFrog,

It might actually be a bug that the thread didn’t end up here as comments

If that’s the case, that’s a good bug in my book.

RunAwayFrog,

I will use the Rust Book first.

Good choice. Follow it with this Little Book of Rust Macros. And don’t verge into the unsafe stuff early, and don’t verge into it later unless it’s really necessary.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • megavids
  • kavyap
  • DreamBathrooms
  • thenastyranch
  • magazineikmin
  • khanakhh
  • InstantRegret
  • Youngstown
  • ngwrru68w68
  • slotface
  • rosin
  • tacticalgear
  • mdbf
  • Durango
  • JUstTest
  • modclub
  • osvaldo12
  • ethstaker
  • cubers
  • normalnudes
  • everett
  • tester
  • GTA5RPClips
  • Leos
  • cisconetworking
  • provamag3
  • anitta
  • lostlight
  • All magazines