pkce_std/check/ascii.rs
1//! Checking strings to be ASCII.
2
3use const_macros::const_early;
4
5#[cfg(feature = "diagnostics")]
6use miette::Diagnostic;
7
8use thiserror::Error;
9
10/// Represents errors that occur when non-ASCII strings are encountered.
11#[derive(Debug, Error)]
12#[error("non-ascii string encountered")]
13#[cfg_attr(
14 feature = "diagnostics",
15 derive(Diagnostic),
16 diagnostic(code(pkce_std::check::ascii), help("ensure the string is ASCII"))
17)]
18pub struct Error;
19
20/// Checks that the given string is ASCII.
21///
22/// # Examples
23///
24/// ```
25/// use pkce_std::check::ascii::check_str;
26///
27/// let string = "<3";
28/// let unicode = "❤️";
29///
30/// assert!(check_str(string).is_ok());
31/// assert!(check_str(unicode).is_err());
32/// ```
33///
34/// # Errors
35///
36/// Returns [`struct@Error`] if the string is non-ASCII.
37pub const fn check_str(string: &str) -> Result<(), Error> {
38 const_early!(!string.is_ascii() => Error);
39
40 Ok(())
41}
42
43/// Similar to [`check_str`], except it is generic over [`AsRef<str>`].
44///
45/// # Errors
46///
47/// Any [`struct@Error`] returned from [`check_str`] is propagated.
48pub fn check<S: AsRef<str>>(string: S) -> Result<(), Error> {
49 check_str(string.as_ref())
50}