1use crate::ser::part::Sink;
2use crate::ser::Error;
3use serde::Serialize;
4use std::borrow::Cow;
5use std::ops::Deref;
6
7pub enum Key<'key> {
8 Static(&'static str),
9 Dynamic(Cow<'key, str>),
10}
11
12impl<'key> Deref for Key<'key> {
13 type Target = str;
14
15 fn deref(&self) -> &str {
16 match *self {
17 Key::Static(key: &str) => key,
18 Key::Dynamic(ref key: &Cow<'_, str>) => key,
19 }
20 }
21}
22
23impl<'key> From<Key<'key>> for Cow<'static, str> {
24 fn from(key: Key<'key>) -> Self {
25 match key {
26 Key::Static(key: &str) => key.into(),
27 Key::Dynamic(key: Cow<'_, str>) => key.into_owned().into(),
28 }
29 }
30}
31
32pub struct KeySink<End> {
33 end: End,
34}
35
36impl<End, Ok> KeySink<End>
37where
38 End: for<'key> FnOnce(Key<'key>) -> Result<Ok, Error>,
39{
40 pub fn new(end: End) -> Self {
41 KeySink { end }
42 }
43}
44
45impl<End, Ok> Sink for KeySink<End>
46where
47 End: for<'key> FnOnce(Key<'key>) -> Result<Ok, Error>,
48{
49 type Ok = Ok;
50
51 fn serialize_static_str(self, value: &'static str) -> Result<Ok, Error> {
52 (self.end)(Key::Static(value))
53 }
54
55 fn serialize_str(self, value: &str) -> Result<Ok, Error> {
56 (self.end)(Key::Dynamic(value.into()))
57 }
58
59 fn serialize_string(self, value: String) -> Result<Ok, Error> {
60 (self.end)(Key::Dynamic(value.into()))
61 }
62
63 fn serialize_none(self) -> Result<Ok, Error> {
64 Err(self.unsupported())
65 }
66
67 fn serialize_some<T: ?Sized + Serialize>(
68 self,
69 _value: &T,
70 ) -> Result<Ok, Error> {
71 Err(self.unsupported())
72 }
73
74 fn unsupported(self) -> Error {
75 Error::Custom("unsupported key".into())
76 }
77}
78