jose_b64/stream/
update.rs

1// SPDX-FileCopyrightText: 2022 Profian Inc. <opensource@profian.com>
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use alloc::string::String;
5use alloc::vec::Vec;
6
7use core::convert::Infallible;
8
9/// A type that can be updated with bytes.
10///
11/// This type is similar to `std::io::Write` or `digest::Update`.
12pub trait Update {
13    /// The error that may occur during update.
14    type Error;
15
16    /// Update the instance with the provided bytes.
17    fn update(&mut self, chunk: impl AsRef<[u8]>) -> Result<(), Self::Error>;
18
19    /// Perform a chain update.
20    fn chain(mut self, chunk: impl AsRef<[u8]>) -> Result<Self, Self::Error>
21    where
22        Self: Sized,
23    {
24        self.update(chunk)?;
25        Ok(self)
26    }
27}
28
29impl Update for Vec<u8> {
30    type Error = Infallible;
31
32    fn update(&mut self, chunk: impl AsRef<[u8]>) -> Result<(), Self::Error> {
33        self.extend(chunk.as_ref());
34        Ok(())
35    }
36}
37
38impl Update for String {
39    type Error = core::str::Utf8Error;
40
41    fn update(&mut self, chunk: impl AsRef<[u8]>) -> Result<(), Self::Error> {
42        self.push_str(core::str::from_utf8(chunk.as_ref())?);
43        Ok(())
44    }
45}
46
47impl<T: Update> Update for Vec<T> {
48    type Error = T::Error;
49
50    fn update(&mut self, chunk: impl AsRef<[u8]>) -> Result<(), Self::Error> {
51        for x in self.iter_mut() {
52            x.update(chunk.as_ref())?;
53        }
54
55        Ok(())
56    }
57}
58
59impl<T: crate::Zeroize + Update> Update for crate::Zeroizing<T> {
60    type Error = T::Error;
61
62    fn update(&mut self, chunk: impl AsRef<[u8]>) -> Result<(), Self::Error> {
63        (**self).update(chunk)
64    }
65}