| 1 |
use crate::utils; |
| 2 |
use crate::{ |
| 3 |
BareItem, Decimal, Dictionary, InnerList, Item, List, ListEntry, Parameters, RefBareItem, |
| 4 |
SFVResult, |
| 5 |
}; |
| 6 |
use data_encoding::BASE64; |
| 7 |
|
| 8 |
/// Serializes structured field value into String. |
| 9 |
pub trait SerializeValue { |
| 10 |
/// Serializes structured field value into String. |
| 11 |
/// # Examples |
| 12 |
/// ``` |
| 13 |
/// # use sfv::{Parser, SerializeValue, ParseValue}; |
| 14 |
/// |
| 15 |
/// let parsed_list_field = Parser::parse_list("\"london\", \t\t\"berlin\"".as_bytes()); |
| 16 |
/// assert!(parsed_list_field.is_ok()); |
| 17 |
/// |
| 18 |
/// assert_eq!( |
| 19 |
/// parsed_list_field.unwrap().serialize_value().unwrap(), |
| 20 |
/// "\"london\", \"berlin\"" |
| 21 |
/// ); |
| 22 |
/// ``` |
| 23 |
fn serialize_value(&self) -> SFVResult<String>; |
| 24 |
} |
| 25 |
|
| 26 |
impl SerializeValue for Dictionary { |
| 27 |
fn serialize_value(&self) -> SFVResult<String> { |
| 28 |
let mut output = String::new(); |
| 29 |
Serializer::serialize_dict(self, &mut output)?; |
| 30 |
Ok(output) |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
impl SerializeValue for List { |
| 35 |
fn serialize_value(&self) -> SFVResult<String> { |
| 36 |
let mut output = String::new(); |
| 37 |
Serializer::serialize_list(self, &mut output)?; |
| 38 |
Ok(output) |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
impl SerializeValue for Item { |
| 43 |
fn serialize_value(&self) -> SFVResult<String> { |
| 44 |
let mut output = String::new(); |
| 45 |
Serializer::serialize_item(self, &mut output)?; |
| 46 |
Ok(output) |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
/// Container serialization functions |
| 51 |
pub(crate) struct Serializer; |
| 52 |
|
| 53 |
impl Serializer { |
| 54 |
pub(crate) fn serialize_item(input_item: &Item, output: &mut String) -> SFVResult<()> { |
| 55 |
// https://httpwg.org/specs/rfc8941.html#ser-item |
| 56 |
|
| 57 |
Self::serialize_bare_item(&input_item.bare_item, output)?; |
| 58 |
Self::serialize_parameters(&input_item.params, output)?; |
| 59 |
Ok(()) |
| 60 |
} |
| 61 |
|
| 62 |
#[allow(clippy::ptr_arg)] |
| 63 |
pub(crate) fn serialize_list(input_list: &List, output: &mut String) -> SFVResult<()> { |
| 64 |
// https://httpwg.org/specs/rfc8941.html#ser-list |
| 65 |
if input_list.is_empty() { |
| 66 |
return Err("serialize_list: serializing empty field is not allowed"); |
| 67 |
} |
| 68 |
|
| 69 |
for (idx, member) in input_list.iter().enumerate() { |
| 70 |
match member { |
| 71 |
ListEntry::Item(item) => { |
| 72 |
Self::serialize_item(item, output)?; |
| 73 |
} |
| 74 |
ListEntry::InnerList(inner_list) => { |
| 75 |
Self::serialize_inner_list(inner_list, output)?; |
| 76 |
} |
| 77 |
}; |
| 78 |
|
| 79 |
// If more items remain in input_list: |
| 80 |
// Append “,” to output. |
| 81 |
// Append a single SP to output. |
| 82 |
if idx < input_list.len() - 1 { |
| 83 |
output.push_str(", "); |
| 84 |
} |
| 85 |
} |
| 86 |
Ok(()) |
| 87 |
} |
| 88 |
|
| 89 |
pub(crate) fn serialize_dict(input_dict: &Dictionary, output: &mut String) -> SFVResult<()> { |
| 90 |
// https://httpwg.org/specs/rfc8941.html#ser-dictionary |
| 91 |
if input_dict.is_empty() { |
| 92 |
return Err("serialize_dictionary: serializing empty field is not allowed"); |
| 93 |
} |
| 94 |
|
| 95 |
for (idx, (member_name, member_value)) in input_dict.iter().enumerate() { |
| 96 |
Serializer::serialize_key(member_name, output)?; |
| 97 |
|
| 98 |
match member_value { |
| 99 |
ListEntry::Item(ref item) => { |
| 100 |
// If dict member is boolean true, no need to serialize it: only its params must be serialized |
| 101 |
// Otherwise serialize entire item with its params |
| 102 |
if item.bare_item == BareItem::Boolean(true) { |
| 103 |
Self::serialize_parameters(&item.params, output)?; |
| 104 |
} else { |
| 105 |
output.push('='); |
| 106 |
Self::serialize_item(item, output)?; |
| 107 |
} |
| 108 |
} |
| 109 |
ListEntry::InnerList(inner_list) => { |
| 110 |
output.push('='); |
| 111 |
Self::serialize_inner_list(inner_list, output)?; |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
// If more items remain in input_dictionary: |
| 116 |
// Append “,” to output. |
| 117 |
// Append a single SP to output. |
| 118 |
if idx < input_dict.len() - 1 { |
| 119 |
output.push_str(", "); |
| 120 |
} |
| 121 |
} |
| 122 |
Ok(()) |
| 123 |
} |
| 124 |
|
| 125 |
fn serialize_inner_list(input_inner_list: &InnerList, output: &mut String) -> SFVResult<()> { |
| 126 |
// https://httpwg.org/specs/rfc8941.html#ser-innerlist |
| 127 |
|
| 128 |
let items = &input_inner_list.items; |
| 129 |
let inner_list_parameters = &input_inner_list.params; |
| 130 |
|
| 131 |
output.push('('); |
| 132 |
for (idx, item) in items.iter().enumerate() { |
| 133 |
Self::serialize_item(item, output)?; |
| 134 |
|
| 135 |
// If more values remain in inner_list, append a single SP to output |
| 136 |
if idx < items.len() - 1 { |
| 137 |
output.push(' '); |
| 138 |
} |
| 139 |
} |
| 140 |
output.push(')'); |
| 141 |
Self::serialize_parameters(inner_list_parameters, output)?; |
| 142 |
Ok(()) |
| 143 |
} |
| 144 |
|
| 145 |
pub(crate) fn serialize_bare_item( |
| 146 |
input_bare_item: &BareItem, |
| 147 |
output: &mut String, |
| 148 |
) -> SFVResult<()> { |
| 149 |
// https://httpwg.org/specs/rfc8941.html#ser-bare-item |
| 150 |
|
| 151 |
let ref_bare_item = input_bare_item.to_ref_bare_item(); |
| 152 |
Self::serialize_ref_bare_item(&ref_bare_item, output) |
| 153 |
} |
| 154 |
|
| 155 |
pub(crate) fn serialize_ref_bare_item( |
| 156 |
value: &RefBareItem, |
| 157 |
output: &mut String, |
| 158 |
) -> SFVResult<()> { |
| 159 |
match value { |
| 160 |
RefBareItem::Boolean(value) => Self::serialize_bool(*value, output)?, |
| 161 |
RefBareItem::String(value) => Self::serialize_string(value, output)?, |
| 162 |
RefBareItem::ByteSeq(value) => Self::serialize_byte_sequence(value, output)?, |
| 163 |
RefBareItem::Token(value) => Self::serialize_token(value, output)?, |
| 164 |
RefBareItem::Integer(value) => Self::serialize_integer(*value, output)?, |
| 165 |
RefBareItem::Decimal(value) => Self::serialize_decimal(*value, output)?, |
| 166 |
}; |
| 167 |
Ok(()) |
| 168 |
} |
| 169 |
|
| 170 |
pub(crate) fn serialize_parameters( |
| 171 |
input_params: &Parameters, |
| 172 |
output: &mut String, |
| 173 |
) -> SFVResult<()> { |
| 174 |
// https://httpwg.org/specs/rfc8941.html#ser-params |
| 175 |
|
| 176 |
for (param_name, param_value) in input_params.iter() { |
| 177 |
Self::serialize_ref_parameter(param_name, ¶m_value.to_ref_bare_item(), output)?; |
| 178 |
} |
| 179 |
Ok(()) |
| 180 |
} |
| 181 |
|
| 182 |
pub(crate) fn serialize_ref_parameter( |
| 183 |
name: &str, |
| 184 |
value: &RefBareItem, |
| 185 |
output: &mut String, |
| 186 |
) -> SFVResult<()> { |
| 187 |
output.push(';'); |
| 188 |
Self::serialize_key(name, output)?; |
| 189 |
|
| 190 |
if value != &RefBareItem::Boolean(true) { |
| 191 |
output.push('='); |
| 192 |
Self::serialize_ref_bare_item(value, output)?; |
| 193 |
} |
| 194 |
Ok(()) |
| 195 |
} |
| 196 |
|
| 197 |
pub(crate) fn serialize_key(input_key: &str, output: &mut String) -> SFVResult<()> { |
| 198 |
// https://httpwg.org/specs/rfc8941.html#ser-key |
| 199 |
|
| 200 |
let disallowed_chars = |
| 201 |
|c: char| !(c.is_ascii_lowercase() || c.is_ascii_digit() || "_-*.".contains(c)); |
| 202 |
|
| 203 |
if input_key.chars().any(disallowed_chars) { |
| 204 |
return Err("serialize_key: disallowed character in input"); |
| 205 |
} |
| 206 |
|
| 207 |
if let Some(char) = input_key.chars().next() { |
| 208 |
if !(char.is_ascii_lowercase() || char == '*') { |
| 209 |
return Err("serialize_key: first character is not lcalpha or '*'"); |
| 210 |
} |
| 211 |
} |
| 212 |
output.push_str(input_key); |
| 213 |
Ok(()) |
| 214 |
} |
| 215 |
|
| 216 |
pub(crate) fn serialize_integer(value: i64, output: &mut String) -> SFVResult<()> { |
| 217 |
//https://httpwg.org/specs/rfc8941.html#ser-integer |
| 218 |
|
| 219 |
let (min_int, max_int) = (-999_999_999_999_999_i64, 999_999_999_999_999_i64); |
| 220 |
if !(min_int <= value && value <= max_int) { |
| 221 |
return Err("serialize_integer: integer is out of range"); |
| 222 |
} |
| 223 |
output.push_str(&value.to_string()); |
| 224 |
Ok(()) |
| 225 |
} |
| 226 |
|
| 227 |
pub(crate) fn serialize_decimal(value: Decimal, output: &mut String) -> SFVResult<()> { |
| 228 |
// https://httpwg.org/specs/rfc8941.html#ser-decimal |
| 229 |
|
| 230 |
let integer_comp_length = 12; |
| 231 |
let fraction_length = 3; |
| 232 |
|
| 233 |
let decimal = value.round_dp(fraction_length); |
| 234 |
let int_comp = decimal.trunc(); |
| 235 |
let fract_comp = decimal.fract(); |
| 236 |
|
| 237 |
// TODO: Replace with > 999_999_999_999_u64 |
| 238 |
if int_comp.abs().to_string().len() > integer_comp_length { |
| 239 |
return Err("serialize_decimal: integer component > 12 digits"); |
| 240 |
} |
| 241 |
|
| 242 |
if fract_comp.is_zero() { |
| 243 |
output.push_str(&int_comp.to_string()); |
| 244 |
output.push('.'); |
| 245 |
output.push('0'); |
| 246 |
} else { |
| 247 |
output.push_str(&decimal.to_string()); |
| 248 |
} |
| 249 |
|
| 250 |
Ok(()) |
| 251 |
} |
| 252 |
|
| 253 |
pub(crate) fn serialize_string(value: &str, output: &mut String) -> SFVResult<()> { |
| 254 |
// https://httpwg.org/specs/rfc8941.html#ser-integer |
| 255 |
|
| 256 |
if !value.is_ascii() { |
| 257 |
return Err("serialize_string: non-ascii character"); |
| 258 |
} |
| 259 |
|
| 260 |
let vchar_or_sp = |char| char == '\x7f' || ('\x00'..='\x1f').contains(&char); |
| 261 |
if value.chars().any(vchar_or_sp) { |
| 262 |
return Err("serialize_string: not a visible character"); |
| 263 |
} |
| 264 |
|
| 265 |
output.push('\"'); |
| 266 |
for char in value.chars() { |
| 267 |
if char == '\\' || char == '\"' { |
| 268 |
output.push('\\'); |
| 269 |
} |
| 270 |
output.push(char); |
| 271 |
} |
| 272 |
output.push('\"'); |
| 273 |
|
| 274 |
Ok(()) |
| 275 |
} |
| 276 |
|
| 277 |
pub(crate) fn serialize_token(value: &str, output: &mut String) -> SFVResult<()> { |
| 278 |
// https://httpwg.org/specs/rfc8941.html#ser-token |
| 279 |
|
| 280 |
if !value.is_ascii() { |
| 281 |
return Err("serialize_string: non-ascii character"); |
| 282 |
} |
| 283 |
|
| 284 |
let mut chars = value.chars(); |
| 285 |
if let Some(char) = chars.next() { |
| 286 |
if !(char.is_ascii_alphabetic() || char == '*') { |
| 287 |
return Err("serialise_token: first character is not ALPHA or '*'"); |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
if chars |
| 292 |
.clone() |
| 293 |
.any(|c| !(utils::is_tchar(c) || c == ':' || c == '/')) |
| 294 |
{ |
| 295 |
return Err("serialise_token: disallowed character"); |
| 296 |
} |
| 297 |
|
| 298 |
output.push_str(value); |
| 299 |
Ok(()) |
| 300 |
} |
| 301 |
|
| 302 |
pub(crate) fn serialize_byte_sequence(value: &[u8], output: &mut String) -> SFVResult<()> { |
| 303 |
// https://httpwg.org/specs/rfc8941.html#ser-binary |
| 304 |
|
| 305 |
output.push(':'); |
| 306 |
let encoded = BASE64.encode(value.as_ref()); |
| 307 |
output.push_str(&encoded); |
| 308 |
output.push(':'); |
| 309 |
Ok(()) |
| 310 |
} |
| 311 |
|
| 312 |
pub(crate) fn serialize_bool(value: bool, output: &mut String) -> SFVResult<()> { |
| 313 |
// https://httpwg.org/specs/rfc8941.html#ser-boolean |
| 314 |
|
| 315 |
let val = if value { "?1" } else { "?0" }; |
| 316 |
output.push_str(val); |
| 317 |
Ok(()) |
| 318 |
} |
| 319 |
} |