netbuf/
buf.rs

1use std::ptr::{copy_nonoverlapping, copy};
2use std::ops::{Index, IndexMut, RangeFrom, RangeTo, RangeFull, Range};
3use std::cmp::{min, max};
4use std::io::{Read, Write, Result};
5use std::fmt::{self, Debug};
6use std::mem::swap;
7
8use range::RangeArgument;
9
10const READ_MIN: usize = 4096;
11const ALLOC_MIN: usize = 16384;
12
13///
14/// A buffer object to be used for reading from network
15///
16/// Assumptions:
17///
18/// 1. Buffer needs to be growable as sometimes requests are large
19///
20/// 2. Buffer should deallocate when empty as
21///    most of the time connections are idle
22///
23///      a. Deallocations are cheap as we have a cool memory allocator
24///      (jemalloc)
25///
26///      b. First allocation should be big (i.e. kilobytes not few bytes)
27///
28/// 3. Should be easy to peek and get a slice as it makes packet parsing easy
29///
30/// 4. Cheap removing bytes at the start of the buf
31///
32pub struct Buf {
33    data: Option<Box<[u8]>>,
34    consumed: usize,
35    remaining: usize,
36}
37
38
39// TODO(tailhook) use std::slice::bytes::copy_memory;
40fn copy_memory(src: &[u8], dst: &mut [u8]) {
41    assert!(src.len() == dst.len());
42    unsafe {
43        copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), dst.len());
44    }
45}
46
47
48impl Buf {
49    /// Create empty buffer. It has no preallocated size. The underlying memory
50    /// chunk is always deallocated when there are no useful bytes in the
51    /// buffer.
52    pub fn new() -> Buf {
53        Buf {
54            data: None,
55            consumed: 0,
56            remaining: 0,
57        }
58    }
59    fn reserve(&mut self, bytes: usize) {
60        self.data = self.data.take().map(|slice| {
61            let old_cap = slice.len();
62            let old_bytes = old_cap - self.consumed() - self.remaining();
63
64            if self.consumed() > 0 { // let's allocate new slice and move
65                let min_size = old_bytes + bytes;
66
67                let mut vec = Vec::with_capacity(max(min_size, old_cap.saturating_mul(2)));
68                let cap = vec.capacity();
69                unsafe { vec.set_len(cap) };
70                copy_memory(&slice[self.consumed()..old_cap - self.remaining()],
71                            &mut vec[..old_bytes]);
72                self.remaining = cap - old_bytes;
73                self.consumed = 0;
74                Some(vec.into_boxed_slice())
75            } else { // just reallocate
76                let mut vec = slice.into_vec();
77                vec.reserve(bytes);
78                let cap = vec.capacity();
79                unsafe { vec.set_len(cap) };
80                self.remaining = cap - old_bytes;
81                Some(vec.into_boxed_slice())
82            }
83        }).unwrap_or_else(|| {
84            let mut vec = Vec::with_capacity(max(bytes, ALLOC_MIN));
85            let cap = vec.capacity();
86            unsafe { vec.set_len(cap) };
87
88            self.remaining = cap;
89            Some(vec.into_boxed_slice())
90        })
91    }
92    fn reserve_exact(&mut self, bytes: usize) {
93        self.data = self.data.take().map(|slice| {
94            let old_cap = slice.len();
95            let old_bytes = old_cap - self.consumed() - self.remaining();
96
97            if self.consumed() > 0 { // let's allocate new slice and move
98                let size = old_bytes + bytes;
99                let mut vec = Vec::with_capacity(size);
100                let cap = vec.capacity();
101                unsafe { vec.set_len(cap) };
102                copy_memory(&slice[self.consumed()..old_cap - self.remaining()],
103                            &mut vec[..old_bytes]);
104                self.remaining = cap - old_bytes;
105                self.consumed = 0;
106                Some(vec.into_boxed_slice())
107            } else { // just reallocate
108                let mut vec = slice.into_vec();
109                vec.reserve_exact(bytes);
110                let cap = vec.capacity();
111                unsafe { vec.set_len(cap) };
112                self.remaining = cap - old_bytes;
113                Some(vec.into_boxed_slice())
114            }
115        }).unwrap_or_else(|| {
116            let mut vec = Vec::with_capacity(bytes);
117            let cap = vec.capacity();
118            unsafe { vec.set_len(cap) };
119
120            self.remaining = cap;
121            Some(vec.into_boxed_slice())
122        })
123    }
124    fn remaining(&self) -> usize {
125        self.remaining as usize
126    }
127    fn consumed(&self) -> usize {
128        self.consumed as usize
129    }
130
131    /// Mark the first `bytes` of the buffer as read. Basically it's shaving
132    /// off bytes from the buffer, but does it efficiently. When there are
133    /// no more bytes in the buffer it's deallocated.
134    ///
135    /// Note: Buffer currently doesn't shrink when calling this method. It's
136    /// assumed that all bytes will be consumed shortly. In case you're
137    /// appending to the buffer after consume, old data is discarded.
138    ///
139    /// # Panics
140    ///
141    /// Panics if `bytes` is larger than current length of buffer
142    pub fn consume(&mut self, bytes: usize) {
143        let ln = self.len();
144        assert!(bytes <= ln);
145        if bytes == ln {
146            *self = Buf::new();
147        } else {
148            self.consumed += bytes;
149        }
150    }
151
152    /// Allows removing an arbitrary range of bytes
153    ///
154    /// A more comprehensive version of `consume()`. It's occasionally useful
155    /// if your data is in frames/chunks but you want to buffer the whole body
156    /// anyway. E.g. in http chunked encoding you have each chunk prefixed by
157    /// its length, but that doesn't mean you can't buffer the whole request
158    /// into memory. This method allows you to continue reading the next chunk
159    /// into the same buffer while removing the chunk length.
160    ///
161    /// Note: it's not super efficient, as it requires to move (copy) bytes
162    /// after the range, in case range is neither at the start nor at the
163    /// end of buffer. Still it should be faster than copying everything
164    /// to yet another buffer.
165    ///
166    /// We never shrink the buffer here (except when it becomes empty, to
167    /// keep this invariant), assuming that you will receive more data into
168    /// the buffer shortly.
169    ///
170    /// The `RangeArgument` type is a temporary type until rust provides
171    /// the one in standard library, you should use the range syntax directly:
172    ///
173    /// ```ignore
174    ///     buf.remove_range(5..7)
175    /// ```
176    ///
177    /// # Panics
178    ///
179    /// Panics if range is invalid for the buffer
180    pub fn remove_range<R: Into<RangeArgument>>(&mut self, range: R) {
181        use range::RangeArgument::*;
182        match range.into() {
183            RangeTo(x) | Range(0, x) => self.consume(x),
184            RangeFrom(0) => *self = Buf::new(),
185            RangeFrom(x) => {
186                let ln = self.len();
187                assert!(x <= ln);
188                self.remaining += ln - x;
189            }
190            Range(x, y) => {
191                let ln = self.len();
192                if x == y { return; }
193                assert!(x < y);
194                let removed_bytes = y - x;
195                assert!(y <= ln);
196                let start = self.consumed() + x;
197                let end = self.consumed() + y;
198                if let Some(ref mut data) = self.data {
199                    let dlen = data.len();
200                    unsafe {
201                        copy(data[end..].as_ptr(),
202                            data[start..dlen - removed_bytes].as_mut_ptr(),
203                            dlen - end);
204                    }
205                    self.remaining += removed_bytes;
206                } else {
207                    panic!("Not-existent buffere where data exists");
208                }
209            }
210        }
211    }
212
213
214    /// Capacity of the buffer. I.e. the bytes it is allocated for. Use for
215    /// debugging or for calculating memory usage. Note it's not guaranteed
216    /// that you can write `buf.capacity() - buf.len()` bytes without resize
217    pub fn capacity(&self) -> usize {
218        self.data.as_ref().map(|x| x.len()).unwrap_or(0)
219    }
220
221    /// Number of useful bytes in the buffer
222    pub fn len(&self) -> usize {
223        self.data.as_ref()
224        .map(|x| x.len() - self.consumed() - self.remaining())
225        .unwrap_or(0)
226    }
227
228    /// If buffer is empty. Potentially a little bit faster than
229    /// getting `len()`
230    pub fn is_empty(&self) -> bool {
231        self.data.is_none()
232    }
233
234    fn future_slice<'x>(&'x mut self) -> &'x mut [u8] {
235        let rem = self.remaining();
236        self.data.as_mut()
237        .map(|x| {
238            let upto = x.len();
239            &mut x[upto - rem .. upto]
240        })
241        .unwrap()
242    }
243
244    /// Extend buffer. Note unlike `Write::write()` and `read_from()` this
245    /// method reserves as small as possible a chunk of memory. So it's
246    /// inefficien to grow with this method.  You may use the Write trait to
247    /// grow incrementally.
248    pub fn extend(&mut self, buf: &[u8]) {
249        if buf.len() == 0 { return; }
250        if self.remaining() < buf.len() {
251            self.reserve_exact(buf.len());
252        }
253        copy_memory(buf, &mut self.future_slice()[..buf.len()]);
254        self.remaining -= buf.len();
255    }
256
257    /// Read some bytes from stream (object implementing `Read`) into buffer
258    ///
259    /// Note this does *not* continue to read until getting `WouldBlock`. It
260    /// passes all errors as is. It preallocates some chunk to read into
261    /// buffer. It may be possible that the stream still has bytes buffered
262    /// after this method returns. This method is expected either to be called
263    /// until `WouldBlock` is returned or is used with level-triggered polling.
264    pub fn read_from<R:Read>(&mut self, stream: &mut R) -> Result<usize> {
265        if self.remaining() < READ_MIN {
266            self.reserve(READ_MIN);
267        }
268        let bytes = match stream.read(self.future_slice()) {
269            res @ Ok(0) | res @ Err(_) => {
270                self.consume(0);
271                return res;
272            }
273            Ok(x) => x,
274        };
275        debug_assert!(bytes <= self.remaining());
276        self.remaining -= bytes;
277        Ok(bytes)
278    }
279
280    /// Reads no more than max bytes into buffer and returns boolean flag
281    /// of whether max bytes are reached
282    ///
283    /// Except for the limit on number of bytes and slightly different
284    /// allocation strategy, this method has the same considerations as
285    /// read_from
286    ///
287    /// Note this method might be used for two purposes:
288    ///
289    /// 1. Limit number of bytes buffered until parser can process data
290    ///   (for example HTTP header size, which is number of bytes read before
291    ///   `\r\n\r\n` delimiter reached)
292    /// 2. Wait until exact number of bytes are fully received
293    ///
294    /// Since we support (1) we don't preallocate buffer for exact size of
295    /// the `max` value. It also helps a little in case (2) for minimizing
296    /// DDoS attack vector. If that doesn't suit you, you may wish to use
297    /// `Vec::with_capacity()` for the purpose of (2).
298    ///
299    /// On the contrary we don't overallocate more than `max` bytes, so if
300    /// you expect data to go after exact number of bytes read, it might be
301    /// better to use `read_from()` and check buffer length.
302    ///
303    pub fn read_max_from<R:Read>(&mut self, max: usize, stream: &mut R)
304        -> Result<bool>
305    {
306        let todo = max.saturating_sub(self.len());
307        if todo == 0 {
308            return Ok(true);
309        }
310        if self.remaining() < READ_MIN {
311            if self.capacity().saturating_mul(2) < max {
312                // TODO is too large we may never need so big buffer
313                self.reserve(READ_MIN);
314            } else {
315                self.reserve_exact(todo);
316            }
317        }
318        let res = {
319            let slc = self.future_slice();
320            let do_now = min(slc.len(), todo);
321            stream.read(&mut slc[..do_now])
322        };
323        let bytes = match res {
324            Ok(0) => {
325                self.consume(0);
326                return Ok(false);
327            }
328            Err(e) => {
329                self.consume(0);
330                return Err(e);
331            }
332            Ok(x) => x,
333        };
334        debug_assert!(bytes <= self.remaining());
335        self.remaining -= bytes;
336        Ok(self.len() >= max)
337    }
338
339    /// Write contents of buffer to the stream (object implementing
340    /// the Write trait). We assume that stream is non-blocking, use
341    /// `Write::write` (instead of `Write::write_all`) and return all errors
342    /// to the caller (including `WouldBlock` or `Interrupted`).
343    ///
344    /// In addition to returning the number of bytes written, it also
345    /// `consume()`s those bytes from the buffer, so it's safe to retry calling
346    /// the method at any moment. Also it's a common pattern to append more
347    /// data to the buffer between calls.
348    pub fn write_to<W:Write>(&mut self, sock: &mut W) -> Result<usize> {
349        let bytes = match sock.write(&self[..]) {
350            Ok(bytes) => bytes,
351            Err(e) => return Err(e),
352        };
353        self.consume(bytes);
354        Ok(bytes)
355    }
356
357    /// Splits buffer into two at the given index.
358    ///
359    /// `self` contains bytes `[0, at)` and the returned `Buf` contains
360    /// bytes `[at, len)`.
361    ///
362    /// Reallocates smaller part of buffer.
363    ///
364    /// # Panics
365    ///
366    /// Panics if at > len.
367    ///
368    /// # Examples
369    /// ```rust
370    /// let mut buf = netbuf::Buf::new();
371    /// buf.extend(b"Hello World!");
372    /// let tail = buf.split_off(6);
373    /// assert_eq!(&buf[..], b"Hello ");
374    /// assert_eq!(&tail[..], b"World!");
375    /// ```
376    pub fn split_off(&mut self, at: usize) -> Buf {
377        assert!(at <= self.len());
378        let mut tail = Buf::new();
379        match self.data.as_ref().map(|x| x.len() - at > at) {
380            Some(true) => { // re-allocate self;
381                swap(&mut tail, self);
382                if at > 0 {
383                    self.extend(&tail[..at]);
384                    tail.consume(at);
385                }
386            },
387            Some(false) => { // allocate for tail;
388                tail.extend(&self[at..]);
389                self.remove_range(at..);
390            },
391            None => {}
392        }
393        tail
394    }
395
396    /// Returns the byte at the index, or `None` if the index is
397    /// out of bounds.
398    pub fn get(&self, index: usize) -> Option<u8> {
399        if index >= self.len() {
400            return None;
401        }
402        let consumed = self.consumed();
403        if let Some(ref data) = self.data {
404            Some(data[consumed + index])
405        } else {
406            None
407        }
408    }
409
410    /// Returns a mutable reference to the byte at the index, or
411    /// `None` if the index is out of bounds.
412    pub fn get_mut(&mut self, index: usize) -> Option<&mut u8> {
413        if index >= self.len() {
414            return None;
415        }
416        let consumed = self.consumed();
417        if let Some(ref mut data) = self.data {
418            Some(&mut data[consumed + index])
419        } else {
420            None
421        }
422    }
423
424}
425
426
427impl Debug for Buf {
428    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
429        write!(f, "Buf {{ len={}; consumed={}; remaining={} }}",
430               self.len(), self.consumed(), self.remaining())
431    }
432}
433
434impl AsRef<[u8]> for Buf {
435    fn as_ref(&self) -> &[u8] {
436        &self[..]
437    }
438}
439
440impl Into<Vec<u8>> for Buf {
441    fn into(mut self) -> Vec<u8> {
442        if self.consumed == 0 {
443            self.data.take().map(|slice| {
444                let mut vec = slice.into_vec();
445                if self.remaining > 0 {
446                    let nlen = vec.len() - self.remaining();
447                    unsafe { vec.set_len(nlen) };
448                }
449                vec
450            }).unwrap_or_else(Vec::new)
451        } else {
452            self[..].to_vec()
453        }
454    }
455}
456
457impl Index<usize> for Buf {
458    type Output = u8;
459    fn index<'x>(&'x self, index: usize) -> &'x u8 {
460        if let Some(ref data) = self.data {
461            return &data[self.consumed() + index]
462        }
463        panic!("cannot index empty buffer");
464
465    }
466}
467
468impl Index<RangeFull> for Buf {
469    type Output = [u8];
470    fn index<'x>(&'x self, _idx: RangeFull) -> &'x[u8] {
471        self.data.as_ref()
472        .map(|x| &x[self.consumed()..x.len() - self.remaining()])
473        .unwrap_or(b"")
474    }
475}
476
477impl Index<RangeTo<usize>> for Buf {
478    type Output = [u8];
479    fn index<'x>(&'x self, slice: RangeTo<usize>) -> &'x[u8] {
480        let idx = slice.end;
481        if idx == 0 {
482            return b"";
483        }
484        assert!(idx <= self.len());
485        &self.data.as_ref().unwrap()[self.consumed()..self.consumed() + idx]
486    }
487}
488
489impl Index<RangeFrom<usize>> for Buf {
490    type Output = [u8];
491    fn index<'x>(&'x self, slice: RangeFrom<usize>) -> &'x[u8] {
492        let idx = slice.start;
493        if idx == self.len() {
494            return b"";
495        }
496        assert!(idx <= self.len());
497        let buf = &self.data.as_ref().unwrap();
498        &buf[self.consumed() + idx .. buf.len() - self.remaining()]
499    }
500}
501
502impl Index<Range<usize>> for Buf {
503    type Output = [u8];
504    fn index<'x>(&'x self, slice: Range<usize>) -> &'x[u8] {
505        let start = slice.start;
506        let end = slice.end;
507        if end == 0 {
508            return b"";
509        }
510        assert!(end <= self.len());
511        assert!(start <= end);
512        let buf = &self.data.as_ref().unwrap();
513        &buf[self.consumed() + start .. self.consumed() + end]
514    }
515}
516
517impl IndexMut<usize> for Buf {
518    fn index_mut<'x>(&'x mut self, index: usize) -> &'x mut u8 {
519        let consumed = self.consumed();
520        if let Some(ref mut data) = self.data {
521            return &mut data[consumed + index]
522        }
523        panic!("cannot index empty buffer");
524    }
525}
526
527impl IndexMut<RangeFull> for Buf {
528    fn index_mut<'x>(&'x mut self, _idx: RangeFull) -> &'x mut[u8] {
529        let consumed = self.consumed();
530        let remaining = self.remaining();
531        self.data.as_mut()
532        .map(|x| {
533            let len = x.len();
534            &mut x[consumed..len - remaining]
535        })
536        .unwrap_or(&mut [])
537    }
538}
539
540impl IndexMut<RangeTo<usize>> for Buf {
541    fn index_mut<'x>(&'x mut self, slice: RangeTo<usize>) -> &'x mut[u8] {
542        let idx = slice.end;
543        if idx == 0 {
544            return &mut [];
545        }
546        assert!(idx <= self.len());
547        let consumed = self.consumed();
548        &mut self.data.as_mut().unwrap()[consumed..consumed + idx]
549    }
550}
551
552impl IndexMut<RangeFrom<usize>> for Buf {
553    fn index_mut<'x>(&'x mut self, slice: RangeFrom<usize>) -> &'x mut[u8] {
554        let idx = slice.start;
555        if idx == self.len() {
556            return &mut [];
557        }
558        assert!(idx <= self.len());
559        let consumed = self.consumed();
560        let remaining = self.remaining();
561        let buf = self.data.as_mut().unwrap();
562        let len = buf.len();
563        &mut buf[consumed + idx .. len - remaining]
564    }
565}
566
567impl IndexMut<Range<usize>> for Buf {
568    fn index_mut<'x>(&'x mut self, slice: Range<usize>) -> &'x mut[u8] {
569        let start = slice.start;
570        let end = slice.end;
571        if end == 0 {
572            return &mut [];
573        }
574        assert!(end <= self.len());
575        assert!(start <= end);
576        let consumed = self.consumed();
577        let buf = self.data.as_mut().unwrap();
578        &mut buf[consumed + start .. consumed + end]
579    }
580}
581
582impl Write for Buf {
583    fn write(&mut self, buf: &[u8]) -> Result<usize> {
584        if buf.len() == 0 {
585            return Ok(0);
586        }
587        if self.remaining() < buf.len() {
588            self.reserve(buf.len());
589        }
590        copy_memory(buf, &mut self.future_slice()[..buf.len()]);
591        self.remaining -= buf.len();
592        Ok(buf.len())
593    }
594    fn flush(&mut self) -> Result<()> { Ok(()) }
595}
596
597impl Default for Buf {
598    fn default() -> Self {
599        Buf::new()
600    }
601}
602
603#[cfg(test)]
604mod test {
605    use std::mem::size_of;
606    use std::io::{self, Read, Write};
607    use super::Buf;
608    use super::ALLOC_MIN;
609    use mockstream::SharedMockStream;
610
611    struct ReadErr;
612
613    impl Read for ReadErr {
614        fn read(&mut self, _: &mut [u8]) -> Result<usize, io::Error> {
615            Err(io::Error::new(io::ErrorKind::WouldBlock, "fake would block"))
616        }
617    }
618
619    #[test]
620    #[cfg(target_arch="x86_64")]
621    fn size32() {
622        assert_eq!(size_of::<Buf>(), 32);
623    }
624
625    #[test]
626    #[cfg(target_arch="x86")]
627    fn size32() {
628        assert_eq!(size_of::<Buf>(), 16);
629    }
630
631    #[test]
632    fn empty() {
633        let buf = Buf::new();
634        assert_eq!(&buf[..], b"");
635        assert_eq!(format!("{:?}", buf), "Buf { len=0; consumed=0; remaining=0 }")
636    }
637
638    #[test]
639    fn read_from_empty() {
640        let mut s = SharedMockStream::new();
641        let mut buf = Buf::new();
642        assert_eq!(buf.read_from(&mut s).unwrap(), 0);
643        assert!(buf.is_empty());
644        assert_eq!(&buf[..], b"");
645        assert_eq!(format!("{:?}", buf), "Buf { len=0; consumed=0; remaining=0 }")
646    }
647
648    #[test]
649    fn read_from_err() {
650        let mut buf = Buf::new();
651        buf.read_from(&mut ReadErr).unwrap_err();
652        assert!(buf.is_empty());
653        assert_eq!(&buf[..], b"");
654        assert_eq!(format!("{:?}", buf), "Buf { len=0; consumed=0; remaining=0 }")
655    }
656
657    #[test]
658    fn read_max_from_empty() {
659        let mut s = SharedMockStream::new();
660        let mut buf = Buf::new();
661        assert_eq!(buf.read_max_from(1024, &mut s).unwrap(), false);
662        assert!(buf.is_empty());
663        assert_eq!(&buf[..], b"");
664        assert_eq!(format!("{:?}", buf), "Buf { len=0; consumed=0; remaining=0 }")
665    }
666
667    #[test]
668    fn read_max_from_err() {
669        let mut buf = Buf::new();
670        buf.read_max_from(1024, &mut ReadErr).unwrap_err();
671        assert!(buf.is_empty());
672        assert_eq!(&buf[..], b"");
673        assert_eq!(format!("{:?}", buf), "Buf { len=0; consumed=0; remaining=0 }")
674    }
675
676    #[test]
677    fn read_from() {
678        let mut s = SharedMockStream::new();
679        s.push_bytes_to_read(b"hello");
680        let mut buf = Buf::new();
681        assert_eq!(buf.read_from(&mut s).unwrap(), 5);
682        assert_eq!(&buf[..], b"hello");
683    }
684
685    #[test]
686    fn read_max_from() {
687        let mut s = SharedMockStream::new();
688        s.push_bytes_to_read(b"hello");
689        let mut buf = Buf::new();
690        s.push_bytes_to_read(b"hello world");
691        assert!(!buf.read_max_from(1024*1024, &mut s).unwrap());
692        assert_eq!(&buf[..], b"hellohello world");
693        assert!(buf.capacity() < ALLOC_MIN*2);
694        s.push_bytes_to_read(b" from me!Oh, crap!");
695        assert!(buf.read_max_from(25, &mut s).unwrap());
696        assert_eq!(&buf[..], b"hellohello world from me!");
697        assert!(buf.capacity() < ALLOC_MIN*2);
698        assert!(buf.read_max_from(25, &mut s).unwrap());
699        assert_eq!(&buf[..], b"hellohello world from me!");
700        assert!(buf.capacity() < ALLOC_MIN*2);
701        buf.consume(5);
702        assert!(buf.read_max_from(22, &mut s).unwrap());
703        assert_eq!(&buf[..], b"hello world from me!Oh");
704        assert!(buf.capacity() < ALLOC_MIN*2);
705    }
706
707    #[test]
708    fn two_reads() {
709        let mut s = SharedMockStream::new();
710        s.push_bytes_to_read(b"hello");
711        let mut buf = Buf::new();
712        buf.read_from(&mut s).unwrap();
713        s.push_bytes_to_read(b" world");
714        buf.read_from(&mut s).unwrap();
715        assert_eq!(&buf[..], b"hello world");
716        assert_eq!(buf.capacity(), ALLOC_MIN);
717    }
718
719    #[test]
720    fn realloc() {
721        let mut s = SharedMockStream::new();
722        s.push_bytes_to_read(b"hello");
723        let mut buf = Buf::new();
724        buf.read_from(&mut s).unwrap();
725        s.push_bytes_to_read(&b"abcdefg".iter().cloned().cycle().take(1024*1024)
726            .collect::<Vec<_>>()[..]);
727        buf.read_from(&mut s).unwrap();
728        assert_eq!(&buf[..9], b"helloabcd");
729        assert_eq!(buf.len(), ALLOC_MIN);
730        assert_eq!(buf.capacity(), ALLOC_MIN);
731        buf.read_from(&mut s).unwrap();
732        assert_eq!(buf.len(), buf.capacity());
733        assert!(buf.capacity() >= 32768);
734        println!("Capacity {}", buf.capacity());
735        buf.read_from(&mut s).unwrap();
736        println!("Capacity {}", buf.capacity());
737        buf.read_from(&mut s).unwrap();
738        println!("Capacity {}", buf.capacity());
739        buf.read_from(&mut s).unwrap();
740        println!("Capacity {}", buf.capacity());
741        buf.read_from(&mut s).unwrap();
742        println!("Capacity {}", buf.capacity());
743        buf.read_from(&mut s).unwrap();
744        println!("Capacity {}", buf.capacity());
745        buf.read_from(&mut s).unwrap();
746        println!("Capacity {}", buf.capacity());
747        assert_eq!(buf.len(), 1048576 + 5);
748        assert!(buf.capacity() >= buf.len());
749        assert!(buf.capacity() <= 2100000);
750        assert_eq!(&buf[buf.len()-10..], b"bcdefgabcd");
751    }
752
753    #[test]
754    fn two_writes() {
755        let mut buf = Buf::new();
756        assert_eq!(buf.write(b"hello").unwrap(), 5);
757        assert_eq!(buf.write(b" world").unwrap(), 6);
758        assert_eq!(&buf[..], b"hello world");
759        assert_eq!(buf.capacity(), ALLOC_MIN);
760    }
761
762    #[test]
763    fn two_extends() {
764        let mut buf = Buf::new();
765        buf.extend(b"hello");
766        buf.extend(b" world");
767        assert_eq!(&buf[..], b"hello world");
768        assert_eq!(buf.capacity(), 11);
769    }
770
771    #[test]
772    fn write_extend() {
773        let mut buf = Buf::new();
774        buf.write(b"hello").unwrap();
775        buf.extend(b" world");
776        assert_eq!(&buf[..], b"hello world");
777        assert_eq!(buf.capacity(), ALLOC_MIN);
778    }
779
780    #[test]
781    fn extend_write() {
782        let mut buf = Buf::new();
783        buf.extend(b"hello");
784        buf.write(b" world").unwrap();
785        assert_eq!(&buf[..], b"hello world");
786        let cap = buf.capacity();
787        // We don't know exact allocation policy for vec
788        // So this check is fuzzy
789        assert!(cap >= 11);
790        assert!(cap < 256);
791    }
792
793    #[test]
794    fn extend_empty() {
795        let mut buf = Buf::new();
796        buf.extend(b"");
797        assert_eq!(&buf[..], b"");
798        assert_eq!(buf.len(), 0);
799        assert_eq!(buf.capacity(), 0);
800    }
801
802    #[test]
803    fn into() {
804        let mut buf = Buf::new();
805        buf.extend(b"hello");
806        buf.write(b" world").unwrap();
807        let vec: Vec<u8> = buf.into();
808        assert_eq!(&vec[..], b"hello world");
809        let cap = vec.capacity();
810        // We don't know exact allocation policy for vec
811        // So this check is fuzzy
812        assert!(cap >= 11);
813        assert!(cap < 256);
814    }
815
816    #[test]
817    fn consumed_into() {
818        let mut buf = Buf::new();
819        buf.extend(b"hello");
820        buf.write(b" world").unwrap();
821        buf.consume(6);
822        let vec: Vec<u8> = buf.into();
823        assert_eq!(&vec[..], b"world");
824        assert_eq!(vec.capacity(), 5);
825    }
826    #[test]
827    fn write_to() {
828        let mut s = SharedMockStream::new();
829        let mut buf = Buf::new();
830        buf.extend(b"hello world");
831        assert_eq!(buf.write_to(&mut s).unwrap(), 11);
832        assert_eq!(&s.pop_bytes_written()[..], b"hello world");
833    }
834
835    #[test]
836    fn empty_write_to_empty() {
837        let mut buf = Buf::new();
838        let mut empty = Buf::new();
839        assert_eq!(empty.write_to(&mut buf).unwrap(), 0);
840    }
841
842    #[test]
843    fn extend_consume_extend() {
844        let mut buf = Buf::new();
845        buf.extend(b"hello");
846        buf.consume(3);
847        buf.extend(b" world");
848        assert_eq!(&buf[..], b"lo world");
849        assert_eq!(buf.capacity(), 8);
850    }
851
852    #[test]
853    fn extend_consume_write() {
854        let mut buf = Buf::new();
855        buf.extend(b"hello");
856        buf.consume(3);
857        buf.write(b"Some larger string for you").unwrap();
858        assert_eq!(&buf[..], b"loSome larger string for you");
859        assert_eq!(buf.capacity(), 28);
860    }
861
862    #[test]
863    fn consume_all() {
864        let mut buf = Buf::new();
865        buf.extend(b"hello");
866        buf.write(b" world").unwrap();
867        buf.consume(11);
868        assert_eq!(buf.capacity(), 0);
869        assert_eq!(&buf[..], b"");
870        let vec: Vec<u8> = buf.into();
871        assert_eq!(&vec[..], b"");
872        assert_eq!(vec.capacity(), 0);
873    }
874
875    #[test]
876    fn index() {
877        let mut buf = Buf::new();
878        buf.extend(b"Hello World!");
879        assert_eq!(buf[0], b'H');
880        assert_eq!(buf[6], b'W');
881        buf.consume(2);
882        assert_eq!(buf[2], b'o');
883        assert_eq!(buf[8], b'd');
884    }
885
886    #[test]
887    fn index_mut() {
888        let mut buf = Buf::new();
889        buf.extend(b"Hello World!");
890        assert_eq!(buf[0], b'H');
891        buf[0] = b'h';
892        assert_eq!(buf[6], b'W');
893        buf[6] = b'M';
894        assert_eq!(&buf[..], b"hello Morld!");
895        buf.consume(2);
896        buf[1] = b'e';
897        buf[5] = b'e';
898        buf[8] = b'e';
899        assert_eq!(&buf[..], b"leo Merle!");
900    }
901
902    #[test]
903    fn get() {
904        let mut buf = Buf::new();
905        assert_eq!(buf.get(0), None);
906        buf.extend(b"Hello World!");
907        assert_eq!(buf.get(0), Some(b'H'));
908        assert_eq!(buf.get(6), Some(b'W'));
909        assert_eq!(buf.get(11), Some(b'!'));
910        assert_eq!(buf.get(12), None);
911        buf.consume(2);
912        assert_eq!(buf.get(2), Some(b'o'));
913        assert_eq!(buf.get(8), Some(b'd'));
914        assert_eq!(buf.get(9), Some(b'!'));
915        assert_eq!(buf.get(10), None);
916    }
917
918    #[test]
919    fn get_mut() {
920        let mut buf = Buf::new();
921        assert_eq!(buf.get_mut(0), None);
922        buf.extend(b"Hello World!");
923        assert_eq!(buf.get_mut(0), Some(&mut b'H'));
924        if let Some(x) = buf.get_mut(0) { *x = b'h'; }
925        assert_eq!(buf.get_mut(6), Some(&mut b'W'));
926        if let Some(x) = buf.get_mut(6) { *x = b'M'; }
927        assert_eq!(&buf[..], b"hello Morld!");
928        assert_eq!(buf.get_mut(11), Some(&mut b'!'));
929        assert_eq!(buf.get_mut(12), None);
930        buf.consume(2);
931        if let Some(x) = buf.get_mut(1) { *x = b'e'; }
932        if let Some(x) = buf.get_mut(5) { *x = b'e'; }
933        if let Some(x) = buf.get_mut(8) { *x = b'e'; }
934        assert_eq!(&buf[..], b"leo Merle!");
935        assert_eq!(buf.get_mut(9), Some(&mut b'!'));
936        assert_eq!(buf.get_mut(10), None);
937    }
938
939    #[test]
940    fn ranges() {
941        let mut buf = Buf::new();
942        buf.extend(b"Hello world!");
943        assert_eq!(&buf[..], b"Hello world!");
944        assert_eq!(&buf[..0], b"");
945        assert_eq!(&buf[..5], b"Hello");
946        assert_eq!(&buf[..12], b"Hello world!");
947        assert_eq!(&buf[..7], b"Hello w");
948        assert_eq!(&buf[0..], b"Hello world!");
949        assert_eq!(&buf[3..], b"lo world!");
950        assert_eq!(&buf[6..], b"world!");
951        assert_eq!(&buf[12..], b"");
952        assert_eq!(&buf[0..0], b"");
953        assert_eq!(&buf[2..8], b"llo wo");
954        assert_eq!(&buf[0..12], b"Hello world!");
955        assert_eq!(&buf[0..5], b"Hello");
956        assert_eq!(&buf[7..12], b"orld!");
957        assert_eq!(&buf[3..3], b"");
958        assert_eq!(&buf[3..9], b"lo wor");
959    }
960
961    #[test]
962    fn consume_ranges() {
963        let mut buf = Buf::new();
964        buf.extend(b"Crappy stuff");
965        buf.extend(b"Hello world!");
966        buf.consume(12);
967        assert_eq!(&buf[..], b"Hello world!");
968        assert_eq!(&buf[..0], b"");
969        assert_eq!(&buf[..5], b"Hello");
970        assert_eq!(&buf[..12], b"Hello world!");
971        assert_eq!(&buf[..7], b"Hello w");
972        assert_eq!(&buf[0..], b"Hello world!");
973        assert_eq!(&buf[3..], b"lo world!");
974        assert_eq!(&buf[6..], b"world!");
975        assert_eq!(&buf[12..], b"");
976        assert_eq!(&buf[2..8], b"llo wo");
977        assert_eq!(&buf[0..12], b"Hello world!");
978        assert_eq!(&buf[0..5], b"Hello");
979        assert_eq!(&buf[7..12], b"orld!");
980        assert_eq!(&buf[3..3], b"");
981        assert_eq!(&buf[3..9], b"lo wor");
982    }
983
984    #[test]
985    fn remove_ranges() {
986        let mut buf = Buf::new();
987        buf.extend(b"Crappy stuff");
988        buf.extend(b"Hello world!");
989        assert_eq!(&buf[..], b"Crappy stuffHello world!");
990        buf.remove_range(..4);
991        assert_eq!(&buf[..], b"py stuffHello world!");
992        buf.remove_range(3..8);
993        assert_eq!(&buf[..], b"py Hello world!");
994        buf.remove_range(7..14);
995        assert_eq!(&buf[..], b"py Hell!");
996        buf.remove_range(7..);
997        assert_eq!(&buf[..], b"py Hell");
998        let end = buf.len();
999        buf.remove_range(2..end);
1000        assert_eq!(&buf[..], b"py");
1001    }
1002
1003    #[test]
1004    fn mut_ranges() {
1005        let mut buf = Buf::new();
1006        buf.extend(b"Crappy stuff");
1007        buf.extend(b"Hello world!");
1008        buf.consume(12);
1009        buf[..].clone_from_slice(b"HELLO WORLD.");
1010        assert_eq!(&buf[..], b"HELLO WORLD.");
1011        buf[..5].clone_from_slice(b"hell!");
1012        assert_eq!(&buf[..], b"hell! WORLD.");
1013        buf[4..10].clone_from_slice(b"o worl");
1014        assert_eq!(&buf[..], b"hello worlD.");
1015        buf[10..].clone_from_slice(b"d!");
1016        assert_eq!(&buf[..], b"hello world!");
1017    }
1018
1019    #[test]
1020    fn split_off_realloc_self() {
1021        let mut buf = Buf::new();
1022        buf.reserve_exact(20);
1023        buf.extend(b"Hello World");
1024        let tail = buf.split_off(5);
1025        assert_eq!(&buf[..], b"Hello");
1026        assert_eq!(buf.consumed(), 0);
1027        assert_eq!(buf.len(), 5);
1028
1029        assert_eq!(&tail[..], b" World");
1030        assert_eq!(tail.consumed(), 5);
1031        assert_eq!(tail.len(), 6);
1032    }
1033
1034    #[test]
1035    fn split_off_alloc_tail() {
1036        let mut buf = Buf::new();
1037        buf.reserve_exact(20);
1038        buf.extend(b"Hello World!...");
1039        assert_eq!(buf.capacity(), 20);
1040
1041        let tail = buf.split_off(11);
1042        assert_eq!(&buf[..], b"Hello World");
1043        assert_eq!(buf.capacity(), 20);
1044        assert_eq!(buf.consumed(), 0);
1045        assert_eq!(buf.len(), 11);
1046
1047        assert_eq!(&tail[..], b"!...");
1048        assert_eq!(tail.capacity(), 4);
1049        assert_eq!(tail.consumed(), 0);
1050        assert_eq!(tail.len(), 4);
1051
1052        let mut buf = Buf::new();
1053        buf.extend(b"abcdefg");
1054        let tail = buf.split_off(0);
1055        assert_eq!(&tail[..], b"abcdefg");
1056        assert_eq!(&buf[..], b"");
1057    }
1058}