Skip to content

Instantly share code, notes, and snippets.

@jam1garner
Created January 12, 2022 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jam1garner/966a9a0f3ba765fc92d8d58c340aa5da to your computer and use it in GitHub Desktop.
Save jam1garner/966a9a0f3ba765fc92d8d58c340aa5da to your computer and use it in GitHub Desktop.
use binrw::binrw;
use binrw::io::{Cursor, Seek, SeekFrom};
use binrw::{BinReaderExt, BinWriterExt};
#[binrw]
#[derive(Debug)]
struct Vec3 {
x: f32,
y: f32,
z: f32,
}
#[binrw]
#[derive(Debug)]
struct Mesh {
#[bw(calc = (vertices.len() - 1) as u32)]
vertex_count: u32,
#[br(count = vertex_count + 1)]
vertices: Vec<Vec3>,
}
fn main() {
let mesh = Mesh {
vertices: vec![
Vec3 {
x: 1.0,
y: 2.0,
z: 3.0,
},
Vec3 {
x: 11.0,
y: 12.0,
z: 13.0,
},
Vec3 {
x: 21.0,
y: 22.0,
z: 23.0,
},
],
};
let mut writer = Cursor::new(Vec::new());
writer.write_le(&mesh).unwrap();
let mut reader = writer;
reader.seek(SeekFrom::Start(0)).unwrap();
let _: Mesh = dbg!(reader.read_le().unwrap());
}
@rain2307
Copy link

rain2307 commented Dec 2, 2023

why it need -1 and +1 ?

@jam1garner
Copy link
Author

@rain2307 merely a demonstration that you can do arbitrary computation in those positions. It effectively translates to "the length as written to disk is one less than the actual length". Not something a normal format would do, but arbitrary computation is useful for implementing arbitrarily complex file formats

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment