tink_core/keyset/
json_io.rs1use crate::{utils::wrap_err, TinkError};
20use serde::Deserialize;
21use std::io::{Read, Write};
22
23#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
25pub struct JsonReader<T: Read> {
26 r: T,
27}
28
29impl<T: Read> JsonReader<T> {
30 #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
32 pub fn new(r: T) -> Self {
33 JsonReader { r }
34 }
35}
36
37impl<T: Read> super::Reader for JsonReader<T> {
38 fn read(&mut self) -> Result<tink_proto::Keyset, TinkError> {
41 let mut de = serde_json::Deserializer::from_reader(&mut self.r);
42 tink_proto::Keyset::deserialize(&mut de).map_err(|e| wrap_err("failed to parse", e))
43 }
44
45 fn read_encrypted(&mut self) -> Result<tink_proto::EncryptedKeyset, TinkError> {
48 let mut de = serde_json::Deserializer::from_reader(&mut self.r);
49 tink_proto::EncryptedKeyset::deserialize(&mut de)
50 .map_err(|e| wrap_err("failed to parse", e))
51 }
52}
53
54#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
56pub struct JsonWriter<T: Write> {
57 w: T,
58}
59
60impl<T: Write> JsonWriter<T> {
61 #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
63 pub fn new(w: T) -> Self {
64 JsonWriter { w }
65 }
66}
67
68impl<T: Write> super::Writer for JsonWriter<T> {
69 fn write(&mut self, keyset: &tink_proto::Keyset) -> Result<(), TinkError> {
71 serde_json::to_writer_pretty(&mut self.w, keyset)
72 .map_err(|e| wrap_err("failed to encode", e))
73 }
74
75 fn write_encrypted(&mut self, keyset: &tink_proto::EncryptedKeyset) -> Result<(), TinkError> {
77 serde_json::to_writer_pretty(&mut self.w, keyset)
78 .map_err(|e| wrap_err("failed to encode", e))
79 }
80}