versatile_data/
field.rs

1use std::{fs, num::NonZeroU32, sync::Arc};
2
3use hashbrown::HashMap;
4use idx_binary::{AvltrieeSearch, IdxBinary};
5
6use crate::Data;
7
8pub type Field = IdxBinary;
9
10pub type FieldName = Arc<String>;
11pub type Fields = HashMap<FieldName, Field>;
12
13impl Data {
14    /// Returns the value of the field with the specified name in the specified row as a slice.
15    pub fn field_bytes(&self, row: NonZeroU32, name: &FieldName) -> &[u8] {
16        self.fields
17            .get(name)
18            .and_then(|v| v.value(row))
19            .unwrap_or(b"")
20    }
21
22    /// Returns the value of the field with the specified name in the specified row as a number.
23    pub fn field_num(&self, row: NonZeroU32, name: &FieldName) -> f64 {
24        self.fields
25            .get(name)
26            .and_then(|v| v.value(row))
27            .and_then(|v| unsafe { std::str::from_utf8_unchecked(v) }.parse().ok())
28            .unwrap_or(0.0)
29    }
30
31    pub(crate) fn create_field(&mut self, name: &FieldName) {
32        if !self.fields.contains_key(name) {
33            let mut fields_dir = self.fields_dir.clone();
34            fields_dir.push(name.as_ref().to_string());
35            fs::create_dir_all(&fields_dir).unwrap();
36            let field = Field::new(fields_dir, self.option.allocation_lot);
37
38            self.fields.insert(name.clone(), field);
39        }
40    }
41
42    pub fn fields(&self) -> &Fields {
43        &self.fields
44    }
45}