oxyroot 0.1.25

Another attempt to make library reading and writing of `.root` binary files which are commonly used in particle physics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
use crate::rdict::StreamerInfo;
use crate::root;
pub use error::Error;
pub use error::Result;
use rbuffer::RBuffer;
use std::any::{type_name, TypeId};
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::hash::Hash;

pub mod consts;
mod error;
pub mod rbuffer;
pub mod wbuffer;

pub(crate) use crate::rbytes::wbuffer::WBuffer;
use paste::paste;

/// Header represents a type header in a ROOT buffer.
///
#[derive(Default, Debug)]
pub(crate) struct Header {
    /// name of the type being guarded by this header.
    _name: String,
    /// version of the type being guarded by this header.
    pub(crate) vers: i16,
    /// position of the type in the ROOT buffer.
    pos: i64,
    /// length of the value in the ROOT buffer.
    len: u32,
}

/// RVersioner is the interface implemented by an object that
/// can tell the ROOT system what is its current version.
pub(crate) trait RVersioner {
    fn rversion(&self) -> i16;
}

/// STREAMER_ELEMENT describes a ROOT STREAMER_ELEMENT
pub(crate) trait StreamerElement: root::traits::Named {}

/// StreamerInfoContext defines the protocol to retrieve a ROOT STREAMER_INFO
/// metadata type by name.
pub trait StreamerInfoContext {
    /// STREAMER_INFO returns the named STREAMER_INFO.
    /// If version is negative, the latest version should be returned.
    fn streamer_info(&self, name: &str, version: i32) -> Option<&StreamerInfo>;
}

/// Trait that permits reading a type from an ROOT file.
///
/// Examples of types that implement this:
///
/// * Primitive integers, floats, etc
/// * Owned byte containers (`Vec<T>`, `HashMap<K,V>`, HashSet<K> )
pub trait Unmarshaler {
    fn unmarshal(&mut self, r: &mut RBuffer) -> Result<()>;

    /// Returns the kind of the type as C++ typename. Used to check if the type is supported.
    fn class_name() -> Option<Vec<String>>
    where
        Self: Sized,
    {
        None
    }
}
#[derive(Debug)]
pub enum MarshallerKindStd {
    Vector { class_name: String },
}

#[derive(Debug)]
pub enum MarshallerKind {
    Primitive,
    Array { shape: Vec<i32>, tys: String },
    Slice { std: MarshallerKindStd },
    String,
    Struct,
}

/// Trait that permits writing a type to an ROOT file.
///
/// Examples of types that implement this:
///
/// * Primitive integers, floats, etc
pub trait Marshaler {
    fn marshal(&self, w: &mut WBuffer) -> Result<i64>;
    fn kind() -> MarshallerKind
    where
        Self: Sized,
    {
        unimplemented!("Marshaler.rust_type_to_kind for {}", type_name::<Self>())
    }

    fn root_code() -> String
    where
        Self: Sized,
    {
        unimplemented!("Marshaler.root_code for {}", type_name::<Self>())
    }

    fn class_name() -> String
    where
        Self: Sized,
    {
        unimplemented!("Marshaler.class_name for {}", type_name::<Self>())
    }
}

/// Used by WBranch to marshal objects into a ROOT buffer.
impl Marshaler for Box<dyn Marshaler> {
    fn marshal(&self, w: &mut WBuffer) -> Result<i64> {
        self.as_ref().marshal(w)
    }
}

macro_rules! impl_marshalers_primitive {
    ($ftype:ty, $buffer_read_fn:ident, $buffer_write_fn:ident) => {
        impl Unmarshaler for $ftype {
            fn unmarshal(&mut self, r: &mut RBuffer) -> Result<()> {
                *self = r.$buffer_read_fn()?;
                Ok(())
            }

            fn class_name() -> Option<Vec<String>>
            where
                Self: Sized,
            {
                let tys = type_name::<Self>();
                let ret = match tys {
                    "i32" => "int32_t",
                    "u32" => "uint32_t",
                    "i64" => "int64_t",
                    "u64" => "uint64_t",
                    "i16" => "int16_t",
                    "u16" => "uint16_t",
                    "i8" => "int8_t",
                    "u8" => "uint8_t",
                    "f32" => "float",
                    "f64" => "double",
                    "bool" => "bool",
                    _ => unimplemented!("Unmarshaler.class_name for {}", type_name::<Self>()),
                };
                Some(vec![ret.to_string()])
            }
        }

        impl Marshaler for $ftype {
            fn marshal(&self, w: &mut WBuffer) -> Result<i64> {
                let beg = w.pos();
                w.$buffer_write_fn(*self)?;
                Ok(w.pos() - beg)
            }

            fn kind() -> MarshallerKind
            where
                Self: Sized,
            {
                MarshallerKind::Primitive
            }

            fn class_name() -> String
            where
                Self: Sized,
            {
                let tys = type_name::<Self>();
                let ret = match tys {
                    "i32" => "int32_t",
                    "u32" => "uint32_t",
                    "i64" => "int64_t",
                    "u64" => "uint64_t",
                    "i16" => "int16_t",
                    "u16" => "uint16_t",
                    "i8" => "int8_t",
                    "u8" => "uint8_t",
                    "f32" => "float",
                    "f64" => "double",

                    _ => unimplemented!("Marshaler.class_name for {}", type_name::<Self>()),
                };
                ret.to_string()
            }

            fn root_code() -> String {
                // TODO: use a macro to generate this
                let ty = TypeId::of::<Self>();
                if ty == TypeId::of::<i8>() {
                    return "B".to_string();
                }

                if ty == TypeId::of::<u8>() {
                    return "b".to_string();
                }

                if ty == TypeId::of::<i16>() {
                    return "S".to_string();
                }

                if ty == TypeId::of::<u16>() {
                    return "s".to_string();
                }

                if ty == TypeId::of::<i32>() {
                    return "I".to_string();
                }

                if ty == TypeId::of::<u32>() {
                    return "i".to_string();
                }

                if ty == TypeId::of::<i64>() {
                    return "L".to_string();
                }

                if ty == TypeId::of::<u64>() {
                    return "l".to_string();
                }

                if ty == TypeId::of::<f32>() {
                    return "F".to_string();
                }

                if ty == TypeId::of::<f64>() {
                    return "D".to_string();
                }

                if ty == TypeId::of::<bool>() {
                    return "B".to_string();
                }

                unimplemented!("Marshaler.root_code for {}", type_name::<Self>())
            }
        }
    };

    ($ftype:ty) => {
        paste! {
            impl_marshalers_primitive!($ftype, [<read_$ftype>], [<write_$ftype>]);
        }

        paste! {
                    impl $crate::root::traits::Object for $ftype {
                fn class(&self) -> &'_ str {
                "[<$ftype>]"
                }
            }
        }
    };
}

impl_marshalers_primitive!(i8);

impl_marshalers_primitive!(u8);
impl_marshalers_primitive!(i16);
impl_marshalers_primitive!(u16);
impl_marshalers_primitive!(i32);
impl_marshalers_primitive!(u32);
impl_marshalers_primitive!(i64);
impl_marshalers_primitive!(u64);

impl_marshalers_primitive!(f32);
impl_marshalers_primitive!(f64);
impl_marshalers_primitive!(bool);

impl Unmarshaler for String {
    fn unmarshal(&mut self, r: &mut RBuffer) -> Result<()> {
        r.do_skip_header()?;
        *self = r.read_string()?.to_string();
        Ok(())
    }

    fn class_name() -> Option<Vec<String>>
    where
        Self: Sized,
    {
        Some(["string", "char*", "TString"].map(String::from).to_vec())
    }
}

impl Marshaler for String {
    fn marshal(&self, w: &mut WBuffer) -> Result<i64> {
        let beg = w.pos();
        w.write_string(self)?;
        Ok(w.pos() - beg)
    }

    fn kind() -> MarshallerKind {
        MarshallerKind::String
    }

    fn root_code() -> String {
        "string".to_string()
    }
}

impl<T> Unmarshaler for Vec<T>
where
    T: UnmarshalerInto<Item = T>,
{
    fn unmarshal(&mut self, r: &mut RBuffer) -> Result<()> {
        r.do_skip_header()?;
        let size = r.read_i32()?;

        self.reserve(size as usize);
        r.set_skip_header(None);

        for _ in 0..size {
            let a = r.read_object_into::<T>()?;
            self.push(a);
        }

        Ok(())
    }

    fn class_name() -> Option<Vec<String>>
    where
        Self: Sized,
    {
        match T::classe_name() {
            None => None,
            Some(tys) => tys
                .iter()
                .map(|t| format!("vector<{}>", t))
                .collect::<Vec<String>>()
                .into(),
        }
    }
}

impl<T> Marshaler for Vec<T>
where
    T: Marshaler,
{
    fn marshal(&self, w: &mut WBuffer) -> Result<i64> {
        let beg = w.pos();
        w.write_i32(self.len() as i32)?;
        for item in self.iter() {
            item.marshal(w)?;
        }
        Ok(w.pos() - beg)
    }

    fn kind() -> MarshallerKind {
        MarshallerKind::Slice {
            std: MarshallerKindStd::Vector {
                class_name: T::class_name(),
            },
        }
    }

    fn root_code() -> String {
        format!("vector<{}>", T::root_code())
    }

    fn class_name() -> String
    where
        Self: Sized,
    {
        format!("vector<{}>", T::class_name())
    }
}

impl<T> Unmarshaler for HashSet<T>
where
    T: UnmarshalerInto<Item = T> + Eq + Hash,
{
    fn unmarshal(&mut self, r: &mut RBuffer) -> Result<()> {
        r.do_skip_header()?;
        let size = r.read_i32()?;
        self.reserve(size as usize);
        r.set_skip_header(None);
        for _ in 0..size {
            let a = r.read_object_into::<T>()?;
            self.insert(a);
        }
        Ok(())
    }

    fn class_name() -> Option<Vec<String>>
    where
        Self: Sized,
    {
        match T::classe_name() {
            None => None,
            Some(tys) => vec![format!("set<{}>", tys.first().unwrap())].into(),
        }
    }
}

impl<K, V> Unmarshaler for HashMap<K, V>
where
    V: UnmarshalerInto<Item = V>,
    K: UnmarshalerInto<Item = K> + Eq + Hash,
{
    fn unmarshal(&mut self, r: &mut RBuffer) -> Result<()> {
        r.do_skip_header()?;

        let size = r.read_i32()?;
        let mut keys = Vec::with_capacity(size as usize);
        let mut values = Vec::with_capacity(size as usize);

        r.set_skip_header(Some(6));

        for _i in 0..size {
            // r.set_skip_header(Some(0));
            let k = r.read_object_into::<K>()?;
            r.set_skip_header(Some(0));
            keys.push(k);
        }

        r.set_skip_header(Some(6));
        for _i in 0..size {
            let v = r.read_object_into::<V>()?;
            r.set_skip_header(Some(0));
            values.push(v);
        }

        self.reserve(size as usize);

        keys.into_iter().zip(values).for_each(|(k, v)| {
            self.insert(k, v);
        });

        Ok(())
    }
}

impl<T, const N: usize> Unmarshaler for [T; N]
where
    T: UnmarshalerInto<Item = T>,
{
    fn unmarshal(&mut self, r: &mut RBuffer) -> Result<()> {
        // for i in 0..N {
        //     self[i].unmarshal(r).unwrap();
        // }

        for item in self.iter_mut().take(N) {
            *item = r.read_object_into::<T>()?;
        }
        Ok(())
    }

    fn class_name() -> Option<Vec<String>>
    where
        Self: Sized,
    {
        match T::classe_name() {
            None => None,
            Some(tys) => tys
                .iter()
                .map(|t| format!("{}[{N}]", t))
                .collect::<Vec<String>>()
                .into(),
        }
    }
}

impl<T, const N: usize> Marshaler for [T; N]
where
    T: Marshaler,
{
    fn marshal(&self, w: &mut WBuffer) -> Result<i64> {
        let beg = w.pos();
        for item in self.iter().take(N) {
            item.marshal(w)?;
        }
        Ok(w.pos() - beg)
    }

    fn kind() -> MarshallerKind {
        MarshallerKind::Array {
            shape: vec![N as i32],
            tys: type_name::<T>().to_string(),
        }
    }

    fn root_code() -> String {
        format!("[{}]/{}", N, T::root_code())
    }
}

/// Automatically implemented if [Unmarshaler] is implemented
pub trait UnmarshalerInto {
    type Item: Default + Unmarshaler;
    fn unmarshal_into(r: &mut RBuffer) -> Result<Self::Item>;
    fn classe_name() -> Option<Vec<String>>;
}

impl<T> UnmarshalerInto for T
where
    T: Default + Unmarshaler,
{
    type Item = T;

    fn unmarshal_into(r: &mut RBuffer) -> Result<Self::Item> {
        let mut a: Self::Item = Self::Item::default();
        Unmarshaler::unmarshal(&mut a, r)?;
        Ok(a)
    }

    fn classe_name() -> Option<Vec<String>> {
        T::class_name()
    }
}

pub fn ensure_maximum_supported_version(
    read_version: i16,
    max_supported_version: i16,
    class_involved: &str,
) -> Result<()> {
    if read_version > max_supported_version {
        return Err(Error::VersionTooHigh {
            class: class_involved.into(),
            version_read: read_version,
            max_expected: max_supported_version,
        });
    }
    Ok(())
}

pub fn ensure_minimum_supported_version(
    read_version: i16,
    min_supported_version: i16,
    class_involved: &str,
) -> Result<()> {
    if read_version <= min_supported_version {
        return Err(Error::VersionTooLow {
            class: class_involved.into(),
            version_read: read_version,
            min_expected: min_supported_version,
        });
    }
    Ok(())
}