Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 93 additions & 1 deletion ByteBuffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ constexpr uint32_t DEFAULT_BUFFER_SIZE = 2048;
// Mark value indicating no mark is set
constexpr uint32_t MARK_UNSET = UINT32_MAX;

// Byte order enumeration for cross-platform data serialization
enum class ByteOrder {
ORDER_BIG_ENDIAN, // Most significant byte first (network byte order)
ORDER_LITTLE_ENDIAN // Least significant byte first
};

class ByteBuffer
{
public:
Expand Down Expand Up @@ -381,7 +387,77 @@ class ByteBuffer
<< "capacity(" << capacity_ << ")." << std::endl;
}

// Array access methods (Java compatibility)
bool hasArray() const { return true; }
uint8_t* array() { return buffer_.data(); }
const uint8_t* array() const { return buffer_.data(); }
uint32_t arrayOffset() const { return 0; }

// Direct buffer check (Java compatibility)
bool isDirect() const { return false; }

// Byte order methods (Java compatibility)
ByteOrder order() const { return byteOrder_; }
ByteBuffer& order(ByteOrder order) { byteOrder_ = order; return *this; }

// Compare buffers (Java compareTo compatibility)
int compareTo(const ByteBuffer& other) const
{
uint32_t len = std::min(limit_, other.limit_);
for (uint32_t i = 0; i < len; i++)
{
uint8_t a = buffer_[i];
uint8_t b = other.buffer_[i];
if (a != b)
return static_cast<int>(a) - static_cast<int>(b);
}
return static_cast<int>(limit_) - static_cast<int>(other.limit_);
}

// Hash function for use in unordered containers
size_t hash() const
{
size_t h = 0;
for (uint32_t i = 0; i < limit_; i++)
{
h = h * 31 + buffer_[i];
}
return h;
}

// String representation (hex dump)
std::string toString() const
{
char buf[64];
std::snprintf(buf, sizeof(buf), "ByteBuffer[pos=%u lim=%u cap=%u]",
position_, limit_, capacity_);
return std::string(buf);
}

// Static method to get native byte order
static ByteOrder nativeOrder()
{
uint16_t test = 0x0001;
return (*reinterpret_cast<uint8_t*>(&test) == 0x01)
? ByteOrder::ORDER_LITTLE_ENDIAN
: ByteOrder::ORDER_BIG_ENDIAN;
}

private:
// Byte swap helper for endianness conversion
template<typename T>
static T byteswap(T value)
{
T result = 0;
uint8_t* src = reinterpret_cast<uint8_t*>(&value);
uint8_t* dst = reinterpret_cast<uint8_t*>(&result);
for (uint32_t i = 0; i < sizeof(T); i++)
{
dst[i] = src[sizeof(T) - 1 - i];
}
return result;
}

template <typename T>
T read(uint32_t index) const
{
Expand All @@ -390,6 +466,12 @@ class ByteBuffer

T data;
memcpy(&data, &buffer_[index], sizeof(T));

// Apply byte order conversion if needed
if (byteOrder_ != nativeOrder())
{
data = byteswap(data);
}
return data;
}

Expand All @@ -408,7 +490,16 @@ class ByteBuffer
uint32_t s = sizeof(data);
checkSize(s);

memcpy(&buffer_[position_], reinterpret_cast<uint8_t*>(&data), s);
// Apply byte order conversion if needed
if (byteOrder_ != nativeOrder())
{
T swapped = byteswap(data);
memcpy(&buffer_[position_], reinterpret_cast<uint8_t*>(&swapped), s);
}
else
{
memcpy(&buffer_[position_], reinterpret_cast<uint8_t*>(&data), s);
}
position_ += s;
}

Expand Down Expand Up @@ -447,6 +538,7 @@ class ByteBuffer
uint32_t limit_;
uint32_t position_;
uint32_t capacity_;
ByteOrder byteOrder_ = nativeOrder(); // Default to native byte order

};

Expand Down
113 changes: 103 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

C++ 实现的 Java NIO ByteBuffer 功能,支持跨平台(Windows、macOS、Linux)。

> **Header-Only**:只需包含 `ByteBuffer.h` 即可使用,无需编译链接额外的库文件。

## 目录

- [ByteBuffer](#bytebuffer)
Expand All @@ -21,10 +23,15 @@ C++ 实现的 Java NIO ByteBuffer 功能,支持跨平台(Windows、macOS、L
- [读取方法](#读取方法)
- [状态方法](#状态方法)
- [其他方法](#其他方法)
- [Java 兼容接口](#java-兼容接口)
- [数组访问方法](#数组访问方法)
- [直接缓冲区方法](#直接缓冲区方法)
- [字节序方法](#字节序方法)
- [比较和辅助方法](#比较和辅助方法)
- [构建与测试](#构建与测试)
- [依赖](#依赖)
- [构建](#构建)
- [运行测试](#运行测试)
- [使用方法(Header-Only)](#使用方法header-only)
- [构建(仅用于测试)](#构建仅用于测试)
- [CI 状态](#ci-状态)
- [注意事项](#注意事项)
- [参考链接](#参考链接)
Expand All @@ -37,6 +44,7 @@ ByteBuffer 是一个字节缓存区,提供了一系列 put 和 get 方法,

## 特性

- ✅ **Header-Only**:只需包含 `ByteBuffer.h` 即可使用
- ✅ 支持多种数据类型的读写(uint8_t、char、short、int、long、float、double)
- ✅ 自动扩容机制,无需担心缓冲区溢出
- ✅ 支持链式操作,所有 put 方法返回 `ByteBuffer&`
Expand Down Expand Up @@ -198,24 +206,109 @@ bb.compact();
| `duplicate()` | 复制一个 ByteBuffer |
| `printInfo()` | 打印缓冲区信息 |

### Java 兼容接口

#### 数组访问方法

| 方法 | 描述 |
|------|------|
| `hasArray()` | 检查是否有可访问数组(始终返回 true) |
| `array()` | 返回底层字节数组指针 |
| `const array() const` | 返回底层字节数组指针(const 版本) |
| `arrayOffset()` | 返回数组偏移量(始终返回 0) |

#### 直接缓冲区方法

| 方法 | 描述 |
|------|------|
| `isDirect()` | 判断是否为直接缓冲区(当前实现返回 false) |

#### 字节序方法

| 方法 | 描述 |
|------|------|
| `ByteOrder` | 枚举类型:`ORDER_BIG_ENDIAN` / `ORDER_LITTLE_ENDIAN` |
| `order()` | 获取当前字节序 |
| `order(ByteOrder)` | 设置字节序,返回 `ByteBuffer&` 支持链式调用 |
| `static nativeOrder()` | 获取主机字节序 |

**字节序使用示例:**

```cpp
#include "ByteBuffer.h"

ByteBuffer bb;

// 设置为大端字节序(网络字节序)
bb.order(ByteOrder::ORDER_BIG_ENDIAN);

// 写入数据(自动按大端字节序存储)
bb.putInt(0x12345678); // 缓冲区中字节顺序:12 34 56 78

// 切换为小端字节序
bb.order(ByteOrder::ORDER_LITTLE_ENDIAN);
bb.putInt(0x12345678); // 缓冲区中字节顺序:78 56 34 12

// 读取时自动转换
bb.flip();
bb.order(ByteOrder::ORDER_BIG_ENDIAN);
uint32_t value = bb.getInt(); // 正确读取 0x12345678
```

#### 比较和辅助方法

| 方法 | 描述 |
|------|------|
| `compareTo(const ByteBuffer&)` | 按字典序比较两个缓冲区,返回负数/0/正数 |
| `hash()` | 计算缓冲区内容的哈希值 |
| `toString()` | 返回缓冲区的字符串表示 |

**使用示例:**

```cpp
// 比较缓冲区
ByteBuffer bb1, bb2;
// ... 填充数据 ...
int result = bb1.compareTo(bb2); // <0: bb1<bb2, =0: 相等,>0: bb1>bb2

// 哈希值(可用于 unordered_map 等容器)
size_t h = bb1.hash();

// 字符串表示
std::string str = bb1.toString(); // "ByteBuffer[pos=5 lim=10 cap=100]"
```

## 构建与测试

### 依赖

- CMake 3.10+
- C++11 兼容编译器
- CMake 3.10+(仅用于构建测试)

### 构建
### 使用方法(Header-Only)

```bash
mkdir build && cd build
cmake ..
make
由于是 Header-Only 库,只需将 `ByteBuffer.h` 复制到你的项目中即可使用:

```cpp
#include "ByteBuffer.h"

int main() {
ByteBuffer bb;
bb.putInt(12345);
return 0;
}
```

### 运行测试
**无需编译链接额外的库文件**,因为所有实现都在头文件中。

### 构建(仅用于测试)

如果你想运行测试:

```bash
mkdir build && cd build
cmake ..
make
./ByteBuffer
```

Expand All @@ -241,7 +334,7 @@ ctest --output-on-failure

2. **内存对齐**:对于多字节类型的读写,某些架构(如 ARM)可能要求内存对齐。未对齐的访问可能导致性能下降或崩溃。建议在处理大量数据时确保数据对齐。

3. **字节序**:本实现使用主机字节序(host byte order)。如需网络传输,请自行处理字节序转换(如使用 `htons`/`ntohs` 等函数)。
3. **字节序**:本实现支持字节序设置,默认使用主机字节序。可通过 `order()` 方法设置大端或小端字节序,适用于跨平台数据序列化和网络传输。

4. **异常处理**:当内存分配失败时,会抛出 `std::bad_alloc` 异常。请确保在调用时进行适当的异常处理。

Expand Down
Loading
Loading