Skip to content

Commit

Permalink
Add AsciiSet::EMPTY and impl ops::Add for AsciiSet
Browse files Browse the repository at this point in the history
In RFCs, the sets of characters to percent-encode are often defined as
the union of multiple sets. This change adds an `EMPTY` constant to
`AsciiSet` and implements the `Add` trait for `AsciiSet` so that sets
can be combined with the `+` operator.

AsciiSet now derives `Debug`, `PartialEq`, and `Eq` so that it can be
used in tests.
  • Loading branch information
joshka committed Sep 19, 2024
1 parent 9404ff5 commit 360b17e
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion percent_encoding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ use alloc::{
string::String,
vec::Vec,
};
use core::{fmt, mem, slice, str};
use core::{fmt, mem, ops, slice, str};

/// Represents a set of characters or bytes in the ASCII range.
///
Expand All @@ -66,6 +66,7 @@ use core::{fmt, mem, slice, str};
/// /// https://url.spec.whatwg.org/#fragment-percent-encode-set
/// const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct AsciiSet {
mask: [Chunk; ASCII_RANGE_LEN / BITS_PER_CHUNK],
}
Expand All @@ -77,6 +78,11 @@ const ASCII_RANGE_LEN: usize = 0x80;
const BITS_PER_CHUNK: usize = 8 * mem::size_of::<Chunk>();

impl AsciiSet {
/// An empty set.
pub const EMPTY: AsciiSet = AsciiSet {
mask: [0; ASCII_RANGE_LEN / BITS_PER_CHUNK],
};

/// Called with UTF-8 bytes rather than code points.
/// Not used for non-ASCII bytes.
const fn contains(&self, byte: u8) -> bool {
Expand All @@ -102,6 +108,18 @@ impl AsciiSet {
}
}

impl ops::Add for AsciiSet {
type Output = Self;

fn add(self, other: Self) -> Self {
let mut mask = self.mask.clone();
for i in 0..mask.len() {
mask[i] |= other.mask[i];
}
AsciiSet { mask }
}
}

/// The set of 0x00 to 0x1F (C0 controls), and 0x7F (DEL).
///
/// Note that this includes the newline and tab characters, but not the space 0x20.
Expand Down Expand Up @@ -478,3 +496,16 @@ fn decode_utf8_lossy(input: Cow<'_, [u8]>) -> Cow<'_, str> {
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn add() {
let left = AsciiSet::EMPTY.add(b'A');
let right = AsciiSet::EMPTY.add(b'B');
let expected = AsciiSet::EMPTY.add(b'A').add(b'B');
assert_eq!(left + right, expected);
}
}

0 comments on commit 360b17e

Please sign in to comment.