1use std::borrow::Cow;
2
3use crate::json::DecodeError;
4
5use super::{Ctx, FromText};
6
7impl<'a> FromText<'a> for &'a str {
8 fn from_text(ctx: &mut Ctx<'a>, text: &str) -> Result<Self, &'static DecodeError> {
9 if let Some(text) = ctx.try_extend_lifetime(text) {
10 Ok(text)
11 } else {
12 Err(&DecodeError {
13 message: "Text does not extend lifetime",
14 })
15 }
16 }
17}
18
19static INVALID_NUMBER: DecodeError = DecodeError {
20 message: "Invalid Number",
21};
22
23macro_rules! impl_from_text_from_str {
24 ($($ty:ty),*) => {
25 $(
26 impl<'a> FromText<'a> for $ty {
27 fn from_text(_ctx: &mut Ctx<'a>, text: &str) -> Result<Self, &'static DecodeError> {
28 match text.parse::<$ty>() {
29 Ok(v) => Ok(v),
30 Err(_) => Err(&INVALID_NUMBER),
31 }
32 }
33 })*
34 };
35}
36
37impl_from_text_from_str! {
38 u8,u16,u32,u64,u128,usize,
39 i8,i16,i32,i64,i128,isize,
40 f32,f64
41}
42
43impl<'a> FromText<'a> for char {
44 fn from_text(_ctx: &mut Ctx<'a>, text: &str) -> Result<Self, &'static DecodeError> {
45 match text.parse::<char>() {
46 Ok(v) => Ok(v),
47 Err(_) => Err(&DecodeError {
48 message: "Invalid char",
49 }),
50 }
51 }
52}
53
54impl<'a> FromText<'a> for Cow<'a, str> {
55 fn from_text(ctx: &mut Ctx<'a>, text: &str) -> Result<Self, &'static DecodeError> {
56 if let Some(text) = ctx.try_extend_lifetime(text) {
57 Ok(Cow::Borrowed(text))
58 } else {
59 Ok(Cow::Owned(text.into()))
60 }
61 }
62}
63
64impl<'a> FromText<'a> for bool {
65 fn from_text(_ctx: &mut Ctx<'a>, text: &str) -> Result<Self, &'static DecodeError> {
66 if text.eq_ignore_ascii_case("true") || text == "1" {
67 Ok(true)
68 } else if text.eq_ignore_ascii_case("false") || text == "0" {
69 return Ok(false);
70 } else {
71 return Err(&DecodeError {
72 message: "Invalid Boolean",
73 });
74 }
75 }
76}
77
78impl<'a> FromText<'a> for Box<str> {
79 fn from_text(_ctx: &mut Ctx<'a>, text: &str) -> Result<Self, &'static DecodeError> {
80 Ok(text.into())
81 }
82}
83
84impl<'a> FromText<'a> for String {
85 fn from_text(_ctx: &mut Ctx<'a>, text: &str) -> Result<Self, &'static DecodeError> {
86 Ok(text.into())
87 }
88}