1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use core::marker::PhantomData;

use crate::api::{InvalidSliceError, StaticVarApi, StaticVarApiImpl};

use super::LockableStaticBuffer;

pub struct StaticBufferRef<M>
where
    M: StaticVarApi,
{
    _phantom: PhantomData<M>,
}

impl<M> StaticBufferRef<M>
where
    M: StaticVarApi,
{
    fn new() -> Self {
        StaticBufferRef {
            _phantom: PhantomData,
        }
    }

    pub fn try_new_from_copy_bytes<F: FnOnce(&mut [u8])>(
        len: usize,
        copy_bytes: F,
    ) -> Option<Self> {
        M::static_var_api_impl().with_lockable_static_buffer(|lsb| {
            if lsb.try_lock_with_copy_bytes(len, copy_bytes) {
                Some(StaticBufferRef::new())
            } else {
                None
            }
        })
    }

    pub fn try_new(bytes: &[u8]) -> Option<Self> {
        Self::try_new_from_copy_bytes(bytes.len(), |dest| dest.copy_from_slice(bytes))
    }
}

impl<M: StaticVarApi> Drop for StaticBufferRef<M> {
    fn drop(&mut self) {
        M::static_var_api_impl().with_lockable_static_buffer(|lsb| {
            lsb.unlock();
        })
    }
}

impl<M: StaticVarApi> StaticBufferRef<M> {
    pub fn len(&self) -> usize {
        M::static_var_api_impl().with_lockable_static_buffer(|lsb| lsb.len())
    }

    pub fn is_empty(&self) -> bool {
        M::static_var_api_impl().with_lockable_static_buffer(|lsb| lsb.is_empty())
    }

    pub fn capacity(&self) -> usize {
        LockableStaticBuffer::capacity()
    }

    pub fn remaining_capacity(&self) -> usize {
        M::static_var_api_impl().with_lockable_static_buffer(|lsb| lsb.remaining_capacity())
    }

    pub fn with_buffer_contents<R, F: FnMut(&[u8]) -> R>(&self, mut f: F) -> R {
        M::static_var_api_impl().with_lockable_static_buffer(|lsb| f(lsb.as_slice()))
    }

    pub fn contents_eq(&self, bytes: &[u8]) -> bool {
        M::static_var_api_impl().with_lockable_static_buffer(|lsb| lsb.as_slice() == bytes)
    }

    pub fn load_slice(
        &self,
        starting_position: usize,
        dest: &mut [u8],
    ) -> Result<(), InvalidSliceError> {
        M::static_var_api_impl()
            .with_lockable_static_buffer(|lsb| lsb.load_slice(starting_position, dest))
    }

    pub fn try_extend_from_slice(&mut self, bytes: &[u8]) -> bool {
        self.try_extend_from_copy_bytes(bytes.len(), |dest| dest.copy_from_slice(bytes))
    }

    pub fn try_extend_from_copy_bytes<F: FnOnce(&mut [u8])>(
        &mut self,
        len: usize,
        copy_bytes: F,
    ) -> bool {
        M::static_var_api_impl()
            .with_lockable_static_buffer(|lsb| lsb.try_extend_from_copy_bytes(len, copy_bytes))
    }
}