meta_language/translation/
source_text_bytes.rs1use super::diagnostics::{Result, type_error};
6use super::frontend_rules::ml_array::number_index;
7use super::source_text_byte_rules::{
8 accept_source_text_byte_slice, accept_source_text_scalar_units, accept_source_text_unit_count,
9 read_source_text_byte as numeric_byte, read_source_text_byte_length as numeric_length,
10};
11
12pub fn read_source_text_units(text: &str) -> Result<Vec<f64>> {
14 let count = serde_json::Number::from(text.encode_utf16().count())
15 .as_f64()
16 .ok_or_else(|| {
17 type_error(
18 "source text exceeds the bounded Unicode code unit model",
19 None,
20 )
21 })?;
22 if !accept_source_text_unit_count(count) {
23 return Err(type_error(
24 "source text exceeds the bounded Unicode code unit model",
25 None,
26 ));
27 }
28 let units: Vec<f64> = text.encode_utf16().map(f64::from).collect();
29 if !accept_source_text_scalar_units(&units) {
30 return Err(type_error(
31 "source text exceeds the bounded Unicode code unit model",
32 None,
33 ));
34 }
35 Ok(units)
36}
37
38pub fn read_source_text_byte_length(text: &str) -> Result<usize> {
40 let units = read_source_text_units(text)?;
41 number_index(numeric_length(&units))
42 .ok_or_else(|| type_error("source text exceeds the bounded byte index model", None))
43}
44
45pub fn read_source_text_byte(text: &str, offset: f64) -> Result<Option<u8>> {
47 let units = read_source_text_units(text)?;
48 Ok(number_index(numeric_byte(&units, offset)).and_then(|byte| u8::try_from(byte).ok()))
49}
50
51pub fn slice_source_text_bytes(text: &str, start: f64, end: f64) -> Result<Option<&str>> {
53 let units = read_source_text_units(text)?;
54 if !accept_source_text_byte_slice(&units, start, end) {
55 return Ok(None);
56 }
57 let Some(start) = number_index(start) else {
58 return Ok(None);
59 };
60 let Some(end) = number_index(end) else {
61 return Ok(None);
62 };
63 Ok(text.get(start..end))
64}