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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
//
// Copyright (c) 2023 ZettaScale Technology
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
//
use crate::{
    buffer::{Buffer, SplitBuffer},
    reader::HasReader,
    vec,
    writer::{BacktrackableWriter, DidntWrite, HasWriter, Writer},
    ZSlice,
};
use alloc::{boxed::Box, sync::Arc};
use core::{fmt, num::NonZeroUsize, option};

#[derive(Clone, PartialEq, Eq)]
pub struct BBuf {
    buffer: Box<[u8]>,
    len: usize,
}

impl BBuf {
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            buffer: vec::uninit(capacity).into_boxed_slice(),
            len: 0,
        }
    }

    #[must_use]
    pub const fn capacity(&self) -> usize {
        self.buffer.len()
    }

    #[must_use]
    pub fn as_slice(&self) -> &[u8] {
        // SAFETY: self.len is ensured by the writer to be smaller than buffer length.
        crate::unsafe_slice!(self.buffer, ..self.len)
    }

    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        // SAFETY: self.len is ensured by the writer to be smaller than buffer length.
        crate::unsafe_slice_mut!(self.buffer, ..self.len)
    }

    pub fn clear(&mut self) {
        self.len = 0;
    }

    fn as_writable_slice(&mut self) -> &mut [u8] {
        // SAFETY: self.len is ensured by the writer to be smaller than buffer length.
        crate::unsafe_slice_mut!(self.buffer, self.len..)
    }
}

impl fmt::Debug for BBuf {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:02x?}", self.as_slice())
    }
}

// Buffer
impl Buffer for BBuf {
    fn len(&self) -> usize {
        self.len
    }
}

impl Buffer for &BBuf {
    fn len(&self) -> usize {
        self.len
    }
}

impl Buffer for &mut BBuf {
    fn len(&self) -> usize {
        self.len
    }
}

// SplitBuffer
impl SplitBuffer for BBuf {
    type Slices<'a> = option::IntoIter<&'a [u8]>;

    fn slices(&self) -> Self::Slices<'_> {
        Some(self.as_slice()).into_iter()
    }
}

// Writer
impl HasWriter for &mut BBuf {
    type Writer = Self;

    fn writer(self) -> Self::Writer {
        self
    }
}

impl Writer for &mut BBuf {
    fn write(&mut self, bytes: &[u8]) -> Result<NonZeroUsize, DidntWrite> {
        let mut writer = self.as_writable_slice().writer();
        let len = writer.write(bytes)?;
        self.len += len.get();
        Ok(len)
    }

    fn write_exact(&mut self, bytes: &[u8]) -> Result<(), DidntWrite> {
        let mut writer = self.as_writable_slice().writer();
        writer.write_exact(bytes)?;
        self.len += bytes.len();
        Ok(())
    }

    fn remaining(&self) -> usize {
        self.capacity() - self.len()
    }

    fn with_slot<F>(&mut self, len: usize, f: F) -> Result<NonZeroUsize, DidntWrite>
    where
        F: FnOnce(&mut [u8]) -> usize,
    {
        if self.remaining() < len {
            return Err(DidntWrite);
        }

        let written = f(self.as_writable_slice());
        self.len += written;

        NonZeroUsize::new(written).ok_or(DidntWrite)
    }
}

impl BacktrackableWriter for &mut BBuf {
    type Mark = usize;

    fn mark(&mut self) -> Self::Mark {
        self.len
    }

    fn rewind(&mut self, mark: Self::Mark) -> bool {
        self.len = mark;
        true
    }
}

#[cfg(feature = "std")]
impl std::io::Write for &mut BBuf {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        match <Self as Writer>::write(self, buf) {
            Ok(n) => Ok(n.get()),
            Err(_) => Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "UnexpectedEof",
            )),
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

// Reader
impl<'a> HasReader for &'a BBuf {
    type Reader = &'a [u8];

    fn reader(self) -> Self::Reader {
        self.as_slice()
    }
}

// From impls
impl From<BBuf> for ZSlice {
    fn from(value: BBuf) -> Self {
        ZSlice {
            buf: Arc::new(value.buffer),
            start: 0,
            end: value.len,
            #[cfg(feature = "shared-memory")]
            kind: crate::ZSliceKind::Raw,
        }
    }
}

#[cfg(feature = "test")]
impl BBuf {
    pub fn rand(len: usize) -> Self {
        #[cfg(not(feature = "std"))]
        use alloc::vec::Vec;
        use rand::Rng;

        let mut rng = rand::thread_rng();
        let buffer = (0..len)
            .map(|_| rng.gen())
            .collect::<Vec<u8>>()
            .into_boxed_slice();

        Self { buffer, len }
    }
}