tink_core/keyset/
mem_io.rs

1// Copyright 2020 The Tink-Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15////////////////////////////////////////////////////////////////////////////////
16
17//! In-memory I/O for keysets (typically for testing).
18
19use crate::TinkError;
20
21/// `MemReaderWriter` implements [`keyset::Reader`](super::Reader) and
22/// [`keyset.Writer`](super::Writer) with in-memory storage.
23#[derive(Default)]
24pub struct MemReaderWriter {
25    pub keyset: Option<tink_proto::Keyset>,
26    pub encrypted_keyset: Option<tink_proto::EncryptedKeyset>,
27}
28
29impl super::Reader for MemReaderWriter {
30    /// Return `Keyset` from memory.
31    fn read(&mut self) -> Result<tink_proto::Keyset, TinkError> {
32        match &self.keyset {
33            Some(keyset) => Ok(keyset.clone()),
34            None => Err("no keyset available".into()),
35        }
36    }
37
38    /// Return `EncryptedKeyset` from memory.
39    fn read_encrypted(&mut self) -> Result<tink_proto::EncryptedKeyset, TinkError> {
40        match &self.encrypted_keyset {
41            Some(keyset) => Ok(keyset.clone()),
42            None => Err("no keyset available".into()),
43        }
44    }
45}
46
47impl super::Writer for MemReaderWriter {
48    /// Write keyset to memory.
49    fn write(&mut self, keyset: &tink_proto::Keyset) -> Result<(), TinkError> {
50        self.keyset = Some(keyset.clone());
51        Ok(())
52    }
53
54    /// Write encrypted keyset to memory.
55    fn write_encrypted(&mut self, keyset: &tink_proto::EncryptedKeyset) -> Result<(), TinkError> {
56        self.encrypted_keyset = Some(keyset.clone());
57        Ok(())
58    }
59}