Struct fixed_width::Reader

source ·
pub struct Reader<R> {
    pub record_width: usize,
    pub linebreak: LineBreak,
    /* private fields */
}
Expand description

A fixed width data reader. It parses fixed width data and provides the data via iterators.

§Example

Parsing fixed width data into a struct;

use serde_derive::Deserialize;
use serde;
use fixed_width::{FieldSet, FixedWidth, Reader};
use serde::Deserialize;
use std::result;

#[derive(Deserialize)]
struct Foo {
    name: String,
    age: usize,
}

// can be derived using the `fixed_width_derive` crate.
impl FixedWidth for Foo {
    fn fields() -> FieldSet {
        FieldSet::Seq(vec![
            FieldSet::new_field(0..6),
            FieldSet::new_field(6..10),
        ])
    }
}

let data = "foobar1234foobaz6789";
let mut reader = Reader::from_string(data).width(10);

for row in reader.byte_reader().filter_map(result::Result::ok) {
    let record: Foo = fixed_width::from_bytes(&row).unwrap();

    println!("{}", record.name);
    println!("{}", record.age);
}

§Example

Parsing fixed width data into a HashMap<String, String>:

use serde;
use fixed_width::{FieldSet, FixedWidth, Deserializer, Reader};
use std::collections::HashMap;
use serde::Deserialize;

 let data = "foobar1234foobaz6789";
 let mut reader = Reader::from_string(data).width(10);
 let fields = FieldSet::Seq(vec![
     FieldSet::new_field(0..6).name("name"),
     FieldSet::new_field(6..10).name("age"),
 ]);

 for row in reader.byte_reader() {
     let bytes = row.unwrap();
     let mut de = Deserializer::new(&bytes, fields.clone());
     let record: HashMap<String, String> = HashMap::deserialize(&mut de).unwrap();

     println!("{}", record.get("name").unwrap());
     println!("{}", record.get("age").unwrap());
 }

§Example

Parsing fixed width data into Vec<String>:

use fixed_width::Reader;

let data = "foobar1234foobaz6789";

let mut reader = Reader::from_string(data).width(10);

for row in reader.string_reader() {
    println!("{:?}", row);
}

§Example

Parsing fixed width data into Vec<Vec<u8>>:

use fixed_width::Reader;

let data = "foobar1234foobaz6789";

let mut reader = Reader::from_string(data).width(10);

for row in reader.byte_reader() {
    println!("{:?}", row);
}

§Example

Read each line without copying:

use fixed_width::Reader;

let data = "foobar1234foobaz6789";

let mut reader = Reader::from_string(data).width(10);

if let Some(Ok(row)) = reader.next_record() {
    assert_eq!(row, b"foobar1234");
}

if let Some(Ok(row)) = reader.next_record() {
    assert_eq!(row, b"foobaz6789");
}

Fields§

§record_width: usize

The width in bytes of the record. Required in order to parse.

§linebreak: LineBreak

The line break that occurs between each record. Defaults to LineBreak::None

Implementations§

source§

impl<R> Reader<R>
where R: Read,

source

pub fn from_reader(rdr: R) -> Self

Creates a new reader from any type that implements io::Read.

source

pub fn string_reader(&mut self) -> StringReader<'_, R>

Reads each record of the data as a String. If the data is not valid UTF-8, then you should use byte_reader instead.

§Example
use fixed_width::Reader;

let mut reader = Reader::from_string("abcd1234").width(8);

for record in reader.string_reader() {
    assert_eq!(record.unwrap(), "abcd1234")
}
source

pub fn byte_reader(&mut self) -> ByteReader<'_, R>

Reads each record of the data as a Vec<u8>.

§Example
use fixed_width::Reader;

let mut reader = Reader::from_bytes("abcd1234".as_bytes()).width(8);

for record in reader.byte_reader() {
    assert_eq!(record.unwrap(), b"abcd1234".to_vec())
}
source

pub fn next_record(&mut self) -> Option<Result<&[u8]>>

Reads the next record as a byte slice

§Example
use fixed_width::Reader;

let data = "foobar1234foobaz6789";

let mut reader = Reader::from_string(data).width(10);

if let Some(Ok(row)) = reader.next_record() {
    assert_eq!(row, b"foobar1234");
}

if let Some(Ok(row)) = reader.next_record() {
    assert_eq!(row, b"foobaz6789");
}
source

pub fn width(self, width: usize) -> Self

Defines the width of each record in the file. It is required to set prior to reading since fixed width data is not self describing. Consumers must tell the reader how many bytes to read for each field. Do not include linebreaks in the width, you should only define a width to be the number of bytes in the record data itself.

§Example
use fixed_width::Reader;
use std::result;

let data = "foobar";
let mut reader = Reader::from_string(data).width(3);
let records: Vec<String> = reader.string_reader().filter_map(result::Result::ok).collect();

assert_eq!(records, vec!["foo".to_string(), "bar".to_string()]);
§Example

With a LineBreak specified:

use fixed_width::{LineBreak, Reader};
use std::result;

let data = "foo\nbar";
let mut reader = Reader::from_string(data).width(3).linebreak(LineBreak::Newline);
let records: Vec<String> = reader.string_reader().filter_map(result::Result::ok).collect();

assert_eq!(records, vec!["foo".to_string(), "bar".to_string()]);
source

pub fn linebreak(self, linebreak: LineBreak) -> Self

Defines the linebreak to use while reading data. Defaults to LineBreak::None, which means there are no bytes between records.

§Example
use fixed_width::{LineBreak, Reader};
use std::result;

let data = "foo\r\nbar";
let mut reader = Reader::from_string(data).width(3).linebreak(LineBreak::CRLF);
let records: Vec<String> = reader.string_reader().filter_map(result::Result::ok).collect();

assert_eq!(records, vec!["foo".to_string(), "bar".to_string()]);
source§

impl Reader<File>

source

pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self>

Creates a new reader from a filepath. Will return an io::Error if there are any issues opening the file.

source§

impl Reader<Cursor<Vec<u8>>>

source

pub fn from_bytes<T>(bytes: T) -> Self
where T: Into<Vec<u8>>,

Creates a new reader from a series of bytes.

source

pub fn from_string<T>(s: T) -> Self
where T: Into<String>,

Creates a new reader from a String or &str.

Trait Implementations§

source§

impl<R> Read for Reader<R>
where R: Read,

source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize>

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
1.36.0 · source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
1.0.0 · source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Read all bytes until EOF in this source, placing them into buf. Read more
1.0.0 · source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Read all bytes until EOF in this source, appending them to buf. Read more
1.6.0 · source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Read the exact number of bytes required to fill buf. Read more
source§

fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Read the exact number of bytes required to fill cursor. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adaptor for this instance of Read. Read more
1.0.0 · source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more

Auto Trait Implementations§

§

impl<R> Freeze for Reader<R>
where R: Freeze,

§

impl<R> RefUnwindSafe for Reader<R>
where R: RefUnwindSafe,

§

impl<R> Send for Reader<R>
where R: Send,

§

impl<R> Sync for Reader<R>
where R: Sync,

§

impl<R> Unpin for Reader<R>
where R: Unpin,

§

impl<R> UnwindSafe for Reader<R>
where R: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.