Skip to main content

reifydb_codec/
constraint.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use reifydb_value::value::{
5	constraint::{Constraint, TypeConstraint, bytes::MaxBytes},
6	dictionary::DictionaryId,
7	sumtype::SumTypeId,
8};
9
10use crate::{
11	error::{DecodeError, EncodeError},
12	reader::Reader,
13	typeinfo::{decode_value_type, encode_value_type},
14};
15
16pub fn encode_type_constraint_info(tc: &TypeConstraint, buf: &mut Vec<u8>) -> Result<(), EncodeError> {
17	encode_value_type(&tc.get_type(), buf)?;
18	encode_constraint_info(tc.constraint().as_ref(), buf)
19}
20
21pub fn decode_type_constraint_info(r: &mut Reader) -> Result<TypeConstraint, DecodeError> {
22	let ty = decode_value_type(r)?;
23	Ok(match decode_constraint_info(r)? {
24		Some(constraint) => TypeConstraint::with_constraint(ty, constraint),
25		None => TypeConstraint::unconstrained(ty),
26	})
27}
28
29pub fn encode_constraint_info(constraint: Option<&Constraint>, buf: &mut Vec<u8>) -> Result<(), EncodeError> {
30	match constraint {
31		None => buf.push(0),
32		Some(Constraint::MaxBytes(max)) => {
33			buf.push(1);
34			buf.extend_from_slice(&max.value().to_le_bytes());
35		}
36		Some(Constraint::Dictionary(dict_id, id_type)) => {
37			buf.push(3);
38			buf.extend_from_slice(&dict_id.to_u64().to_le_bytes());
39			encode_value_type(id_type, buf)?;
40		}
41		Some(Constraint::SumType(id)) => {
42			buf.push(4);
43			buf.extend_from_slice(&id.to_u64().to_le_bytes());
44		}
45	}
46	Ok(())
47}
48
49pub fn decode_constraint_info(r: &mut Reader) -> Result<Option<Constraint>, DecodeError> {
50	Ok(match r.u8()? {
51		0 => None,
52		1 => Some(Constraint::MaxBytes(MaxBytes::new(r.u32()?))),
53		3 => {
54			let dict_id = DictionaryId::from(r.u64()?);
55			Some(Constraint::Dictionary(dict_id, decode_value_type(r)?))
56		}
57		4 => Some(Constraint::SumType(SumTypeId::from(r.u64()?))),
58		other => return Err(DecodeError::InvalidData(format!("unknown constraint tag {other}"))),
59	})
60}