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::sync::Arc;
24
25#[allow(dead_code)]
26enum StrEncoding {
27 Latin1 = 0,
28 Utf16 = 1,
29 Utf8 = 2,
30}
31
32impl Serializer for String {
33 type Target = Self;
34
35 const READ_DATA_ALWAYS_ADVANCES: bool = true;
36
37 #[inline(always)]
38 fn write_data(value: &Self, context: &mut WriteContext) -> Result<(), Error> {
39 let header = (value.len() as i32 as u64) << 2 | StrEncoding::Utf8 as u64;
40 context.writer.write_var_u36_small(header);
41 context.writer.write_utf8_string(value);
42 Ok(())
43 }
44
45 #[inline(always)]
46 fn read_data(context: &mut ReadContext) -> Result<Self, Error> {
47 let header = context.reader.read_var_u36_small()?;
48 let len = (header >> 2) as usize;
49 match header & 0b11 {
50 0 => context.reader.read_latin1_string(len),
51 1 => context.reader.read_utf16_string(len),
52 2 if context.is_check_string_read() => context.reader.read_utf8_string(len),
53 2 => context.reader.read_utf8_string_unchecked(len),
54 encoding => Err(Error::encoding_error(format!(
55 "wrong encoding value: {}",
56 encoding
57 ))),
58 }
59 }
60
61 #[inline(always)]
62 fn default_value(_: &mut ReadContext) -> Result<Self, Error> {
63 Ok(String::new())
64 }
65
66 #[inline(always)]
67 fn read_arc_any(
68 context: &mut ReadContext,
69 ) -> Result<Arc<dyn std::any::Any + Send + Sync>, Error> {
70 Ok(Arc::new(Self::read_data(context)?))
71 }
72
73 #[inline(always)]
74 fn reserved_space() -> usize {
75 std::mem::size_of::<i32>()
76 }
77
78 #[inline(always)]
79 fn static_type_id() -> TypeId {
80 TypeId::STRING
81 }
82
83 #[inline(always)]
84 fn write_type_info(context: &mut WriteContext) -> Result<(), Error> {
85 context.writer.write_u8(TypeId::STRING as u8);
86 Ok(())
87 }
88
89 #[inline(always)]
90 fn read_type_info(context: &mut ReadContext) -> Result<(), Error> {
91 read_basic_type_info::<Self>(context)
92 }
93}