Skip to main content

reifydb_codec/
constraint.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use reifydb_abi::data::constraint::FFITypeConstraint;
5use reifydb_value::value::{
6	constraint::{Constraint, TypeConstraint, bytes::MaxBytes, precision::Precision, scale::Scale},
7	dictionary::DictionaryId,
8	sumtype::SumTypeId,
9};
10
11use crate::{
12	error::{DecodeError, EncodeError},
13	tag::TypeTag,
14};
15
16pub fn type_constraint_to_ffi(tc: &TypeConstraint) -> Result<FFITypeConstraint, EncodeError> {
17	let base_type = TypeTag::of_type(&tc.get_type())?.byte();
18	Ok(match tc.constraint() {
19		None => FFITypeConstraint {
20			base_type,
21			constraint_type: 0,
22			constraint_param1: 0,
23			constraint_param2: 0,
24		},
25		Some(Constraint::MaxBytes(max)) => FFITypeConstraint {
26			base_type,
27			constraint_type: 1,
28			constraint_param1: max.value(),
29			constraint_param2: 0,
30		},
31		Some(Constraint::PrecisionScale(p, s)) => FFITypeConstraint {
32			base_type,
33			constraint_type: 2,
34			constraint_param1: p.value() as u32,
35			constraint_param2: s.value() as u32,
36		},
37		Some(Constraint::Dictionary(dict_id, id_type)) => FFITypeConstraint {
38			base_type,
39			constraint_type: 3,
40			constraint_param1: dict_id.to_u64() as u32,
41			constraint_param2: TypeTag::of_type(id_type)?.byte() as u32,
42		},
43		Some(Constraint::SumType(id)) => FFITypeConstraint {
44			base_type,
45			constraint_type: 4,
46			constraint_param1: id.to_u64() as u32,
47			constraint_param2: 0,
48		},
49	})
50}
51
52pub fn type_constraint_from_ffi(ffi: &FFITypeConstraint) -> Result<TypeConstraint, DecodeError> {
53	let ty = TypeTag::from_byte(ffi.base_type)?.to_type()?;
54	Ok(match ffi.constraint_type {
55		1 => TypeConstraint::with_constraint(ty, Constraint::MaxBytes(MaxBytes::new(ffi.constraint_param1))),
56		2 => TypeConstraint::with_constraint(
57			ty,
58			Constraint::PrecisionScale(
59				Precision::new(ffi.constraint_param1 as u8),
60				Scale::new(ffi.constraint_param2 as u8),
61			),
62		),
63		3 => TypeConstraint::with_constraint(
64			ty,
65			Constraint::Dictionary(
66				DictionaryId::from(ffi.constraint_param1 as u64),
67				TypeTag::from_byte(ffi.constraint_param2 as u8)?.to_type()?,
68			),
69		),
70		4 => TypeConstraint::with_constraint(
71			ty,
72			Constraint::SumType(SumTypeId::from(ffi.constraint_param1 as u64)),
73		),
74		_ => TypeConstraint::unconstrained(ty),
75	})
76}