Debian Codegraph @

src/divbuf.rs

raw symbols SCIP
1 // vim: tw=80
2
3 use std::{
4 borrow::{Borrow, BorrowMut},
5 cmp,
6 convert::TryFrom,
7 error,
8 fmt::{self, Debug, Formatter},
9 hash,
10 io,
11 mem,
12 ops,
13 sync::atomic::{
14 self,
15 AtomicUsize,
16 Ordering::{AcqRel, Acquire, Relaxed, Release},
17 },
18 };
19
20 #[cfg(target_pointer_width = "64")]
21 const WRITER_SHIFT: usize = 32;
22 #[cfg(target_pointer_width = "64")]
23 const READER_MASK: usize = 0xFFFF_FFFF;
24 #[cfg(target_pointer_width = "32")]
25 const WRITER_SHIFT: usize = 16;
26 #[cfg(target_pointer_width = "32")]
27 const READER_MASK: usize = 0xFFFF;
28 const ONE_WRITER: usize = 1 << WRITER_SHIFT;
29
30 /// DivBuf's error type
31 #[derive(Clone, Copy, Debug)]
32 pub struct Error(&'static str);
33
34 impl fmt::Display for Error {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 write!(f, "{}", self.0)
37 }
38 }
39
40 impl error::Error for Error {}
41
42 /// The return type of
43 /// [`DivBuf::into_chunks`](struct.DivBuf.html#method.into_chunks)
44 // LCOV_EXCL_START
45 #[derive(Debug)]
46 pub struct Chunks {
47 db: DivBuf,
48 chunksize: usize,
49 }
50 // LCOV_EXCL_STOP
51
52 impl Chunks {
53 fn new(db: DivBuf, chunksize: usize) -> Self {
54 Chunks { db, chunksize }
55 }
56 }
57
58 impl Iterator for Chunks {
59 type Item = DivBuf;
60
61 fn next(&mut self) -> Option<DivBuf> {
62 if self.db.is_empty() {
63 None
64 } else {
65 let size = cmp::min(self.chunksize, self.db.len());
66 Some(self.db.split_to(size))
67 }
68 }
69
70 fn size_hint(&self) -> (usize, Option<usize>) {
71 let mut c = self.db.len() / self.chunksize;
72 if self.db.len() % self.chunksize != 0 {
73 c += 1;
74 }
75 (c, Some(c))
76 }
77 }
78
79 /// The return type of
80 /// [`DivBufMut::into_chunks`](struct.DivBufMut.html#method.into_chunks)
81 // LCOV_EXCL_START
82 #[derive(Debug)]
83 pub struct ChunksMut {
84 db: DivBufMut,
85 chunksize: usize,
86 }
87 // LCOV_EXCL_STOP
88
89 impl ChunksMut {
90 fn new(db: DivBufMut, chunksize: usize) -> Self {
91 ChunksMut { db, chunksize }
92 }
93 }
94
95 impl Iterator for ChunksMut {
96 type Item = DivBufMut;
97
98 fn next(&mut self) -> Option<DivBufMut> {
99 if self.db.is_empty() {
100 None
101 } else {
102 let size = cmp::min(self.chunksize, self.db.len());
103 Some(self.db.split_to(size))
104 }
105 }
106
107 fn size_hint(&self) -> (usize, Option<usize>) {
108 let mut c = self.db.len() / self.chunksize;
109 if self.db.len() % self.chunksize != 0 {
110 c += 1;
111 }
112 (c, Some(c))
113 }
114 }
115
116 // LCOV_EXCL_START
117 #[derive(Debug)]
118 struct Inner {
119 vec: Vec<u8>,
120 /// Stores the number of readers in the low half, and writers in the high
121 /// half.
122 accessors: AtomicUsize,
123 /// Stores the total number of DivBufShareds owning this Inner
124 sharers: AtomicUsize,
125 }
126 // LCOV_EXCL_STOP
127
128 /// The "entry point" to the `divbuf` crate.
129 ///
130 /// A `DivBufShared` owns storage, but cannot directly access it. An
131 /// application will typically create an instance of this class for every
132 /// independent buffer it wants to manage, and then create child `DivBuf`s or
133 /// `DivBufMut`s to access the storage.
134 pub struct DivBufShared {
135 inner: *mut Inner,
136 }
137
138 /// Provides read-only access to a buffer.
139 ///
140 /// This struct provides a window into a region of a `DivBufShared`, allowing
141 /// read-only access. It can be divided into smaller `DivBuf` using the
142 /// [`split_to`], [`split_off`], [`slice`], [`slice_from`], and [`slice_to`]
143 /// methods. Adjacent `DivBuf`s can be combined using the [`unsplit`] method.
144 /// Finally, a `DivBuf` can be upgraded to a writable [`DivBufMut`] using the
145 /// [`try_mut`] method, but only if there are no other `DivBuf`s that reference
146 /// the same `DivBufShared`.
147 ///
148 /// # Examples
149 ///
150 /// ```
151 /// # use divbuf::*;
152 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
153 /// let mut db0 : DivBuf = dbs.try_const().unwrap();
154 /// assert_eq!(db0, [1, 2, 3, 4, 5, 6][..]);
155 /// ```
156 ///
157 /// Unlike [`DivBufMut`], a `DivBuf` cannot be used to modify the buffer. The
158 /// following example will fail.
159 ///
160 /// ```compile_fail
161 /// # use divbuf::*;
162 /// let dbs = DivBufShared::from(vec![1, 2, 3]);
163 /// let mut db = dbs.try_const().unwrap();
164 /// db[0] = 9;
165 /// ```
166 ///
167 /// [`DivBufMut`]: struct.DivBufMut.html
168 /// [`slice_from`]: #method.slice_from
169 /// [`slice_to`]: #method.slice_to
170 /// [`slice`]: #method.slice
171 /// [`split_off`]: #method.split_off
172 /// [`split_to`]: #method.split_to
173 /// [`try_mut`]: #method.try_mut
174 /// [`unsplit`]: #method.unsplit
175 // LCOV_EXCL_START
176 #[derive(Debug)]
177 pub struct DivBuf {
178 // inner must be *mut just to support the try_mut method
179 inner: *mut Inner,
180 // In the future, consider optimizing by replacing begin with a pointer
181 begin: usize,
182 len: usize,
183 }
184 // LCOV_EXCL_STOP
185
186 /// Provides read-write access to a buffer
187 ///
188 /// This structure provides a window into a region of a `DivBufShared`, allowing
189 /// read-write access. It can be divided into smaller `DivBufMut` using the
190 /// [`split_to`], and [`split_off`] methods. Adjacent `DivBufMut`s can be
191 /// combined using the [`unsplit`] method. `DivBufMut` dereferences to a
192 /// `&[u8]`, which is usually the easiest way to access its contents. However,
193 /// it can also be modified using the `Vec`-like methods [`extend`],
194 /// [`try_extend`], [`reserve`], and [`try_truncate`]. Crucially, those methods
195 /// will only work for terminal `DivBufMut`s. That is, a `DivBufMut` whose
196 /// range includes the end of the `DivBufShared`'s buffer.
197 ///
198 /// `divbuf` includes a primitive form of range-locking. It's possible to have
199 /// multiple `DivBufMut`s simultaneously referencing a single `DivBufShared`,
200 /// but there's no way to create overlapping `DivBufMut`s.
201 ///
202 /// # Examples
203 ///
204 /// ```
205 /// # use divbuf::*;
206 /// let dbs = DivBufShared::from(vec![0; 64]);
207 /// let mut dbm = dbs.try_mut().unwrap();
208 /// dbm[0..4].copy_from_slice(&b"Blue"[..]);
209 /// ```
210 ///
211 /// [`split_off`]: #method.split_off
212 /// [`split_to`]: #method.split_to
213 /// [`unsplit`]: #method.unsplit
214 /// [`extend`]: #method.extend
215 /// [`try_extend`]: #method.try_extend
216 /// [`reserve`]: #method.reserve
217 /// [`try_truncate`]: #method.try_truncate
218 // LCOV_EXCL_START
219 #[derive(Debug)]
220 pub struct DivBufMut {
221 inner: *mut Inner,
222 // In the future, consider optimizing by replacing begin with a pointer
223 begin: usize,
224 len: usize,
225 }
226 // LCOV_EXCL_STOP
227
228 /// Does not offer either read or write access to the data, but can be upgraded
229 /// to a buffer that does.
230 ///
231 /// Useful because it implements `Clone`, and does not block other [`DivBufMut`]
232 /// structures from existing.
233 #[derive(Debug)]
234 pub struct DivBufInaccessible {
235 inner: *mut Inner,
236 // In the future, consider optimizing by replacing begin with a pointer
237 begin: usize,
238 len: usize,
239 }
240
241 impl DivBufShared {
242 /// Returns the number of bytes the buffer can hold without reallocating.
243 pub fn capacity(&self) -> usize {
244 let inner = unsafe { &*self.inner };
245 inner.vec.capacity()
246 }
247
248 /// Returns true if the `DivBufShared` has length 0
249 pub fn is_empty(&self) -> bool {
250 let inner = unsafe { &*self.inner };
251 inner.vec.is_empty()
252 }
253
254 /// Returns the number of bytes contained in this buffer.
255 pub fn len(&self) -> usize {
256 let inner = unsafe { &*self.inner };
257 inner.vec.len()
258 }
259
260 #[deprecated(since = "0.3.1", note = "use try_const instead")]
261 #[doc(hidden)]
262 pub fn r#try(&self) -> Result<DivBuf, Error> {
263 self.try_const()
264 }
265
266 /// Try to create a read-only [`DivBuf`] that refers to the entirety of this
267 /// buffer. Will fail if there are any [`DivBufMut`] objects referring to
268 /// this buffer.
269 ///
270 /// # Examples
271 /// ```
272 /// # use divbuf::*;
273 /// let dbs = DivBufShared::with_capacity(4096);
274 /// let db = dbs.try_const().unwrap();
275 /// ```
276 ///
277 /// [`DivBuf`]: struct.DivBuf.html
278 /// [`DivBufMut`]: struct.DivBufMut.html
279 pub fn try_const(&self) -> Result<DivBuf, Error> {
280 let inner = unsafe { &*self.inner };
281 if inner.accessors.fetch_add(1, Acquire) >> WRITER_SHIFT != 0 {
282 inner.accessors.fetch_sub(1, Relaxed);
283 Err(Error("Cannot create a DivBuf when DivBufMuts are active"))
284 } else {
285 let l = inner.vec.len();
286 Ok(DivBuf {
287 inner: self.inner,
288 begin: 0,
289 len: l,
290 })
291 }
292 }
293
294 /// Try to create a mutable `DivBufMut` that refers to the entirety of this
295 /// buffer. Will fail if there are any [`DivBufMut`] or [`DivBuf`] objects
296 /// referring to this buffer.
297 ///
298 /// # Examples
299 /// ```
300 /// # use divbuf::*;
301 /// let dbs = DivBufShared::with_capacity(4096);
302 /// let dbm = dbs.try_mut().unwrap();
303 /// ```
304 ///
305 /// [`DivBuf`]: struct.DivBuf.html
306 /// [`DivBufMut`]: struct.DivBufMut.html
307 pub fn try_mut(&self) -> Result<DivBufMut, Error> {
308 let inner = unsafe { &*self.inner };
309 if inner
310 .accessors
311 .compare_exchange(0, ONE_WRITER, AcqRel, Acquire)
312 .is_ok()
313 {
314 let l = inner.vec.len();
315 Ok(DivBufMut {
316 inner: self.inner,
317 begin: 0,
318 len: l,
319 })
320 } else {
321 Err(Error(
322 "Cannot create a new DivBufMut when other DivBufs or \
323 DivBufMuts are active",
324 ))
325 }
326 }
327
328 /// Create a new DivBufShared with an uninitialized buffer of specified
329 /// length.
330 ///
331 /// # Safety
332 ///
333 /// This method technically causes undefined behavior, but it works with
334 /// current compilers. A good replacement is not possible until the
335 /// read-buf feature stabilizes.
336 ///
337 /// <https://github.com/rust-lang/rust/issues/78485>
338 #[cfg(any(feature = "experimental", docsrs))]
339 #[cfg_attr(docsrs, doc(cfg(feature = "experimental")))]
340 #[allow(clippy::uninit_vec)] // Needs the read-buf feature to fix
341 pub fn uninitialized(capacity: usize) -> Self {
342 let mut v = Vec::<u8>::with_capacity(capacity);
343 // safe because all possible byte patterns for u8 are valid
344 unsafe { v.set_len(capacity) };
345 Self::from(v)
346 }
347
348 /// Creates a new, empty, `DivBufShared` with a specified capacity.
349 ///
350 /// After constructing a `DivBufShared` this way, it can only be populated
351 /// via a child `DivBufMut`.
352 pub fn with_capacity(capacity: usize) -> Self {
353 Self::from(Vec::with_capacity(capacity))
354 }
355 }
356
357 impl Debug for DivBufShared {
358 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
359 let inner = unsafe { &*self.inner };
360 write!(f, "DivBufShared {{ inner: {:?} }}", inner)
361 }
362 }
363
364 impl Drop for DivBufShared {
365 fn drop(&mut self) {
366 let inner = unsafe { &*self.inner };
367 if inner.sharers.fetch_sub(1, Release) == 1
368 && inner.accessors.load(Relaxed) == 0
369 {
370 // See the comments in std::sync::Arc::drop for why the fence is
371 // required.
372 atomic::fence(Acquire);
373 unsafe {
374 drop(Box::from_raw(self.inner));
375 }
376 }
377 }
378 }
379
380 impl<'a> From<&'a [u8]> for DivBufShared {
381 fn from(src: &'a [u8]) -> DivBufShared {
382 DivBufShared::from(src.to_vec())
383 }
384 }
385
386 impl From<Vec<u8>> for DivBufShared {
387 fn from(src: Vec<u8>) -> DivBufShared {
388 let rc = AtomicUsize::new(0);
389 let sharers = AtomicUsize::new(1);
390 let inner = Box::new(Inner {
391 vec: src,
392 accessors: rc,
393 sharers,
394 });
395 DivBufShared {
396 inner: Box::into_raw(inner),
397 }
398 }
399 }
400
401 impl TryFrom<DivBufShared> for Vec<u8> {
402 type Error = DivBufShared;
403
404 /// Attempt to extract the owned storage from a DivBufShared.
405 ///
406 /// This will fail if there are any other living references to this same
407 /// `DivBufShared` (`DivBuf`s, `DivBufMut`s, etc), in which case the
408 /// `DivBufShared` will be returned unmodified.
409 ///
410 /// # Examples
411 ///
412 /// ```
413 /// # use divbuf::*;
414 /// use std::convert::TryInto;
415 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
416 /// let vec: Vec<u8> = dbs.try_into().unwrap();
417 /// assert_eq!(vec, vec![1, 2, 3, 4, 5, 6]);
418 /// ```
419 fn try_from(buf: DivBufShared) -> Result<Self, Self::Error> {
420 let inner = unsafe { &*buf.inner };
421 if inner.sharers.load(Acquire) == 1
422 && inner.accessors.load(Acquire) == 0
423 {
424 // See the comments in std::sync::Arc::drop for why the fence is
425 // required.
426 atomic::fence(Acquire);
427 let mut inner_box = unsafe { Box::from_raw(buf.inner) };
428 mem::forget(buf);
429 Ok(mem::take(&mut inner_box.vec))
430 } else {
431 Err(buf)
432 }
433 }
434 }
435
436 // DivBufShared owns the target of the `inner` pointer, and no method allows
437 // that pointer to be mutated. Atomic refcounts guarantee that no more than one
438 // writer at a time can modify `inner`'s contents (as long as DivBufMut is Sync,
439 // which it is). Therefore, DivBufShared is both Send and Sync.
440 unsafe impl Send for DivBufShared {}
441 unsafe impl Sync for DivBufShared {}
442
443 impl DivBuf {
444 /// Create a [`DivBufInaccessible`].
445 ///
446 /// It may later be upgraded to one of the accessible forms.
447 ///
448 /// # Examples
449 /// ```
450 /// # use divbuf::*;
451 /// let dbs = DivBufShared::with_capacity(4096);
452 /// let db = dbs.try_const().unwrap();
453 /// let _dbi = db.clone_inaccessible();
454 /// ```
455 pub fn clone_inaccessible(&self) -> DivBufInaccessible {
456 let inner = unsafe { &*self.inner };
457 let old = inner.sharers.fetch_add(1, Acquire);
458 debug_assert!(old > 0);
459 DivBufInaccessible {
460 inner: self.inner,
461 begin: self.begin,
462 len: self.len,
463 }
464 }
465
466 /// Break the buffer up into equal sized chunks
467 ///
468 /// Returns an interator which will yield equal sized chunks as smaller
469 /// `DivBuf`s. If the `DivBuf` is not evenly divisible by `size`, then the
470 /// last chunk will be smaller. This method is based on
471 /// `slice::chunks`, but with a few key differences:
472 ///
473 /// - It consumes `self`
474 /// - Yields smaller `DivBuf`s, not slices
475 /// - Yields owned objects, not references
476 ///
477 /// # Examples
478 /// ```
479 /// # use divbuf::*;
480 /// let dbs = DivBufShared::from(vec![0, 1, 2, 3, 4, 5, 6, 7]);
481 /// let db = dbs.try_const().unwrap();
482 /// let mut iter = db.into_chunks(3);
483 /// assert_eq!(&iter.next().unwrap()[..], &[0, 1, 2][..]);
484 /// assert_eq!(&iter.next().unwrap()[..], &[3, 4, 5][..]);
485 /// assert_eq!(&iter.next().unwrap()[..], &[6, 7][..]);
486 /// assert!(&iter.next().is_none())
487 /// ```
488 pub fn into_chunks(self, size: usize) -> Chunks {
489 assert!(size != 0);
490 Chunks::new(self, size)
491 }
492
493 /// Returns true if the `DivBuf` has length 0
494 pub fn is_empty(&self) -> bool {
495 self.len == 0
496 }
497
498 /// Get the length of this `DivBuf`, _not_ the underlying storage
499 pub fn len(&self) -> usize {
500 self.len
501 }
502
503 /// Create a new DivBuf that spans a subset of this one.
504 ///
505 /// # Examples
506 /// ```
507 /// # use divbuf::*;
508 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
509 /// let db0 = dbs.try_const().unwrap();
510 /// let db1 = db0.slice(1, 4);
511 /// assert_eq!(db1, [2, 3, 4][..]);
512 /// ```
513 pub fn slice(&self, begin: usize, end: usize) -> DivBuf {
514 assert!(begin <= end);
515 assert!(end <= self.len);
516 let inner = unsafe { &*self.inner };
517 let old_accessors = inner.accessors.fetch_add(1, Relaxed);
518 debug_assert!(old_accessors & READER_MASK > 0);
519 DivBuf {
520 inner: self.inner,
521 begin: self.begin + begin,
522 len: end - begin,
523 }
524 }
525
526 /// Creates a new DivBuf that spans a subset of this one, including the end
527 ///
528 /// # Examples
529 /// ```
530 /// # use divbuf::*;
531 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
532 /// let db0 = dbs.try_const().unwrap();
533 /// let db1 = db0.slice_from(3);
534 /// assert_eq!(db1, [4, 5, 6][..]);
535 /// ```
536 pub fn slice_from(&self, begin: usize) -> DivBuf {
537 self.slice(begin, self.len())
538 }
539
540 /// Creates a new DivBuf that spans a subset of self, including the
541 /// beginning
542 ///
543 /// # Examples
544 /// ```
545 /// # use divbuf::*;
546 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
547 /// let db0 = dbs.try_const().unwrap();
548 /// let db1 = db0.slice_to(3);
549 /// assert_eq!(db1, [1, 2, 3][..]);
550 /// ```
551 pub fn slice_to(&self, end: usize) -> DivBuf {
552 self.slice(0, end)
553 }
554
555 /// Splits the DivBuf into two at the given index.
556 ///
557 /// Afterwards self contains elements `[0, at)`, and the returned DivBuf
558 /// contains elements `[at, self.len)`.
559 ///
560 /// This is an O(1) operation
561 ///
562 /// # Examples
563 ///
564 /// ```
565 /// # use divbuf::*;
566 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
567 /// let mut db0 = dbs.try_const().unwrap();
568 /// let db1 = db0.split_off(4);
569 /// assert_eq!(db0, [1, 2, 3, 4][..]);
570 /// assert_eq!(db1, [5, 6][..]);
571 /// ```
572 pub fn split_off(&mut self, at: usize) -> DivBuf {
573 assert!(at <= self.len, "Can't split past the end");
574 let inner = unsafe { &*self.inner };
575 let old_accessors = inner.accessors.fetch_add(1, Relaxed);
576 debug_assert!(old_accessors & READER_MASK > 0);
577 let right_half = DivBuf {
578 inner: self.inner,
579 begin: self.begin + at,
580 len: self.len - at,
581 };
582 self.len = at;
583 right_half
584 }
585
586 /// Splits the DivBuf into two at the given index.
587 ///
588 /// Afterwards self contains elements `[at, self.len)`, and the returned
589 /// DivBuf contains elements `[0, at)`.
590 /// This is an O(1) operation.
591 ///
592 /// # Examples
593 ///
594 /// ```
595 /// # use divbuf::*;
596 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
597 /// let mut db0 = dbs.try_const().unwrap();
598 /// let db1 = db0.split_to(4);
599 /// assert_eq!(db0, [5, 6][..]);
600 /// assert_eq!(db1, [1, 2, 3, 4][..]);
601 /// ```
602 pub fn split_to(&mut self, at: usize) -> DivBuf {
603 assert!(at <= self.len, "Can't split past the end");
604 let inner = unsafe { &*self.inner };
605 let old_accessors = inner.accessors.fetch_add(1, Relaxed);
606 debug_assert!(old_accessors & READER_MASK > 0);
607 let left_half = DivBuf {
608 inner: self.inner,
609 begin: self.begin,
610 len: at,
611 };
612 self.begin += at;
613 self.len -= at;
614 left_half
615 }
616
617 /// Attempt to upgrade Self to a writable DivBufMut
618 ///
619 /// This will fail if there are any other living DivBufs for this same
620 /// DivBufShared
621 ///
622 /// # Examples
623 /// ```
624 /// # use divbuf::*;
625 /// let dbs = DivBufShared::with_capacity(4096);
626 /// let db = dbs.try_const().unwrap();
627 /// db.try_mut().unwrap();
628 /// ```
629 pub fn try_mut(self) -> Result<DivBufMut, DivBuf> {
630 let inner = unsafe { &*self.inner };
631 if inner
632 .accessors
633 .compare_exchange(1, ONE_WRITER, AcqRel, Acquire)
634 .is_ok()
635 {
636 let mutable_self = Ok(DivBufMut {
637 inner: self.inner,
638 begin: self.begin,
639 len: self.len,
640 });
641 mem::forget(self);
642 mutable_self
643 } else {
644 // LCOV_EXCL_LINE kcov false negative
645 Err(self)
646 }
647 }
648
649 /// Combine splitted DivBuf objects back into a contiguous single
650 ///
651 /// If `DivBuf` objects were not contiguous originally, the operation will
652 /// fail and return `other` unmodified
653 ///
654 /// # Examples
655 ///
656 /// ```
657 /// # use divbuf::*;
658 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
659 /// let mut db0 = dbs.try_const().unwrap();
660 /// let db1 = db0.split_off(4);
661 /// db0.unsplit(db1);
662 /// assert_eq!(db0, [1, 2, 3, 4, 5, 6][..]);
663 /// ```
664 pub fn unsplit(&mut self, other: DivBuf) -> Result<(), DivBuf> {
665 if self.inner != other.inner || (self.begin + self.len) != other.begin {
666 Err(other)
667 } else {
668 self.len += other.len;
669 Ok(())
670 }
671 }
672 }
673
674 impl AsRef<[u8]> for DivBuf {
675 fn as_ref(&self) -> &[u8] {
676 unsafe {
677 let inner = &*self.inner;
678 &inner.vec[self.begin..(self.begin + self.len)][..]
679 }
680 }
681 }
682
683 impl Borrow<[u8]> for DivBuf {
684 fn borrow(&self) -> &[u8] {
685 let inner = unsafe { &*self.inner };
686 &inner.vec[..]
687 }
688 }
689
690 impl hash::Hash for DivBuf {
691 fn hash<H>(&self, state: &mut H)
692 where
693 H: hash::Hasher,
694 {
695 let s: &[u8] = self.as_ref();
696 s.hash(state);
697 }
698 }
699
700 impl ops::Deref for DivBuf {
701 type Target = [u8];
702
703 fn deref(&self) -> &[u8] {
704 unsafe {
705 let inner = &*self.inner;
706 &inner.vec[self.begin..(self.begin + self.len)][..]
707 }
708 }
709 }
710
711 impl Clone for DivBuf {
712 fn clone(&self) -> DivBuf {
713 self.slice_from(0)
714 }
715 }
716
717 impl Drop for DivBuf {
718 fn drop(&mut self) {
719 let inner = unsafe { &*self.inner };
720 if inner.accessors.fetch_sub(1, Release) == 1
721 && inner.sharers.load(Relaxed) == 0
722 {
723 atomic::fence(Acquire);
724 unsafe {
725 drop(Box::from_raw(self.inner));
726 }
727 }
728 }
729 }
730
731 impl Eq for DivBuf {}
732
733 impl From<DivBufMut> for DivBuf {
734 fn from(src: DivBufMut) -> DivBuf {
735 src.freeze()
736 }
737 }
738
739 impl Ord for DivBuf {
740 fn cmp(&self, other: &DivBuf) -> cmp::Ordering {
741 self.as_ref().cmp(other.as_ref())
742 }
743 }
744
745 impl PartialEq for DivBuf {
746 fn eq(&self, other: &DivBuf) -> bool {
747 self.as_ref() == other.as_ref()
748 }
749 }
750
751 impl PartialEq<[u8]> for DivBuf {
752 fn eq(&self, other: &[u8]) -> bool {
753 self.as_ref() == other
754 }
755 }
756
757 impl PartialOrd for DivBuf {
758 fn partial_cmp(&self, other: &DivBuf) -> Option<cmp::Ordering> {
759 Some(self.cmp(other))
760 }
761 }
762
763 // Atomic refcounts provide shared ownership over the `inner` pointer,
764 // guaranteeing that it won't be freed as long as a `DivBuf` exists. No method
765 // allows that pointer to be mutated. Atomic refcounts also guarantee that no
766 // more than one writer at a time can modify `inner`'s contents (as long as
767 // DivBufMut is Sync, which it is). Therefore, DivBuf is both Send and Sync.
768 unsafe impl Send for DivBuf {}
769 unsafe impl Sync for DivBuf {}
770
771 impl DivBufMut {
772 /// Create a [`DivBufInaccessible`].
773 ///
774 /// It may later be upgraded to one of the accessible forms.
775 ///
776 /// # Examples
777 /// ```
778 /// # use divbuf::*;
779 /// let dbs = DivBufShared::with_capacity(4096);
780 /// let dbm = dbs.try_mut().unwrap();
781 /// let _dbi = dbm.clone_inaccessible();
782 /// ```
783 pub fn clone_inaccessible(&self) -> DivBufInaccessible {
784 let inner = unsafe { &*self.inner };
785 let old = inner.sharers.fetch_add(1, Acquire);
786 debug_assert!(old > 0);
787 DivBufInaccessible {
788 inner: self.inner,
789 begin: self.begin,
790 len: self.len,
791 }
792 }
793
794 /// Extend self from iterator, without checking for validity
795 fn extend_unchecked<'a, T>(&mut self, iter: T)
796 where
797 T: IntoIterator<Item = &'a u8>,
798 {
799 let inner = unsafe { &mut *self.inner };
800 let oldlen = inner.vec.len();
801 inner.vec.extend(iter);
802 self.len += inner.vec.len() - oldlen;
803 }
804
805 /// Downgrade this `DivBufMut` into a read-only `DivBuf`
806 ///
807 /// Note that this method will always succeed, but subsequently calling
808 /// [`try_mut`] on the returned `DivBuf` may not.
809 ///
810 /// # Examples
811 /// ```
812 /// # use divbuf::*;
813 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
814 /// let dbm0 = dbs.try_mut().unwrap();
815 /// let db : DivBuf = dbm0.freeze();
816 /// ```
817 ///
818 /// [`try_mut`]: struct.DivBuf.html#method.try_mut
819 pub fn freeze(self) -> DivBuf {
820 // Construct a new DivBuf, then drop self. We know that there are no
821 // other DivButMuts that overlap with this one, so it's safe to create a
822 // DivBuf whose range is restricted to what self covers
823 let inner = unsafe { &*self.inner };
824 let old_accessors = inner.accessors.fetch_add(1, Relaxed);
825 debug_assert!(old_accessors >> WRITER_SHIFT > 0);
826 DivBuf {
827 inner: self.inner,
828 begin: self.begin,
829 len: self.len,
830 }
831 }
832
833 /// Break the buffer up into equal sized chunks
834 ///
835 /// Returns an interator which will yield equal sized chunks as smaller
836 /// `DivBufMut`s. If the `DivBufMut` is not evenly divisible by `size`,
837 /// then the last chunk will be smaller. This method is based on
838 /// `slice::chunk_muts`, but with a few key differences:
839 ///
840 /// - It consumes `self`
841 /// - Yields smaller `DivBufMut`s, not slices
842 /// - Yields owned objects, not references
843 ///
844 /// # Examples
845 /// ```
846 /// # use divbuf::*;
847 /// let dbs = DivBufShared::from(vec![0, 1, 2, 3, 4, 5, 6, 7]);
848 /// let dbm = dbs.try_mut().unwrap();
849 /// let mut iter = dbm.into_chunks(3);
850 /// assert_eq!(&iter.next().unwrap()[..], &[0, 1, 2][..]);
851 /// assert_eq!(&iter.next().unwrap()[..], &[3, 4, 5][..]);
852 /// assert_eq!(&iter.next().unwrap()[..], &[6, 7][..]);
853 /// assert!(&iter.next().is_none())
854 /// ```
855 pub fn into_chunks(self, size: usize) -> ChunksMut {
856 assert!(size != 0);
857 ChunksMut::new(self, size)
858 }
859
860 /// Returns true if the `DivBufMut` has length 0
861 pub fn is_empty(&self) -> bool {
862 self.len == 0
863 }
864
865 /// Returns true if the `DivBufMut` extends to the end of the `DivBufShared`
866 fn is_terminal(&self) -> bool {
867 let inner = unsafe { &*self.inner };
868 let oldlen = inner.vec.len();
869 self.begin + self.len == oldlen
870 }
871
872 /// Get the length of this `DivBufMut`, _not_ the underlying storage
873 pub fn len(&self) -> usize {
874 self.len
875 }
876
877 /// Reserves capacity for at least `additional` more bytes to be inserted
878 /// into the buffer.
879 ///
880 /// Like [`extend`], this method will panic if the `DivBufMut` is
881 /// non-terminal.
882 ///
883 /// [`extend`]: #method.extend
884 pub fn reserve(&mut self, additional: usize) {
885 // panic if this DivBufMut does not extend to the end of the
886 // DivBufShared
887 assert!(
888 self.is_terminal(),
889 "Can't reserve from the middle of a buffer"
890 );
891 let inner = unsafe { &mut *self.inner };
892 inner.vec.reserve(additional)
893 }
894
895 /// Splits the DivBufMut into two at the given index.
896 ///
897 /// Afterwards self contains elements `[0, at)`, and the returned DivBufMut
898 /// contains elements `[at, self.len)`.
899 ///
900 /// This is an O(1) operation
901 ///
902 /// # Examples
903 ///
904 /// ```
905 /// # use divbuf::*;
906 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
907 /// let mut dbm0 = dbs.try_mut().unwrap();
908 /// let dbm1 = dbm0.split_off(4);
909 /// assert_eq!(dbm0, [1, 2, 3, 4][..]);
910 /// assert_eq!(dbm1, [5, 6][..]);
911 /// ```
912 pub fn split_off(&mut self, at: usize) -> DivBufMut {
913 assert!(at <= self.len, "Can't split past the end");
914 let inner = unsafe { &*self.inner };
915 let old_accessors = inner.accessors.fetch_add(ONE_WRITER, Relaxed);
916 debug_assert!(old_accessors >> WRITER_SHIFT > 0);
917 let right_half = DivBufMut {
918 inner: self.inner,
919 begin: self.begin + at,
920 len: self.len - at,
921 };
922 self.len = at;
923 right_half
924 }
925
926 /// Splits the DivBufMut into two at the given index.
927 ///
928 /// Afterwards self contains elements `[at, self.len)`, and the returned
929 /// DivBufMut contains elements `[0, at)`.
930 /// This is an O(1) operation.
931 ///
932 /// # Examples
933 ///
934 /// ```
935 /// # use divbuf::*;
936 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
937 /// let mut dbm0 = dbs.try_mut().unwrap();
938 /// let dbm1 = dbm0.split_to(4);
939 /// assert_eq!(dbm0, [5, 6][..]);
940 /// assert_eq!(dbm1, [1, 2, 3, 4][..]);
941 /// ```
942 pub fn split_to(&mut self, at: usize) -> DivBufMut {
943 assert!(at <= self.len, "Can't split past the end");
944 let inner = unsafe { &*self.inner };
945 let old_accessors = inner.accessors.fetch_add(ONE_WRITER, Relaxed);
946 debug_assert!(old_accessors >> WRITER_SHIFT > 0);
947 let left_half = DivBufMut {
948 inner: self.inner,
949 begin: self.begin,
950 len: at,
951 };
952 self.begin += at;
953 self.len -= at;
954 left_half
955 }
956
957 /// Attempt to extend this `DivBufMut` with bytes from the provided
958 /// iterator.
959 ///
960 /// If this `DivBufMut` is not terminal, that is if it does not extend to
961 /// the end of the `DivBufShared`, then this operation will return an error
962 /// and the buffer will not be modified. The [`extend`] method from the
963 /// `Extend` Trait, by contrast, will panic under the same condition.
964 ///
965 /// # Examples
966 /// ```
967 /// # use divbuf::*;
968 /// let dbs = DivBufShared::with_capacity(64);
969 /// let mut dbm0 = dbs.try_mut().unwrap();
970 /// assert!(dbm0.try_extend([1, 2, 3].iter()).is_ok());
971 /// ```
972 ///
973 /// [`extend`]: #method.extend
974 pub fn try_extend<'a, T>(&mut self, iter: T) -> Result<(), Error>
975 where
976 T: IntoIterator<Item = &'a u8>,
977 {
978 if self.is_terminal() {
979 self.extend_unchecked(iter);
980 Ok(())
981 } else {
982 Err(Error("Can't extend into the middle of a buffer"))
983 }
984 }
985
986 /// Attempt to resize this `DivBufMut` in-place.
987 ///
988 /// If `new_len` is greater than the existing length, then the buffer will
989 /// be extended by the difference, with each element filled by `value`. If
990 /// `new_len` is less than the existing length, then the buffer is simply
991 /// truncated.
992 ///
993 /// If this `DivBufMut` is not terminal, that is if it does not extend to
994 /// the end of the `DivBufShared`, then this operation will return an error
995 /// and the buffer will not be modified.
996 ///
997 /// # Examples
998 /// ```
999 /// # use divbuf::*;
1000 /// let dbs = DivBufShared::with_capacity(64);
1001 /// let mut dbm0 = dbs.try_mut().unwrap();
1002 /// assert!(dbm0.try_resize(4, 0).is_ok());
1003 /// assert_eq!(&dbm0[..], &[0, 0, 0, 0][..]);
1004 /// ```
1005 pub fn try_resize(
1006 &mut self,
1007 new_len: usize,
1008 value: u8,
1009 ) -> Result<(), Error> {
1010 if self.is_terminal() {
1011 let inner = unsafe { &mut *self.inner };
1012 inner.vec.resize(new_len + self.begin, value);
1013 self.len = new_len;
1014 Ok(())
1015 } else {
1016 Err(Error("Can't resize from a non-terminal buffer"))
1017 }
1018 }
1019
1020 /// Shortens the buffer, keeping the first `len` bytes and dropping the
1021 /// rest.
1022 ///
1023 /// If `len` is greater than the buffer's current length, this has no
1024 /// effect.
1025 ///
1026 /// Like [`try_extend`], will fail if this DivButMut is non-terminal.
1027 ///
1028 /// # Examples
1029 ///
1030 /// ```
1031 /// # use divbuf::*;
1032 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
1033 /// let mut dbm0 = dbs.try_mut().unwrap();
1034 /// assert!(dbm0.try_truncate(3).is_ok());
1035 /// assert_eq!(dbm0, [1, 2, 3][..]);
1036 /// ```
1037 ///
1038 /// [`try_extend`]: #method.try_extend
1039 pub fn try_truncate(&mut self, len: usize) -> Result<(), Error> {
1040 if self.is_terminal() {
1041 let inner = unsafe { &mut *self.inner };
1042 inner.vec.truncate(self.begin + len);
1043 self.len = cmp::min(self.len, len);
1044 Ok(())
1045 } else {
1046 Err(Error("Can't truncate a non-terminal DivBufMut"))
1047 }
1048 }
1049
1050 /// Combine splitted DivBufMut objects back into a contiguous single
1051 ///
1052 /// If `DivBufMut` objects were not contiguous originally, the operation
1053 /// will fail and return `other` unmodified
1054 ///
1055 /// # Examples
1056 ///
1057 /// ```
1058 /// # use divbuf::*;
1059 /// let dbs = DivBufShared::from(vec![1, 2, 3, 4, 5, 6]);
1060 /// let mut dbm0 = dbs.try_mut().unwrap();
1061 /// let dbm1 = dbm0.split_off(4);
1062 /// dbm0.unsplit(dbm1);
1063 /// assert_eq!(dbm0, [1, 2, 3, 4, 5, 6][..]);
1064 /// ```
1065 pub fn unsplit(&mut self, other: DivBufMut) -> Result<(), DivBufMut> {
1066 if self.inner != other.inner || (self.begin + self.len) != other.begin {
1067 Err(other)
1068 } else {
1069 self.len += other.len;
1070 Ok(())
1071 }
1072 }
1073 }
1074
1075 impl AsRef<[u8]> for DivBufMut {
1076 fn as_ref(&self) -> &[u8] {
1077 unsafe {
1078 let inner = &*self.inner;
1079 &inner.vec[self.begin..(self.begin + self.len)][..]
1080 }
1081 }
1082 }
1083
1084 impl Borrow<[u8]> for DivBufMut {
1085 fn borrow(&self) -> &[u8] {
1086 let inner = unsafe { &*self.inner };
1087 &inner.vec[..]
1088 }
1089 }
1090
1091 impl BorrowMut<[u8]> for DivBufMut {
1092 fn borrow_mut(&mut self) -> &mut [u8] {
1093 let inner = unsafe { &mut *self.inner };
1094 &mut inner.vec[..]
1095 }
1096 }
1097
1098 impl ops::Deref for DivBufMut {
1099 type Target = [u8];
1100
1101 fn deref(&self) -> &[u8] {
1102 unsafe {
1103 let inner = &*self.inner;
1104 &inner.vec[self.begin..(self.begin + self.len)][..]
1105 }
1106 }
1107 }
1108
1109 impl ops::DerefMut for DivBufMut {
1110 fn deref_mut(&mut self) -> &mut [u8] {
1111 unsafe {
1112 let inner = &mut *self.inner;
1113 &mut inner.vec[self.begin..(self.begin + self.len)][..]
1114 }
1115 }
1116 }
1117
1118 impl Drop for DivBufMut {
1119 fn drop(&mut self) {
1120 let inner = unsafe { &*self.inner };
1121 if inner.accessors.fetch_sub(ONE_WRITER, Release) == ONE_WRITER
1122 && inner.sharers.load(Relaxed) == 0
1123 {
1124 atomic::fence(Acquire);
1125 unsafe {
1126 drop(Box::from_raw(self.inner));
1127 }
1128 }
1129 }
1130 }
1131
1132 impl<'a> Extend<&'a u8> for DivBufMut {
1133 fn extend<T>(&mut self, iter: T)
1134 where
1135 T: IntoIterator<Item = &'a u8>,
1136 {
1137 // panic if this DivBufMut does not extend to the end of the
1138 // DivBufShared
1139 assert!(
1140 self.is_terminal(),
1141 "Can't extend into the middle of a buffer"
1142 );
1143 self.extend_unchecked(iter);
1144 }
1145 }
1146
1147 impl hash::Hash for DivBufMut {
1148 fn hash<H>(&self, state: &mut H)
1149 where
1150 H: hash::Hasher,
1151 {
1152 let s: &[u8] = self.as_ref();
1153 s.hash(state);
1154 }
1155 }
1156
1157 impl Eq for DivBufMut {}
1158
1159 impl Ord for DivBufMut {
1160 fn cmp(&self, other: &DivBufMut) -> cmp::Ordering {
1161 self.as_ref().cmp(other.as_ref())
1162 }
1163 }
1164
1165 impl PartialEq for DivBufMut {
1166 fn eq(&self, other: &DivBufMut) -> bool {
1167 self.as_ref() == other.as_ref()
1168 }
1169 }
1170
1171 impl PartialEq<[u8]> for DivBufMut {
1172 fn eq(&self, other: &[u8]) -> bool {
1173 self.as_ref() == other
1174 }
1175 }
1176
1177 impl PartialOrd for DivBufMut {
1178 fn partial_cmp(&self, other: &DivBufMut) -> Option<cmp::Ordering> {
1179 Some(self.cmp(other))
1180 }
1181 }
1182
1183 // Atomic refcounts provide shared ownership over the `inner` pointer,
1184 // guaranteeing that it won't be freed as long as a `DivBufMut` exists. No method
1185 // allows that pointer to be mutated. Atomic refcounts also guarantee that no
1186 // more than one writer at a time can modify `inner`'s contents (as long as
1187 // DivBufMut is Sync, which it is). Thereforce, DivBufMut is Send. And while
1188 // DivBufMut allows `inner`'s contents to be mutated, it does not provide
1189 // interior mutability; a &mut DivButMut is required. Therefore, DivBufMut is
1190 // Sync as well.
1191 unsafe impl Send for DivBufMut {}
1192 unsafe impl Sync for DivBufMut {}
1193
1194 impl io::Write for DivBufMut {
1195 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1196 self.try_extend(buf)
1197 .map(|_| buf.len())
1198 .map_err(|s| io::Error::new(io::ErrorKind::Other, s))
1199 }
1200
1201 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1202 self.try_extend(buf)
1203 .map_err(|s| io::Error::new(io::ErrorKind::Other, s))
1204 }
1205
1206 fn flush(&mut self) -> io::Result<()> {
1207 Ok(())
1208 }
1209 }
1210
1211 impl DivBufInaccessible {
1212 /// Try to upgrade to a [`DivBuf`].
1213 ///
1214 /// Will fail if there are any [`DivBufMut`]s referring to this same buffer.
1215 ///
1216 /// # Examples
1217 /// ```
1218 /// # use divbuf::*;
1219 /// let dbs = DivBufShared::with_capacity(4096);
1220 /// let dbm = dbs.try_mut().unwrap();
1221 /// let dbi = dbm.clone_inaccessible();
1222 /// drop(dbm);
1223 /// let _db: DivBuf = dbi.try_const().unwrap();
1224 /// ```
1225 pub fn try_const(&self) -> Result<DivBuf, Error> {
1226 let inner = unsafe { &*self.inner };
1227 if inner.accessors.fetch_add(1, Acquire) >> WRITER_SHIFT != 0 {
1228 inner.accessors.fetch_sub(1, Relaxed);
1229 Err(Error("Cannot create a DivBuf when DivBufMuts are active"))
1230 } else {
1231 Ok(DivBuf {
1232 inner: self.inner,
1233 begin: self.begin,
1234 len: self.len,
1235 })
1236 }
1237 }
1238
1239 /// Try to upgrade to a [`DivBufMut`].
1240 ///
1241 /// Will fail if there are any [`DivBufMut`]s referring to this same buffer.
1242 ///
1243 /// # Examples
1244 /// ```
1245 /// # use divbuf::*;
1246 /// let dbs = DivBufShared::with_capacity(4096);
1247 /// let dbm = dbs.try_mut().unwrap();
1248 /// let dbi = dbm.clone_inaccessible();
1249 /// drop(dbm);
1250 /// let _dbm: DivBufMut = dbi.try_mut().unwrap();
1251 /// ```
1252 pub fn try_mut(&self) -> Result<DivBufMut, Error> {
1253 let inner = unsafe { &*self.inner };
1254 if inner
1255 .accessors
1256 .compare_exchange(0, ONE_WRITER, AcqRel, Acquire)
1257 .is_ok()
1258 {
1259 Ok(DivBufMut {
1260 inner: self.inner,
1261 begin: self.begin,
1262 len: self.len,
1263 })
1264 } else {
1265 Err(Error("Cannot upgrade when DivBufMuts are active"))
1266 }
1267 }
1268 }
1269
1270 impl Clone for DivBufInaccessible {
1271 fn clone(&self) -> Self {
1272 let inner = unsafe { &*self.inner };
1273 let old = inner.sharers.fetch_add(1, Acquire);
1274 debug_assert!(old > 0);
1275 DivBufInaccessible {
1276 inner: self.inner,
1277 begin: self.begin,
1278 len: self.len,
1279 }
1280 }
1281 }
1282
1283 impl Drop for DivBufInaccessible {
1284 fn drop(&mut self) {
1285 let inner = unsafe { &*self.inner };
1286 if inner.sharers.fetch_sub(1, Release) == 1
1287 && inner.accessors.load(Relaxed) == 0
1288 {
1289 // See the comments in std::sync::Arc::drop for why the fence is
1290 // required.
1291 atomic::fence(Acquire);
1292 unsafe {
1293 drop(Box::from_raw(self.inner));
1294 }
1295 }
1296 }
1297 }
1298
1299 // DivBufInaccessible owns the target of the `inner` pointer, and no method
1300 // allows that pointer to be mutated. Atomic refcounts guarantee that no more
1301 // than one writer at a time can modify `inner`'s contents (as long as DivBufMut
1302 // is Sync, which it is). Therefore, DivBufInaccessible is both Send and Sync.
1303 unsafe impl Send for DivBufInaccessible {}
1304 unsafe impl Sync for DivBufInaccessible {}