1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
use std::{alloc, ptr, slice};
use crate::byte_buffer_read::ByteBufferRead;
use crate::byte_buffer_write::ByteBufferWrite;
use crate::error::{Result, ByteBufferError};
/// A resizeable buffer to store data in.
///
/// Provides a resizeable buffer with an initial capacity of N bytes.
/// All data written to the [`ByteBuffer`] has to implement the [`ByteBufferWrite`] trait or be a slice of type [u8].
///
/// Data read from the [`ByteBuffer`] has to implement the [`ByteBufferRead`] trait.
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 200;
///
/// // stores the value in the buffer and moves the cursor by 4
/// // due to u32 being 4 bytes in size
/// buffer.write(&value);
///
/// buffer.move_cursor(0);
///
/// // prints 200
/// println!("The stored value is: {}!", buffer.read::<u32>().unwrap());
/// ```
///
pub struct ByteBuffer {
layout: alloc::Layout,
length: usize,
cursor: usize,
pointer: *mut u8
}
impl ByteBuffer {
/// The maximum size the [`ByteBuffer`] will allocate.
///
/// The maximum size the [`ByteBuffer`] should be able to allocate is [`isize::MAX`] due to LLVM's GEP Inbounds instruction.
///
/// # Sources
/// [Rustonomicon](https://doc.rust-lang.org/nomicon/vec/vec-alloc.html)
///
/// [LLVM documentation](https://llvm.org/docs/GetElementPtr.html)
///
pub const MAX_SIZE: usize = isize::MAX as usize;
// TODO: Add configs to change MIN_SIZE depending on compile target, e.g. the smallest chunk windows 10 64-bit allocates is 24 bytes
/// The minimum capacity a [`ByteBuffer`] should have in theory.
///
/// Most, if not all, modern operating systems have at least a minimum heap allocation block of 8 bytes.
/// So it makes little sense to have a [`ByteBuffer`] smaller than 8 bytes.
pub const MIN_SIZE: usize = 8;
/// Constructs a new [`ByteBuffer`] of capacity [`MIN_SIZE`](Self::MIN_SIZE)
///
///
/// See [`with_capacity`](Self::with_capacity).
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// ```
pub fn new() -> Result<Self> {
Self::with_capacity(Self::MIN_SIZE)
}
/// Constructs a new [`ByteBuffer`] with the given capacity.
///
/// # Errors
/// - [`ByteBufferError::MinCapacity`] is returned if the given capacity is 0.
/// - [`ByteBufferError::MaxCapacity`] is returned if the given capacity exceeds [`MAX_SIZE`](Self::MAX_SIZE).
/// - [`ByteBufferError::AllocationFailure`] is returned if the memory allocation failed due to any reason(see [`alloc::alloc`]).
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::with_capacity(256).unwrap();
/// ```
pub fn with_capacity(capacity: usize) -> Result<Self> {
if capacity == 0 {
return Err(ByteBufferError::MinCapacity);
} else if capacity > Self::MAX_SIZE {
return Err(ByteBufferError::MaxCapacity);
}
let layout = unsafe {
alloc::Layout::from_size_align_unchecked(capacity, 1)
};
let pointer = unsafe {
alloc::alloc(layout)
};
if pointer.is_null() {
return Err(ByteBufferError::AllocationFailure {
size: capacity
});
}
Ok(Self {
layout,
length: 0,
cursor: 0,
pointer
})
}
/// Resize the [`ByteBuffer`] to the given capacity.
///
/// # Behaviour
/// - If the current **length** of the [`ByteBuffer`] exceeds the given capacity, the length will be brought back to equal the given capacity.
/// - If the current **cursor** position exceeds the length of the buffer, the cursor will be moved back to equal the length of the [`ByteBuffer`].
///
/// To prevent undefined behaviour.
///
/// # Errors
/// - [`ByteBufferError::MinCapacity`] is returned if the given capacity is 0.
/// - [`ByteBufferError::MaxCapacity`] is returned if the given capacity exceeds [`MAX_SIZE`](Self::MAX_SIZE).
/// - [`ByteBufferError::AllocationFailure`] is returned if the memory allocation failed due to any reason(see [`alloc::realloc`]).
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
///
/// buffer.resize(16);
/// ```
pub fn resize(&mut self, capacity: usize) -> Result<&mut Self> {
if capacity == 0 {
return Err(ByteBufferError::MinCapacity);
} else if capacity > Self::MAX_SIZE {
return Err(ByteBufferError::MaxCapacity);
}
let layout = unsafe {
alloc::Layout::from_size_align_unchecked(capacity, 1)
};
let pointer = unsafe {
alloc::realloc(self.pointer, layout, capacity)
};
if pointer.is_null() {
return Err(ByteBufferError::AllocationFailure {
size: capacity
});
}
if self.length >= capacity {
self.length = capacity;
if self.cursor >= self.length {
self.cursor = self.length;
}
}
self.layout = layout;
self.pointer = pointer;
Ok(self)
}
/// Expands the capacity of the [`ByteBuffer`] by the given amount.
///
/// # Errors
/// - [`ByteBufferError::MaxCapacity`] is returned if the given amount results in an overflow on capacity
/// or if the result of **capacity + amount** exceeds [`MAX_SIZE`](Self::MAX_SIZE).
/// - [`ByteBufferError::AllocationFailure`] is returned if the memory allocation failed due to any reason(see [`alloc::realloc`]).
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
///
/// buffer.expand(4);
/// ```
pub fn expand(&mut self, amount: usize) -> Result<&mut Self> {
self.resize(self.layout.size().checked_add(amount).ok_or(ByteBufferError::MaxCapacity)?)
}
/// Shrinks the capacity of the [`ByteBuffer`] by the given amount.
///
/// # Errors
/// - [`ByteBufferError::MinCapacity`] is returned if the given amount results in an underflow on capacity
/// or if the result of **capacity - amount** equals 0.
/// - [`ByteBufferError::AllocationFailure`] is returned if the memory allocation failed due to any reason(see [`alloc::realloc`]).
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
///
/// buffer.expand(4);
/// ```
pub fn shrink(&mut self, amount: usize) -> Result<&mut Self> {
self.resize(self.layout.size().checked_sub(amount).ok_or(ByteBufferError::MinCapacity)?)
}
/// Writes a slice of type [u8] to the [`ByteBuffer`] **without safety checks**.
///
/// # Safety
///
/// This method is unsafe because undefined behaviour can result if the caller does not ensure all of the following:
/// - The length of the slice doesn't exceed the capacity.
/// - The cursor position + length of the slice does not exceed the capacity.
/// - The cursor position is not out of bounds
///
/// # Behaviour
/// The current cursor position will be increased by the length of the slice.
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let values: [u8; 4] = [0, 1, 2, 3];
///
/// unsafe {
/// buffer.write_slice_unchecked(&values);
/// }
/// ```
pub unsafe fn write_slice_unchecked(&mut self, source: &[u8]) -> &mut Self {
let source_length = source.len();
ptr::copy_nonoverlapping(source.as_ptr(), self.pointer.add(self.cursor), source_length);
self.cursor += source.len();
self
}
/// Writes a slice of type [u8] to the [`ByteBuffer`].
///
/// # Behaviour
/// - If the result of the **current cursor position + length of the slice** exceeds the capacity of the buffer,
/// the buffer will resize to the next power of two that fits the result.
/// - The current cursor position will be increased by the length of the slice.
///
/// # Errors
/// - [`ByteBufferError::MaxCapacity`] is returned if the buffer has to resize to a capacity larger than [`MAX_SIZE`](Self::MAX_SIZE)
/// or if the resulting capacity overflows.
/// - [`ByteBufferError::AllocationFailure`] is returned if the memory allocation failed due to any reason(see [`alloc::realloc`]).
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let values: [u8; 4] = [0, 1, 2, 3];
///
/// buffer.write_slice(&values);
/// ```
pub fn write_slice(&mut self, source: &[u8]) -> Result<&mut Self> {
if self.cursor + source.len() > self.layout.size() {
let capacity = (self.cursor + source.len()).checked_next_power_of_two().ok_or(ByteBufferError::MaxCapacity)?;
if capacity > Self::MAX_SIZE {
return Err(ByteBufferError::MaxCapacity);
}
let layout = unsafe {
alloc::Layout::from_size_align_unchecked(capacity, 1)
};
let pointer = unsafe {
alloc::realloc(self.pointer, layout, capacity)
};
if pointer.is_null() {
return Err(ByteBufferError::AllocationFailure {
size: layout.size()
});
}
self.layout = layout;
self.pointer = pointer;
}
unsafe {
self.write_slice_unchecked(source);
}
if self.cursor > self.length {
self.length += self.cursor - self.length
}
Ok(self)
}
/// Writes the given value to the [`ByteBuffer`].
///
/// The value has to implement the [`ByteBufferWrite`] trait.
///
/// # Errors & Behaviour
/// See [`write_slice`](Self::write_slice).
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 12345;
///
/// buffer.write(&value);
/// ```
pub fn write<T: ByteBufferWrite>(&mut self, source: T) -> Result<&mut Self> {
source.write_to_buffer(self)?;
Ok(self)
}
/// Writes the given value to the [`ByteBuffer`] in **little endian** ordering.
///
/// The value has to implement the [`ByteBufferWrite`] trait.
///
/// # Errors & Behaviour
/// See [`write_slice`](Self::write_slice).
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 12345;
///
/// buffer.write_le(&value);
/// ```
pub fn write_le<T: ByteBufferWrite>(&mut self, source: T) -> Result<&mut Self> {
source.write_to_buffer_le(self)?;
Ok(self)
}
/// Writes the given value to the [`ByteBuffer`] in **big endian** ordering.
///
/// The value has to implement the [`ByteBufferWrite`] trait.
///
/// # Errors & Behaviour
/// See [`write_slice`](Self::write_slice).
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 12345;
///
/// buffer.write_be(&value);
/// ```
pub fn write_be<T: ByteBufferWrite>(&mut self, source: T) -> Result<&mut Self> {
source.write_to_buffer_be(self)?;
Ok(self)
}
/// Reads a slice of type [u8] from the [`ByteBuffer`] of the given size **without safety checks**.
///
/// # Safety
/// This method is unsafe because undefined behaviour can result if the caller does not ensure all of the following:
/// - The size does not exceed the capacity of the buffer.
/// - The result of cursor position + the given size does not exceed the length of the buffer.
/// - The cursor position is not out of bounds
///
/// # Behaviour
/// The current cursor position will be increased by the given size.
///
/// # Examples
///```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 12345;
///
/// buffer.write(&value);
/// buffer.move_cursor(0);
///
/// unsafe {
/// println!("{:?}", buffer.read_slice_unchecked(4));
/// }
///```
pub unsafe fn read_slice_unchecked(&mut self, size: usize) -> &[u8] {
let ret = slice::from_raw_parts(self.pointer.add(self.cursor), size);
self.cursor += size;
ret
}
/// Reads a slice of type [u8] from the [`ByteBuffer`] of the given size.
///
/// # Behaviour
/// The current cursor position will be increased by the given size.
///
/// # Errors
/// - [`ByteBufferError::ReadOutOfBounds`] is returned if the result of the current cursor position + the given size exceeds the buffer's length
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 12345;
///
/// buffer.write(&value);
/// buffer.move_cursor(0);
///
/// println!("{:?}", buffer.read_slice(4));
/// ```
pub fn read_slice(&mut self, size: usize) -> Result<&[u8]> {
if self.cursor + size > self.length {
return Err(ByteBufferError::ReadOutOfBounds {
length: self.length,
start: self.cursor,
end: self.cursor + size
});
}
Ok(unsafe {
self.read_slice_unchecked(size)
})
}
/// Reads a value of type T that implements the [`ByteBufferRead`] trait from the buffer.
///
/// # Errors & Behaviour
/// See [`read_slice`](Self::read_slice).
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 12345;
///
/// buffer.write(&value);
/// buffer.move_cursor(0);
///
/// println!("{}", buffer.read::<u32>().unwrap());
/// buffer.move_cursor(0);
///
/// let x: u32 = buffer.read().unwrap();
/// ```
pub fn read<T: ByteBufferRead>(&mut self) -> Result<T> {
T::read_from_buffer(self)
}
/// Reads a value of type T that implements the [`ByteBufferRead`] trait from the buffer in **little endian** ordering.
///
/// # Errors & Behaviour
/// See [`read_slice`](Self::read_slice).
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 12345;
///
/// buffer.write_le(&value);
/// buffer.move_cursor(0);
///
/// println!("{}", buffer.read_le::<u32>().unwrap());
/// buffer.move_cursor(0);
///
/// let x: u32 = buffer.read_le().unwrap();
/// ```
pub fn read_le<T: ByteBufferRead>(&mut self) -> Result<T> {
T::read_from_buffer_le(self)
}
/// Reads a value of type T that implements the [`ByteBufferRead`] trait from the buffer in **big endian** ordering.
///
/// # Errors & Behaviour
/// See [`read_slice`](Self::read_slice).
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 12345;
///
/// buffer.write_be(&value);
/// buffer.move_cursor(0);
///
/// println!("{}", buffer.read_be::<u32>().unwrap());
/// buffer.move_cursor(0);
///
/// let x: u32 = buffer.read_be().unwrap();
/// ```
pub fn read_be<T: ByteBufferRead>(&mut self) -> Result<T> {
T::read_from_buffer_be(self)
}
/// Moves the current cursor position **without safety checks**.
///
/// # Safety
/// This method is unsafe because undefined behaviour can result if the caller does not ensure the given location does not exceed the buffer's length.
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 12345;
///
/// buffer.write(&value);
///
/// unsafe {
/// buffer.move_cursor_unchecked(2);
/// }
/// ```
pub unsafe fn move_cursor_unchecked(&mut self, location: usize) -> &mut Self {
self.cursor = location;
self
}
/// Moves the current cursor position.
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 12345;
///
/// buffer.write(&value);
///
/// buffer.move_cursor(2);
/// ```
pub fn move_cursor(&mut self, location: usize) -> Result<&mut Self> {
if location > self.length {
return Err(ByteBufferError::CursorOutOfBounds {
length: self.length,
cursor: location
})
}
self.cursor = location;
Ok(self)
}
/// Returns the length of the [`ByteBuffer`].
///
/// The length of the buffer is the last index written to - 1.
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 12345;
///
/// buffer.write(&value);
///
/// println!("{}", buffer.length());
/// ```
pub fn length(&self) -> usize {
self.length
}
/// Returns the capacity of the [`ByteBuffer`].
///
/// The capacity of the buffer is the size of the heap allocation used to store data.
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
///
/// println!("{}", buffer.capacity());
/// ```
pub fn capacity(&self) -> usize {
self.layout.size()
}
/// Returns the current cursor position of the [`ByteBuffer`].
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let value: u32 = 12345;
///
/// buffer.write(&value);
///
/// println!("{}", buffer.cursor());
/// ```
pub fn cursor(&self) -> usize {
self.cursor
}
/// Returns the [`layout`](alloc::Layout) of the [`ByteBuffer`].
///
/// # Examples
/// ```
/// use bytey_byte_buffer::byte_buffer::ByteBuffer;
///
/// let mut buffer = ByteBuffer::new().unwrap();
/// let layout = buffer.layout();
/// ```
pub fn layout(&self) -> alloc::Layout {
self.layout
}
pub unsafe fn pointer(&self) -> *const u8 {
self.pointer
}
pub unsafe fn mut_pointer(&self) -> *mut u8 {
self.pointer
}
}
impl Drop for ByteBuffer {
fn drop(&mut self) {
unsafe {
alloc::dealloc(self.pointer, self.layout);
}
}
}