r/rust•
CrystalDev

Why `std` does not contain functionality for reading primitive types?

Hello everyone,

I have been trying to learn Rust for a couple of months now and I am finally coming to understand more and more of the language (still think it's great). However, one thing that I just fail to understand is why the Rust std does not contain functionality for reading primitive types. Of course, we have the Read trait which enables us to read bytes (much like Java's InputStream but then only for reading bytes). But why is there no functionality to read u32 or i64 from Read? I know that we have the byteorder crate which extends the Read trait to do such operations, however, reading primitive types feels like such a basic operation that one would suspect such functionality to be contained inside std. But maybe this assumption of mine just does not hold :)

I hope someone can clarify this for me :)

Posted Apr 9, 2019, 12:32 PM UTC

44
CAD1997•

A big issue for read_u64 or read::<u64> is that there are four ways to interpret them, which are all wanted at some point:

  • read four bytes and interpret them as bigendian bytes of a u64
  • read four bytes and interpret them as littleendian bytes of a u64
  • read for bytes and interpret them as platformendian bytes of a u64
  • read an undetermined amount of bytes and interpret them as ASCII characters and parse a u64 from textual representation

So the deliberately minimal and attempted unopinionated standard library doesn't offer this functionality, because then it'd have to bless one of the four options. People coming from higher level languages will probably expect the fourth, from lower level languages the third (but also often treat the third as the second).

Because Cargo makes pulling in library crates so easy, a sparse standard library doesn't matter as much. You can have properly versioned libraries to handle these situations which require these kinds of issues.

In cases when you want to parse text rather than interpret bytes, you're almost always better off reading and splitting strings first, as that makes the intent and effect a lot clearer than, say, Java's Scanner where if you scan for numbers you have no control over how whitespace is/isn't present.

In cases when you want to interpret bytes, the endianness really matters, because even if "all practical systems are littleendian in practice", many protocols aren't. You have to be explicit about what you want if you want consistent behavior. That's what the byteorder crate offers.

26
oberien•

Not to forget middle-endian, which isn't used widely, but required for completeness sake.

17
CrystalDevOP•

Thanks for your answer! Makes it clear to me :)

3
K900_•

Because std is designed to be pretty minimal. You have a method to read a bunch of bytes, and then you're free to interpret them however you like. Endianness conversion is not exactly simple either, especially if you want to do it in a way that's both portable and fast.

7