Coverage Report

Created: 2025-02-25 06:39

/rust/registry/src/index.crates.io-6f17d22bba15001f/rustls-0.23.22/src/conn/unbuffered.rs
Line
Count
Source (jump to first uncovered line)
1
//! Unbuffered connection API
2
3
use alloc::vec::Vec;
4
use core::num::NonZeroUsize;
5
use core::{fmt, mem};
6
#[cfg(feature = "std")]
7
use std::error::Error as StdError;
8
9
use super::UnbufferedConnectionCommon;
10
use crate::client::ClientConnectionData;
11
use crate::msgs::deframer::buffers::DeframerSliceBuffer;
12
use crate::server::ServerConnectionData;
13
use crate::Error;
14
15
impl UnbufferedConnectionCommon<ClientConnectionData> {
16
    /// Processes the TLS records in `incoming_tls` buffer until a new [`UnbufferedStatus`] is
17
    /// reached.
18
0
    pub fn process_tls_records<'c, 'i>(
19
0
        &'c mut self,
20
0
        incoming_tls: &'i mut [u8],
21
0
    ) -> UnbufferedStatus<'c, 'i, ClientConnectionData> {
22
0
        self.process_tls_records_common(incoming_tls, |_| None, |_, _, ()| unreachable!())
23
0
    }
24
}
25
26
impl UnbufferedConnectionCommon<ServerConnectionData> {
27
    /// Processes the TLS records in `incoming_tls` buffer until a new [`UnbufferedStatus`] is
28
    /// reached.
29
0
    pub fn process_tls_records<'c, 'i>(
30
0
        &'c mut self,
31
0
        incoming_tls: &'i mut [u8],
32
0
    ) -> UnbufferedStatus<'c, 'i, ServerConnectionData> {
33
0
        self.process_tls_records_common(
34
0
            incoming_tls,
35
0
            |conn| conn.pop_early_data(),
36
0
            |conn, incoming_tls, chunk| ReadEarlyData::new(conn, incoming_tls, chunk).into(),
37
0
        )
38
0
    }
39
}
40
41
impl<Data> UnbufferedConnectionCommon<Data> {
42
0
    fn process_tls_records_common<'c, 'i, T>(
43
0
        &'c mut self,
44
0
        incoming_tls: &'i mut [u8],
45
0
        mut check: impl FnMut(&mut Self) -> Option<T>,
46
0
        execute: impl FnOnce(&'c mut Self, &'i mut [u8], T) -> ConnectionState<'c, 'i, Data>,
47
0
    ) -> UnbufferedStatus<'c, 'i, Data> {
48
0
        let mut buffer = DeframerSliceBuffer::new(incoming_tls);
49
0
        let mut buffer_progress = self.core.hs_deframer.progress();
50
51
0
        let (discard, state) = loop {
52
0
            if let Some(value) = check(self) {
53
0
                break (buffer.pending_discard(), execute(self, incoming_tls, value));
54
0
            }
55
56
0
            if let Some(chunk) = self
57
0
                .core
58
0
                .common_state
59
0
                .received_plaintext
60
0
                .pop()
61
            {
62
0
                break (
63
0
                    buffer.pending_discard(),
64
0
                    ReadTraffic::new(self, incoming_tls, chunk).into(),
65
0
                );
66
0
            }
67
68
0
            if let Some(chunk) = self
69
0
                .core
70
0
                .common_state
71
0
                .sendable_tls
72
0
                .pop()
73
            {
74
0
                break (
75
0
                    buffer.pending_discard(),
76
0
                    EncodeTlsData::new(self, chunk).into(),
77
0
                );
78
0
            }
79
80
0
            let deframer_output =
81
0
                match self
82
0
                    .core
83
0
                    .deframe(None, buffer.filled_mut(), &mut buffer_progress)
84
                {
85
0
                    Err(err) => {
86
0
                        buffer.queue_discard(buffer_progress.take_discard());
87
0
                        return UnbufferedStatus {
88
0
                            discard: buffer.pending_discard(),
89
0
                            state: Err(err),
90
0
                        };
91
                    }
92
0
                    Ok(r) => r,
93
                };
94
95
0
            if let Some(msg) = deframer_output {
96
0
                let mut state =
97
0
                    match mem::replace(&mut self.core.state, Err(Error::HandshakeNotComplete)) {
98
0
                        Ok(state) => state,
99
0
                        Err(e) => {
100
0
                            buffer.queue_discard(buffer_progress.take_discard());
101
0
                            self.core.state = Err(e.clone());
102
0
                            return UnbufferedStatus {
103
0
                                discard: buffer.pending_discard(),
104
0
                                state: Err(e),
105
0
                            };
106
                        }
107
                    };
108
109
0
                match self.core.process_msg(msg, state, None) {
110
0
                    Ok(new) => state = new,
111
112
0
                    Err(e) => {
113
0
                        buffer.queue_discard(buffer_progress.take_discard());
114
0
                        self.core.state = Err(e.clone());
115
0
                        return UnbufferedStatus {
116
0
                            discard: buffer.pending_discard(),
117
0
                            state: Err(e),
118
0
                        };
119
                    }
120
                }
121
122
0
                buffer.queue_discard(buffer_progress.take_discard());
123
0
124
0
                self.core.state = Ok(state);
125
0
            } else if self.wants_write {
126
0
                break (
127
0
                    buffer.pending_discard(),
128
0
                    TransmitTlsData { conn: self }.into(),
129
0
                );
130
0
            } else if self
131
0
                .core
132
0
                .common_state
133
0
                .has_received_close_notify
134
            {
135
0
                break (buffer.pending_discard(), ConnectionState::Closed);
136
0
            } else if self
137
0
                .core
138
0
                .common_state
139
0
                .may_send_application_data
140
            {
141
0
                break (
142
0
                    buffer.pending_discard(),
143
0
                    ConnectionState::WriteTraffic(WriteTraffic { conn: self }),
144
0
                );
145
            } else {
146
0
                break (buffer.pending_discard(), ConnectionState::BlockedHandshake);
147
            }
148
        };
149
150
0
        UnbufferedStatus {
151
0
            discard,
152
0
            state: Ok(state),
153
0
        }
154
0
    }
Unexecuted instantiation: <rustls::conn::UnbufferedConnectionCommon<rustls::client::client_conn::ClientConnectionData>>::process_tls_records_common::<(), <rustls::conn::UnbufferedConnectionCommon<rustls::client::client_conn::ClientConnectionData>>::process_tls_records::{closure#0}, <rustls::conn::UnbufferedConnectionCommon<rustls::client::client_conn::ClientConnectionData>>::process_tls_records::{closure#1}>
Unexecuted instantiation: <rustls::conn::UnbufferedConnectionCommon<rustls::server::server_conn::ServerConnectionData>>::process_tls_records_common::<alloc::vec::Vec<u8>, <rustls::conn::UnbufferedConnectionCommon<rustls::server::server_conn::ServerConnectionData>>::process_tls_records::{closure#0}, <rustls::conn::UnbufferedConnectionCommon<rustls::server::server_conn::ServerConnectionData>>::process_tls_records::{closure#1}>
155
}
156
157
/// The current status of the `UnbufferedConnection*`
158
#[must_use]
159
#[derive(Debug)]
160
pub struct UnbufferedStatus<'c, 'i, Data> {
161
    /// Number of bytes to discard
162
    ///
163
    /// After the `state` field of this object has been handled, `discard` bytes must be
164
    /// removed from the *front* of the `incoming_tls` buffer that was passed to
165
    /// the [`UnbufferedConnectionCommon::process_tls_records`] call that returned this object.
166
    ///
167
    /// This discard operation MUST happen *before*
168
    /// [`UnbufferedConnectionCommon::process_tls_records`] is called again.
169
    pub discard: usize,
170
171
    /// The current state of the handshake process
172
    ///
173
    /// This value MUST be handled prior to calling
174
    /// [`UnbufferedConnectionCommon::process_tls_records`] again. See the documentation on the
175
    /// variants of [`ConnectionState`] for more details.
176
    pub state: Result<ConnectionState<'c, 'i, Data>, Error>,
177
}
178
179
/// The state of the [`UnbufferedConnectionCommon`] object
180
#[non_exhaustive] // for forwards compatibility; to support caller-side certificate verification
181
pub enum ConnectionState<'c, 'i, Data> {
182
    /// One, or more, application data records are available
183
    ///
184
    /// See [`ReadTraffic`] for more details on how to use the enclosed object to access
185
    /// the received data.
186
    ReadTraffic(ReadTraffic<'c, 'i, Data>),
187
188
    /// Connection has been cleanly closed by the peer
189
    Closed,
190
191
    /// One, or more, early (RTT-0) data records are available
192
    ReadEarlyData(ReadEarlyData<'c, 'i, Data>),
193
194
    /// A Handshake record is ready for encoding
195
    ///
196
    /// Call [`EncodeTlsData::encode`] on the enclosed object, providing an `outgoing_tls`
197
    /// buffer to store the encoding
198
    EncodeTlsData(EncodeTlsData<'c, Data>),
199
200
    /// Previously encoded handshake records need to be transmitted
201
    ///
202
    /// Transmit the contents of the `outgoing_tls` buffer that was passed to previous
203
    /// [`EncodeTlsData::encode`] calls to the peer.
204
    ///
205
    /// After transmitting the contents, call [`TransmitTlsData::done`] on the enclosed object.
206
    /// The transmitted contents MUST not be sent to the peer more than once so they SHOULD be
207
    /// discarded at this point.
208
    ///
209
    /// At some stages of the handshake process, it's possible to send application-data alongside
210
    /// handshake records. Call [`TransmitTlsData::may_encrypt_app_data`] on the enclosed
211
    /// object to probe if that's allowed.
212
    TransmitTlsData(TransmitTlsData<'c, Data>),
213
214
    /// More TLS data is needed to continue with the handshake
215
    ///
216
    /// Request more data from the peer and append the contents to the `incoming_tls` buffer that
217
    /// was passed to [`UnbufferedConnectionCommon::process_tls_records`].
218
    BlockedHandshake,
219
220
    /// The handshake process has been completed.
221
    ///
222
    /// [`WriteTraffic::encrypt`] can be called on the enclosed object to encrypt application
223
    /// data into an `outgoing_tls` buffer. Similarly, [`WriteTraffic::queue_close_notify`] can
224
    /// be used to encrypt a close_notify alert message into a buffer to signal the peer that the
225
    /// connection is being closed. Data written into `outgoing_buffer` by either method MAY be
226
    /// transmitted to the peer during this state.
227
    ///
228
    /// Once this state has been reached, data MAY be requested from the peer and appended to an
229
    /// `incoming_tls` buffer that will be passed to a future
230
    /// [`UnbufferedConnectionCommon::process_tls_records`] invocation. When enough data has been
231
    /// appended to `incoming_tls`, [`UnbufferedConnectionCommon::process_tls_records`] will yield
232
    /// the [`ConnectionState::ReadTraffic`] state.
233
    WriteTraffic(WriteTraffic<'c, Data>),
234
}
235
236
impl<'c, 'i, Data> From<ReadTraffic<'c, 'i, Data>> for ConnectionState<'c, 'i, Data> {
237
0
    fn from(v: ReadTraffic<'c, 'i, Data>) -> Self {
238
0
        Self::ReadTraffic(v)
239
0
    }
Unexecuted instantiation: <rustls::conn::unbuffered::ConnectionState<rustls::client::client_conn::ClientConnectionData> as core::convert::From<rustls::conn::unbuffered::ReadTraffic<rustls::client::client_conn::ClientConnectionData>>>::from
Unexecuted instantiation: <rustls::conn::unbuffered::ConnectionState<rustls::server::server_conn::ServerConnectionData> as core::convert::From<rustls::conn::unbuffered::ReadTraffic<rustls::server::server_conn::ServerConnectionData>>>::from
240
}
241
242
impl<'c, 'i, Data> From<ReadEarlyData<'c, 'i, Data>> for ConnectionState<'c, 'i, Data> {
243
0
    fn from(v: ReadEarlyData<'c, 'i, Data>) -> Self {
244
0
        Self::ReadEarlyData(v)
245
0
    }
246
}
247
248
impl<'c, Data> From<EncodeTlsData<'c, Data>> for ConnectionState<'c, '_, Data> {
249
0
    fn from(v: EncodeTlsData<'c, Data>) -> Self {
250
0
        Self::EncodeTlsData(v)
251
0
    }
Unexecuted instantiation: <rustls::conn::unbuffered::ConnectionState<rustls::client::client_conn::ClientConnectionData> as core::convert::From<rustls::conn::unbuffered::EncodeTlsData<rustls::client::client_conn::ClientConnectionData>>>::from
Unexecuted instantiation: <rustls::conn::unbuffered::ConnectionState<rustls::server::server_conn::ServerConnectionData> as core::convert::From<rustls::conn::unbuffered::EncodeTlsData<rustls::server::server_conn::ServerConnectionData>>>::from
252
}
253
254
impl<'c, Data> From<TransmitTlsData<'c, Data>> for ConnectionState<'c, '_, Data> {
255
0
    fn from(v: TransmitTlsData<'c, Data>) -> Self {
256
0
        Self::TransmitTlsData(v)
257
0
    }
Unexecuted instantiation: <rustls::conn::unbuffered::ConnectionState<rustls::client::client_conn::ClientConnectionData> as core::convert::From<rustls::conn::unbuffered::TransmitTlsData<rustls::client::client_conn::ClientConnectionData>>>::from
Unexecuted instantiation: <rustls::conn::unbuffered::ConnectionState<rustls::server::server_conn::ServerConnectionData> as core::convert::From<rustls::conn::unbuffered::TransmitTlsData<rustls::server::server_conn::ServerConnectionData>>>::from
258
}
259
260
impl<Data> fmt::Debug for ConnectionState<'_, '_, Data> {
261
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262
0
        match self {
263
0
            Self::ReadTraffic(..) => f.debug_tuple("ReadTraffic").finish(),
264
265
0
            Self::Closed => write!(f, "Closed"),
266
267
0
            Self::ReadEarlyData(..) => f.debug_tuple("ReadEarlyData").finish(),
268
269
0
            Self::EncodeTlsData(..) => f.debug_tuple("EncodeTlsData").finish(),
270
271
0
            Self::TransmitTlsData(..) => f
272
0
                .debug_tuple("TransmitTlsData")
273
0
                .finish(),
274
275
0
            Self::BlockedHandshake => f
276
0
                .debug_tuple("BlockedHandshake")
277
0
                .finish(),
278
279
0
            Self::WriteTraffic(..) => f.debug_tuple("WriteTraffic").finish(),
280
        }
281
0
    }
282
}
283
284
/// Application data is available
285
pub struct ReadTraffic<'c, 'i, Data> {
286
    _conn: &'c mut UnbufferedConnectionCommon<Data>,
287
    // for forwards compatibility; to support in-place decryption in the future
288
    _incoming_tls: &'i mut [u8],
289
    chunk: Vec<u8>,
290
    taken: bool,
291
}
292
293
impl<'c, 'i, Data> ReadTraffic<'c, 'i, Data> {
294
0
    fn new(
295
0
        _conn: &'c mut UnbufferedConnectionCommon<Data>,
296
0
        _incoming_tls: &'i mut [u8],
297
0
        chunk: Vec<u8>,
298
0
    ) -> Self {
299
0
        Self {
300
0
            _conn,
301
0
            _incoming_tls,
302
0
            chunk,
303
0
            taken: false,
304
0
        }
305
0
    }
Unexecuted instantiation: <rustls::conn::unbuffered::ReadTraffic<rustls::client::client_conn::ClientConnectionData>>::new
Unexecuted instantiation: <rustls::conn::unbuffered::ReadTraffic<rustls::server::server_conn::ServerConnectionData>>::new
306
307
    /// Decrypts and returns the next available app-data record
308
    // TODO deprecate in favor of `Iterator` implementation, which requires in-place decryption
309
0
    pub fn next_record(&mut self) -> Option<Result<AppDataRecord<'_>, Error>> {
310
0
        if self.taken {
311
0
            None
312
        } else {
313
0
            self.taken = true;
314
0
            Some(Ok(AppDataRecord {
315
0
                discard: 0,
316
0
                payload: &self.chunk,
317
0
            }))
318
        }
319
0
    }
320
321
    /// Returns the payload size of the next app-data record *without* decrypting it
322
    ///
323
    /// Returns `None` if there are no more app-data records
324
0
    pub fn peek_len(&self) -> Option<NonZeroUsize> {
325
0
        if self.taken {
326
0
            None
327
        } else {
328
0
            NonZeroUsize::new(self.chunk.len())
329
        }
330
0
    }
331
}
332
333
/// Early application-data is available.
334
pub struct ReadEarlyData<'c, 'i, Data> {
335
    _conn: &'c mut UnbufferedConnectionCommon<Data>,
336
    // for forwards compatibility; to support in-place decryption in the future
337
    _incoming_tls: &'i mut [u8],
338
    chunk: Vec<u8>,
339
    taken: bool,
340
}
341
342
impl<'c, 'i, Data> ReadEarlyData<'c, 'i, Data> {
343
0
    fn new(
344
0
        _conn: &'c mut UnbufferedConnectionCommon<Data>,
345
0
        _incoming_tls: &'i mut [u8],
346
0
        chunk: Vec<u8>,
347
0
    ) -> Self {
348
0
        Self {
349
0
            _conn,
350
0
            _incoming_tls,
351
0
            chunk,
352
0
            taken: false,
353
0
        }
354
0
    }
355
}
356
357
impl ReadEarlyData<'_, '_, ServerConnectionData> {
358
    /// decrypts and returns the next available app-data record
359
    // TODO deprecate in favor of `Iterator` implementation, which requires in-place decryption
360
0
    pub fn next_record(&mut self) -> Option<Result<AppDataRecord<'_>, Error>> {
361
0
        if self.taken {
362
0
            None
363
        } else {
364
0
            self.taken = true;
365
0
            Some(Ok(AppDataRecord {
366
0
                discard: 0,
367
0
                payload: &self.chunk,
368
0
            }))
369
        }
370
0
    }
371
372
    /// returns the payload size of the next app-data record *without* decrypting it
373
    ///
374
    /// returns `None` if there are no more app-data records
375
0
    pub fn peek_len(&self) -> Option<NonZeroUsize> {
376
0
        if self.taken {
377
0
            None
378
        } else {
379
0
            NonZeroUsize::new(self.chunk.len())
380
        }
381
0
    }
382
}
383
384
/// A decrypted application-data record
385
pub struct AppDataRecord<'i> {
386
    /// Number of additional bytes to discard
387
    ///
388
    /// This number MUST be added to the value of [`UnbufferedStatus.discard`] *prior* to the
389
    /// discard operation. See [`UnbufferedStatus.discard`] for more details
390
    pub discard: usize,
391
392
    /// The payload of the app-data record
393
    pub payload: &'i [u8],
394
}
395
396
/// Allows encrypting app-data
397
pub struct WriteTraffic<'c, Data> {
398
    conn: &'c mut UnbufferedConnectionCommon<Data>,
399
}
400
401
impl<Data> WriteTraffic<'_, Data> {
402
    /// Encrypts `application_data` into the `outgoing_tls` buffer
403
    ///
404
    /// Returns the number of bytes that were written into `outgoing_tls`, or an error if
405
    /// the provided buffer is too small. In the error case, `outgoing_tls` is not modified
406
0
    pub fn encrypt(
407
0
        &mut self,
408
0
        application_data: &[u8],
409
0
        outgoing_tls: &mut [u8],
410
0
    ) -> Result<usize, EncryptError> {
411
0
        self.conn
412
0
            .core
413
0
            .maybe_refresh_traffic_keys();
414
0
        self.conn
415
0
            .core
416
0
            .common_state
417
0
            .write_plaintext(application_data.into(), outgoing_tls)
418
0
    }
419
420
    /// Encrypts a close_notify warning alert in `outgoing_tls`
421
    ///
422
    /// Returns the number of bytes that were written into `outgoing_tls`, or an error if
423
    /// the provided buffer is too small. In the error case, `outgoing_tls` is not modified
424
0
    pub fn queue_close_notify(&mut self, outgoing_tls: &mut [u8]) -> Result<usize, EncryptError> {
425
0
        self.conn
426
0
            .core
427
0
            .common_state
428
0
            .eager_send_close_notify(outgoing_tls)
429
0
    }
430
431
    /// Arranges for a TLS1.3 `key_update` to be sent.
432
    ///
433
    /// This consumes the `WriteTraffic` state:  to actually send the message,
434
    /// call [`UnbufferedConnectionCommon::process_tls_records`] again which will
435
    /// return a `ConnectionState::EncodeTlsData` that emits the `key_update`
436
    /// message.
437
    ///
438
    /// See [`ConnectionCommon::refresh_traffic_keys()`] for full documentation,
439
    /// including why you might call this and in what circumstances it will fail.
440
    ///
441
    /// [`ConnectionCommon::refresh_traffic_keys()`]: crate::ConnectionCommon::refresh_traffic_keys
442
0
    pub fn refresh_traffic_keys(self) -> Result<(), Error> {
443
0
        self.conn.core.refresh_traffic_keys()
444
0
    }
445
}
446
447
/// A handshake record must be encoded
448
pub struct EncodeTlsData<'c, Data> {
449
    conn: &'c mut UnbufferedConnectionCommon<Data>,
450
    chunk: Option<Vec<u8>>,
451
}
452
453
impl<'c, Data> EncodeTlsData<'c, Data> {
454
0
    fn new(conn: &'c mut UnbufferedConnectionCommon<Data>, chunk: Vec<u8>) -> Self {
455
0
        Self {
456
0
            conn,
457
0
            chunk: Some(chunk),
458
0
        }
459
0
    }
Unexecuted instantiation: <rustls::conn::unbuffered::EncodeTlsData<rustls::client::client_conn::ClientConnectionData>>::new
Unexecuted instantiation: <rustls::conn::unbuffered::EncodeTlsData<rustls::server::server_conn::ServerConnectionData>>::new
460
461
    /// Encodes a handshake record into the `outgoing_tls` buffer
462
    ///
463
    /// Returns the number of bytes that were written into `outgoing_tls`, or an error if
464
    /// the provided buffer is too small. In the error case, `outgoing_tls` is not modified
465
0
    pub fn encode(&mut self, outgoing_tls: &mut [u8]) -> Result<usize, EncodeError> {
466
0
        let Some(chunk) = self.chunk.take() else {
467
0
            return Err(EncodeError::AlreadyEncoded);
468
        };
469
470
0
        let required_size = chunk.len();
471
0
472
0
        if required_size > outgoing_tls.len() {
473
0
            self.chunk = Some(chunk);
474
0
            Err(InsufficientSizeError { required_size }.into())
475
        } else {
476
0
            let written = chunk.len();
477
0
            outgoing_tls[..written].copy_from_slice(&chunk);
478
0
479
0
            self.conn.wants_write = true;
480
0
481
0
            Ok(written)
482
        }
483
0
    }
484
}
485
486
/// Previously encoded TLS data must be transmitted
487
pub struct TransmitTlsData<'c, Data> {
488
    pub(crate) conn: &'c mut UnbufferedConnectionCommon<Data>,
489
}
490
491
impl<Data> TransmitTlsData<'_, Data> {
492
    /// Signals that the previously encoded TLS data has been transmitted
493
0
    pub fn done(self) {
494
0
        self.conn.wants_write = false;
495
0
    }
496
497
    /// Returns an adapter that allows encrypting application data
498
    ///
499
    /// If allowed at this stage of the handshake process
500
0
    pub fn may_encrypt_app_data(&mut self) -> Option<WriteTraffic<'_, Data>> {
501
0
        if self
502
0
            .conn
503
0
            .core
504
0
            .common_state
505
0
            .may_send_application_data
506
        {
507
0
            Some(WriteTraffic { conn: self.conn })
508
        } else {
509
0
            None
510
        }
511
0
    }
512
}
513
514
/// Errors that may arise when encoding a handshake record
515
#[derive(Debug)]
516
pub enum EncodeError {
517
    /// Provided buffer was too small
518
    InsufficientSize(InsufficientSizeError),
519
520
    /// The handshake record has already been encoded; do not call `encode` again
521
    AlreadyEncoded,
522
}
523
524
impl From<InsufficientSizeError> for EncodeError {
525
0
    fn from(v: InsufficientSizeError) -> Self {
526
0
        Self::InsufficientSize(v)
527
0
    }
528
}
529
530
impl fmt::Display for EncodeError {
531
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532
0
        match self {
533
0
            Self::InsufficientSize(InsufficientSizeError { required_size }) => write!(
534
0
                f,
535
0
                "cannot encode due to insufficient size, {} bytes are required",
536
0
                required_size
537
0
            ),
538
0
            Self::AlreadyEncoded => "cannot encode, data has already been encoded".fmt(f),
539
        }
540
0
    }
541
}
542
543
#[cfg(feature = "std")]
544
impl StdError for EncodeError {}
545
546
/// Errors that may arise when encrypting application data
547
#[derive(Debug)]
548
pub enum EncryptError {
549
    /// Provided buffer was too small
550
    InsufficientSize(InsufficientSizeError),
551
552
    /// Encrypter has been exhausted
553
    EncryptExhausted,
554
}
555
556
impl From<InsufficientSizeError> for EncryptError {
557
0
    fn from(v: InsufficientSizeError) -> Self {
558
0
        Self::InsufficientSize(v)
559
0
    }
560
}
561
562
impl fmt::Display for EncryptError {
563
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
564
0
        match self {
565
0
            Self::InsufficientSize(InsufficientSizeError { required_size }) => write!(
566
0
                f,
567
0
                "cannot encrypt due to insufficient size, {required_size} bytes are required"
568
0
            ),
569
0
            Self::EncryptExhausted => f.write_str("encrypter has been exhausted"),
570
        }
571
0
    }
572
}
573
574
#[cfg(feature = "std")]
575
impl StdError for EncryptError {}
576
577
/// Provided buffer was too small
578
#[derive(Clone, Copy, Debug)]
579
pub struct InsufficientSizeError {
580
    /// buffer must be at least this size
581
    pub required_size: usize,
582
}