Get a list of filenames for a directory in Rust

Am I doing this right?

Homeless People Are Sexy Shirt $21.68

Black Rifle Cuck Company, Conservative Humor Shirt $21.68

Homeless People Are Sexy Shirt $21.68

  1. 2 weeks ago
    Anonymous

    You could have done worse

  2. 2 weeks ago
    Anonymous

    You probably shouldn't turn the file name into a string
    Just return a io::Result<Vec<the type of file_name()>>

    • 2 weeks ago
      Anonymous

      OsString? why? I want to eventually send it over as a response to http request

      • 2 weeks ago
        Anonymous

        what if it's not utf-8 encoded?

        • 2 weeks ago
          Anonymous

          Then I don't think I can send it anyway since most clients don't support other encodings?

          • 2 weeks ago
            Anonymous

            rewrite it in a serious language

      • 2 weeks ago
        Anonymous

        Then I don't think I can send it anyway since most clients don't support other encodings?

        >OsString? why? I want to eventually send it over as a response to http request
        This means that your response will either be serialized, probably using serde, which already supports Path/OsStr/... in its Serialize/Deserialize traits.
        Or you will be passing the path as raw bytes, in which case check out one of these two approaches, the first is often used:
        https://docs.rs/os_str_bytes/latest/os_str_bytes/trait.OsStrBytes.html
        https://docs.rs/bstr/latest/bstr/#file-paths-and-os-strings
        Of course, you can decide a constraint/requirement that file paths must be valid utf8.
        But it would be that, a defined constraint/requirement, not because "I want to eventually send it over as a response to http request".

  3. 2 weeks ago
    Anonymous

    Lol can you even believe rust doesnt have small string optimization
    What a shitty language its std is magnitudes slower than c++s std with all its stupid checks (rust has bounds checking in release mode that cannot be turned off LOL so cucked)

    • 2 weeks ago
      Anonymous

      C++ std has small string optimization?
      I thought you needed another library

      • 2 weeks ago
        Anonymous

        GCC and Clang both have SSO for their std::string implementations.

    • 2 weeks ago
      Anonymous

      >rust has bounds checking in release mode that cannot be turned off LOL so cucked
      moron alert
      get_unchecked(i)

      • 2 weeks ago
        Anonymous

        at this point, why are you even using rust if you're sidestepping the intended design philosophy (memory safety AT ALL COSTS)

        this is a design flaw innate to the language, so they either need to find some way to hard code this shit into the language itself, or to just scrap the shit and admit that while a good effort, it's still a fail

        • 2 weeks ago
          Anonymous

          Rust has more features than just memory safety

          • 2 weeks ago
            Anonymous

            So many other features, but none of them meaningfully unique from any other language that already exists (kind of comes off like it just failed to make the niche)

          • 2 weeks ago
            Anonymous

            >but none of them meaningfully unique from any other language that already exists
            Yes, if you count only compiled languages. I don't think C++ has zero cost iterators yet. And C, Zig, Hare, Odin ... don't make me laugh, they will never have them. Macro system ain't to bad either, I think it is better than Zig's comptime

          • 2 weeks ago
            Anonymous

            c++ does have zero cost abstractions, yeah

          • 2 weeks ago
            Anonymous

            Okay, but iterators and functional style

        • 2 weeks ago
          Anonymous

          >noooo why are you using the feature that lets you do things that I like to say you can't do
          I use rust because it is better for righting fast reliable software than anything else. Other languages with similar performance waste a lot more time debugging. Rust's memory safety works great at reducing debug time. It does not come at all costs, it is available for the places where the compiler is able to guarantee memory safety and gets out of the way for cases where it can't. That's exactly how it should be.

    • 2 weeks ago
      Anonymous

      >What a shitty language its std is magnitudes slower than c++s std with all its stupid checks (rust has bounds checking in release mode that cannot be turned off LOL so cucked)
      That's not how complexity works. Adding O(1) check to get/set does not make it magnitude slower. Also Rust is pretty good at removing them during compilation. For example typical collection iterators won't do any bounds checks.

  4. 2 weeks ago
    Anonymous

    >ok
    >and_then
    It's the valley girl of programming languages

  5. 2 weeks ago
    Anonymous

    So, can anyone who is good in Rust help me with this one?
    pub struct ServerConfig<'a> {
    port: u16,
    dir_path: &'a str
    }

    pub struct Server<'a> {
    conf: ServerConfig<'a>
    }

    impl<'a> Server<'a> {
    pub fn list_dir(&self) -> io::Result<Vec<String>> {
    let result = read_dir(self.conf.dir_path)?;
    let res = result.filter_map(|x| x.ok().and_then(|y| {
    if y.file_type().is_ok_and(|ft| ft.is_file()) {
    return y.file_name().to_str().map(|s| String::from(s));
    }
    return None;
    })).collect();
    Ok(res)
    }

    async fn index(r: Request<&Self>) -> tide::Result {
    Ok(r.state().list_dir()?.join("n").into())
    }

    async fn start(&self) {
    tide::log::start();
    let mut server = tide::with_state(self);
    server.at("/").get(Self::index);
    server.listen(format!("127.0.0.1:{}", self.conf.port)).await.unwrap();
    }
    }

    It says "borrowed data escapes outside of method". All examples from tide that I see use functions and not methods for routes. how can I make it use a method?

    • 2 weeks ago
      Anonymous

      The lifetime errors you see are due to tide requireing the things that you pass to them have 'static lifetime. `static lifetime means that something has the possibility to life to the end of program. You are using Server<'a> and that 'a may not be 'static. Making either ServerConfig own dir_path OR enforcing your impls for Server be defined for `static lifetime as opposed to 'a you have currently, ie
      impl Server<'static> { .. }

      would fix one issue

      The other issue is tide::with_state(..) requireing 'static lifetime too but you're passing &self which, once again has implicit lifetime 'whatever that may not be 'static. How you're going to fix that is up to you, but I guess not passing reference there but an owned object is the simplest option

      >non utf-8 filename
      lmao, filenames aren't encoded, they're just arbitrary strings

      They are, in platform specific way. Storing filenames in a cross platform manner is impossible, read up on the makefile problem https://wiki.mercurial-scm.org/EncodingStrategy#The_.22makefile_problem.22

      • 2 weeks ago
        Anonymous

        >The other issue is tide::with_state(..) requireing 'static lifetime too but you're passing &self which, once again has implicit lifetime 'whatever that may not be 'static. How you're going to fix that is up to you, but I guess not passing reference there but an owned object is the simplest option
        What would I use for an owned object? A Box?

        • 2 weeks ago
          Anonymous

          not referenced one, so for example u8, String, self. In contrast, non-owned (that means borrowed) ones are &u8, &str or &String, &self.
          For your usecase you should pass ServerConfig to tide::with_state() instead of self. You also need Clone, Send and Sync for state for this to work so consider this
          pub struct ServerConfig {
          port: u16,
          dir_path: PathBuf,
          }

          pub struct Server {
          conf: Arc<ServerConfig>,
          }

          impl Server {
          pub fn list_dir(config: &ServerConfig) -> io::Result<Vec<String>> {
          let result = fs::read_dir(&config.dir_path)?;
          let res = result
          .filter_map(|x| {
          x.ok().and_then(|y| {
          if y.file_type().is_ok_and(|ft| ft.is_file()) {
          return y.file_name().to_str().map(|s| String::from(s));
          }
          return None;
          })
          })
          .collect();
          Ok(res)
          }

          async fn index(r: tide::Request<Arc<ServerConfig>>) -> tide::Result {
          Ok(Self::list_dir(r.state())?.join("n").into())
          }

          async fn start(&self) {
          tide::log::start();
          let mut server = tide::with_state(self.conf.clone());
          server.at("/").get(Self::index);
          server
          .listen(format!("127.0.0.1:{}", self.conf.port))
          .await
          .unwrap();
          }
          }

          • 2 weeks ago
            Anonymous

            But won't this be inefficient? Thanks

          • 2 weeks ago
            Anonymous

            Why would it be? It's just a pointer with an atomic counter

      • 2 weeks ago
        Anonymous

        >makefile
        >on windows

      • 2 weeks ago
        Anonymous

        >Storing filenames in a cross platform manner is impossible
        And yet people do it.
        >read up on the makefile problem https://wiki.mercurial-scm.org/EncodingStrategy#The_.22makefile_problem.22
        Was that written by an absolute fricking moron?
        >mercurial
        Oh. Yes, it was written by a brain-damaged idiot. Someone who literally doesn't understand the difference between bytes and characters, or concrete and abstract concepts. I bet they use Python 2 and think they're being REALLY CLEVER.
        Strings are complicated. The interaction of strings with the OS is particularly complicated (but if you only ever use Linux you won't understand why). Making most programmers deal with all of that complexity directly is a mistake; they're not dealing with the awful edge cases that can occur.

    • 2 weeks ago
      Anonymous

      fyi, for handling strings in a cross platform manner there is this great crate https://crates.io/crates/camino

      • 2 weeks ago
        Anonymous

        I don't know man. I only have tide, async_std and git2 dependencies so far and my debug binary is already at 850MB. I don't know how much write cycles my SSD can handle, I hope it is not rewriting the whole 850MB every compile ...

        • 2 weeks ago
          Anonymous

          Good lord wtf?

        • 2 weeks ago
          Anonymous

          >and my debug binary is already at 850MB
          S-surely it does more than just parse filenames right? Right?

          • 2 weeks ago
            Anonymous

            No, it doesn't. But I actually made a mistake. The binary itself is 50MB, but the target folder as a whole is 850MB

  6. 2 weeks ago
    Anonymous

    Depends on what you really need to do but I'd probably handle symlinks and not quietly ignore errors, but I guess that depends on what exactly do you need to do

    pub fn list_dir(path: impl AsRef<Path>) -> io::Result<Vec<String>> {
    fs::read_dir(path)?
    .filter_map(|entry| {
    entry
    .and_then(|entry| {
    let file_type = entry.file_type()?;
    if file_type.is_file() || file_type.is_symlink() {
    entry
    .file_name()
    .into_string()
    .map_err(|err| {
    io::Error::new(
    ErrorKind::InvalidData,
    format!("non utf-8 filename: `{}`", err.to_string_lossy()),
    )
    })
    .map(Some)
    } else {
    Ok(None)
    }
    })
    .transpose()
    })
    .collect()
    }

    • 2 weeks ago
      Anonymous

      >non utf-8 filename
      lmao, filenames aren't encoded, they're just arbitrary strings

  7. 2 weeks ago
    Anonymous

    such an awful, awful syntax lmao

    • 2 weeks ago
      Anonymous

      Honestly, anons should fork it illegally and fix it and call it "Ack".

  8. 2 weeks ago
    Anonymous

    why is dealing with assci characters always trash in every language?
    why can't i just deal with numbers
    100 101 97 116 104 32 116 111 32 97 108 108 32 106 101 119 115

    • 2 weeks ago
      Anonymous

      the real problem is c-style strings

  9. 2 weeks ago
    Anonymous

    why the frick would anyone ever used this language

    • 2 weeks ago
      Anonymous

      the biggest issue is that it doesn't have a stable ABI or an equivalent of .a or .o files, meaning compilation will be slow and targets will be large. also plugin system completely out of the question. Outside of that it is a neat little language if you only need what is in the std and nothing else. There is not much there though, not even argument parsing ... but I guess for kernels it works just fine

      • 2 weeks ago
        Anonymous

        >meaning compilation will be slow and targets will be large.
        You don't need stable ABI for incremental compilation. It only matters when you are dealing with changing compiler version.

        >an equivalent of .a or .o files
        It literally does. Use --emit obj flag.

        >Outside of that it is a neat little language if you only need what is in the std and nothing else.
        That's couldn't be further from truth. Rust's stdlib is purposefully minimal, so you can choose from many different external crates in modular fashion depending on your specific needs.

        >There is not much there though, not even argument parsing
        Putting argument parsing into stdlib is moronic. All sorts of programs need different argument parsing. Adding one battery-included standard version will never cover everyone's use-cases and will surely come of bloated for simple use-cases.

        • 2 weeks ago
          Anonymous

          External libraries are the devil and source of all evil. The more there is in the std (which is maintained by professionals, mathematicians and very smart people as opposed to randos who get psyoped easily by cia agent jia tay), the better

    • 2 weeks ago
      Anonymous

      Because you spend much less time debugging than any other language that gets similar performance. The memory safety features work wonders in that regard. The borrow checker stops being an issue once you've written one or two programs in it.

      • 2 weeks ago
        Anonymous

        Sunk cost, you say?

        • 2 weeks ago
          Anonymous

          Learning curves aren't a problem for competent people. Also it looks like you missed this part
          >Because you spend much less time debugging than any other language that gets similar performance

      • 2 weeks ago
        Anonymous

        Until you try to debug someone else's logical error and it's unclear what is going on due to syntax. It's fun to write but holy frick do I hate reading it

        >inb4 brainlet

  10. 2 weeks ago
    Anonymous

    uglier than perl

    • 2 weeks ago
      Anonymous

      okay, it is not THAT ugly

      • 2 weeks ago
        Anonymous

        yes it is
        opendir(my $dh, $some_dir) || die "Can't open $some_dir: $!";
        while (readdir $dh) {
        print "$some_dir/$_n";
        }
        closedir $dh;

        • 2 weeks ago
          Anonymous

          Now do actual perl code, not cherrypick

          • 2 weeks ago
            Anonymous

            brother, the only reason it looks convoluted is because it uses regex
            filtered by regex perhaps?

          • 2 weeks ago
            Anonymous

            there's like 1% perl and 99% regex, but let's see how you do that in rust

          • 2 weeks ago
            Anonymous

            Looks like it's doing something with XML or HTML. I'd use a real XML or HTML parser instead of Regex shit, probably something with a nice streaming API.

  11. 2 weeks ago
    Anonymous

    do rust trannies really?

  12. 2 weeks ago
    Anonymous

    This thing will never, ever catch on kek. Just look at it. It's absolutely disgusting. The Rust trannies have completely lost their minds designing the most disgusting programming language. It defies all logic, I thought one of the main motivations was "C++ is ugly!" and yet they make me find C++ quite pleasant to look at in comparison with this piece of shit.

    • 2 weeks ago
      Anonymous

      Oh and every single time a Rust troony will show up with the usual cope:
      >OH WELL THAT GUY'S AN IDIOT WHO DOESN'T KNOW HOW TO WRITE "GOOD" RUST CODE
      Every fricking time. With the frequency you see this shit what does that say about the design of the language that seemingly everyone sucks shit at writing Rust code? The lack of self-awareness never stops being funny.

  13. 2 weeks ago
    Anonymous

    no-coders are out in force with their usual generic no-coder drivel. lamo.
    UGLY
    troony
    MAKES X LOOK GOOD
    SLOWER THAN Y
    STUPID
    BLA BLA
    It's a bummer. I'm always on the look out for some original rust hate.

    • 2 weeks ago
      Anonymous

      ynbaw

  14. 2 weeks ago
    Anonymous

    Thanks, but I'm sticking with Odin. At least gingerbill's not a massive homosexual like andrew kelly or jonblowjob.

  15. 2 weeks ago
    Anonymous

    Use the fricking glob crate:

    cargo add glob

    main.rs
    use glob::glob;

    fn main() {
    for f in glob("./*").unwrap() {
    println!("f: {:?}", f);
    }
    }

Your email address will not be published. Required fields are marked *