Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fuzzing fixes #147

Merged
merged 3 commits into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ fn complex_ok() -> Result<(), EdnError> {
- [x] String `"\"string\""`
- [x] Numbers `"324352"`, `"3442.234"`, `"3/4"`
- [x] Keywords `:a`
- [x] Symbol `sym-bol-s` with a maximum of 200 chars
- [x] Symbol `sym-bol-s`
- [x] Vector `"[1 :2 \"d\"]"`
- [x] List `"(1 :2 \"d\")"`
- [x] Set `"#{1 2 3}"`
Expand Down
54 changes: 38 additions & 16 deletions src/deserialize/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ fn read_symbol(a: char, chars: &mut iter::Enumerate<core::str::Chars<'_>>) -> Re
let c_len = chars
.clone()
.enumerate()
.take_while(|&(i, c)| i <= 200 && !c.1.is_whitespace() && !DELIMITERS.contains(&c.1))
.take_while(|&(_, c)| !c.1.is_whitespace() && !DELIMITERS.contains(&c.1))
.count();
let i = chars
.clone()
Expand Down Expand Up @@ -205,11 +205,6 @@ fn num_den_from_slice(slice: impl AsRef<str>) -> Option<(i64, u64)> {
}

fn read_number(n: char, chars: &mut iter::Enumerate<core::str::Chars<'_>>) -> Result<Edn, Error> {
let i = chars
.clone()
.next()
.ok_or_else(|| Error::ParseEdn("Could not identify symbol index".to_string()))?
.0;
let c_len = chars
.clone()
.take_while(|(_, c)| !c.is_whitespace() && !DELIMITERS.contains(c))
Expand Down Expand Up @@ -286,22 +281,49 @@ fn read_number(n: char, chars: &mut iter::Enumerate<core::str::Chars<'_>>) -> Re
read_symbol(n.next().unwrap_or(' '), &mut n.enumerate())
}
_ => Err(Error::ParseEdn(format!(
"{number} could not be parsed at char count {i} with radix {radix}"
"{number} could not be parsed with radix {radix}"
))),
}
}

fn read_char(chars: &mut iter::Enumerate<core::str::Chars<'_>>) -> Result<Edn, Error> {
let i = chars
let element = chars
.clone()
.next()
.ok_or_else(|| Error::ParseEdn("Could not identify symbol index".to_string()))?
.0;
let c = chars.next();
c.ok_or(format!("{c:?} could not be parsed at char count {i}"))
.map(|c| c.1)
.map(Edn::Char)
.map_err(Error::ParseEdn)
.enumerate()
.take_while(|&(_, c)| !c.1.is_whitespace())
.map(|(_, c)| c.1)
.collect::<String>();

let mut consume_chars = |n| {
// We need to map/collect to consume out of the Enumerate
let _ = chars.take(n).map(|c| c.1).collect::<String>();
};

match element {
_ if element.starts_with("newline") => {
consume_chars(7);
Ok(Edn::Char('\n'))
}
_ if element.starts_with("return") => {
consume_chars(6);
Ok(Edn::Char('\r'))
}
_ if element.starts_with("tab") => {
consume_chars(3);
Ok(Edn::Char('\t'))
}
_ if element.starts_with("space") => {
consume_chars(5);
Ok(Edn::Char(' '))
}
c if !c.is_empty() => {
consume_chars(1);
Ok(Edn::Char(c.chars().next().unwrap()))
}
_ => Err(Error::ParseEdn(format!(
"{element:?} could not be parsed as a symbol"
))),
}
}

fn read_bool_or_nil(
Expand Down
12 changes: 11 additions & 1 deletion src/edn/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,16 @@ impl core::fmt::Display for Map {
}
}

fn char_to_edn(c: char) -> String {
match c {
'\n' => "\\newline".to_string(),
'\r' => "\\return".to_string(),
' ' => "\\space".to_string(),
'\t' => "\\tab".to_string(),
_ => format!("\\{c}"),
}
}

impl core::fmt::Display for Edn {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let text = match self {
Expand All @@ -246,7 +256,7 @@ impl core::fmt::Display for Edn {
Self::Double(d) => format!("{d}"),
Self::Rational((n, d)) => format!("{n}/{d}"),
Self::Bool(b) => format!("{b}"),
Self::Char(c) => format!("\\{c}"),
Self::Char(c) => char_to_edn(*c),
Self::Nil => String::from("nil"),
Self::Empty => String::new(),
Self::Tagged(tag, edn) => format!("#{tag} {edn}"),
Expand Down
50 changes: 48 additions & 2 deletions tests/deserialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ mod test {

#[test]
fn parse_number() {
assert_eq!(Edn::from_str("7").unwrap(), Edn::UInt(7));
assert_eq!(Edn::from_str("143").unwrap(), Edn::UInt(143));
assert_eq!(Edn::from_str("-435143").unwrap(), Edn::Int(-435_143));
assert_eq!(
Expand Down Expand Up @@ -683,6 +684,9 @@ mod test {
Edn::Symbol("your-hair!-is+_parsed?".to_string()),
]));
assert_eq!(edn, expected);

let lorem = "Lorem-ipsum-dolor-sit-amet-consectetur-adipiscing-elit-sed-do-eiusmod-tempor-incididunt-ut-labore-et-dolore-magna-aliqua.-Ut-enim-ad-minim-veniam-quis-nostrud-exercitation-ullamco-laboris-nisi-ut-aliquip-ex-ea-commodo-consequat.-Duis-aute-irure-dolor-in-reprehenderit-in-voluptate-velit-esse-cillum-dolore-eu-fugiat-nulla-pariatur.-Excepteur-sint-occaecat-cupidatat-non-proident-sunt-in-culpa-qui-officia-deserunt-mollit-anim-id-est-laborum".to_string();
assert_eq!(Edn::from_str(lorem.as_str()).unwrap(), Edn::Symbol(lorem));
}

#[test]
Expand Down Expand Up @@ -852,14 +856,14 @@ mod test {
assert_eq!(
Edn::from_str("42invalid123"),
Err(Error::ParseEdn(
"42invalid123 could not be parsed at char count 1 with radix 10".to_string()
"42invalid123 could not be parsed with radix 10".to_string()
))
);

assert_eq!(
Edn::from_str("0xxyz123"),
Err(Error::ParseEdn(
"xyz123 could not be parsed at char count 1 with radix 16".to_string()
"xyz123 could not be parsed with radix 16".to_string()
))
);

Expand Down Expand Up @@ -945,4 +949,46 @@ mod test {
))
);
}

#[test]
fn special_chars() {
let edn = "[\\space \\@ \\` \\tab \\return \\newline \\# \\% \\' \\g \\( \\* \\j \\+ \\, \\l \\- \\. \\/ \\0 \\2 \\r \\: \\; \\< \\\\ \\] \\} \\~ \\? \\_]";

assert_eq!(
Edn::from_str(edn).unwrap(),
Edn::Vector(Vector::new(vec![
Edn::Char(' '),
Edn::Char('@'),
Edn::Char('`'),
Edn::Char('\t'),
Edn::Char('\r'),
Edn::Char('\n'),
Edn::Char('#'),
Edn::Char('%'),
Edn::Char('\''),
Edn::Char('g'),
Edn::Char('('),
Edn::Char('*'),
Edn::Char('j'),
Edn::Char('+'),
Edn::Char(','),
Edn::Char('l'),
Edn::Char('-'),
Edn::Char('.'),
Edn::Char('/'),
Edn::Char('0'),
Edn::Char('2'),
Edn::Char('r'),
Edn::Char(':'),
Edn::Char(';'),
Edn::Char('<'),
Edn::Char('\\'),
Edn::Char(']'),
Edn::Char('}'),
Edn::Char('~'),
Edn::Char('?'),
Edn::Char('_'),
]))
);
}
}
3 changes: 3 additions & 0 deletions tests/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,8 @@ mod tests {
fn char_formatting() {
let edn = edn_to_string_unwrap("(\\b \\g \\m)");
assert_eq!(edn, "(\\b \\g \\m)");

assert_eq!(edn_to_string_unwrap("[\\space \\@ \\` \\tab \\return \\newline \\# \\% \\' \\g \\( \\* \\j \\+ \\, \\l \\- \\. \\/ \\0 \\2 \\r \\: \\; \\< \\\\ \\] \\} \\~ \\? \\_]"),
"[\\space \\@ \\` \\tab \\return \\newline \\# \\% \\' \\g \\( \\* \\j \\+ \\, \\l \\- \\. \\/ \\0 \\2 \\r \\: \\; \\< \\\\ \\] \\} \\~ \\? \\_]")
}
}