Skip to main content

reifydb_codec/primitive/
utf8.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use std::str;
5
6use reifydb_value::{reifydb_assertions, value::value_type::ValueType};
7
8use crate::row::{bytes::RowBuilder, shape::RowShape};
9
10impl RowShape {
11	pub fn set_utf8(&self, row: &mut impl RowBuilder, index: usize, value: impl AsRef<str>) {
12		reifydb_assertions! {
13			assert!(
14				row.len() >= self.total_static_size(),
15				"row/shape size mismatch: row.len()={} < total_static_size()={}",
16				row.len(),
17				self.total_static_size()
18			);
19			assert_eq!(*self.fields()[index].constraint.get_type().inner_type(), ValueType::Utf8);
20		}
21		self.replace_dynamic_data(row, index, value.as_ref().as_bytes());
22	}
23
24	pub fn get_utf8<'a>(&'a self, row: &'a [u8], index: usize) -> &'a str {
25		let field = &self.fields()[index];
26		reifydb_assertions! {
27			assert!(
28				row.len() >= self.total_static_size(),
29				"row/shape size mismatch: row.len()={} < total_static_size()={}",
30				row.len(),
31				self.total_static_size()
32			);
33			assert_eq!(*field.constraint.get_type().inner_type(), ValueType::Utf8);
34		}
35
36		let ref_slice = &row[field.offset as usize..field.offset as usize + 8];
37		let offset = u32::from_le_bytes([ref_slice[0], ref_slice[1], ref_slice[2], ref_slice[3]]) as usize;
38		let length = u32::from_le_bytes([ref_slice[4], ref_slice[5], ref_slice[6], ref_slice[7]]) as usize;
39
40		let dynamic_start = self.dynamic_section_start();
41		let string_start = dynamic_start + offset;
42		let string_slice = &row[string_start..string_start + length];
43
44		// SAFETY: set_utf8 is the only writer of a Utf8 field and stores `&str` bytes verbatim, so the slice
45		// delimited by this field's dynamic offset and length is valid UTF-8.
46		unsafe { str::from_utf8_unchecked(string_slice) }
47	}
48
49	pub fn try_get_utf8<'a>(&'a self, row: &'a [u8], index: usize) -> Option<&'a str> {
50		if self.is_defined(row, index) && self.fields()[index].constraint.get_type() == ValueType::Utf8 {
51			Some(self.get_utf8(row, index))
52		} else {
53			None
54		}
55	}
56}