json_api/value/
stringify.rs

1use std::borrow::Cow;
2
3/// A specializable version of `std::string::ToString`.
4pub trait Stringify {
5    /// Returns the string representation of the give value as a byte vector.
6    ///
7    /// # Example
8    ///
9    /// ```
10    /// # extern crate json_api;
11    /// #
12    /// # use json_api::value::Stringify;
13    /// #
14    /// # fn main() {
15    /// use json_api::value::Stringify;
16    /// assert_eq!(25.to_bytes(), vec![50, 53]);
17    /// #
18    /// # }
19    /// ```
20    fn to_bytes(&self) -> Vec<u8>;
21
22    /// Returns the string representation of the given value.
23    ///
24    /// # Example
25    ///
26    /// ```
27    /// # extern crate json_api;
28    /// #
29    /// # use json_api::value::Stringify;
30    /// #
31    /// # fn main() {
32    /// use json_api::value::Stringify;
33    /// assert_eq!(25.stringify(), "25");
34    /// #
35    /// # }
36    /// ```
37    fn stringify(&self) -> String {
38        let bytes = self.to_bytes();
39        unsafe { String::from_utf8_unchecked(bytes) }
40    }
41}
42
43impl Stringify for String {
44    fn to_bytes(&self) -> Vec<u8> {
45        self.as_bytes().into()
46    }
47
48    fn stringify(&self) -> String {
49        self.to_owned()
50    }
51}
52
53impl<'a> Stringify for Cow<'a, str> {
54    fn to_bytes(&self) -> Vec<u8> {
55        self.as_bytes().into()
56    }
57
58    fn stringify(&self) -> String {
59        self[..].to_owned()
60    }
61}
62
63impl Stringify for str {
64    fn to_bytes(&self) -> Vec<u8> {
65        self.as_bytes().into()
66    }
67
68    fn stringify(&self) -> String {
69        self.to_owned()
70    }
71}
72
73macro_rules! impl_stringify_for_display {
74    { $($ty:ty),* $(,)* } => {
75        $(impl Stringify for $ty {
76            fn to_bytes(&self) -> Vec<u8> {
77                self.to_string().into_bytes()
78            }
79
80            fn stringify(&self) -> String {
81                self.to_string()
82            }
83        })*
84    }
85}
86
87impl_stringify_for_display!{
88    f32, f64,
89    i8, i16, i32, i64,
90    u8, u16, u32, u64,
91}