use core::fmt; use crate::{ Buffer, ParseError, err::{perr, ParseErrorKind::*}, escape::unescape, }; /// A (single) byte literal, e.g. `b'k'` or `b'!'`. /// /// See [the reference][ref] for more information. /// /// [ref]: https://doc.rust-lang.org/reference/tokens.html#byte-literals #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ByteLit { raw: B, value: u8, } impl ByteLit { /// Parses the input as a byte literal. Returns an error if the input is /// invalid or represents a different kind of literal. pub fn parse(input: B) -> Result { if input.is_empty() { return Err(perr(None, Empty)); } if !input.starts_with("b'") { return Err(perr(None, InvalidByteLiteralStart)); } let value = parse_impl(&input)?; Ok(Self { raw: input, value }) } /// Returns the byte value that this literal represents. pub fn value(&self) -> u8 { self.value } /// Returns the raw input that was passed to `parse`. pub fn raw_input(&self) -> &str { &self.raw } /// Returns the raw input that was passed to `parse`, potentially owned. pub fn into_raw_input(self) -> B { self.raw } } impl ByteLit<&str> { /// Makes a copy of the underlying buffer and returns the owned version of /// `Self`. pub fn to_owned(&self) -> ByteLit { ByteLit { raw: self.raw.to_owned(), value: self.value, } } } impl fmt::Display for ByteLit { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad(&self.raw) } } /// Precondition: must start with `b'`. #[inline(never)] pub(crate) fn parse_impl(input: &str) -> Result { if input.len() == 2 { return Err(perr(None, UnterminatedByteLiteral)); } if *input.as_bytes().last().unwrap() != b'\'' { return Err(perr(None, UnterminatedByteLiteral)); } let inner = &input[2..input.len() - 1]; let first = inner.as_bytes().get(0).ok_or(perr(None, EmptyByteLiteral))?; let (c, len) = match first { b'\'' => return Err(perr(2, UnescapedSingleQuote)), b'\n' | b'\t' | b'\r' => return Err(perr(2, UnescapedSpecialWhitespace)), b'\\' => unescape::(inner, 2)?, other if other.is_ascii() => (*other, 1), _ => return Err(perr(2, NonAsciiInByteLiteral)), }; let rest = &inner[len..]; if !rest.is_empty() { return Err(perr(len + 2..input.len() - 1, OverlongByteLiteral)); } Ok(c) } #[cfg(test)] mod tests;