Skip to content

Commit

Permalink
Fix FromMeta for chars (#126)
Browse files Browse the repository at this point in the history
* Fix FromMeta for char
* Get rid of unwrap in from_string impl for char

Co-authored-by: Veetaha <[email protected]>
Co-authored-by: Oleksandr Kryvytskyi <[email protected]>
  • Loading branch information
3 people authored Apr 8, 2021
1 parent 7152c53 commit 3b03d92
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions core/src/from_meta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ use {Error, Result};
/// * As a boolean literal, e.g. `foo = true`.
/// * As a string literal, e.g. `foo = "true"`.
///
/// ## char
/// * As a char literal, e.g. `foo = '#'`.
/// * As a string literal consisting of a single character, e.g. `foo = "#"`.
///
/// ## String
/// * As a string literal, e.g. `foo = "hello"`.
/// * As a raw string literal, e.g. `foo = r#"hello "world""#`.
Expand Down Expand Up @@ -98,6 +102,7 @@ pub trait FromMeta: Sized {
(match *value {
Lit::Bool(ref b) => Self::from_bool(b.value),
Lit::Str(ref s) => Self::from_string(&s.value()),
Lit::Char(ref ch) => Self::from_char(ch.value()),
_ => Err(Error::unexpected_lit_type(value)),
})
.map_err(|e| e.with_span(value))
Expand Down Expand Up @@ -152,6 +157,24 @@ impl FromMeta for AtomicBool {
}
}

impl FromMeta for char {
fn from_char(value: char) -> Result<Self> {
Ok(value)
}

fn from_string(s: &str) -> Result<Self> {
let mut chars = s.chars();
let char1 = chars.next();
let char2 = chars.next();

if let (Some(char), None) = (char1, char2) {
Ok(char)
} else {
Err(Error::unexpected_type("string"))
}
}
}

impl FromMeta for String {
fn from_string(s: &str) -> Result<Self> {
Ok(s.to_string())
Expand Down Expand Up @@ -595,6 +618,15 @@ mod tests {
assert_eq!(fm::<bool>(quote!(ignore = "false")), false);
}

#[test]
fn char_succeeds() {
// char literal
assert_eq!(fm::<char>(quote!(ignore = '😬')), '😬');

// string literal
assert_eq!(fm::<char>(quote!(ignore = "😬")), '😬');
}

#[test]
fn string_succeeds() {
// cooked form
Expand Down

0 comments on commit 3b03d92

Please sign in to comment.