1use uuid::Uuid;
7
8pub fn write_le_u64(buf: &mut [u8], off: usize, val: u64) {
10 buf[off..off + 8].copy_from_slice(&val.to_le_bytes());
11}
12
13pub fn write_le_u32(buf: &mut [u8], off: usize, val: u32) {
15 buf[off..off + 4].copy_from_slice(&val.to_le_bytes());
16}
17
18pub fn write_le_u16(buf: &mut [u8], off: usize, val: u16) {
20 buf[off..off + 2].copy_from_slice(&val.to_le_bytes());
21}
22
23pub fn write_uuid(buf: &mut [u8], off: usize, uuid: &Uuid) {
25 buf[off..off + 16].copy_from_slice(uuid.as_bytes());
26}
27
28pub fn raw_crc32c(seed: u32, data: &[u8]) -> u32 {
34 !crc32c::crc32c_append(!seed, data)
38}
39
40pub fn csum_tree_block(buf: &mut [u8]) {
47 assert!(buf.len() > 32, "buffer too small for tree block checksum");
48 let csum = raw_crc32c(0, &buf[32..]);
49 buf[0..4].copy_from_slice(&csum.to_le_bytes());
50 buf[4..32].fill(0);
51}
52
53#[cfg(test)]
54mod tests {
55 use super::*;
56
57 #[test]
58 fn test_write_le_u64() {
59 let mut buf = [0u8; 8];
60 write_le_u64(&mut buf, 0, 0x0807060504030201);
61 assert_eq!(buf, [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]);
62 }
63
64 #[test]
65 fn test_write_le_u32() {
66 let mut buf = [0u8; 4];
67 write_le_u32(&mut buf, 0, 0x04030201);
68 assert_eq!(buf, [0x01, 0x02, 0x03, 0x04]);
69 }
70
71 #[test]
72 fn test_write_le_u16() {
73 let mut buf = [0u8; 2];
74 write_le_u16(&mut buf, 0, 0x0201);
75 assert_eq!(buf, [0x01, 0x02]);
76 }
77
78 #[test]
79 fn test_write_uuid() {
80 let uuid =
81 Uuid::parse_str("deadbeef-dead-beef-dead-beefdeadbeef").unwrap();
82 let mut buf = [0u8; 16];
83 write_uuid(&mut buf, 0, &uuid);
84 assert_eq!(buf, *uuid.as_bytes());
85 }
86
87 #[test]
88 fn test_roundtrip_u64() {
89 let mut buf = [0u8; 16];
90 write_le_u64(&mut buf, 4, 0xDEADBEEF_CAFEBABE);
91 assert_eq!(
92 u64::from_le_bytes(buf[4..12].try_into().unwrap()),
93 0xDEADBEEF_CAFEBABE
94 );
95 }
96
97 #[test]
98 fn test_roundtrip_uuid() {
99 let uuid =
100 Uuid::parse_str("01234567-89ab-cdef-0123-456789abcdef").unwrap();
101 let mut buf = [0u8; 16];
102 write_uuid(&mut buf, 0, &uuid);
103 assert_eq!(Uuid::from_bytes(buf), uuid);
104 }
105}