public class LoopQueue {
private byte[] _buf;
private int _head;
private int _tail;
private int _size;
private int _capacity;
public LoopQueue(int capacity){
_capacity = capacity;
_buf = new byte[_capacity];
_head = 0;
_tail = 0;
_size = 0;
}
//将len长的buf加入到lp中
public boolean push(byte[] buf, int len){
if(this._size+len>this._capacity){
Public.mylog.d(LOG_TAG,"_buf is over flow");
return false;
}
for (int i = 0; i < len; i++) {
_buf[(_tail + i) % _capacity] = buf[i];
}
_tail = (_tail+len)%_capacity;
_size +=len;
return true;
}
//消费掉len长的数据
public boolean pop(int len){
if(_size<len){
Public.mylog.d(LOG_TAG,"loopQueue demanding more than exists");
return false;
}
_head = (_head+len)%_capacity;
_size -=len;
return true;
}
//查看从head开始的len长度的内容,把这些内容放到buf里面
public boolean peek(byte[] buf, int len){
if(_size<len){
Public.mylog.d(LOG_TAG,"loopQueue demanding more than exists");
return false;
}
for(int i=0;i<len;i++){
buf[i]=_buf[(_head+i)%_capacity];
}
return true;
}
//判断是不是满了
public boolean isfull(){
return (_capacity == _size);
}
//判断是不是空的
public boolean isempty(){
return (_size==0);
}
//总的大小
public int capacity(){
return _capacity;
}
//当前数据量
public int size(){
return _size;
}
//clear all data
public void clear(){
_tail = _head;
_size = 0;
}
public int read(byte[] buf){
int size = size();
size = Math.min(size,buf.length);
if(size>0) {
peek(buf, size);
pop(size);
return size;
}else
return 0;
}
}