use hurl_core::reader::Reader;
use super::{ParseError, ParseErrorKind, ParseResult};
pub fn expect_str(s: &str, reader: &mut Reader) -> ParseResult<()> {
let start = reader.cursor();
if reader.is_eof() {
let kind = ParseErrorKind::Expecting(s.to_string());
let error = ParseError::new(start.pos, kind);
return Err(error);
}
for c in s.chars() {
match reader.read() {
None => {
let kind = ParseErrorKind::Expecting(s.to_string());
let error = ParseError::new(start.pos, kind);
return Err(error);
}
Some(x) => {
if x != c {
let kind = ParseErrorKind::Expecting(s.to_string());
let error = ParseError::new(start.pos, kind);
return Err(error);
} else {
continue;
}
}
}
}
Ok(())
}
pub fn match_str(s: &str, reader: &mut Reader) -> bool {
let initial_state = reader.cursor();
if expect_str(s, reader).is_ok() {
true
} else {
reader.seek(initial_state);
false
}
}
pub fn skip_whitespace(reader: &mut Reader) {
while let Some(c) = reader.peek() {
if c == ' ' || c == '\t' || c == '\n' || c == '\r' {
reader.read();
} else {
break;
}
}
}
#[cfg(test)]
mod tests {
use hurl_core::reader::{CharPos, Pos};
use super::*;
#[test]
fn test_expect_str() {
let mut reader = Reader::new("hello");
assert_eq!(expect_str("hello", &mut reader), Ok(()));
assert_eq!(reader.cursor().index, CharPos(5));
let mut reader = Reader::new("hello ");
assert_eq!(expect_str("hello", &mut reader), Ok(()));
assert_eq!(reader.cursor().index, CharPos(5));
let mut reader = Reader::new("");
let error = expect_str("hello", &mut reader).err().unwrap();
assert_eq!(
error,
ParseError::new(
Pos { line: 1, column: 1 },
ParseErrorKind::Expecting("hello".to_string())
)
);
assert_eq!(reader.cursor().index, CharPos(0));
let mut reader = Reader::new("hi");
let error = expect_str("hello", &mut reader).err().unwrap();
assert_eq!(
error,
ParseError::new(
Pos { line: 1, column: 1 },
ParseErrorKind::Expecting("hello".to_string())
)
);
assert_eq!(reader.cursor().index, CharPos(2));
let mut reader = Reader::new("he");
let error = expect_str("hello", &mut reader).err().unwrap();
assert_eq!(
error,
ParseError::new(
Pos { line: 1, column: 1 },
ParseErrorKind::Expecting("hello".to_string())
)
);
assert_eq!(reader.cursor().index, CharPos(2));
}
}