simdjson_rust/dom/
element.rs

1use std::{marker::PhantomData, ptr::NonNull};
2
3use simdjson_sys as ffi;
4
5use super::{array::Array, document::Document, object::Object};
6use crate::{
7    macros::{impl_drop, map_primitive_result, map_ptr_result},
8    utils::string_view_struct_to_str,
9    Result,
10};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13pub enum ElementType {
14    Array     = '[' as _,
15    Object    = '{' as _,
16    Int64     = 'l' as _,
17    UInt64    = 'u' as _,
18    Double    = 'd' as _,
19    String    = '"' as _,
20    Bool      = 't' as _,
21    NullValue = 'n' as _,
22}
23
24impl From<i32> for ElementType {
25    fn from(value: i32) -> Self {
26        match value as u8 as char {
27            '[' => Self::Array,
28            '{' => Self::Object,
29            'l' => Self::Int64,
30            'u' => Self::UInt64,
31            'd' => Self::Double,
32            '"' => Self::String,
33            't' => Self::Bool,
34            'n' => Self::NullValue,
35            _ => unreachable!(),
36        }
37    }
38}
39
40pub struct Element<'a> {
41    ptr: NonNull<ffi::SJ_DOM_element>,
42    _doc: PhantomData<&'a Document>,
43}
44
45impl<'a> Element<'a> {
46    pub fn new(ptr: NonNull<ffi::SJ_DOM_element>) -> Self {
47        Self {
48            ptr,
49            _doc: PhantomData,
50        }
51    }
52
53    pub fn get_type(&self) -> ElementType {
54        unsafe { ElementType::from(ffi::SJ_DOM_element_type(self.ptr.as_ptr())) }
55    }
56
57    pub fn get_array(&self) -> Result<Array> {
58        map_ptr_result!(ffi::SJ_DOM_element_get_array(self.ptr.as_ptr())).map(Array::new)
59    }
60
61    pub fn get_object(&self) -> Result<Object> {
62        map_ptr_result!(ffi::SJ_DOM_element_get_object(self.ptr.as_ptr())).map(Object::new)
63    }
64
65    pub fn get_string(&self) -> Result<&'a str> {
66        map_primitive_result!(ffi::SJ_DOM_element_get_string(self.ptr.as_ptr()))
67            .map(string_view_struct_to_str)
68    }
69
70    pub fn get_int64(&self) -> Result<i64> {
71        map_primitive_result!(ffi::SJ_DOM_element_get_int64(self.ptr.as_ptr()))
72    }
73
74    pub fn get_uint64(&self) -> Result<u64> {
75        map_primitive_result!(ffi::SJ_DOM_element_get_uint64(self.ptr.as_ptr()))
76    }
77
78    pub fn get_double(&self) -> Result<f64> {
79        map_primitive_result!(ffi::SJ_DOM_element_get_double(self.ptr.as_ptr()))
80    }
81
82    pub fn get_bool(&self) -> Result<bool> {
83        map_primitive_result!(ffi::SJ_DOM_element_get_bool(self.ptr.as_ptr()))
84    }
85
86    pub fn at_pointer(&self, json_pointer: &str) -> Result<Element> {
87        map_ptr_result!(ffi::SJ_DOM_element_at_pointer(
88            self.ptr.as_ptr(),
89            json_pointer.as_ptr().cast(),
90            json_pointer.len()
91        ))
92        .map(Element::new)
93    }
94}
95
96impl_drop!(Element<'a>, ffi::SJ_DOM_element_free);