fory_core/serializer/
string.rs1use crate::context::{ReadContext, WriteContext};
19use crate::error::Error;
20use crate::serializer::util::read_basic_type_info;
21use crate::serializer::Serializer;
22use crate::type_id::TypeId;
23use std::convert::TryFrom;
24use std::sync::Arc;
25
26#[allow(dead_code)]
27enum StrEncoding {
28 Latin1 = 0,
29 Utf16 = 1,
30 Utf8 = 2,
31}
32
33#[inline(always)]
34pub(super) fn checked_string_len(len: u64) -> Result<usize, Error> {
35 match usize::try_from(len) {
36 Ok(len) => Ok(len),
37 Err(_) => Err(string_len_overflow(len)),
38 }
39}
40
41#[cold]
42#[inline(never)]
43fn string_len_overflow(len: u64) -> Error {
44 Error::invalid_data(format!(
45 "string byte length {len} exceeds the platform address space"
46 ))
47}
48
49impl Serializer for String {
50 type Target = Self;
51
52 const READ_DATA_ALWAYS_ADVANCES: bool = true;
53
54 #[inline(always)]
55 fn write_data(value: &Self, context: &mut WriteContext) -> Result<(), Error> {
56 let header = (value.len() as i32 as u64) << 2 | StrEncoding::Utf8 as u64;
57 context.writer.write_var_u36_small(header);
58 context.writer.write_utf8_string(value);
59 Ok(())
60 }
61
62 #[inline(always)]
63 fn read_data(context: &mut ReadContext) -> Result<Self, Error> {
64 let header = context.reader.read_var_u36_small()?;
65 let len = checked_string_len(header >> 2)?;
66 match header & 0b11 {
67 0 => context.reader.read_latin1_string(len),
68 1 => context.reader.read_utf16_string(len),
69 2 if context.is_check_string_read() => context.reader.read_utf8_string(len),
70 2 => unsafe { context.reader.read_utf8_string_unchecked(len) },
73 encoding => Err(Error::encoding_error(format!(
74 "wrong encoding value: {}",
75 encoding
76 ))),
77 }
78 }
79
80 #[inline(always)]
81 fn default_value(_: &mut ReadContext) -> Result<Self, Error> {
82 Ok(String::new())
83 }
84
85 #[inline(always)]
86 fn read_arc_any(
87 context: &mut ReadContext,
88 ) -> Result<Arc<dyn std::any::Any + Send + Sync>, Error> {
89 Ok(Arc::new(Self::read_data(context)?))
90 }
91
92 #[inline(always)]
93 fn reserved_space() -> usize {
94 std::mem::size_of::<i32>()
95 }
96
97 #[inline(always)]
98 fn static_type_id() -> TypeId {
99 TypeId::STRING
100 }
101
102 #[inline(always)]
103 fn write_type_info(context: &mut WriteContext) -> Result<(), Error> {
104 context.writer.write_u8(TypeId::STRING as u8);
105 Ok(())
106 }
107
108 #[inline(always)]
109 fn read_type_info(context: &mut ReadContext) -> Result<(), Error> {
110 read_basic_type_info::<Self>(context)
111 }
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117
118 #[test]
119 fn checked_length_range() {
120 assert_eq!(checked_string_len(17).unwrap(), 17);
121
122 let beyond_u32 = u64::from(u32::MAX) + 1;
123 if usize::BITS > u32::BITS {
124 assert_eq!(checked_string_len(beyond_u32).unwrap() as u64, beyond_u32);
125 } else {
126 assert!(checked_string_len(beyond_u32).is_err());
127 }
128 }
129}