Skip to main content

reifydb_codec/encoded/
dictionary_id.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use std::ptr;
5
6use reifydb_value::{
7	reifydb_assertions,
8	value::{constraint::Constraint, dictionary::DictionaryEntryId, value_type::ValueType},
9};
10
11use crate::encoded::{row::EncodedRow, shape::RowShape};
12
13impl RowShape {
14	pub fn set_dictionary_id(&self, row: &mut EncodedRow, index: usize, entry: &DictionaryEntryId) {
15		let field = &self.fields()[index];
16		reifydb_assertions! {
17			assert!(
18				row.len() >= self.total_static_size(),
19				"row/shape size mismatch: row.len()={} < total_static_size()={}",
20				row.len(),
21				self.total_static_size()
22			);
23			assert_eq!(*field.constraint.get_type().inner_type(), ValueType::DictionaryId);
24		}
25		row.set_valid(index, true);
26		unsafe {
27			let ptr = row.make_mut().as_mut_ptr().add(field.offset as usize);
28			match entry {
29				DictionaryEntryId::U1(v) => ptr.write_unaligned(*v),
30				DictionaryEntryId::U2(v) => ptr::write_unaligned(ptr as *mut u16, *v),
31				DictionaryEntryId::U4(v) => ptr::write_unaligned(ptr as *mut u32, *v),
32				DictionaryEntryId::U8(v) => ptr::write_unaligned(ptr as *mut u64, *v),
33				DictionaryEntryId::U16(v) => ptr::write_unaligned(ptr as *mut u128, *v),
34			}
35		}
36	}
37
38	pub fn get_dictionary_id(&self, row: &EncodedRow, index: usize) -> DictionaryEntryId {
39		let field = &self.fields()[index];
40		reifydb_assertions! {
41			assert!(
42				row.len() >= self.total_static_size(),
43				"row/shape size mismatch: row.len()={} < total_static_size()={}",
44				row.len(),
45				self.total_static_size()
46			);
47			assert_eq!(*field.constraint.get_type().inner_type(), ValueType::DictionaryId);
48		}
49		let id_type = match field.constraint.constraint() {
50			Some(Constraint::Dictionary(_, id_type)) => id_type.clone(),
51			_ => ValueType::Uint4,
52		};
53		unsafe {
54			let ptr = row.as_ptr().add(field.offset as usize);
55			let raw: u128 = match id_type {
56				ValueType::Uint1 => ptr.read_unaligned() as u128,
57				ValueType::Uint2 => (ptr as *const u16).read_unaligned() as u128,
58				ValueType::Uint4 => (ptr as *const u32).read_unaligned() as u128,
59				ValueType::Uint8 => (ptr as *const u64).read_unaligned() as u128,
60				ValueType::Uint16 => (ptr as *const u128).read_unaligned(),
61				_ => (ptr as *const u32).read_unaligned() as u128,
62			};
63			DictionaryEntryId::from_u128(raw, id_type).unwrap()
64		}
65	}
66
67	pub fn try_get_dictionary_id(&self, row: &EncodedRow, index: usize) -> Option<DictionaryEntryId> {
68		if row.is_defined(index) && self.fields()[index].constraint.get_type() == ValueType::DictionaryId {
69			Some(self.get_dictionary_id(row, index))
70		} else {
71			None
72		}
73	}
74}