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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#![deny(clippy::undocumented_unsafe_blocks)]
mod raw_bytes;
use std::{
fmt::Debug,
ops::{Deref, Index, RangeBounds},
slice::SliceIndex,
sync::Arc,
};
use raw_bytes::RawBytes;
#[derive(Debug)]
pub struct AppendOnlyBytes {
raw: Arc<RawBytes>,
len: usize,
}
#[derive(Debug)]
pub struct BytesSlice {
raw: Arc<RawBytes>,
start: usize,
end: usize,
}
unsafe impl Send for AppendOnlyBytes {}
unsafe impl Sync for AppendOnlyBytes {}
const MIN_CAPACITY: usize = 32;
impl AppendOnlyBytes {
#[inline(always)]
pub fn new() -> Self {
Self::with_capacity(0)
}
#[inline(always)]
pub fn as_bytes(&self) -> &[u8] {
&self.raw.as_bytes()[..self.len]
}
#[inline(always)]
pub fn with_capacity(capacity: usize) -> Self {
let raw = Arc::new(RawBytes::with_capacity(capacity));
Self { raw, len: 0 }
}
#[inline(always)]
pub fn len(&self) -> usize {
self.len
}
#[inline(always)]
pub fn capacity(&self) -> usize {
self.raw.capacity()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline(always)]
pub fn push_slice(&mut self, slice: &[u8]) {
self.reserve(slice.len());
unsafe {
std::ptr::copy_nonoverlapping(
slice.as_ptr(),
self.raw.ptr().add(self.len),
slice.len(),
);
self.len += slice.len();
}
}
#[inline(always)]
pub fn push_str(&mut self, slice: &str) {
self.push_slice(slice.as_bytes());
}
#[inline(always)]
pub fn push(&mut self, byte: u8) {
self.reserve(1);
unsafe {
std::ptr::write(self.raw.ptr().add(self.len), byte);
self.len += 1;
}
}
#[inline]
pub fn reserve(&mut self, size: usize) {
let target_capacity = self.len() + size;
if target_capacity > self.capacity() {
let mut new_capacity = (self.capacity() * 2).max(MIN_CAPACITY);
while new_capacity < target_capacity {
new_capacity *= 2;
}
let src = std::mem::replace(self, Self::with_capacity(new_capacity));
unsafe {
std::ptr::copy_nonoverlapping(src.raw.ptr(), self.raw.ptr(), src.len());
self.len = src.len();
}
}
}
#[inline]
pub fn slice_str(&self, range: impl RangeBounds<usize>) -> Result<&str, std::str::Utf8Error> {
let (start, end) = get_range(range, self.len());
std::str::from_utf8(self.raw.slice(start..end))
}
#[inline]
pub fn slice(&self, range: impl RangeBounds<usize>) -> BytesSlice {
let (start, end) = get_range(range, self.len());
BytesSlice {
raw: self.raw.clone(),
start,
end,
}
}
#[inline(always)]
pub fn to_slice(self) -> BytesSlice {
BytesSlice {
end: self.len(),
raw: self.raw,
start: 0,
}
}
}
impl Default for AppendOnlyBytes {
#[inline(always)]
fn default() -> Self {
Self::new()
}
}
#[inline(always)]
fn get_range(range: impl RangeBounds<usize>, max_len: usize) -> (usize, usize) {
let start = match range.start_bound() {
std::ops::Bound::Included(&v) => v,
std::ops::Bound::Excluded(&v) => v + 1,
std::ops::Bound::Unbounded => 0,
};
let end = match range.end_bound() {
std::ops::Bound::Included(&v) => v + 1,
std::ops::Bound::Excluded(&v) => v,
std::ops::Bound::Unbounded => max_len,
};
assert!(start <= end);
assert!(end <= max_len);
(start, end)
}
impl<I: SliceIndex<[u8]>> Index<I> for AppendOnlyBytes {
type Output = I::Output;
#[inline]
fn index(&self, index: I) -> &Self::Output {
Index::index(self.raw.slice(..), index)
}
}
unsafe impl Send for BytesSlice {}
unsafe impl Sync for BytesSlice {}
impl BytesSlice {
#[inline(always)]
fn bytes(&self) -> &[u8] {
self.raw.slice(self.start..self.end)
}
#[inline(always)]
pub fn len(&self) -> usize {
self.end - self.start
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.end == self.start
}
#[inline]
pub fn slice_clone(&self, range: impl std::ops::RangeBounds<usize>) -> Self {
let (start, end) = get_range(range, self.end - self.start);
Self {
raw: self.raw.clone(),
start: self.start + start,
end: self.start + end,
}
}
#[inline(always)]
pub fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.raw, &other.raw)
}
#[inline(always)]
pub fn can_merge(&self, other: &Self) -> bool {
self.ptr_eq(other) && self.end == other.start
}
#[inline(always)]
pub fn try_merge(&mut self, other: &Self) -> Result<(), MergeFailed> {
if self.can_merge(other) {
self.end = other.end;
Ok(())
} else {
Err(MergeFailed)
}
}
#[inline]
pub fn slice_str(&self, range: impl RangeBounds<usize>) -> Result<&str, std::str::Utf8Error> {
let (start, end) = get_range(range, self.len());
std::str::from_utf8(&self.deref()[start..end])
}
}
#[derive(Debug)]
pub struct MergeFailed;
impl Deref for BytesSlice {
type Target = [u8];
#[inline(always)]
fn deref(&self) -> &Self::Target {
self.bytes()
}
}
#[cfg(test)]
mod tests {
use std::{
sync::mpsc::{self, Receiver, Sender},
thread,
};
use super::*;
#[test]
fn test() {
let mut a = AppendOnlyBytes::new();
let mut count = 0;
for _ in 0..100 {
a.push(8);
count += 1;
assert_eq!(a.len(), count);
}
for _ in 0..100 {
a.push_slice(&[1, 2]);
count += 2;
assert_eq!(a.len(), count);
}
}
#[test]
fn it_works() {
let mut a = AppendOnlyBytes::new();
a.push_str("123");
assert_eq!(a.slice_str(0..1).unwrap(), "1");
let b = a.slice(..);
for _ in 0..10 {
a.push_str("456");
dbg!(a.slice_str(..).unwrap());
}
let c = a.slice(..);
drop(a);
dbg!(c.slice_str(..).unwrap());
assert_eq!(c.len(), 33);
assert_eq!(c.slice_str(..6).unwrap(), "123456");
assert_eq!(b.deref(), "123".as_bytes());
}
#[test]
fn push_large() {
let mut a = AppendOnlyBytes::new();
a.push_slice(&[1; 10000]);
assert_eq!(a.as_bytes(), &[1; 10000]);
}
#[test]
fn threads() {
let mut a = AppendOnlyBytes::new();
a.push_str("123");
assert_eq!(a.slice_str(0..1).unwrap(), "1");
let (tx, rx): (Sender<AppendOnlyBytes>, Receiver<AppendOnlyBytes>) = mpsc::channel();
let b = a.slice(..);
let t = thread::spawn(move || {
for _ in 0..10 {
a.push_str("456");
dbg!(a.slice_str(..).unwrap());
}
let c = a.slice(..);
tx.send(a).unwrap();
dbg!(c.slice_str(..).unwrap());
assert_eq!(c.len(), 33);
assert_eq!(c.slice_str(..6).unwrap(), "123456");
});
let t1 = thread::spawn(move || {
assert_eq!(b.deref(), "123".as_bytes());
for _ in 0..10 {
let c = b.slice_clone(0..1);
assert_eq!(c.deref(), "1".as_bytes());
}
});
let a = rx.recv().unwrap();
assert_eq!(a.len(), 33);
assert_eq!(&a[..6], "123456".as_bytes());
t.join().unwrap();
t1.join().unwrap()
}
}