tmontaigu / dbase-rs

Rust library to read & write dBase files.
MIT License
29 stars 30 forks source link

Using structs as possible record types #5

Closed tmontaigu closed 4 years ago

tmontaigu commented 5 years ago

It may be nice to be able to use Custom struct as dBase record type by defining a Trait in the crate, so that using the API gets nicer and maybe faster since when using structs there would be no use of hashing functions from the HashMap.


struct AlbumRecord {
    name: String,
    artist: String,
    price: f64,
    released: dbase::Date,
}

impl dbase::DbaseRecord for AlbumRecord {
  // some fns to be determined
}

fn main() {
 let records = vec![
        AlbumRecord { ... },
        AlbumRecord { ... },
    ];

    let writer = dbase::Writer::new(Cursor::new(Vec::<u8>::new()));
    let mut cursor = writer.write_records(records).unwrap();
    cursor.seek(SeekFrom::Start(0)).unwrap();

    let reader = dbase::Reader::new(cursor).unwrap();
    let read_records = reader.read_as::<AlbumRecord>().unwrap();
}

And maybe even more nicer would be a derive implementation and / or a macro_rules

#[derive(DBaseRecord)]
struct AlbumRecord {
    name: String,
    artist: String,
   #[FieldType::Numeric]
    price: f64,
    released: dbase::Date,
}

or

dbase_record! {
    struct AlbumRecord {
        name: String,
        artist: String,
        price: f64,
        released: dbase::Date,
    }
}