#read-write #write-file #write #read #read-file #file #binary

fast_io

用于读取和写入 &str 以及实现 copy 特性的类型的文件库

6 个稳定版本

使用旧的 Rust 2015

1.2.2 2017年9月8日
1.2.1 2017年8月23日
1.1.1 2017年8月12日
1.0.0 2017年8月12日

#2796解析器实现


neural_network 中使用

Apache-2.0

12KB
186

fast_io

为 Rust 编程语言提供简单且快速的文件 I/O

该库使您能够读取和写入 &str 以及实现 copy 特性的类型。

如何使用

将其添加到您的依赖项中(Cargo.toml)

[dependecies]
fast_io = 1.2

在您的代码中包含并使用它(src/main.rs)

extern crate fast_io;
use fast_io::prelude::*;
use std::fs::{File, remove_file};

fn main() {
    let file_path = "some_file.txt";

    // Content to read and write to the file
    let a: i32 = -42;
    let b: f64 = 42.42;
    let c: u16 = 42;
    let d: Point = Point { x: 42.0, y: 42.0 };
    let e: Neuron = Neuron { bias: 17.0, prev_delta: 18.42, output: 19.0};
    let g: Vec<Neuron> = vec![e.clone(); 18];
    let h: &str = "Hello World!";
    let i: Vec<Point> = vec![Point { x: 42.0, y: 42.0}; 42];
    let j: Option<Neuron> = Some(Neuron {bias: 39.39, prev_delta: 27.27, output: 42.42});
    let k: Option<Neuron> = None;

    // Create the file
    let mut f = File::create(file_path).unwrap();

    // Write to the file
    f.write_copy(&a).unwrap();
    f.write_copy(&b).unwrap();
    f.write_copy(&c).unwrap();
    f.write_copy(&d).unwrap();
    e.save(&mut f).unwrap();
    g.save(&mut f).unwrap();
    f.write_str(h).unwrap();
    f.write_slice(&i).unwrap();
    j.save(&mut f).unwrap();
    k.save(&mut f).unwrap();

    // re-open the file for reading
    let mut f = File::open(file_path).unwrap();

    // Read the file content
    let a2: i32 = f.read_copy().unwrap();
    let b2: f64 = f.read_copy().unwrap();
    let c2: u16 = f.read_copy().unwrap();
    let d2: Point = f.read_copy().unwrap();
    let e2 = Neuron::load(&mut f).unwrap();
    let g2 = Vec::<Neuron>::load(&mut f).unwrap();
    let h2 = &f.read_str().unwrap();
    let i2: Vec<Point> = f.read_slice().unwrap();
    let j2: Option<Neuron> = Option::<Neuron>::load(&mut f).unwrap();
    let k2: Option<Neuron> = Option::<Neuron>::load(&mut f).unwrap();

    assert_eq!(a, a2);
    assert_eq!(b, b2);
    assert_eq!(c, c2);
    assert_eq!(d, d2);
    assert_eq!(e, e2);
    assert_eq!(g, g2);
    assert_eq!(h, h2);
    assert_eq!(i, i2);
    assert_eq!(j, j2);
    assert_eq!(k, k2);

    remove_file(file_path).unwrap();
}

#[derive(Debug, Copy, Clone, PartialEq)]
struct Point {
    x: f64,
    y: f64
}

#[derive(Debug, Clone)]
struct Neuron {
    bias: f64,
    prev_delta: f64,
    output: f64
}

impl PartialEq for Neuron {
    fn eq(&self, rhs: &Self) -> bool {
        self.bias == rhs.bias
    }
}

impl CustomIO for Neuron {
    fn save<T: CopyIO>(&self, f: &mut T) -> Result<()> {
        f.write_copy(&self.bias)
    }
    fn load<T: CopyIO>(f: &mut T) -> Result<Self> {
        Ok(Neuron {
            bias: f.read_copy()?,
            prev_delta: 0.0,
            output: 0.0
        })
    }
}

无运行时依赖