BurntSushi / byteorder

Rust library for reading/writing numbers in big-endian and little-endian.
The Unlicense
981 stars 143 forks source link

Endianness-managing Read/Write wrapper? #187

Closed masklinn closed 2 years ago

masklinn commented 2 years ago

This is more of a feature question, to know if it'd be considered interesting / in-scope.

Currently, both the read/write extensions and ByteOrder essentially require specifying the requested byteorder on a per-operation basis (as the subject / instance for ByteOrder, and as type parameter for the Read/WriteBytesExt extensions).

In my experience though byte order rarely changes between reads or writes, generally the entire stream is in one endianness or the other. So maybe the endianness types could be used to create a stream wrapper, which would use unparameterised methods? e.g.

let mut wtr = vec![];
wtr.write_u16::<LittleEndian>(517).unwrap();
wtr.write_u16::<LittleEndian>(768).unwrap();
assert_eq!(wtr, vec![5, 2, 0, 3]);

or

let mut wtr = vec![];
LittleEndian.write_u16(&mut wtr, 517).unwrap();
LittleEndian.write_u16(&mut wtr, 768).unwrap();
assert_eq!(wtr, vec![5, 2, 0, 3]);

could become the somewhat better-flowing

let mut wtr = LittleEndian::wrap(vec![]);
wtr.write_u16(517).unwrap();
wtr.write_u16(768).unwrap();
assert_eq!(wtr.into_inner(), vec![5, 2, 0, 3]);

The gain is limited for such a small amounts of writes, but for larger spans with possibly dozens of reads/writes the readability would be pretty significant.

Not quite sure how that would integrate with #95 though.

BurntSushi commented 2 years ago

See also: #27, #41, #59, #67, #124, #143 and #145.

In general, I've been pretty resistant to expanding the API much beyond what's already here. I'm not necessarily opposed, but:

  1. I would want to see the API proposal.
  2. It shouldn't carry with it performance footguns.
  3. It must be easy to clearly explain its use case in a way that differentiates it from existing APIs.

There might be other requirements, but that's what is top of mind at the moment.

masklinn commented 2 years ago

Ah apparently I missed #67 of which this is in fact a duplicate, sorry about that (though I do agree with the original user / reporter that it's a different angle / axis than #27, and more of a competing change in direction).

My thinking was rather similar to the other proposal, a convenience layer sitting atop the existing system, would perform the endianness adaption without having to specify it every time.