📄 databuffer.java
字号:
package org.tuna.net.rdt;
import java.io.*;
/**
* 最大容量为MAX_LEN - 1
*/
class DataBuffer
{
private int MAX_LEN = 102401;
private byte[] buffer;
private int head;
private int tail;
/**
* 创建一个默认容量的缓冲区
*/
public DataBuffer()
{
buffer = new byte[MAX_LEN];
head = 0;
tail = 0;
}
/**
* 创建一个指定容量的缓冲区
*/
public DataBuffer(int len)
{
MAX_LEN = len + 1;
buffer = new byte[MAX_LEN];
head = 0;
tail = 0;
}
// ------ Public Methods ------
/**
* 将给定的字节追加至buffer
* @param b 待存储的字节数组
* @return 实际存入的字节数
*/
public int append(byte b)
{
if ( !isFull() ){
buffer[tail] = b;
tail = getNext(tail);
return 1;
}
else{
return 0;
}
}
/**
* 将给定的字节数组内容追加至buffer
* 若待存入的数组长度比缓冲区中余下
* 空间要大,则不执行存入,返回0
* 若成功执行,则返回实际存入的字节数
*
* @param b 待存储的字节数组
* @return 实际存入的字节数
*/
public int append(byte[] b)
{
if (getSpace() < b.length)
return 0;
if (tail + b.length < MAX_LEN){
System.arraycopy(b, 0, buffer, tail, b.length);
tail = tail + b.length;
}
else if (tail + b.length == MAX_LEN){
System.arraycopy(b, 0, buffer, tail, b.length);
tail = 0;
}
else{
System.arraycopy(b, 0, buffer, tail, MAX_LEN - tail); //第一部分
System.arraycopy(b, MAX_LEN - tail, buffer, 0, b.length - (MAX_LEN - tail));
tail = (tail+b.length)%MAX_LEN;
}
return b.length;
}
/**
* 清空缓冲区
*/
public void flush()
{
head = 0;
tail = 0;
}
/**
* 得到可用的空间大小
* @return 缓冲区可用空间的字节数
*/
public int getSpace()
{
return MAX_LEN - getUsed() - 1;
}
/**
* 返回当前已使用空间大小
*/
public int getUsed()
{
return (tail + MAX_LEN - head) % MAX_LEN;
}
/**
* 返回缓冲区是否为空
*/
public boolean isEmpty()
{
if ( head == tail ) return true;
else return false;
}
/**
* 返回缓冲区是否已满
*/
public boolean isFull()
{
if (getNext(tail) == head)
return true;
else
return false;
}
/**
* 读取一个字节,若缓冲为空,则抛出异常
*/
public byte read() throws IOException
{
if ( isEmpty() )
throw new IOException("buffer empty");
byte b = buffer[head];
head = getNext(head);
return b;
}
/**
* 从缓冲区中读取指定长度的字节数
* 并以数组形式返回,若缓冲区中剩
* 余容量不足,则返回实际长度的数
* 组
*
* @param len 指定要读取的字节数
* @return 指定长度的字节数组
*/
public byte[] read(int len)
{
if (len <= 0 || isEmpty()) return null;
int realLen = len > getUsed() ? getUsed() : len;
byte[] b = new byte[realLen];
if (head + realLen <= MAX_LEN)
System.arraycopy(buffer, head, b, 0, realLen);
else{
System.arraycopy(buffer, head, b, 0, MAX_LEN - head);
System.arraycopy(buffer, 0, b, MAX_LEN - head, len - (MAX_LEN - head));
}
head = (realLen + head) % MAX_LEN;
return b;
}
// ------ Private Methods ------
/**
* 跟据当前位置计算下一个位置标号
* @param now 当前位置序号
* @return 下一个位置的序号
*/
private int getNext(int now)
{
return (now + 1) % MAX_LEN;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -