Enum std::io::SeekFrom

The enum std::io::SeekFrom is defined as

pub enum SeekFrom {
    Start(u64),
    End(i64),
    Current(i64),
}

I just curious to know why Start alone should contain u64 type other as i64 .
Does it mean that I can read the bytes in reverse if I have negative value for End ?.

Thanks,
S.Gopinath

With enough work, yes! You can seek in the negative direction, but bytes will still always be read "forward", so you'll need to seek backwards again after every time you read a byte. If you alternate calls to Read::read_exact() with a 1-byte buffer and Seek::seek(SeekFrom::Current(-2), it'll just read backwards, albeit inefficiently. It'd be better to read chunks of bytes, and go backwards once per chunk.

thanks for clarification.

The Start variant has u64 because seeking to a negative position from the start of the file would be nonsensical. It is commonly possible to seek in either direction from the Current position. I don't know of any valid use case for seeking forward from the End position, but then again Rust does not have an int flavor that only provides negative values.

2 Likes

https://stackoverflow.com/a/4931593

This link is about Delphi, but it says that it is reasonable to allow seeking beyond EOF (and allow programs to write that position).
I don't know whether std::fs::File and other std readers/writers allows seeking beyond EOF or not, but allowing it could be useful or efficient in some situations (e.g. writing sparse file).

1 Like

nice!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.