serde_querystring/parsers/duplicate.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
use std::{borrow::Cow, collections::BTreeMap};
use crate::decode::{parse_bytes, Reference};
struct Key<'a>(&'a [u8]);
impl<'a> Key<'a> {
fn parse(slice: &'a [u8]) -> Self {
let mut index = 0;
while index < slice.len() {
match slice[index] {
b'&' | b'=' => break,
_ => index += 1,
}
}
Self(&slice[..index])
}
fn len(&self) -> usize {
self.0.len()
}
fn decode<'s>(&self, scratch: &'s mut Vec<u8>) -> Reference<'a, 's, [u8]> {
parse_bytes(self.0, scratch)
}
}
struct Value<'a>(&'a [u8]);
impl<'a> Value<'a> {
fn parse(slice: &'a [u8]) -> Option<Self> {
if *slice.get(0)? == b'&' {
return None;
}
let mut index = 1;
while index < slice.len() {
match slice[index] {
b'&' => break,
_ => index += 1,
}
}
Some(Self(&slice[1..index]))
}
fn len(&self) -> usize {
self.0.len()
}
fn decode<'s>(&self, scratch: &'s mut Vec<u8>) -> Reference<'a, 's, [u8]> {
parse_bytes(self.0, scratch)
}
fn slice(&self) -> &'a [u8] {
self.0
}
}
struct Pair<'a>(Key<'a>, Option<Value<'a>>);
impl<'a> Pair<'a> {
fn parse(slice: &'a [u8]) -> Self {
let key = Key::parse(slice);
let value = Value::parse(&slice[key.len()..]);
Self(key, value)
}
/// It report how many chars we should move forward after this pair, to see a new one.
/// It might report invalid result at the end of the slice,
/// so calling site should check the validity of resulting index
fn skip_len(&self) -> usize {
match &self.1 {
Some(v) => self.0.len() + v.len() + 2,
None => self.0.len() + 1,
}
}
}
/// A querystring parser with support for vectors/lists of values by repeating keys.
///
/// # Note
/// Keys are decoded when calling the `parse` method, but values are lazily decoded when you
/// call the `value` method for their keys.
///
/// # Example
/// ```rust
///# use std::borrow::Cow;
/// use serde_querystring::DuplicateQS;
///
/// let slice = b"foo=bar&foo=baz&foo&foo=";
///
/// let parser = DuplicateQS::parse(slice);
///
/// // `values` method returns ALL the values as a vector.
/// assert_eq!(
/// parser.values(b"foo"),
/// Some(vec![
/// Some("bar".as_bytes().into()),
/// Some("baz".as_bytes().into()),
/// None,
/// Some("".as_bytes().into())
/// ])
///);
///
/// // `value` method returns the last seen value
/// assert_eq!(parser.value(b"foo"), Some(Some("".as_bytes().into())));
/// ```
pub struct DuplicateQS<'a> {
pairs: BTreeMap<Cow<'a, [u8]>, Vec<Pair<'a>>>,
}
impl<'a> DuplicateQS<'a> {
/// Parse a slice of bytes into a `DuplicateQS`
pub fn parse(slice: &'a [u8]) -> Self {
let mut pairs: BTreeMap<Cow<'a, [u8]>, Vec<Pair<'a>>> = BTreeMap::new();
let mut scratch = Vec::new();
let mut index = 0;
while index < slice.len() {
let pair = Pair::parse(&slice[index..]);
index += pair.skip_len();
let decoded_key = pair.0.decode(&mut scratch);
if let Some(values) = pairs.get_mut(decoded_key.as_ref()) {
values.push(pair);
} else {
pairs.insert(decoded_key.into_cow(), vec![pair]);
}
}
Self { pairs }
}
/// Returns a vector containing all the keys in querystring.
pub fn keys(&self) -> Vec<&Cow<'a, [u8]>> {
self.pairs.keys().collect()
}
/// Returns a vector containing all the values assigned to a key.
///
/// It returns None if the **key doesn't exist** in the querystring,
/// the resulting vector may contain None if the **key had assignments without a value**, ex `&key&`
///
/// # Note
/// Percent decoding the value is done on-the-fly **every time** this function is called.
pub fn values(&self, key: &'a [u8]) -> Option<Vec<Option<Cow<'a, [u8]>>>> {
let mut scratch = Vec::new();
Some(
self.pairs
.get(key)?
.iter()
.map(|p| p.1.as_ref().map(|v| v.decode(&mut scratch).into_cow()))
.collect(),
)
}
/// Returns the last value assigned to a key.
///
/// It returns `None` if the **key doesn't exist** in the querystring,
/// and returns `Some(None)` if the last assignment to a **key doesn't have a value**, ex `"&key&"`
///
/// # Note
/// Percent decoding the value is done on-the-fly **every time** this function is called.
pub fn value(&self, key: &'a [u8]) -> Option<Option<Cow<'a, [u8]>>> {
let mut scratch = Vec::new();
self.pairs
.get(key)?
.iter()
.last()
.map(|p| p.1.as_ref().map(|v| v.decode(&mut scratch).into_cow()))
}
}
#[cfg(feature = "serde")]
mod de {
use _serde::Deserialize;
use crate::de::{
Error, ErrorKind, QSDeserializer,
__implementors::{DecodedSlice, IntoRawSlices, RawSlice},
};
use super::DuplicateQS;
impl<'a> DuplicateQS<'a> {
/// Deserialize the parsed slice into T
pub fn deserialize<T: Deserialize<'a>>(self) -> Result<T, Error> {
T::deserialize(QSDeserializer::new(self.into_iter()))
}
pub(crate) fn into_iter(
self,
) -> impl Iterator<
Item = (
DecodedSlice<'a>,
DuplicateValueIter<impl Iterator<Item = RawSlice<'a>>>,
),
> {
self.pairs.into_iter().map(|(key, pairs)| {
(
DecodedSlice(key),
DuplicateValueIter(
pairs
.into_iter()
.map(|v| RawSlice(v.1.map(|v| v.slice()).unwrap_or_default())),
),
)
})
}
}
pub(crate) struct DuplicateValueIter<I>(I);
impl<'a, I> IntoRawSlices<'a> for DuplicateValueIter<I>
where
I: Iterator<Item = RawSlice<'a>>,
{
type SizedIterator = I;
type UnSizedIterator = I;
#[inline]
fn into_sized_iterator(self, size: usize) -> Result<I, Error> {
if self.0.size_hint().0 == size {
Ok(self.0)
} else {
Err(Error::new(ErrorKind::InvalidLength))
}
}
#[inline]
fn into_unsized_iterator(self) -> I {
self.0
}
#[inline]
fn into_single_slice(self) -> RawSlice<'a> {
self.0
.last()
.expect("Iterator has at least one value in it")
}
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use super::DuplicateQS;
#[test]
fn parse_pair() {
let slice = b"key=value";
let parser = DuplicateQS::parse(slice);
assert_eq!(parser.keys(), vec![&Cow::Borrowed(b"key")]);
assert_eq!(
parser.values(b"key"),
Some(vec![Some(Cow::Borrowed("value".as_bytes()))])
);
assert_eq!(
parser.value(b"key"),
Some(Some(Cow::Borrowed("value".as_bytes())))
);
}
#[test]
fn parse_multiple_pairs() {
let slice = b"foo=bar&foobar=baz&qux=box";
let parser = DuplicateQS::parse(slice);
assert_eq!(
parser.values(b"foo"),
Some(vec![Some("bar".as_bytes().into())])
);
assert_eq!(
parser.values(b"foobar"),
Some(vec![Some("baz".as_bytes().into())])
);
assert_eq!(
parser.values(b"qux"),
Some(vec![Some("box".as_bytes().into())])
);
}
#[test]
fn parse_no_value() {
let slice = b"foo&foobar=";
let parser = DuplicateQS::parse(slice);
assert_eq!(parser.value(b"key"), None);
assert_eq!(parser.values(b"key"), None);
assert_eq!(parser.value(b"foo"), Some(None));
assert_eq!(parser.values(b"foo"), Some(vec![None]));
assert_eq!(
parser.values(b"foobar"),
Some(vec![Some("".as_bytes().into())])
);
assert_eq!(parser.value(b"foobar"), Some(Some("".as_bytes().into())));
}
#[test]
fn parse_multiple_values() {
let slice = b"foo=bar&foo=baz&foo=foobar&foo&foo=";
let parser = DuplicateQS::parse(slice);
assert_eq!(
parser.values(b"foo"),
Some(vec![
Some("bar".as_bytes().into()),
Some("baz".as_bytes().into()),
Some("foobar".as_bytes().into()),
None,
Some("".as_bytes().into())
])
);
assert_eq!(parser.value(b"foo"), Some(Some("".as_bytes().into())));
}
}