- UID
- 1029342
- 性别
- 男
|
缓冲区大小10M,用来存放二进制数据,缓冲区的使用遵循以下规则
1)先入先出
2)取出后的空间视为空,可以再次存放数据
请写出存取接口函数:
1)存数据函数要求第一个参数为要存入数据的大小,第二个参数为存入数据的指针
2) 取数据函数要求第一个参数为要取出数据的大小,第二个参数为存放取出数据的指针
#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace std;
class MyBuf
{
public:
MyBuf(int n = 10 * 1024 * 1024)
{
assert (n > 0);
m_buf = new char[n];
m_head = m_buf;
m_size = 0;
m_capacity = n;
}
~MyBuf() { delete []m_buf;}
public:
int write(int size, const char* data);
int read(int size, char* buf);
private:
const char* getBufferEnd() const { return (m_buf + m_capacity); }
private:
char* m_buf;
char* m_head;
int m_size;
int m_capacity;
};
//return size if OK. -1 means overflow.
int MyBuf::write(int size, const char* data)
{
assert(size > 0);
if ((size + m_size) > m_capacity) return -1;
int tailBytes = getBufferEnd() - (m_head + m_size);
if (tailBytes > = size){
memcpy(m_head + m_size, data, size);
}else{
if (tailBytes > 0){
memcpy(m_head + m_size, data, tailBytes);
memcpy(m_buf, data + tailBytes, size - tailBytes);
}else{
memcpy(m_buf - tailBytes, data, size);
}
}
m_size += size; |
|