Skip to content

Instantly share code, notes, and snippets.

@supermacro
Created February 13, 2019 02:31
Show Gist options
  • Save supermacro/2f8dc53a740ae31cf5eb5e4d7c4164eb to your computer and use it in GitHub Desktop.
Save supermacro/2f8dc53a740ae31cf5eb5e4d7c4164eb to your computer and use it in GitHub Desktop.
const BUFFER_CAPACITY: usize = 4;
pub struct Buffer {
size: usize,
read_idx: usize,
write_idx: usize,
buffer: [u8; BUFFER_CAPACITY] // unsigned 8bit integer
}
impl Buffer {
pub fn new() -> Buffer {
Buffer {
size: 0,
read_idx: 0,
write_idx: 0,
buffer: [0; BUFFER_CAPACITY]
}
}
pub fn is_empty(&self) -> bool {
self.size == 0
}
pub fn get_size(&self) -> usize {
self.size
}
// write
pub fn enqueue(&mut self, val: u8) -> Result<(), String> {
if self.size == BUFFER_CAPACITY {
Err("HEY, WAT DE FAQ".into())
} else {
self.buffer[self.write_idx] = val;
self.write_idx += Buffer::increment_index(self.write_idx);
self.size += 1;
Ok(())
}
}
// read
pub fn dequeue(&mut self) -> Option<u8> {
if self.size == 0 {
None // empty
} else {
let value = self.buffer[self.read_idx];
self.read_idx += Buffer::increment_index(self.read_idx);
self.size -= 1;
Some(value)
}
}
fn increment_index(val: usize) -> usize {
(val + 1) % BUFFER_CAPACITY
}
}
#[cfg(test)]
mod tests {
// import the Buffer struct into this testing module
use super::*;
#[test]
fn is_empty_when_initialized() {
let buffer = Buffer::new();
assert_eq!(buffer.is_empty(), true);
}
#[test]
fn successfully_enqueues_value() {
let mut buffer = Buffer::new();
buffer.enqueue(12);
assert_eq!(buffer.get_size(), 1);
}
#[test]
fn successfully_dequeues_value() {
let val = 33;
let mut buffer = Buffer::new();
buffer.enqueue(val);
assert_eq!(
val,
buffer.dequeue().unwrap()
);
}
#[test]
fn tells_users_buffer_is_full() {
// create buffer
let mut buffer = Buffer::new();
// fill up the buffer
for x in 0..BUFFER_CAPACITY {
buffer.enqueue(x as u8);
}
// try adding additional value
let result = buffer.enqueue(23);
// check to see if .enqueue() returned Error
assert!(result.is_err());
assert_eq!(String::from("HEY, WAT DE FAQ"), result.unwrap_err())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment