json_write/
key.rs

1#[cfg(feature = "alloc")]
2use alloc::borrow::Cow;
3#[cfg(feature = "alloc")]
4use alloc::string::String;
5
6use crate::JsonWrite;
7
8#[cfg(feature = "alloc")]
9pub trait ToJsonKey {
10    fn to_json_key(&self) -> String;
11}
12
13#[cfg(feature = "alloc")]
14impl<T> ToJsonKey for T
15where
16    T: WriteJsonKey + ?Sized,
17{
18    fn to_json_key(&self) -> String {
19        let mut result = String::new();
20        let _ = self.write_json_key(&mut result);
21        result
22    }
23}
24
25pub trait WriteJsonKey {
26    fn write_json_key<W: JsonWrite + ?Sized>(&self, writer: &mut W) -> core::fmt::Result;
27}
28
29impl WriteJsonKey for str {
30    fn write_json_key<W: JsonWrite + ?Sized>(&self, writer: &mut W) -> core::fmt::Result {
31        crate::value::write_json_str(self, writer)
32    }
33}
34
35#[cfg(feature = "alloc")]
36impl WriteJsonKey for String {
37    fn write_json_key<W: JsonWrite + ?Sized>(&self, writer: &mut W) -> core::fmt::Result {
38        self.as_str().write_json_key(writer)
39    }
40}
41
42#[cfg(feature = "alloc")]
43impl WriteJsonKey for Cow<'_, str> {
44    fn write_json_key<W: JsonWrite + ?Sized>(&self, writer: &mut W) -> core::fmt::Result {
45        self.as_ref().write_json_key(writer)
46    }
47}
48
49impl<V: WriteJsonKey + ?Sized> WriteJsonKey for &V {
50    fn write_json_key<W: JsonWrite + ?Sized>(&self, writer: &mut W) -> core::fmt::Result {
51        (*self).write_json_key(writer)
52    }
53}