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
use crate::rdict::Streamer;
use crate::rmeta::{EReadWrite, Enum, EnumNamed};
use lazy_static::lazy_static;
use log::trace;
use regex::Regex;

lazy_static! {
    static ref RE: Regex =
        Regex::new(r"(\b([A-Za-z_0-9]+)(\s*::\s*[A-Za-z_][A-Za-z_0-9]*)*\b(\s*\*)*|<|>|,)")
            .unwrap();
}

pub fn parse_typename(typename: &str) -> i32 {
    let tokens = RE.captures(typename).unwrap();

    trace!("tokens = {:?}", tokens);

    if tokens.get(0).unwrap().as_str() == "vector" {
        return 6;
    }

    if tokens.get(0).unwrap().as_str() == "set" {
        return 6;
    }

    if tokens.get(0).unwrap().as_str() == "map" {
        return 12;
    }

    0
}

pub(crate) fn header_bytes_from_type(
    ty: i32,
    streamer: Option<&Streamer>,
    class_name: &str,
) -> i32 {
    trace!(
        "ty = {} streamer = {} class_name = {}",
        ty,
        match streamer {
            None => {
                "None"
            }
            Some(s) => {
                s.name()
            }
        },
        class_name
    );
    match streamer {
        None => {}
        Some(streamer) => match streamer {
            Streamer::String(s) => match s.element().etype() {
                Enum::Named(a) => match a {
                    EnumNamed::Base => {}
                    EnumNamed::Char => {}
                    EnumNamed::Short => {}
                    EnumNamed::Int => {}
                    EnumNamed::Long => {}
                    EnumNamed::Float => {}
                    EnumNamed::Counter => {}
                    EnumNamed::CharStar => {}
                    EnumNamed::Double => {}
                    EnumNamed::Double32 => {}
                    EnumNamed::LegacyChar => {}
                    EnumNamed::UChar => {}
                    EnumNamed::UShort => {}
                    EnumNamed::UInt => {}
                    EnumNamed::ULong => {}
                    EnumNamed::Bits => {}
                    EnumNamed::Long64 => {}
                    EnumNamed::ULong64 => {}
                    EnumNamed::Bool => {}
                    EnumNamed::Float16 => {}
                    EnumNamed::OffsetL => {}
                    EnumNamed::OffsetP => {}
                    EnumNamed::Object => {}
                    EnumNamed::Any => {}
                    EnumNamed::Objectp => {}
                    EnumNamed::ObjectP => {}
                    EnumNamed::TString => {
                        return 0;
                    }
                    EnumNamed::TObject => {}
                    EnumNamed::TNamed => {}
                    EnumNamed::Anyp => {}
                    EnumNamed::AnyP => {}
                    EnumNamed::AnyPnoVT => {}
                    EnumNamed::STLp => {}
                    EnumNamed::Skip => {}
                    EnumNamed::SkipL => {}
                    EnumNamed::SkipP => {}
                    EnumNamed::Conv => {}
                    EnumNamed::ConvL => {}
                    EnumNamed::ConvP => {}
                    EnumNamed::Stl => {}
                    EnumNamed::STLstring => {}
                    EnumNamed::Streamer => {}
                    EnumNamed::StreamLoop => {}
                    EnumNamed::Cache => {}
                    EnumNamed::Artificial => {}
                    EnumNamed::CacheNew => {}
                    EnumNamed::CacheDelete => {}
                    EnumNamed::NeedObjectForVirtualBaseClass => {}
                    EnumNamed::Missing => {}
                    EnumNamed::OffsetP16 => {
                        todo!()
                    }
                },
                Enum::Int(_a) => {}
            },
            Streamer::STLstring(_) => {
                return 6;
            }
            Streamer::BasicType(_) => {}
            Streamer::BasicPointer(_) => {}
            Streamer::ObjectAny(_) => {}
            Streamer::Stl(_) => {}
            Streamer::Base(_) => {}
            Streamer::Object(_) => {}
            Streamer::ObjectPointer(_) => {}
        },
    }

    if ty == -1 {
        return parse_typename(class_name);
    } else if ty < EReadWrite::Object {
        if ty > EReadWrite::OffsetP {
            return 1;
        } else {
            return 0;
        }
    } else if ty == EReadWrite::TString {
        return 0;
    } else if ty == EReadWrite::Stl {
        return 6;
    }

    todo!();
}

pub(crate) fn _from_leaftype_to_str(leaftype: i32) -> Option<&'static str> {
    // trace!("leaftype = {}", leaftype);

    trace!(";_from_leaftype_to_str.leaftype:{}", leaftype);

    if leaftype < 0 {
        return None;
    }

    let leaftype = if EReadWrite::OffsetL < leaftype && leaftype < EReadWrite::OffsetP {
        leaftype - EReadWrite::OffsetL.to_i32()
    } else {
        leaftype
    };

    // trace!("leaftype = {}", leaftype);
    let leaftype = if leaftype > EReadWrite::OffsetP
        && (leaftype - EReadWrite::OffsetP.to_i32()) < EReadWrite::OffsetP
    {
        leaftype - EReadWrite::OffsetP.to_i32()
    } else {
        leaftype
    };

    // assert!(leaftype > 0);

    // trace!("leaftype = {}", leaftype);

    match EReadWrite::from_i32(leaftype) {
        Ok(leaftype) => match leaftype {
            EReadWrite::Char => Some("int8_t"),
            EReadWrite::UChar => Some("uint8_t"),

            EReadWrite::Short => Some("int16_t"),
            EReadWrite::UShort => Some("uint16_t"),

            EReadWrite::Int => Some("int32_t"),
            EReadWrite::UInt | EReadWrite::Bits | EReadWrite::Counter => Some("uint32_t"),

            EReadWrite::Long => Some("int64_t"),
            EReadWrite::ULong => Some("uint64_t"),

            EReadWrite::Float => Some("float"),
            EReadWrite::Double => Some("double"),

            EReadWrite::TString => Some("TString"),

            _ => {
                // todo!()
                None
            }
        },
        _ => None,
    }
}

pub fn replace_string(s: &str, from: &str, to: &str) -> String {
    let mut ret = String::new();
    let indices: Vec<_> = s.match_indices(from).collect();
    let mut g_indices = Vec::new();
    let chars = s.chars().collect::<Vec<_>>();
    for (i, _) in indices.iter() {
        let start = {
            if *i == 0 {
                None
            } else {
                chars.get(*i - 1)
            }
        };

        let end = chars.get(*i + from.len());

        match (start, end) {
            (Some(start), Some(end)) => {
                if start.is_alphabetic() || end.is_alphabetic() {
                    continue;
                } else {
                    g_indices.push(*i);
                }
            }
            (Some(start), None) => {
                if start.is_alphabetic() {
                    continue;
                } else {
                    g_indices.push(*i);
                }
            }
            (None, Some(end)) => {
                if end.is_alphabetic() {
                    continue;
                } else {
                    g_indices.push(*i);
                }
            }
            (None, None) => {
                g_indices.push(*i);
            }
        }
    }

    let mut last_end = 0;

    for start in g_indices.iter() {
        let start = *start;
        ret.push_str(&s[last_end..start]);
        ret.push_str(to);
        last_end = start + from.len();
    }
    ret.push_str(&s[last_end..s.len()]);

    ret
}

/// change c++ typename from "int" to int32_t and so on
pub(crate) fn clean_type_name<T: AsRef<str>>(ty: T) -> String {
    let ret = ty.as_ref().to_string().replace("unsigned int", "uint32_t");
    let ret = replace_string(&ret, "int", "int32_t");
    // undo change (uint32_t -> uint32_t32_t)
    let ret = ret.replace("uint32_t32_t", "uint32_t");
    // undo change (int32_t -> int32_t32_t)
    let ret = ret.replace("int32_t32_t", "int32_t");
    let ret = ret.replace("uint32_t16_t", "uint16_t");
    let ret = ret.replace("uint32_t8_t", "uint8_t");
    let ret = ret.replace("int32_t16_t", "int16_t");
    let ret = ret.replace("int32_t8_t", "int8_t");
    let ret = ret.replace("int32_t64_t", "int64_t");

    let ret = ret.replace("unsigned short", "uint16_t");
    let ret = ret.replace("short", "int16_t");

    let ret = ret.replace("unsigned long", "uint64_t");
    let ret = ret.replace("long", "int64_t");

    ret.replace(' ', "")
}

/// Convert C++ templated name to a rust one
/// Example vector<int> -> Vec<i32>
pub(crate) fn type_name_cpp_to_rust(ty: &str) -> String {
    let ty = clean_type_name(ty);
    let ret = ty.replace("string", "String");
    let ret = ret.replace("vector", "Vec");
    let ret = ret.replace("map", "HashMap");
    let mut ret = ret.replace("set", "HashSet");

    let replaces = [
        ("uint64_t", "u64"),
        ("int64_t", "i64"),
        ("uint32_t", "u32"),
        ("int32_t", "i32"),
        ("uint16_t", "u16"),
        ("int16_t", "i16"),
        ("uint8_t", "u8"),
        ("int8_t", "i8"),
        ("float", "f32"),
        ("double", "f64"),
        ("bool", "bool"),
    ];

    for (cpp, rust) in replaces.iter() {
        ret = ret.replace(cpp, rust);

        //i32[] -> Slice<i32>
        let cpp_s = format!("{}[]", rust);
        let rust_s = format!("Slice<{}>", rust);
        ret = ret.replace(cpp_s.as_str(), rust_s.as_str());

        let start = &format!("{}[", rust);
        let end = "]";
        // trace!("ty = {} -> ret = {}", ty, ret);
        if let Some(start) = ret.find(start) {
            let start = start + rust.len() + 1;
            // trace!("\tstart = {}", start);

            let right = ret.get(start..).unwrap();
            // trace!("\tright = {}", right);
            if !right.starts_with(']') {
                let end = right.find(end).unwrap();
                // trace!("\t\tend = {}", end);
                let inner = ret.get(start..(end + start)).unwrap();
                // trace!("\t\tinner = {}", inner);
                let rust_s = format!("{}[{}]", rust, inner);
                let rust_o = format!("[{};{}]", rust, inner);
                // trace!("\t\trust_s = {}", rust_s);
                ret = ret.replace(rust_s.as_str(), rust_o.as_str());
            }
        }
    }

    ret.replace("char*", "String")
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::Result;

    #[test]
    fn test_replace_string() -> Result<()> {
        let s = "int";
        let from = "int";
        let to = "int32_t";
        assert_eq!(replace_string(s, from, to), "int32_t");

        let s = "unsigned int";
        let from = "unsigned int";
        let to = "uint32_t";
        assert_eq!(replace_string(s, from, to), "uint32_t");

        let s = "Point";
        let from = "int";
        let to = "uint32_t";
        assert_eq!(replace_string(s, from, to), "Point");

        let s = "vector<int>";
        let from = "int";
        let to = "int32_t";
        assert_eq!(replace_string(s, from, to), "vector<int32_t>");

        Ok(())
    }

    #[test]
    fn test_clean_type_name() -> Result<()> {
        let dirties_clean = [
            ("vector<long>", "vector<int64_t>"),
            ("vector<long>", "vector<int64_t>"),
            ("vector<int>", "vector<int32_t>"),
            ("vector<set<int>>", "vector<set<int32_t>>"),
            ("vector<unsigned int>", "vector<uint32_t>"),
            ("vector<short>", "vector<int16_t>"),
            ("vector<unsigned short>", "vector<uint16_t>"),
            ("int[10]", "int32_t[10]"),
            ("unsigned int[10]", "uint32_t[10]"),
            ("Point", "Point"),
        ];

        dirties_clean.iter().for_each(|(dirty, clean)| {
            assert_eq!(clean_type_name(dirty), *clean);
            assert_eq!(clean_type_name(dirty), clean_type_name(clean));
            assert_eq!(clean_type_name(clean_type_name(dirty).as_str()), *clean);
        });

        Ok(())
    }

    #[test]
    fn test_clean_type_to_rust() -> Result<()> {
        let names = [
            ("int8_t", "i8"),
            ("vector<int>", "Vec<i32>"),
            ("vector<set<int>>", "Vec<HashSet<i32>>"),
            ("vector<unsigned int>", "Vec<u32>"),
            ("vector<short>", "Vec<i16>"),
            ("vector<unsigned short>", "Vec<u16>"),
            ("int[10]", "[i32;10]"),
            ("vector<int[10]>", "Vec<[i32;10]>"),
            ("int[]", "Slice<i32>"),
            ("unsigned int[10]", "[u32;10]"),
        ];

        names.iter().for_each(|(cpp, rust)| {
            assert_eq!(type_name_cpp_to_rust(cpp), *rust);
            // assert_eq!(clean_type_name(cpp), clean_type_name(rust));
            // assert_eq!(clean_type_name(clean_type_name(cpp).as_str()), *rust);
        });

        Ok(())
    }
}