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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#![deny(clippy::undocumented_unsafe_blocks)]
mod raw_bytes;
use std::{
fmt::Debug,
ops::{Deref, Index, RangeBounds},
slice::SliceIndex,
sync::{Arc, Weak},
};
use raw_bytes::RawBytes;
#[derive(Debug)]
pub struct AppendOnlyBytes {
raw: Arc<RawBytes>,
len: usize,
}
impl Clone for AppendOnlyBytes {
fn clone(&self) -> Self {
let new = RawBytes::with_capacity(self.capacity());
unsafe {
std::ptr::copy_nonoverlapping(self.raw.ptr(), new.ptr(), self.len);
}
Self {
raw: Arc::new(new),
len: self.len,
}
}
}
#[derive(Debug, Clone)]
pub struct BytesSlice {
raw: Arc<RawBytes>,
#[cfg(not(feature = "u32_range"))]
start: usize,
#[cfg(not(feature = "u32_range"))]
end: usize,
#[cfg(feature = "u32_range")]
start: u32,
#[cfg(feature = "u32_range")]
end: u32,
}
#[derive(Debug, Clone)]
pub struct WeakBytesSlice {
raw: Weak<RawBytes>,
#[cfg(not(feature = "u32_range"))]
start: usize,
#[cfg(not(feature = "u32_range"))]
end: usize,
#[cfg(feature = "u32_range")]
start: u32,
#[cfg(feature = "u32_range")]
end: u32,
}
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::new(self.raw.clone(), start, end)
}
#[inline]
pub fn slice_weak(&self, range: impl RangeBounds<usize>) -> WeakBytesSlice {
let (start, end) = get_range(range, self.len());
WeakBytesSlice::new(Arc::downgrade(&self.raw), start, end)
}
#[inline(always)]
pub fn to_slice(self) -> BytesSlice {
let end = self.len();
BytesSlice::new(self.raw, 0, end)
}
}
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 {}
unsafe impl Send for WeakBytesSlice {}
unsafe impl Sync for WeakBytesSlice {}
impl BytesSlice {
#[inline(always)]
fn new(raw: Arc<RawBytes>, start: usize, end: usize) -> Self {
Self {
raw,
#[cfg(feature = "u32_range")]
start: start as u32,
#[cfg(feature = "u32_range")]
end: end as u32,
#[cfg(not(feature = "u32_range"))]
start,
#[cfg(not(feature = "u32_range"))]
end,
}
}
#[inline(always)]
fn bytes(&self) -> &[u8] {
self.raw.slice(self.start as usize..self.end as usize)
}
#[inline(always)]
pub fn len(&self) -> usize {
(self.end - self.start) as usize
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.end == self.start
}
#[inline(always)]
pub fn slice_clone(&self, range: impl std::ops::RangeBounds<usize>) -> Self {
let (start, end) = get_range(range, (self.end - self.start) as usize);
Self::new(self.raw.clone(), self.start() + start, 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])
}
#[inline(always)]
pub fn start(&self) -> usize {
self.start as usize
}
#[inline(always)]
pub fn end(&self) -> usize {
self.end as usize
}
#[inline(always)]
pub fn downgrade(&self) -> WeakBytesSlice {
WeakBytesSlice::new(Arc::downgrade(&self.raw), self.start(), self.end())
}
}
impl WeakBytesSlice {
#[inline(always)]
fn new(raw: Weak<RawBytes>, start: usize, end: usize) -> Self {
Self {
raw,
#[cfg(feature = "u32_range")]
start: start as u32,
#[cfg(feature = "u32_range")]
end: end as u32,
#[cfg(not(feature = "u32_range"))]
start,
#[cfg(not(feature = "u32_range"))]
end,
}
}
#[inline(always)]
pub fn len(&self) -> usize {
(self.end - self.start) as usize
}
#[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) as usize);
Self::new(
self.raw.clone(),
self.start as usize + start,
self.start as usize + end,
)
}
#[inline(always)]
pub fn ptr_eq(&self, other: &Self) -> bool {
Weak::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(always)]
pub fn start(&self) -> usize {
self.start as usize
}
#[inline(always)]
pub fn end(&self) -> usize {
self.end as usize
}
#[inline]
pub fn upgrade(&self) -> Option<BytesSlice> {
self.raw.upgrade().map(|x| BytesSlice {
raw: x,
start: self.start,
end: self.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_weak(..);
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.upgrade().unwrap().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()
}
}