rdf_fusion_encoding/object_id/
scalar.rs

1use crate::TermEncoding;
2use crate::encoding::EncodingScalar;
3use crate::object_id::ObjectIdEncoding;
4use datafusion::common::{ScalarValue, exec_err};
5use rdf_fusion_model::{DFResult, ObjectId};
6
7/// Represents an Arrow scalar with a [ObjectIdEncoding].
8pub struct ObjectIdScalar {
9    encoding: ObjectIdEncoding,
10    inner: ScalarValue,
11}
12
13impl ObjectIdScalar {
14    /// Tries to create a new [ObjectIdScalar] from a regular [ScalarValue].
15    ///
16    /// # Errors
17    ///
18    /// Returns an error if the data type of `value` is unexpected.
19    pub fn try_new(encoding: ObjectIdEncoding, value: ScalarValue) -> DFResult<Self> {
20        if value.data_type() != encoding.data_type() {
21            return exec_err!(
22                "Expected scalar value with ObjectID encoding. Expected: {:?}, got {:?}",
23                encoding.data_type(),
24                value.data_type()
25            );
26        }
27        Ok(Self::new_unchecked(encoding, value))
28    }
29
30    /// Creates a new [ObjectIdScalar] without checking invariants.
31    pub fn new_unchecked(encoding: ObjectIdEncoding, inner: ScalarValue) -> Self {
32        Self { encoding, inner }
33    }
34
35    /// Creates a new [ObjectIdScalar] from the given `object_id`.
36    pub fn null(encoding: ObjectIdEncoding) -> Self {
37        let scalar = ScalarValue::UInt32(None);
38        Self::new_unchecked(encoding, scalar)
39    }
40
41    /// Creates a new [ObjectIdScalar] from the given `object_id`.
42    pub fn from_object_id(encoding: ObjectIdEncoding, object_id: ObjectId) -> Self {
43        let scalar = ScalarValue::UInt32(Some(object_id.0));
44        Self::new_unchecked(encoding, scalar)
45    }
46
47    /// Returns an [ObjectId] from this scalar.
48    pub fn as_object(&self) -> Option<ObjectId> {
49        match &self.inner {
50            ScalarValue::UInt32(scalar) => scalar.map(ObjectId::from),
51            _ => unreachable!("Checked in constructor."),
52        }
53    }
54}
55
56impl EncodingScalar for ObjectIdScalar {
57    type Encoding = ObjectIdEncoding;
58
59    fn encoding(&self) -> &Self::Encoding {
60        &self.encoding
61    }
62
63    fn scalar_value(&self) -> &ScalarValue {
64        &self.inner
65    }
66
67    fn into_scalar_value(self) -> ScalarValue {
68        self.inner
69    }
70}