wlan_common/test_utils/
mod.rs

1// Copyright 2019 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::append::{Append, BufferTooSmall, TrackedAppend, VecCursor};
6use fuchsia_async::{DurationExt, OnTimeout, TimeoutExt};
7
8use futures::Future;
9
10pub mod fake_capabilities;
11pub mod fake_features;
12pub mod fake_frames;
13pub mod fake_stas;
14
15/// A trait which allows to expect a future to terminate within a given time or panic otherwise.
16pub trait ExpectWithin: Future + Sized {
17    fn expect_within<S: ToString + Clone>(
18        self,
19        duration: zx::MonotonicDuration,
20        msg: S,
21    ) -> OnTimeout<Self, Box<dyn FnOnce() -> Self::Output>> {
22        let msg = msg.to_string();
23        self.on_timeout(duration.after_now(), Box::new(move || panic!("{}", msg)))
24    }
25}
26
27impl<F: Future + Sized> ExpectWithin for F {}
28
29pub struct FixedSizedTestBuffer(VecCursor);
30impl FixedSizedTestBuffer {
31    pub fn new(capacity: usize) -> Self {
32        Self(VecCursor::with_capacity(capacity))
33    }
34}
35
36impl Append for FixedSizedTestBuffer {
37    fn append_bytes(&mut self, bytes: &[u8]) -> Result<(), BufferTooSmall> {
38        if !self.can_append(bytes.len()) {
39            return Err(BufferTooSmall);
40        }
41        self.0.append_bytes(bytes)
42    }
43
44    fn append_bytes_zeroed(&mut self, len: usize) -> Result<&mut [u8], BufferTooSmall> {
45        if !self.can_append(len) {
46            return Err(BufferTooSmall);
47        }
48        self.0.append_bytes_zeroed(len)
49    }
50
51    fn can_append(&self, bytes: usize) -> bool {
52        self.0.len() + bytes <= self.0.capacity()
53    }
54}
55
56impl TrackedAppend for FixedSizedTestBuffer {
57    fn bytes_appended(&self) -> usize {
58        self.0.bytes_appended()
59    }
60}