[][src]Crate positioned_io_preview

This crate allows you to specify an offset for reads and writes, without changing the current position in a file. This is similar to pread() and pwrite() in C.

The major advantages of this type of I/O are:

  • You don't need to seek before doing a random-access read or write, which is convenient.
  • Reads don't modify the file at all, so don't require mutability.

Preview release!

This is a preview release of positioned-io. All examples assume you are using it as:

extern crate positioned_io_preview as positioned_io;

Examples

Read the fifth 512-byte sector of a file:

use std::fs::File;
use positioned_io::ReadAt;

// note that file does not need to be mut
let file = File::open("tests/pi.txt")?;

// read up to 512 bytes
let mut buf = [0; 512];
let bytes_read = file.read_at(2048, &mut buf)?;

Note: If possible use the RandomAccessFile wrapper. ReadAt directly on File is very slow on Windows.

Write an integer to the middle of a file:

use std::fs::OpenOptions;
use positioned_io::WriteAt;
use byteorder::{ByteOrder, LittleEndian};

// put the integer in a buffer
let mut buf = [0; 4];
LittleEndian::write_u32(&mut buf, 1234);

// write it to the file
let mut file = OpenOptions::new().write(true).open("foo.data")?;
file.write_all_at(1 << 20, &buf)?;

Or, more simply:

use std::fs::OpenOptions;
use byteorder::LittleEndian;
use positioned_io::WriteBytesAtExt;

let mut file = OpenOptions::new().write(true).open("foo.data")?;
file.write_u32_at::<LittleEndian>(1 << 20, 1234)?;

Read from anything else that supports ReadAt, like a byte array:

use byteorder::BigEndian;
use positioned_io::ReadBytesAtExt;

let buf = [0, 5, 254, 212, 0, 3];
let n = buf.as_ref().read_i16_at::<BigEndian>(2)?;
assert_eq!(n, -300);

Structs

ByteIo

Read or write with a given inherent byte-order.

Cursor

Adapts a ReadAt or WriteAt into a Read or Write.

RandomAccessFile

A wrapper for File that provides optimized random access through ReadAt and WriteAt.

SizeCursor

Adapts a ReadAt or WriteAt into a Read or Write, with better seeking.

Slice

A window into another ReadAt or WriteAt.

Traits

ReadAt

Trait for reading bytes at an offset.

ReadBytesAtExt

Extends ReadAt with methods for reading numbers at offsets.

Size

Trait to get the size in bytes of an I/O object.

WriteAt

Trait for writing bytes at an offset.

WriteBytesAtExt

Extends WriteAt with methods for writing numbers at offsets.