HackerTrans
TopNewTrendsCommentsPastAskShowJobs

throwaway8948

no profile record

comments

throwaway8948
·4 anni fa·discuss
>Can you point out an example on reading a bunch of structs from a file? Without std? Now I'm really curious.

Not really, but here is really simple example:

  use std::fs::File;
  use std::io::Read;
  
  #[derive(Debug)]
  struct Point {
      x: i32,
      y: i32,
  }
  
  fn bytes2point(buf: [u8; 8]) -> Point {
      Point {
          // Slices to arrays is a bit unwieldy...
          x: i32::from_le_bytes(buf[..4].try_into().unwrap()),
          y: i32::from_le_bytes(buf[4..].try_into().unwrap()),
      }
  }
  
  fn main() {
      let mut buf: [u8; 8] = [0; 8];
      let mut file: File = File::open("data.txt").unwrap();
      Read::read(&mut file, &mut buf).unwrap();
      let point: Point = bytes2point(buf);
      println!("{:?}", point);
  }
It doesn't do any extra i/o compared to C. Std is only used for filesystem access and printing. It does require extra buffer.
throwaway8948
·4 anni fa·discuss
>It should be simple, right?

Well, no. If you want to have memory safe subset, you absolutely cannot initialize structs with random bag of bytes in general case. C let's you cut corners here, but in Rust you need to implement (de)serializing logic (no need for unsafe).

>Then I learned that structs are not laid out as declared (OMG!), etc. >It should be simple! I tried to create a variadic function and you can guess how it went.

This is only surprising if you have this weird assumption that things should work like they do in C + some extra.