| 1 | use std::borrow::Cow; |
| 2 | use std::convert::{Into, TryFrom}; |
| 3 | use std::fmt::{self, Debug, Display}; |
| 4 | use std::iter::Iterator; |
| 5 | use std::str::{self, FromStr}; |
| 6 | use std::string::*; |
| 7 | |
| 8 | #[cfg(feature = "serde")] |
| 9 | use serde::{ |
| 10 | de::{self, MapAccess, SeqAccess, Visitor}, |
| 11 | ser::SerializeMap, |
| 12 | Deserialize, Deserializer, Serialize, Serializer, |
| 13 | }; |
| 14 | |
| 15 | use crate::*; |
| 16 | |
| 17 | /// Quotes types in [`Value`] strings |
| 18 | #[derive(Debug, PartialEq, Eq, Clone, Copy)] |
| 19 | pub enum Quote { |
| 20 | None, |
| 21 | Single, |
| 22 | Double, |
| 23 | Braces, |
| 24 | } |
| 25 | |
| 26 | #[derive(Clone, PartialEq)] |
| 27 | /// [`Value`]s parsed as hexadecimal, decimal, or octal numbers |
| 28 | pub enum Number { |
| 29 | Hex(u64), |
| 30 | Dec(i64), |
| 31 | Oct(u64), |
| 32 | } |
| 33 | |
| 34 | impl Debug for Number { |
| 35 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 36 | write!(f, "Num:<{self}>") |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | impl Display for Number { |
| 41 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 42 | match self { |
| 43 | Number::Hex(n) => write!(f, "0x{n:x}"), |
| 44 | Number::Oct(n) => write!(f, "0o{n:o}"), |
| 45 | Number::Dec(n) => write!(f, "{n}"), |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl FromStr for Number { |
| 51 | type Err = std::num::ParseIntError; |
| 52 | fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 53 | if let Some(s) = s.strip_prefix("0x") { |
| 54 | Ok(Number::Hex(u64::from_str_radix(s, 16)?)) |
| 55 | } else if let Some(s) = s.strip_prefix("0o") { |
| 56 | Ok(Number::Oct(u64::from_str_radix(s, 8)?)) |
| 57 | } else { |
| 58 | Ok(Number::Dec(i64::from_str(s)?)) |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | #[cfg(feature = "serde")] |
| 64 | impl Serialize for Number { |
| 65 | #[inline(always)] |
| 66 | fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { |
| 67 | match self { |
| 68 | Number::Dec(n) => s.serialize_i64(*n), |
| 69 | _ => s.collect_str(&self), |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | #[cfg(feature = "serde")] |
| 75 | impl<'de> Deserialize<'de> for Number { |
| 76 | fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { |
| 77 | d.deserialize_any(NumberVisitor) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | #[cfg(feature = "serde")] |
| 82 | struct NumberVisitor; |
| 83 | |
| 84 | #[cfg(feature = "serde")] |
| 85 | impl Visitor<'_> for NumberVisitor { |
| 86 | type Value = Number; |
| 87 | |
| 88 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 89 | formatter.write_str("a string or an integer") |
| 90 | } |
| 91 | |
| 92 | fn visit_i64<E: de::Error>(self, value: i64) -> Result<Self::Value, E> { |
| 93 | Ok(Number::Dec(value)) |
| 94 | } |
| 95 | |
| 96 | fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> { |
| 97 | Ok(Number::Dec(value as _)) |
| 98 | } |
| 99 | |
| 100 | fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> { |
| 101 | Number::from_str(value).map_err(E::custom) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | /// Representation of the value part of key/value pairs in [`Body`] |
| 106 | #[derive(Clone, PartialEq, Default)] |
| 107 | pub enum Value<'a> { |
| 108 | /// Empty value. |
| 109 | #[default] |
| 110 | Empty, |
| 111 | /// A byte string. |
| 112 | Str(&'a [u8], Quote), |
| 113 | /// Parsed number. |
| 114 | Number(Number), |
| 115 | /// A list of byte strings. |
| 116 | List(Vec<Value<'a>>), |
| 117 | /// A byte string that is not stored within the [`Body`]. Used for |
| 118 | /// decoded hex-strings. |
| 119 | Owned(Vec<u8>), |
| 120 | /// An internal key/value map. Used when [`Parser::split_msg`] is set. |
| 121 | Map(Vec<(Key, Value<'a>)>), |
| 122 | /// Non-contiguous byte string. Not produced by the parser. |
| 123 | Segments(Vec<&'a [u8]>), |
| 124 | StringifiedList(Vec<Value<'a>>), |
| 125 | /// Elements removed from ARGV lists. Not produced by the parser. |
| 126 | Skipped((usize, usize)), |
| 127 | /// A literal string. Not produced by the parser. |
| 128 | Literal(&'static str), |
| 129 | } |
| 130 | |
| 131 | impl Value<'_> { |
| 132 | pub fn str_len(&self) -> usize { |
| 133 | match self { |
| 134 | Value::Str(r, _) => r.len(), |
| 135 | Value::Segments(vr) => vr.iter().map(|r| r.len()).sum(), |
| 136 | _ => 0, |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | impl TryFrom<Value<'_>> for Vec<u8> { |
| 142 | type Error = &'static str; |
| 143 | fn try_from(v: Value) -> Result<Self, Self::Error> { |
| 144 | match v { |
| 145 | Value::Str(r, Quote::Braces) => { |
| 146 | let mut s = Vec::with_capacity(r.len() + 2); |
| 147 | s.push(b'{'); |
| 148 | s.extend(Vec::from(r)); |
| 149 | s.push(b'}'); |
| 150 | Ok(s) |
| 151 | } |
| 152 | Value::Str(r, _) => Ok(Vec::from(r)), |
| 153 | Value::Empty => Ok("".into()), |
| 154 | Value::Segments(ranges) => { |
| 155 | let l = ranges.iter().map(|r| r.len()).sum(); |
| 156 | let mut sb = Vec::with_capacity(l); |
| 157 | for r in ranges { |
| 158 | sb.extend(Vec::from(r)); |
| 159 | } |
| 160 | Ok(sb) |
| 161 | } |
| 162 | Value::Number(_) => Err("Won't convert number to string"), |
| 163 | Value::List(_) | Value::StringifiedList(_) => Err("Can't convert list to scalar"), |
| 164 | Value::Map(_) => Err("Can't convert map to scalar"), |
| 165 | Value::Skipped(_) => Err("Can't convert skipped to scalar"), |
| 166 | Value::Literal(s) => Ok(s.to_string().into()), |
| 167 | Value::Owned(v) => Ok(v), |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | impl TryFrom<Value<'_>> for Vec<Vec<u8>> { |
| 173 | type Error = &'static str; |
| 174 | fn try_from(value: Value) -> Result<Self, Self::Error> { |
| 175 | match value { |
| 176 | Value::List(values) | Value::StringifiedList(values) => { |
| 177 | let mut rv = Vec::with_capacity(values.len()); |
| 178 | for v in values { |
| 179 | let s = Vec::try_from(v)?; |
| 180 | rv.push(s); |
| 181 | } |
| 182 | Ok(rv) |
| 183 | } |
| 184 | _ => Err("not a list"), |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | impl Debug for Value<'_> { |
| 190 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 191 | match self { |
| 192 | Value::Str(r, _q) => write!(f, "Str:<{}>", String::from_utf8_lossy(r)), |
| 193 | Value::Empty => write!(f, "Empty"), |
| 194 | Value::Segments(segs) => { |
| 195 | write!(f, "Segments<")?; |
| 196 | for (n, r) in segs.iter().enumerate() { |
| 197 | if n > 0 { |
| 198 | write!(f, ", ")?; |
| 199 | } |
| 200 | write!(f, "{}", String::from_utf8_lossy(r))?; |
| 201 | } |
| 202 | write!(f, ">") |
| 203 | } |
| 204 | Value::List(vs) => { |
| 205 | write!(f, "List:<")?; |
| 206 | for (n, v) in vs.iter().enumerate() { |
| 207 | if n > 0 { |
| 208 | write!(f, ", ")?; |
| 209 | } |
| 210 | match v { |
| 211 | Value::Str(r, _) => { |
| 212 | write!(f, "{}", String::from_utf8_lossy(r))?; |
| 213 | } |
| 214 | Value::Segments(rs) => { |
| 215 | for r in rs { |
| 216 | write!(f, "{}", String::from_utf8_lossy(r))?; |
| 217 | } |
| 218 | } |
| 219 | Value::Number(n) => write!(f, "{n:?}")?, |
| 220 | Value::Skipped((elems, bytes)) => { |
| 221 | write!(f, "Skip<elems{elems} bytes={bytes}>")?; |
| 222 | } |
| 223 | Value::Empty => panic!("list can't contain empty value"), |
| 224 | Value::List(_) | Value::StringifiedList(_) => { |
| 225 | panic!("list can't contain list") |
| 226 | } |
| 227 | Value::Map(_) => panic!("list can't contain map"), |
| 228 | Value::Literal(v) => write!(f, "{v:?}")?, |
| 229 | Value::Owned(v) => write!(f, "{}", String::from_utf8_lossy(v))?, |
| 230 | } |
| 231 | } |
| 232 | write!(f, ">") |
| 233 | } |
| 234 | Value::StringifiedList(vs) => { |
| 235 | write!(f, "StringifiedList:<")?; |
| 236 | for (n, v) in vs.iter().enumerate() { |
| 237 | if n > 0 { |
| 238 | write!(f, " ")?; |
| 239 | } |
| 240 | match v { |
| 241 | Value::Str(r, _) => { |
| 242 | write!(f, "{}", String::from_utf8_lossy(r))?; |
| 243 | } |
| 244 | Value::Segments(rs) => { |
| 245 | for r in rs { |
| 246 | write!(f, "{}", String::from_utf8_lossy(r))?; |
| 247 | } |
| 248 | } |
| 249 | Value::Number(n) => write!(f, "{n:?}")?, |
| 250 | Value::Skipped((elems, bytes)) => { |
| 251 | write!(f, "Skip<elems={elems} bytes={bytes}>")?; |
| 252 | } |
| 253 | Value::Empty => panic!("list can't contain empty value"), |
| 254 | Value::List(_) | Value::StringifiedList(_) => { |
| 255 | panic!("list can't contain list") |
| 256 | } |
| 257 | Value::Map(_) => panic!("List can't contain mapr"), |
| 258 | Value::Literal(v) => write!(f, "{v}")?, |
| 259 | Value::Owned(v) => write!(f, "{}", String::from_utf8_lossy(v))?, |
| 260 | } |
| 261 | } |
| 262 | write!(f, ">") |
| 263 | } |
| 264 | Value::Map(vs) => { |
| 265 | write!(f, "Map:<")?; |
| 266 | for (n, (k, v)) in vs.iter().enumerate() { |
| 267 | if n > 0 { |
| 268 | write!(f, " ")?; |
| 269 | } |
| 270 | write!(f, "{k:?}={v:?}")?; |
| 271 | } |
| 272 | write!(f, ">") |
| 273 | } |
| 274 | Value::Number(n) => write!(f, "{n:?}"), |
| 275 | Value::Skipped((elems, bytes)) => write!(f, "Skip<elems={elems} bytes={bytes}>"), |
| 276 | Value::Literal(s) => write!(f, "{s:?}"), |
| 277 | Value::Owned(v) => write!(f, "{}", String::from_utf8_lossy(v)), |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | #[cfg(feature = "serde")] |
| 283 | impl Serialize for Value<'_> { |
| 284 | #[inline(always)] |
| 285 | fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { |
| 286 | match self { |
| 287 | Value::Empty => s.serialize_unit(), |
| 288 | Value::Str(r, Quote::Braces) => { |
| 289 | let mut buf = Vec::with_capacity(r.len() + 2); |
| 290 | buf.push(b'{'); |
| 291 | buf.extend(*r); |
| 292 | buf.push(b'}'); |
| 293 | s.serialize_bytes(&buf) |
| 294 | } |
| 295 | Value::Str(r, _) => s.serialize_bytes(r), |
| 296 | Value::Segments(segs) => { |
| 297 | let l = segs.iter().map(|r| r.len()).sum(); |
| 298 | let mut buf = Vec::with_capacity(l); |
| 299 | for seg in segs { |
| 300 | buf.extend(*seg); |
| 301 | } |
| 302 | s.serialize_bytes(&buf) |
| 303 | } |
| 304 | Value::List(vs) => s.collect_seq(vs.iter()), |
| 305 | Value::StringifiedList(vs) => { |
| 306 | let mut buf: Vec<u8> = Vec::with_capacity(vs.len()); |
| 307 | let mut first = true; |
| 308 | for v in vs { |
| 309 | if first { |
| 310 | first = false; |
| 311 | } else { |
| 312 | buf.push(b' '); |
| 313 | } |
| 314 | if let Value::Skipped((args, bytes)) = v { |
| 315 | buf.extend(format!("<<< Skipped: args={args}, bytes={bytes} >>>").bytes()); |
| 316 | } else { |
| 317 | buf.extend(v.clone().try_into().unwrap_or_else(|_| vec![b'x'])); |
| 318 | } |
| 319 | } |
| 320 | s.serialize_bytes(&buf) |
| 321 | } |
| 322 | Value::Number(n) => n.serialize(s), |
| 323 | Value::Map(vs) => s.collect_map(vs.iter().cloned()), |
| 324 | Value::Skipped((args, bytes)) => { |
| 325 | let mut map = s.serialize_map(Some(2))?; |
| 326 | map.serialize_entry("skipped_args", args)?; |
| 327 | map.serialize_entry("skipped_bytes", bytes)?; |
| 328 | map.end() |
| 329 | } |
| 330 | Value::Literal(v) => s.collect_str(v), |
| 331 | Value::Owned(v) => s.serialize_bytes(v), |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | #[cfg(feature = "serde")] |
| 337 | struct ValueVisitor; |
| 338 | |
| 339 | #[cfg(feature = "serde")] |
| 340 | impl<'de> Visitor<'de> for ValueVisitor { |
| 341 | type Value = Value<'de>; |
| 342 | |
| 343 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 344 | formatter.write_str("a string, integer, sequence, map, or null value") |
| 345 | } |
| 346 | |
| 347 | fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> { |
| 348 | Ok(Value::Empty) |
| 349 | } |
| 350 | |
| 351 | fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> { |
| 352 | Ok(Value::Empty) |
| 353 | } |
| 354 | |
| 355 | fn visit_i64<E: de::Error>(self, value: i64) -> Result<Self::Value, E> { |
| 356 | Ok(Value::Number(Number::Dec(value))) |
| 357 | } |
| 358 | |
| 359 | fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> { |
| 360 | Ok(Value::Number(Number::Dec(value as _))) |
| 361 | } |
| 362 | |
| 363 | fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> { |
| 364 | if let Ok(n) = Number::from_str(value) { |
| 365 | Ok(Value::Number(n)) |
| 366 | } else { |
| 367 | Ok(Value::from(value.to_string())) |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | fn visit_bytes<E: de::Error>(self, value: &[u8]) -> Result<Self::Value, E> { |
| 372 | Ok(Value::from(value.to_vec())) |
| 373 | } |
| 374 | |
| 375 | fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> { |
| 376 | let mut v = vec![]; |
| 377 | while let Some(elem) = seq.next_element()? { |
| 378 | v.push(elem); |
| 379 | } |
| 380 | Ok(Value::List(v)) |
| 381 | } |
| 382 | |
| 383 | fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { |
| 384 | let mut kv = vec![]; |
| 385 | while let Some((k, v)) = map.next_entry::<Key, Value>()? { |
| 386 | kv.push((k, v)); |
| 387 | } |
| 388 | Ok(Value::Map(kv)) |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | #[cfg(feature = "serde")] |
| 393 | impl<'de> Deserialize<'de> for Value<'de> { |
| 394 | #[inline(always)] |
| 395 | fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { |
| 396 | d.deserialize_any(ValueVisitor) |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | impl PartialEq<str> for Value<'_> { |
| 401 | fn eq(&self, other: &str) -> bool { |
| 402 | self == other.as_bytes() |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | impl PartialEq<[u8]> for Value<'_> { |
| 407 | fn eq(&self, other: &[u8]) -> bool { |
| 408 | match self { |
| 409 | Value::Empty => other.is_empty(), |
| 410 | Value::Str(r, _) => r == &other, |
| 411 | Value::Segments(segs) => { |
| 412 | let l = segs.iter().map(|s| s.len()).sum(); |
| 413 | let mut buf: Vec<u8> = Vec::with_capacity(l); |
| 414 | for s in segs { |
| 415 | buf.extend(*s); |
| 416 | } |
| 417 | buf == other |
| 418 | } |
| 419 | Value::Literal(s) => s.as_bytes() == other, |
| 420 | Value::Owned(v) => v == other, |
| 421 | Value::List(_) |
| 422 | | Value::StringifiedList(_) |
| 423 | | Value::Map(_) |
| 424 | | Value::Skipped(_) |
| 425 | | Value::Number(_) => false, |
| 426 | } |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | impl<'a> From<Option<Cow<'a, [u8]>>> for Value<'a> { |
| 431 | fn from(value: Option<Cow<'a, [u8]>>) -> Self { |
| 432 | match value { |
| 433 | Some(Cow::Borrowed(v)) => Value::Str(v, Quote::Double), |
| 434 | Some(Cow::Owned(v)) => Value::Owned(v), |
| 435 | None => Value::Empty, |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | impl<'a> From<&'a [u8]> for Value<'a> { |
| 441 | fn from(value: &'a [u8]) -> Self { |
| 442 | Value::Str(value, Quote::None) |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | impl<'a> From<&'a str> for Value<'a> { |
| 447 | fn from(value: &'a str) -> Self { |
| 448 | Self::from(value.as_bytes()) |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | impl From<Vec<u8>> for Value<'_> { |
| 453 | fn from(value: Vec<u8>) -> Self { |
| 454 | Value::Owned(value) |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | impl From<String> for Value<'_> { |
| 459 | fn from(value: String) -> Self { |
| 460 | Self::from(Vec::from(value)) |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | impl From<i64> for Value<'_> { |
| 465 | fn from(value: i64) -> Self { |
| 466 | Value::Number(Number::Dec(value)) |
| 467 | } |
| 468 | } |