Skip to content

Commit

Permalink
implement constant power-of-two check
Browse files Browse the repository at this point in the history
  • Loading branch information
jdonszelmann committed Apr 1, 2023
1 parent 7925252 commit 64803e6
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 7 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const_panic = "0.2"

[dev-dependencies]
criterion = "0.1.2"
compiletest_rs = "0.9.0"

[features]
default = ["alloc"]
Expand Down
12 changes: 5 additions & 7 deletions src/with_const_generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,14 @@ impl<T: PartialEq, const CAP: usize> PartialEq for ConstGenericRingBuffer<T, CAP
impl<T: PartialEq, const CAP: usize> Eq for ConstGenericRingBuffer<T, CAP> {}

impl<T, const CAP: usize> ConstGenericRingBuffer<T, CAP> {
const ERROR_CAPACITY_IS_NOT_ALLOWED_TO_BE_ZERO: () =
assert!(CAP != 0, "Capacity is not allowed to be zero");

/// Creates a const generic ringbuffer, size is passed as a const generic.
#[inline]
pub const fn new() -> Self {
assert!(CAP != 0, "Capacity is not allowed to be zero");
#[allow(clippy::let_unit_value)]
let _ = Self::ERROR_CAPACITY_IS_NOT_ALLOWED_TO_BE_ZERO;

// allow here since we are constructing an array of MaybeUninit<T>
// which explicitly *is* defined behavior
Expand Down Expand Up @@ -232,12 +236,6 @@ impl<T, const CAP: usize> IndexMut<isize> for ConstGenericRingBuffer<T, CAP> {
mod tests {
use super::*;

#[test]
#[should_panic]
fn test_no_empty() {
let _ = ConstGenericRingBuffer::<u32, 0>::new();
}

#[test]
fn test_not_power_of_two() {
let mut rb = ConstGenericRingBuffer::<usize, 10>::new();
Expand Down
9 changes: 9 additions & 0 deletions tests/compile-fail/test_const_generic_array_zero_length.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
extern crate ringbuffer;

use ringbuffer::ConstGenericRingBuffer;

fn main() {
let _ = ConstGenericRingBuffer::<i32, 0>::new();
//~^ note: the above error was encountered while instantiating `fn ringbuffer::ConstGenericRingBuffer::<i32, 0>::new`
// ringbuffer can't be zero length
}
19 changes: 19 additions & 0 deletions tests/compiletests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
extern crate compiletest_rs as compiletest;

use std::path::PathBuf;

fn run_mode(mode: &'static str) {
let mut config = compiletest::Config::default();

config.mode = mode.parse().expect("Invalid mode");
config.src_base = PathBuf::from(format!("tests/{}", mode));
config.link_deps(); // Populate config.target_rustcflags with dependencies on the path
config.clean_rmeta(); // If your tests import the parent crate, this helps with E0464

compiletest::run_tests(&config);
}

#[test]
fn compile_test() {
run_mode("compile-fail");
}

0 comments on commit 64803e6

Please sign in to comment.