use serde::{
Serialize,
ser::{self, SerializeMap, SerializeSeq, SerializeStruct, SerializeTuple},
};
use std::fmt::{self, Write};
use url::form_urlencoded::byte_serialize;
#[derive(Debug)]
pub(super) enum Error {
Limit,
Invalid,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Limit => "URL-encoded fields exceed their allowance",
Self::Invalid => "unsupported URL-encoded fields",
})
}
}
impl std::error::Error for Error {}
impl ser::Error for Error {
fn custom<T: fmt::Display>(_error: T) -> Self {
Self::Invalid
}
}
pub(super) fn encode(value: &(impl Serialize + ?Sized), limit: usize) -> Result<String, Error> {
let mut output = Output::new(limit);
let result = value.serialize(Encoder::Form(&mut output));
if output.exceeded {
return Err(Error::Limit);
}
result.map(|()| output.text)
}
struct Output {
text: String,
limit: usize,
exceeded: bool,
}
impl Output {
fn new(limit: usize) -> Self {
Self {
text: String::new(),
limit,
exceeded: false,
}
}
fn remaining(&self) -> usize {
self.limit - self.text.len()
}
fn check(&mut self, length: usize) -> Result<(), Error> {
if self.exceeded || length > self.remaining() {
self.exceeded = true;
return Err(Error::Limit);
}
Ok(())
}
fn append(&mut self, encoded: &str) -> Result<(), Error> {
self.check(encoded.len())?;
self.text.push_str(encoded);
Ok(())
}
fn encode_text(&mut self, text: &str) -> Result<(), Error> {
self.check(text.len())?;
byte_serialize(text.as_bytes()).try_for_each(|encoded| self.append(encoded))
}
fn encode_bytes(&mut self, bytes: &[u8]) -> Result<(), Error> {
self.check(bytes.len())?;
let text = std::str::from_utf8(bytes).map_err(|_| Error::Invalid)?;
self.encode_text(text)
}
fn key(&self, key: &(impl Serialize + ?Sized)) -> Result<Key<'static>, Error> {
let mut name = None;
let separators = 1 + usize::from(!self.text.is_empty());
key.serialize(Encoder::Key {
name: &mut name,
limit: self.remaining().saturating_sub(separators),
})?;
name.ok_or(Error::Invalid)
}
fn pair(
&mut self,
key: &Key<'_>,
value: impl FnOnce(&mut Self) -> Result<(), Error>,
) -> Result<(), Error> {
let original_len = self.text.len();
let result = self.write_pair(key, value);
if result.is_err() {
self.text.truncate(original_len);
}
result
}
fn write_pair(
&mut self,
key: &Key<'_>,
value: impl FnOnce(&mut Self) -> Result<(), Error>,
) -> Result<(), Error> {
if !self.text.is_empty() {
self.append("&")?;
}
match key {
Key::Raw(text) => self.encode_text(text)?,
Key::Encoded(text) => self.append(text)?,
Key::TooLarge => {
self.exceeded = true;
return Err(Error::Limit);
}
}
self.append("=")?;
value(self)
}
}
impl fmt::Write for Output {
fn write_str(&mut self, text: &str) -> fmt::Result {
self.encode_text(text).map_err(|_| fmt::Error)
}
}
enum Key<'a> {
Raw(&'a str),
Encoded(String),
TooLarge,
}
enum Encoder<'a> {
Form(&'a mut Output),
Pair(&'a mut Output),
Key {
name: &'a mut Option<Key<'static>>,
limit: usize,
},
Value {
output: &'a mut Output,
key: &'a Key<'a>,
},
}
impl Encoder<'_> {
fn write(self, write: impl FnOnce(&mut Output) -> Result<(), Error>) -> Result<(), Error> {
match self {
Self::Key { name, limit } => {
let mut output = Output::new(limit);
*name = Some(match write(&mut output) {
Ok(()) => Key::Encoded(output.text),
Err(Error::Limit) => Key::TooLarge,
Err(error) => return Err(error),
});
Ok(())
}
Self::Value { output, key } => output.pair(key, write),
Self::Form(_) | Self::Pair(_) => Err(Error::Invalid),
}
}
fn floating(self, number: impl Serialize) -> Result<(), Error> {
let encoded = serde_urlencoded::to_string([("", number)]).map_err(|_| Error::Invalid)?;
let value = encoded.strip_prefix('=').ok_or(Error::Invalid)?;
self.write(|output| output.append(value))
}
}
macro_rules! integer_methods {
($($method:ident($type:ty)),+ $(,)?) => {
$(
fn $method(self, value: $type) -> Result<(), Error> {
self.serialize_str(&value.to_string())
}
)+
};
}
impl<'a> ser::Serializer for Encoder<'a> {
type Ok = ();
type Error = Error;
type SerializeSeq = &'a mut Output;
type SerializeTuple = Tuple<'a>;
type SerializeTupleStruct = ser::Impossible<(), Error>;
type SerializeTupleVariant = ser::Impossible<(), Error>;
type SerializeMap = Map<'a>;
type SerializeStruct = &'a mut Output;
type SerializeStructVariant = ser::Impossible<(), Error>;
integer_methods!(
serialize_i8(i8),
serialize_i16(i16),
serialize_i32(i32),
serialize_i64(i64),
serialize_i128(i128),
serialize_u8(u8),
serialize_u16(u16),
serialize_u32(u32),
serialize_u64(u64),
serialize_u128(u128),
);
fn serialize_bool(self, value: bool) -> Result<(), Error> {
self.serialize_str(if value { "true" } else { "false" })
}
fn serialize_f32(self, value: f32) -> Result<(), Error> {
self.floating(value)
}
fn serialize_f64(self, value: f64) -> Result<(), Error> {
self.floating(value)
}
fn serialize_char(self, value: char) -> Result<(), Error> {
self.serialize_str(value.encode_utf8(&mut [0; 4]))
}
fn serialize_str(self, value: &str) -> Result<(), Error> {
self.write(|output| output.encode_text(value))
}
fn serialize_bytes(self, value: &[u8]) -> Result<(), Error> {
self.write(|output| output.encode_bytes(value))
}
fn collect_str<T: fmt::Display + ?Sized>(self, value: &T) -> Result<(), Error> {
self.write(|output| {
let result = write!(output, "{value}");
if output.exceeded {
return Err(Error::Limit);
}
result.map_err(|_| Error::Invalid)
})
}
fn serialize_none(self) -> Result<(), Error> {
match self {
Self::Key { .. } => Err(Error::Invalid),
_ => Ok(()),
}
}
fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<(), Error> {
match self {
Self::Key { .. } => Err(Error::Invalid),
_ => value.serialize(self),
}
}
fn serialize_unit(self) -> Result<(), Error> {
match self {
Self::Form(_) => Ok(()),
_ => Err(Error::Invalid),
}
}
fn serialize_unit_struct(self, name: &'static str) -> Result<(), Error> {
match self {
Self::Form(_) => Ok(()),
_ => self.serialize_str(name),
}
}
fn serialize_unit_variant(
self,
_name: &'static str,
_index: u32,
variant: &'static str,
) -> Result<(), Error> {
self.serialize_str(variant)
}
fn serialize_newtype_struct<T: Serialize + ?Sized>(
self,
_name: &'static str,
value: &T,
) -> Result<(), Error> {
value.serialize(self)
}
fn serialize_newtype_variant<T: Serialize + ?Sized>(
self,
_name: &'static str,
_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<(), Error> {
Err(Error::Invalid)
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
match self {
Self::Form(output) => Ok(output),
_ => Err(Error::Invalid),
}
}
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Error> {
match self {
Self::Form(output) => Ok(Tuple::Form(output)),
Self::Pair(output) if len == 2 => Ok(Tuple::Pair(output, PairField::Key)),
_ => Err(Error::Invalid),
}
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct, Error> {
Err(Error::Invalid)
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Error> {
Err(Error::Invalid)
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> {
match self {
Self::Form(output) => Ok(Map { output, key: None }),
_ => Err(Error::Invalid),
}
}
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
self.serialize_seq(None)
}
fn serialize_struct_variant(
self,
_name: &'static str,
_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Error> {
Err(Error::Invalid)
}
}
impl SerializeSeq for &mut Output {
type Ok = ();
type Error = Error;
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
value.serialize(Encoder::Pair(self))
}
fn end(self) -> Result<(), Error> {
Ok(())
}
}
impl SerializeStruct for &mut Output {
type Ok = ();
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), Error> {
value.serialize(Encoder::Value {
output: self,
key: &Key::Raw(key),
})
}
fn end(self) -> Result<(), Error> {
Ok(())
}
}
enum Tuple<'a> {
Form(&'a mut Output),
Pair(&'a mut Output, PairField),
}
enum PairField {
Key,
Value(Key<'static>),
Done,
}
impl SerializeTuple for Tuple<'_> {
type Ok = ();
type Error = Error;
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
match self {
Self::Form(output) => value.serialize(Encoder::Pair(output)),
Self::Pair(output, part) => {
*part = match part {
PairField::Key => PairField::Value(output.key(value)?),
PairField::Value(key) => {
value.serialize(Encoder::Value { output, key })?;
PairField::Done
}
PairField::Done => return Err(Error::Invalid),
};
Ok(())
}
}
}
fn end(self) -> Result<(), Error> {
match self {
Self::Form(_) | Self::Pair(_, PairField::Done) => Ok(()),
_ => Err(Error::Invalid),
}
}
}
struct Map<'a> {
output: &'a mut Output,
key: Option<Key<'static>>,
}
impl SerializeMap for Map<'_> {
type Ok = ();
type Error = Error;
fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<(), Error> {
self.key = Some(self.output.key(key)?);
Ok(())
}
fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
let key = self.key.as_ref().ok_or(Error::Invalid)?;
value.serialize(Encoder::Value {
output: self.output,
key,
})?;
self.key = None;
Ok(())
}
fn end(self) -> Result<(), Error> {
Ok(())
}
}
#[cfg(test)]
#[path = "form_test.rs"]
mod tests;