2016-09-23 12:05:32 -07:00
|
|
|
use {Buf, MutBuf};
|
2016-08-10 15:45:31 -07:00
|
|
|
use std::{cmp};
|
2015-07-28 12:51:24 -07:00
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
|
pub struct Take<T> {
|
|
|
|
|
inner: T,
|
|
|
|
|
limit: usize,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T> Take<T> {
|
|
|
|
|
pub fn new(inner: T, limit: usize) -> Take<T> {
|
|
|
|
|
Take {
|
|
|
|
|
inner: inner,
|
|
|
|
|
limit: limit,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn into_inner(self) -> T {
|
|
|
|
|
self.inner
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn get_ref(&self) -> &T {
|
|
|
|
|
&self.inner
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn get_mut(&mut self) -> &mut T {
|
|
|
|
|
&mut self.inner
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn limit(&self) -> usize {
|
|
|
|
|
self.limit
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn set_limit(&mut self, lim: usize) {
|
|
|
|
|
self.limit = lim
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T: Buf> Buf for Take<T> {
|
|
|
|
|
fn remaining(&self) -> usize {
|
|
|
|
|
cmp::min(self.inner.remaining(), self.limit)
|
|
|
|
|
}
|
|
|
|
|
|
2016-09-23 14:51:48 -07:00
|
|
|
fn bytes(&self) -> &[u8] {
|
2015-07-28 12:51:24 -07:00
|
|
|
&self.inner.bytes()[..self.limit]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn advance(&mut self, cnt: usize) {
|
|
|
|
|
let cnt = cmp::min(cnt, self.limit);
|
|
|
|
|
self.limit -= cnt;
|
|
|
|
|
self.inner.advance(cnt);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T: MutBuf> MutBuf for Take<T> {
|
|
|
|
|
fn remaining(&self) -> usize {
|
|
|
|
|
cmp::min(self.inner.remaining(), self.limit)
|
|
|
|
|
}
|
|
|
|
|
|
2016-09-23 14:51:48 -07:00
|
|
|
unsafe fn mut_bytes(&mut self) -> &mut [u8] {
|
2015-07-28 12:51:24 -07:00
|
|
|
&mut self.inner.mut_bytes()[..self.limit]
|
|
|
|
|
}
|
|
|
|
|
|
2015-12-03 19:57:08 -08:00
|
|
|
unsafe fn advance(&mut self, cnt: usize) {
|
2015-07-28 12:51:24 -07:00
|
|
|
let cnt = cmp::min(cnt, self.limit);
|
|
|
|
|
self.limit -= cnt;
|
|
|
|
|
self.inner.advance(cnt);
|
|
|
|
|
}
|
|
|
|
|
}
|