use std::cmp::Ordering;
use std::fmt;
use std::ops::{Add, AddAssign, Deref, DerefMut, Index, IndexMut};
#[derive(Debug, Clone)]
pub struct Vector<T> {
data: Vec<T>,
}
impl<T> Vector<T> {
pub fn new() -> Self {
Self { data: Vec::new() }
}
pub fn with_capacity(cap: usize) -> Self {
Self {
data: Vec::with_capacity(cap),
}
}
pub fn size(&self) -> usize {
self.data.len()
}
pub fn empty(&self) -> bool {
self.data.is_empty()
}
pub fn capacity(&self) -> usize {
self.data.capacity()
}
pub fn reserve(&mut self, new_cap: usize) {
self.data.reserve(new_cap)
}
pub fn resize(&mut self, new_len: usize, value: T)
where
T: Clone,
{
self.data.resize(new_len, value)
}
pub fn clear(&mut self) {
self.data.clear()
}
pub fn shrink_to_fit(&mut self) {
self.data.shrink_to_fit()
}
pub fn push_back(&mut self, value: T) {
self.data.push(value)
}
pub fn pop_back(&mut self) -> Option<T> {
self.data.pop()
}
pub fn get(&self, i: usize) -> Option<&T> {
self.data.get(i)
}
pub fn get_mut(&mut self, i: usize) -> Option<&mut T> {
self.data.get_mut(i)
}
pub fn front(&self) -> Option<&T> {
self.data.first()
}
pub fn back(&self) -> Option<&T> {
self.data.last()
}
pub fn front_mut(&mut self) -> Option<&mut T> {
self.data.first_mut()
}
pub fn back_mut(&mut self) -> Option<&mut T> {
self.data.last_mut()
}
pub fn iter(&self) -> std::slice::Iter<'_, T> {
self.data.iter()
}
pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> {
self.data.iter_mut()
}
pub fn data_ptr(&self) -> *const T {
self.data.as_ptr()
}
pub fn data_ptr_mut(&mut self) -> *mut T {
self.data.as_mut_ptr()
}
pub fn insert(&mut self, index: usize, value: T) {
self.data.insert(index, value)
}
pub fn erase(&mut self, index: usize) -> T {
self.data.remove(index)
}
pub fn emplace_back(&mut self, value: T) {
self.data.push(value)
}
pub fn swap(&mut self, other: &mut Self) {
std::mem::swap(&mut self.data, &mut other.data)
}
pub fn assign(&mut self, count: usize, value: T)
where
T: Clone,
{
self.data.clear();
self.data.resize(count, value);
}
pub fn as_slice(&self) -> &[T] {
self.data.as_slice()
}
pub fn as_mut_slice(&mut self) -> &mut [T] {
self.data.as_mut_slice()
}
}
impl<T> Default for Vector<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> Index<usize> for Vector<T> {
type Output = T;
fn index(&self, i: usize) -> &T {
&self.data[i]
}
}
impl<T> IndexMut<usize> for Vector<T> {
fn index_mut(&mut self, i: usize) -> &mut T {
&mut self.data[i]
}
}
impl<T: PartialEq> PartialEq for Vector<T> {
fn eq(&self, other: &Self) -> bool {
self.data == other.data
}
}
impl<T: Eq> Eq for Vector<T> {}
impl<T: PartialOrd> PartialOrd for Vector<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.data.partial_cmp(&other.data)
}
}
impl<T> From<Vec<T>> for Vector<T> {
fn from(data: Vec<T>) -> Self {
Self { data }
}
}
impl<T> IntoIterator for Vector<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.data.into_iter()
}
}
#[derive(Debug, Clone, Default)]
pub struct StdString {
inner: String,
}
impl StdString {
pub fn new() -> Self {
Self {
inner: String::new(),
}
}
pub fn from_str(s: &str) -> Self {
Self {
inner: s.to_string(),
}
}
pub fn with_capacity(cap: usize) -> Self {
Self {
inner: String::with_capacity(cap),
}
}
pub fn c_str(&self) -> &str {
&self.inner
}
pub fn length(&self) -> usize {
self.inner.len()
}
pub fn size(&self) -> usize {
self.inner.len()
}
pub fn empty(&self) -> bool {
self.inner.is_empty()
}
pub fn capacity(&self) -> usize {
self.inner.capacity()
}
pub fn clear(&mut self) {
self.inner.clear()
}
pub fn reserve(&mut self, additional: usize) {
self.inner.reserve(additional)
}
pub fn shrink_to_fit(&mut self) {
self.inner.shrink_to_fit()
}
pub fn at(&self, index: usize) -> Option<char> {
self.inner.chars().nth(index)
}
pub fn append(&mut self, s: &str) {
self.inner.push_str(s)
}
pub fn append_int(&mut self, n: i32) {
self.inner.push_str(&n.to_string())
}
pub fn push_back(&mut self, ch: char) {
self.inner.push(ch)
}
pub fn pop_back(&mut self) -> Option<char> {
self.inner.pop()
}
pub fn substr(&self, pos: usize, count: usize) -> StdString {
let s: String = self.inner.chars().skip(pos).take(count).collect();
StdString { inner: s }
}
pub fn find(&self, pattern: &str) -> Option<usize> {
self.inner.find(pattern)
}
pub fn find_char(&self, ch: char) -> Option<usize> {
self.inner.find(ch)
}
pub fn rfind(&self, pattern: &str) -> Option<usize> {
self.inner.rfind(pattern)
}
pub fn replace(&self, from: &str, to: &str) -> StdString {
StdString {
inner: self.inner.replace(from, to),
}
}
pub fn compare(&self, other: &StdString) -> Ordering {
self.inner.cmp(&other.inner)
}
pub fn starts_with(&self, prefix: &str) -> bool {
self.inner.starts_with(prefix)
}
pub fn ends_with(&self, suffix: &str) -> bool {
self.inner.ends_with(suffix)
}
pub fn as_str(&self) -> &str {
&self.inner
}
pub fn as_bytes(&self) -> &[u8] {
self.inner.as_bytes()
}
pub fn npos() -> usize {
usize::MAX
}
pub fn to_std_string(&self) -> String {
self.inner.clone()
}
}
impl From<&str> for StdString {
fn from(s: &str) -> Self {
Self::from_str(s)
}
}
impl From<String> for StdString {
fn from(s: String) -> Self {
Self { inner: s }
}
}
impl fmt::Display for StdString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.inner)
}
}
impl Index<usize> for StdString {
type Output = str;
fn index(&self, _i: usize) -> &str {
&self.inner
}
}
impl Add<&StdString> for &StdString {
type Output = StdString;
fn add(self, rhs: &StdString) -> StdString {
StdString {
inner: format!("{}{}", self.inner, rhs.inner),
}
}
}
impl Add<&str> for &StdString {
type Output = StdString;
fn add(self, rhs: &str) -> StdString {
StdString {
inner: format!("{}{}", self.inner, rhs),
}
}
}
impl AddAssign<&StdString> for StdString {
fn add_assign(&mut self, rhs: &StdString) {
self.inner.push_str(&rhs.inner);
}
}
impl AddAssign<&str> for StdString {
fn add_assign(&mut self, rhs: &str) {
self.inner.push_str(rhs);
}
}
impl PartialEq for StdString {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl Eq for StdString {}
impl PartialOrd for StdString {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.inner.cmp(&other.inner))
}
}
impl Ord for StdString {
fn cmp(&self, other: &Self) -> Ordering {
self.inner.cmp(&other.inner)
}
}
pub fn to_string<T: ToString>(value: &T) -> StdString {
StdString::from_str(&value.to_string())
}
pub fn stoi(s: &str) -> Result<i32, String> {
s.parse::<i32>().map_err(|e| format!("stoi: {}", e))
}
pub fn stol(s: &str) -> Result<i64, String> {
s.parse::<i64>().map_err(|e| format!("stol: {}", e))
}
pub fn stoll(s: &str) -> Result<i64, String> {
s.parse::<i64>().map_err(|e| format!("stoll: {}", e))
}
pub fn stof(s: &str) -> Result<f32, String> {
s.parse::<f32>().map_err(|e| format!("stof: {}", e))
}
pub fn stod(s: &str) -> Result<f64, String> {
s.parse::<f64>().map_err(|e| format!("stod: {}", e))
}
#[derive(Debug, Clone)]
pub struct MapEntry<K, V> {
pub key: K,
pub value: V,
}
#[derive(Debug, Clone)]
pub struct OrderedMap<K: Ord, V> {
inner: std::collections::BTreeMap<K, V>,
}
impl<K: Ord, V> OrderedMap<K, V> {
pub fn new() -> Self {
Self {
inner: std::collections::BTreeMap::new(),
}
}
pub fn size(&self) -> usize {
self.inner.len()
}
pub fn empty(&self) -> bool {
self.inner.is_empty()
}
pub fn clear(&mut self) {
self.inner.clear()
}
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
self.inner.insert(key, value)
}
pub fn get_or_default(&mut self, key: K, default: V) -> &mut V
where
K: Clone,
{
self.inner.entry(key).or_insert(default)
}
pub fn find(&self, key: &K) -> Option<&V> {
self.inner.get(key)
}
pub fn find_mut(&mut self, key: &K) -> Option<&mut V> {
self.inner.get_mut(key)
}
pub fn contains(&self, key: &K) -> bool {
self.inner.contains_key(key)
}
pub fn erase(&mut self, key: &K) -> Option<V> {
self.inner.remove(key)
}
pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> {
self.inner.iter()
}
pub fn keys(&self) -> impl Iterator<Item = &K> {
self.inner.keys()
}
pub fn values(&self) -> impl Iterator<Item = &V> {
self.inner.values()
}
pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
self.inner.values_mut()
}
pub fn lower_bound(&self, key: &K) -> Option<(&K, &V)> {
self.inner.range(key..).next()
}
pub fn upper_bound(&self, key: &K) -> Option<(&K, &V)> {
use std::ops::Bound;
self.inner
.range::<K, _>((Bound::Excluded(key), Bound::Unbounded))
.next()
}
pub fn begin(&self) -> Option<(&K, &V)> {
self.inner.iter().next()
}
pub fn end(&self) -> Option<(&K, &V)> {
self.inner.iter().next_back()
}
}
impl<K: Ord, V> Default for OrderedMap<K, V> {
fn default() -> Self {
Self::new()
}
}
impl<K: Ord + Clone, V: Default> Index<K> for OrderedMap<K, V> {
type Output = V;
fn index(&self, key: K) -> &V {
self.inner.get(&key).expect("key not found in map")
}
}
#[derive(Debug, Clone)]
pub struct OrderedSet<T: Ord> {
inner: std::collections::BTreeSet<T>,
}
impl<T: Ord> OrderedSet<T> {
pub fn new() -> Self {
Self {
inner: std::collections::BTreeSet::new(),
}
}
pub fn size(&self) -> usize {
self.inner.len()
}
pub fn empty(&self) -> bool {
self.inner.is_empty()
}
pub fn clear(&mut self) {
self.inner.clear()
}
pub fn insert(&mut self, value: T) -> bool {
self.inner.insert(value)
}
pub fn find(&self, value: &T) -> Option<&T> {
self.inner.get(value)
}
pub fn contains(&self, value: &T) -> bool {
self.inner.contains(value)
}
pub fn erase(&mut self, value: &T) -> bool {
self.inner.remove(value)
}
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.inner.iter()
}
pub fn lower_bound(&self, value: &T) -> Option<&T> {
self.inner.range(value..).next()
}
pub fn upper_bound(&self, value: &T) -> Option<&T> {
use std::ops::Bound;
self.inner
.range::<T, _>((Bound::Excluded(value), Bound::Unbounded))
.next()
}
}
impl<T: Ord> Default for OrderedSet<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Ord> IntoIterator for OrderedSet<T> {
type Item = T;
type IntoIter = std::collections::btree_set::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.inner.into_iter()
}
}
pub fn sort<T: Ord>(slice: &mut [T]) {
slice.sort()
}
pub fn sort_by<T>(slice: &mut [T], compare: impl Fn(&T, &T) -> Ordering) {
slice.sort_by(compare)
}
pub fn stable_sort<T: Ord>(slice: &mut [T]) {
slice.sort(); }
pub fn stable_sort_by<T>(slice: &mut [T], compare: impl Fn(&T, &T) -> Ordering) {
slice.sort_by(compare); }
pub fn find<T: PartialEq>(slice: &[T], value: &T) -> Option<usize> {
slice.iter().position(|x| x == value)
}
pub fn find_if<T>(slice: &[T], pred: impl Fn(&T) -> bool) -> Option<usize> {
slice.iter().position(pred)
}
pub fn count<T: PartialEq>(slice: &[T], value: &T) -> usize {
slice.iter().filter(|&x| x == value).count()
}
pub fn count_if<T>(slice: &[T], pred: impl Fn(&T) -> bool) -> usize {
slice.iter().filter(|&x| pred(x)).count()
}
pub fn copy<T: Copy>(src: &[T], dst: &mut [T]) -> usize {
let n = src.len().min(dst.len());
for i in 0..n {
dst[i] = src[i];
}
n
}
pub fn transform<T, U>(src: &[T], dst: &mut [U], f: impl Fn(&T) -> U) -> usize {
let n = src.len().min(dst.len());
for i in 0..n {
dst[i] = f(&src[i]);
}
n
}
pub fn accumulate<T: Copy + Add<Output = T>>(slice: &[T], init: T) -> T {
slice.iter().fold(init, |acc, &x| acc + x)
}
pub fn max_element<T: Ord>(slice: &[T]) -> Option<(usize, &T)> {
slice
.iter()
.enumerate()
.max_by(|(_, a), (_, b)| a.cmp(b))
}
pub fn min_element<T: Ord>(slice: &[T]) -> Option<(usize, &T)> {
slice
.iter()
.enumerate()
.min_by(|(_, a), (_, b)| a.cmp(b))
}
pub fn binary_search<T: Ord>(slice: &[T], value: &T) -> Option<usize> {
match slice.binary_search(value) {
Ok(idx) => Some(idx),
Err(_) => None,
}
}
pub fn lower_bound<T: Ord>(slice: &[T], value: &T) -> usize {
slice.partition_point(|x| x < value)
}
pub fn upper_bound<T: Ord>(slice: &[T], value: &T) -> usize {
slice.partition_point(|x| x <= value)
}
pub fn unique<T: PartialEq>(slice: &mut Vec<T>) -> usize {
let mut j = 0;
for i in 0..slice.len() {
if i == 0 || slice[i] != slice[i - 1] {
slice[j] = slice.remove(i);
j += 1;
}
}
slice.truncate(j);
j
}
pub fn reverse<T>(slice: &mut [T]) {
slice.reverse()
}
pub fn rotate<T>(slice: &mut [T], mid: usize) {
if mid < slice.len() {
slice.rotate_left(mid);
}
}
pub fn partition<T>(slice: &mut [T], pred: impl Fn(&T) -> bool) -> usize {
let mut i = 0;
for j in 0..slice.len() {
if pred(&slice[j]) {
slice.swap(i, j);
i += 1;
}
}
i
}
pub fn next_permutation<T: Ord>(slice: &mut [T]) -> bool {
let n = slice.len();
if n < 2 {
return false;
}
let mut i = n - 1;
while i > 0 && slice[i - 1] >= slice[i] {
i -= 1;
}
if i == 0 {
slice.reverse();
return false;
}
let mut j = n - 1;
while slice[j] <= slice[i - 1] {
j -= 1;
}
slice.swap(i - 1, j);
slice[i..].reverse();
true
}
pub fn for_each<T>(slice: &[T], mut f: impl FnMut(&T)) {
for x in slice {
f(x);
}
}
pub fn for_each_mut<T>(slice: &mut [T], mut f: impl FnMut(&mut T)) {
for x in slice.iter_mut() {
f(x);
}
}
pub trait IteratorTraits {
type ValueType;
type DifferenceType;
type Pointer;
type Reference;
type IteratorCategory;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IteratorCategory {
Input,
Output,
Forward,
Bidirectional,
RandomAccess,
Contiguous,
}
pub fn advance<I>(iter: &mut I, n: usize)
where
I: Iterator,
{
for _ in 0..n {
iter.next();
}
}
pub fn distance<A, B>(_first: A, _last: B) -> usize
where
A: IntoIterator,
B: IntoIterator,
{
0 }
pub fn next<I: Clone>(iter: &I, n: usize) -> I
where
I: Iterator,
{
let mut result = iter.clone();
advance(&mut result, n);
result
}
pub fn prev<I>(_iter: &I) -> Option<I>
where
I: Clone,
{
None }
pub fn begin<T>(collection: &[T]) -> std::slice::Iter<'_, T> {
collection.iter()
}
pub fn end<T>(_collection: &[T]) -> std::slice::Iter<'_, T> {
[].iter() }
#[derive(Debug, Clone)]
pub struct ReverseIterator<I> {
inner: I,
}
impl<I> ReverseIterator<I> {
pub fn new(inner: I) -> Self {
Self { inner }
}
pub fn base(&self) -> &I {
&self.inner
}
pub fn base_mut(&mut self) -> &mut I {
&mut self.inner
}
}
#[derive(Debug)]
pub struct BackInserter<C> {
container: C,
}
impl<C> BackInserter<C> {
pub fn new(container: C) -> Self {
Self { container }
}
pub fn into_inner(self) -> C {
self.container
}
}
#[derive(Debug)]
pub struct FrontInserter<C> {
container: C,
}
impl<C> FrontInserter<C> {
pub fn new(container: C) -> Self {
Self { container }
}
}
#[derive(Debug)]
pub struct UniquePtr<T> {
ptr: *mut T,
}
impl<T> UniquePtr<T> {
pub unsafe fn from_raw(ptr: *mut T) -> Self {
Self { ptr }
}
pub fn new(value: T) -> Self {
Self {
ptr: Box::into_raw(Box::new(value)),
}
}
pub fn get(&self) -> *mut T {
self.ptr
}
pub fn release(mut self) -> *mut T {
let ptr = self.ptr;
self.ptr = std::ptr::null_mut();
ptr
}
pub fn reset(&mut self, ptr: *mut T) {
unsafe {
if !self.ptr.is_null() {
drop(Box::from_raw(self.ptr));
}
}
self.ptr = ptr;
}
pub fn swap(&mut self, other: &mut Self) {
std::mem::swap(&mut self.ptr, &mut other.ptr);
}
pub fn is_valid(&self) -> bool {
!self.ptr.is_null()
}
pub fn to_bool(&self) -> bool {
self.is_valid()
}
}
impl<T> Drop for UniquePtr<T> {
fn drop(&mut self) {
unsafe {
if !self.ptr.is_null() {
drop(Box::from_raw(self.ptr));
}
}
}
}
impl<T> Deref for UniquePtr<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.ptr }
}
}
impl<T> DerefMut for UniquePtr<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.ptr }
}
}
pub fn make_unique<T>(value: T) -> UniquePtr<T> {
UniquePtr::new(value)
}
#[derive(Debug)]
pub struct SharedPtr<T> {
ptr: *mut T,
ref_count: *mut usize,
}
impl<T> SharedPtr<T> {
pub fn from_unique(unique: UniquePtr<T>) -> Self {
let ptr = unique.release();
let ref_count = Box::into_raw(Box::new(1usize));
Self { ptr, ref_count }
}
pub fn new(value: T) -> Self {
Self::from_unique(UniquePtr::new(value))
}
pub fn get(&self) -> *mut T {
self.ptr
}
pub fn use_count(&self) -> usize {
if self.ref_count.is_null() {
0
} else {
unsafe { *self.ref_count }
}
}
pub fn unique(&self) -> bool {
self.use_count() == 1
}
pub fn reset(&mut self) {
self.decrement();
self.ptr = std::ptr::null_mut();
self.ref_count = std::ptr::null_mut();
}
pub fn swap(&mut self, other: &mut Self) {
std::mem::swap(&mut self.ptr, &mut other.ptr);
std::mem::swap(&mut self.ref_count, &mut other.ref_count);
}
fn decrement(&mut self) {
if !self.ref_count.is_null() {
unsafe {
*self.ref_count -= 1;
if *self.ref_count == 0 {
drop(Box::from_raw(self.ptr));
drop(Box::from_raw(self.ref_count));
}
}
}
}
}
impl<T> Clone for SharedPtr<T> {
fn clone(&self) -> Self {
if !self.ref_count.is_null() {
unsafe {
*self.ref_count += 1;
}
}
Self {
ptr: self.ptr,
ref_count: self.ref_count,
}
}
}
impl<T> Drop for SharedPtr<T> {
fn drop(&mut self) {
self.decrement();
}
}
impl<T> Deref for SharedPtr<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.ptr }
}
}
pub fn make_shared<T>(value: T) -> SharedPtr<T> {
SharedPtr::new(value)
}
#[derive(Debug)]
pub struct WeakPtr<T> {
ptr: *mut T,
ref_count: *mut usize,
weak_count: *mut usize,
}
impl<T> WeakPtr<T> {
pub fn new() -> Self {
Self {
ptr: std::ptr::null_mut(),
ref_count: std::ptr::null_mut(),
weak_count: std::ptr::null_mut(),
}
}
pub fn from_shared(_shared: &SharedPtr<T>) -> Self {
Self::new()
}
pub fn lock(&self) -> Option<SharedPtr<T>> {
if self.expired() {
None
} else {
None
}
}
pub fn expired(&self) -> bool {
self.ref_count.is_null() || unsafe { *self.ref_count == 0 }
}
pub fn use_count(&self) -> usize {
if self.ref_count.is_null() {
0
} else {
unsafe { *self.ref_count }
}
}
pub fn reset(&mut self) {
self.ptr = std::ptr::null_mut();
self.ref_count = std::ptr::null_mut();
self.weak_count = std::ptr::null_mut();
}
}
impl<T> Default for WeakPtr<T> {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Copy)]
pub struct Allocator;
impl Allocator {
pub fn new() -> Self {
Self
}
pub fn allocate<T>(&self, n: usize) -> *mut T {
let layout = std::alloc::Layout::array::<T>(n).unwrap();
unsafe { std::alloc::alloc(layout) as *mut T }
}
pub fn deallocate<T>(&self, ptr: *mut T, n: usize) {
let layout = std::alloc::Layout::array::<T>(n).unwrap();
unsafe { std::alloc::dealloc(ptr as *mut u8, layout) }
}
pub fn construct<T>(&self, ptr: *mut T, value: T) {
unsafe {
std::ptr::write(ptr, value);
}
}
pub fn destroy<T>(&self, ptr: *mut T) {
unsafe {
std::ptr::drop_in_place(ptr);
}
}
pub fn max_size(&self) -> usize {
usize::MAX
}
}
impl Default for Allocator {
fn default() -> Self {
Self::new()
}
}
pub struct AllocatorTraits<A> {
allocator: A,
}
impl<A: AllocatorLike> AllocatorTraits<A> {
pub fn new(alloc: A) -> Self {
Self { allocator: alloc }
}
pub fn allocate<T>(&self, n: usize) -> *mut T {
self.allocator.allocate(n)
}
pub fn deallocate<T>(&self, ptr: *mut T, n: usize) {
self.allocator.deallocate(ptr, n)
}
pub fn construct<T>(&self, ptr: *mut T, value: T) {
self.allocator.construct(ptr, value)
}
pub fn destroy<T>(&self, ptr: *mut T) {
self.allocator.destroy(ptr)
}
}
pub trait AllocatorLike {
fn allocate<T>(&self, n: usize) -> *mut T;
fn deallocate<T>(&self, ptr: *mut T, n: usize);
fn construct<T>(&self, ptr: *mut T, value: T);
fn destroy<T>(&self, ptr: *mut T);
fn max_size(&self) -> usize;
}
impl AllocatorLike for Allocator {
fn allocate<T>(&self, n: usize) -> *mut T {
Allocator::allocate::<T>(self, n)
}
fn deallocate<T>(&self, ptr: *mut T, n: usize) {
Allocator::deallocate::<T>(self, ptr, n)
}
fn construct<T>(&self, ptr: *mut T, value: T) {
Allocator::construct::<T>(self, ptr, value)
}
fn destroy<T>(&self, ptr: *mut T) {
Allocator::destroy::<T>(self, ptr)
}
fn max_size(&self) -> usize {
Allocator::max_size(self)
}
}
pub fn numeric_accumulate<T: Copy + Add<Output = T>>(slice: &[T], init: T) -> T {
slice.iter().fold(init, |acc, &x| acc + x)
}
pub fn inner_product<T: Copy + std::ops::Mul<Output = T> + Add<Output = T>>(
a: &[T],
b: &[T],
init: T,
) -> T {
let n = a.len().min(b.len());
(0..n).fold(init, |acc, i| acc + a[i] * b[i])
}
pub fn adjacent_difference<T: Copy + std::ops::Sub<Output = T>>(
src: &[T],
dst: &mut [T],
) -> usize {
let n = src.len().min(dst.len());
if n == 0 {
return 0;
}
dst[0] = src[0];
for i in 1..n {
dst[i] = src[i] - src[i - 1];
}
n
}
pub fn partial_sum<T: Copy + Add<Output = T>>(src: &[T], dst: &mut [T]) -> usize {
let n = src.len().min(dst.len());
if n == 0 {
return 0;
}
dst[0] = src[0];
for i in 1..n {
dst[i] = dst[i - 1] + src[i];
}
n
}
pub fn iota<T: Copy + Add<Output = T> + From<u8>>(slice: &mut [T], mut value: T) {
let one = T::from(1u8);
for x in slice.iter_mut() {
*x = value;
value = value + one;
}
}
pub fn gcd<T: std::ops::Rem<Output = T> + PartialEq + Copy + From<u8>>(mut a: T, mut b: T) -> T {
let zero = T::from(0u8);
while b != zero {
let t = b;
b = a % b;
a = t;
}
a
}
pub fn lcm<T: std::ops::Rem<Output = T> + std::ops::Div<Output = T> + std::ops::Mul<Output = T> + PartialEq + Copy + From<u8>>(a: T, b: T) -> T {
let zero = T::from(0u8);
if a == zero || b == zero {
return zero;
}
a / gcd(a, b) * b
}
#[derive(Debug, Clone)]
pub struct IStream;
#[derive(Debug, Clone)]
pub struct OStream;
#[derive(Debug, Clone)]
pub struct IOStream;
#[derive(Debug, Clone)]
pub struct IFStream;
#[derive(Debug, Clone)]
pub struct OFStream;
#[derive(Debug, Clone)]
pub struct FStream;
#[derive(Debug, Clone)]
pub struct IStringStream;
#[derive(Debug, Clone)]
pub struct OStringStream;
#[derive(Debug, Clone)]
pub struct StringStream;
pub static CIN: IStream = IStream;
pub static COUT: OStream = OStream;
pub static CERR: OStream = OStream;
pub static CLOG: OStream = OStream;
#[derive(Debug, Clone)]
pub struct Exception {
message: String,
}
impl Exception {
pub fn new(msg: &str) -> Self {
Self {
message: msg.to_string(),
}
}
pub fn what(&self) -> &str {
&self.message
}
}
impl fmt::Display for Exception {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)
}
}
#[derive(Debug, Clone)]
pub struct LogicError {
inner: Exception,
}
impl LogicError {
pub fn new(msg: &str) -> Self {
Self {
inner: Exception::new(msg),
}
}
pub fn what(&self) -> &str {
self.inner.what()
}
}
impl fmt::Display for LogicError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "logic_error: {}", self.inner)
}
}
#[derive(Debug, Clone)]
pub struct RuntimeError {
inner: Exception,
}
impl RuntimeError {
pub fn new(msg: &str) -> Self {
Self {
inner: Exception::new(msg),
}
}
pub fn what(&self) -> &str {
self.inner.what()
}
}
impl fmt::Display for RuntimeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "runtime_error: {}", self.inner)
}
}
#[derive(Debug, Clone)]
pub struct OutOfRange {
inner: LogicError,
}
impl OutOfRange {
pub fn new(msg: &str) -> Self {
Self {
inner: LogicError::new(msg),
}
}
pub fn what(&self) -> &str {
self.inner.what()
}
}
impl fmt::Display for OutOfRange {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "out_of_range: {}", self.inner)
}
}
#[derive(Debug, Clone)]
pub struct InvalidArgument {
inner: LogicError,
}
impl InvalidArgument {
pub fn new(msg: &str) -> Self {
Self {
inner: LogicError::new(msg),
}
}
pub fn what(&self) -> &str {
self.inner.what()
}
}
impl fmt::Display for InvalidArgument {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid_argument: {}", self.inner)
}
}
#[derive(Debug, Clone)]
pub struct LengthError {
inner: LogicError,
}
impl LengthError {
pub fn new(msg: &str) -> Self {
Self {
inner: LogicError::new(msg),
}
}
pub fn what(&self) -> &str {
self.inner.what()
}
}
impl fmt::Display for LengthError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "length_error: {}", self.inner)
}
}
#[derive(Debug, Clone)]
pub struct OverflowError {
inner: RuntimeError,
}
impl OverflowError {
pub fn new(msg: &str) -> Self {
Self {
inner: RuntimeError::new(msg),
}
}
pub fn what(&self) -> &str {
self.inner.what()
}
}
impl fmt::Display for OverflowError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "overflow_error: {}", self.inner)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_vector_new_empty() {
let v: Vector<i32> = Vector::new();
assert!(v.empty());
assert_eq!(v.size(), 0);
}
#[test]
fn test_vector_push_back_size() {
let mut v = Vector::new();
v.push_back(1);
v.push_back(2);
v.push_back(3);
assert_eq!(v.size(), 3);
assert!(!v.empty());
}
#[test]
fn test_vector_index() {
let mut v = Vector::new();
v.push_back(10);
v.push_back(20);
v.push_back(30);
assert_eq!(v[0], 10);
assert_eq!(v[1], 20);
assert_eq!(v[2], 30);
}
#[test]
fn test_vector_pop_back() {
let mut v = Vector::new();
v.push_back(1);
v.push_back(2);
assert_eq!(v.pop_back(), Some(2));
assert_eq!(v.size(), 1);
assert_eq!(v.pop_back(), Some(1));
assert_eq!(v.pop_back(), None);
}
#[test]
fn test_vector_front_back() {
let mut v = Vector::new();
v.push_back(100);
v.push_back(200);
assert_eq!(*v.front().unwrap(), 100);
assert_eq!(*v.back().unwrap(), 200);
}
#[test]
fn test_vector_clear() {
let mut v = Vector::new();
v.push_back(1);
v.push_back(2);
v.clear();
assert!(v.empty());
assert_eq!(v.size(), 0);
}
#[test]
fn test_vector_resize() {
let mut v = Vector::new();
v.resize(5, 42);
assert_eq!(v.size(), 5);
assert_eq!(v[0], 42);
assert_eq!(v[4], 42);
}
#[test]
fn test_vector_insert() {
let mut v = Vector::new();
v.push_back(1);
v.push_back(3);
v.insert(1, 2);
assert_eq!(v[0], 1);
assert_eq!(v[1], 2);
assert_eq!(v[2], 3);
assert_eq!(v.size(), 3);
}
#[test]
fn test_vector_erase() {
let mut v = Vector::new();
v.push_back(1);
v.push_back(2);
v.push_back(3);
let removed = v.erase(1);
assert_eq!(removed, 2);
assert_eq!(v.size(), 2);
assert_eq!(v[0], 1);
assert_eq!(v[1], 3);
}
#[test]
fn test_vector_emplace_back() {
let mut v = Vector::new();
v.emplace_back(10);
v.emplace_back(20);
assert_eq!(v.size(), 2);
assert_eq!(v[0], 10);
}
#[test]
fn test_vector_iter() {
let mut v = Vector::new();
v.push_back(1);
v.push_back(2);
v.push_back(3);
let sum: i32 = v.iter().sum();
assert_eq!(sum, 6);
}
#[test]
fn test_vector_swap() {
let mut a = Vector::new();
a.push_back(1);
let mut b = Vector::new();
b.push_back(2);
a.swap(&mut b);
assert_eq!(a[0], 2);
assert_eq!(b[0], 1);
}
#[test]
fn test_vector_assign() {
let mut v = Vector::new();
v.assign(3, 99);
assert_eq!(v.size(), 3);
assert_eq!(v[0], 99);
assert_eq!(v[1], 99);
assert_eq!(v[2], 99);
}
#[test]
fn test_vector_capacity() {
let mut v = Vector::with_capacity(10);
assert!(v.capacity() >= 10);
v.push_back(1);
v.reserve(20);
assert!(v.capacity() >= 20);
}
#[test]
fn test_vector_slice() {
let mut v = Vector::new();
v.push_back(1);
v.push_back(2);
v.push_back(3);
let s = v.as_slice();
assert_eq!(s, &[1, 2, 3]);
}
#[test]
fn test_string_new_empty() {
let s = StdString::new();
assert!(s.empty());
assert_eq!(s.length(), 0);
}
#[test]
fn test_string_from_str() {
let s = StdString::from_str("hello");
assert_eq!(s.length(), 5);
assert!(!s.empty());
}
#[test]
fn test_string_c_str() {
let s = StdString::from_str("hello");
assert_eq!(s.c_str(), "hello");
}
#[test]
fn test_string_append() {
let mut s = StdString::from_str("hello");
s.append(" world");
assert_eq!(s.as_str(), "hello world");
}
#[test]
fn test_string_push_pop() {
let mut s = StdString::from_str("abc");
s.push_back('d');
assert_eq!(s.as_str(), "abcd");
assert_eq!(s.pop_back(), Some('d'));
assert_eq!(s.as_str(), "abc");
}
#[test]
fn test_string_substr() {
let s = StdString::from_str("hello world");
let sub = s.substr(0, 5);
assert_eq!(sub.as_str(), "hello");
let sub2 = s.substr(6, 5);
assert_eq!(sub2.as_str(), "world");
}
#[test]
fn test_string_find() {
let s = StdString::from_str("hello world");
assert_eq!(s.find("world"), Some(6));
assert_eq!(s.find("xyz"), None);
}
#[test]
fn test_string_find_char() {
let s = StdString::from_str("hello");
assert_eq!(s.find_char('h'), Some(0));
assert_eq!(s.find_char('o'), Some(4));
assert_eq!(s.find_char('x'), None);
}
#[test]
fn test_string_rfind() {
let s = StdString::from_str("hello hello");
assert_eq!(s.rfind("hello"), Some(6));
assert_eq!(s.rfind("xyz"), None);
}
#[test]
fn test_string_replace() {
let s = StdString::from_str("hello world");
let r = s.replace("world", "rust");
assert_eq!(r.as_str(), "hello rust");
}
#[test]
fn test_string_compare() {
let a = StdString::from_str("abc");
let b = StdString::from_str("abd");
assert_eq!(a.compare(&b), Ordering::Less);
assert_eq!(b.compare(&a), Ordering::Greater);
assert_eq!(a.compare(&a), Ordering::Equal);
}
#[test]
fn test_string_concatenation() {
let a = StdString::from_str("hello ");
let b = StdString::from_str("world");
let c = &a + &b;
assert_eq!(c.as_str(), "hello world");
}
#[test]
fn test_string_add_assign() {
let mut a = StdString::from_str("hello");
a += &StdString::from_str(" world");
assert_eq!(a.as_str(), "hello world");
}
#[test]
fn test_string_starts_ends_with() {
let s = StdString::from_str("hello world");
assert!(s.starts_with("hello"));
assert!(s.ends_with("world"));
assert!(!s.starts_with("world"));
}
#[test]
fn test_string_clear() {
let mut s = StdString::from_str("hello");
s.clear();
assert!(s.empty());
}
#[test]
fn test_stoi() {
assert_eq!(stoi("42").unwrap(), 42);
assert_eq!(stoi("-10").unwrap(), -10);
assert!(stoi("hello").is_err());
}
#[test]
fn test_stol() {
assert_eq!(stol("123456789").unwrap(), 123456789);
assert!(stol("abc").is_err());
}
#[test]
fn test_stoll() {
assert_eq!(stoll("9223372036854775807").unwrap(), 9223372036854775807i64);
assert!(stoll("xyz").is_err());
}
#[test]
fn test_stof() {
let val = stof("3.14").unwrap();
assert!((val - 3.14f32).abs() < 0.001);
assert!(stof("abc").is_err());
}
#[test]
fn test_stod() {
let val = stod("2.718281828").unwrap();
assert!((val - 2.718281828).abs() < 0.0001);
assert!(stod("xyz").is_err());
}
#[test]
fn test_map_new_empty() {
let m: OrderedMap<i32, i32> = OrderedMap::new();
assert!(m.empty());
assert_eq!(m.size(), 0);
}
#[test]
fn test_map_insert_find() {
let mut m = OrderedMap::new();
m.insert(1, 100);
m.insert(2, 200);
assert_eq!(m.size(), 2);
assert_eq!(*m.find(&1).unwrap(), 100);
assert_eq!(*m.find(&2).unwrap(), 200);
assert!(m.find(&3).is_none());
}
#[test]
fn test_map_insert_overwrite() {
let mut m = OrderedMap::new();
assert_eq!(m.insert(1, 100), None);
assert_eq!(m.insert(1, 200), Some(100));
assert_eq!(*m.find(&1).unwrap(), 200);
}
#[test]
fn test_map_contains() {
let mut m = OrderedMap::new();
m.insert(1, 10);
assert!(m.contains(&1));
assert!(!m.contains(&2));
}
#[test]
fn test_map_erase() {
let mut m = OrderedMap::new();
m.insert(1, 10);
m.insert(2, 20);
assert_eq!(m.erase(&1), Some(10));
assert_eq!(m.size(), 1);
assert!(!m.contains(&1));
}
#[test]
fn test_map_iter() {
let mut m = OrderedMap::new();
m.insert(3, 30);
m.insert(1, 10);
m.insert(2, 20);
let keys: Vec<i32> = m.keys().copied().collect();
assert_eq!(keys, vec![1, 2, 3]); }
#[test]
fn test_map_begin_end() {
let mut m = OrderedMap::new();
m.insert(5, 50);
m.insert(1, 10);
assert_eq!(m.begin().unwrap().0, &1);
assert_eq!(m.end().unwrap().0, &5);
}
#[test]
fn test_map_lower_upper_bound() {
let mut m = OrderedMap::new();
m.insert(10, 100);
m.insert(20, 200);
m.insert(30, 300);
assert_eq!(m.lower_bound(&15).unwrap().0, &20);
assert_eq!(m.upper_bound(&20).unwrap().0, &30);
}
#[test]
fn test_set_new_empty() {
let s: OrderedSet<i32> = OrderedSet::new();
assert!(s.empty());
assert_eq!(s.size(), 0);
}
#[test]
fn test_set_insert_find() {
let mut s = OrderedSet::new();
assert!(s.insert(1));
assert!(!s.insert(1)); assert_eq!(s.size(), 1);
assert_eq!(*s.find(&1).unwrap(), 1);
assert!(s.find(&2).is_none());
}
#[test]
fn test_set_contains() {
let mut s = OrderedSet::new();
s.insert(42);
assert!(s.contains(&42));
assert!(!s.contains(&99));
}
#[test]
fn test_set_erase() {
let mut s = OrderedSet::new();
s.insert(1);
s.insert(2);
assert!(s.erase(&1));
assert!(!s.contains(&1));
assert_eq!(s.size(), 1);
}
#[test]
fn test_set_iter() {
let mut s = OrderedSet::new();
s.insert(3);
s.insert(1);
s.insert(2);
let v: Vec<i32> = s.iter().copied().collect();
assert_eq!(v, vec![1, 2, 3]);
}
#[test]
fn test_set_lower_upper_bound() {
let mut s = OrderedSet::new();
s.insert(10);
s.insert(20);
s.insert(30);
assert_eq!(*s.lower_bound(&15).unwrap(), 20);
assert_eq!(*s.upper_bound(&20).unwrap(), 30);
}
#[test]
fn test_sort_ints() {
let mut v = vec![3, 1, 4, 1, 5, 9, 2, 6];
sort(&mut v);
assert_eq!(v, vec![1, 1, 2, 3, 4, 5, 6, 9]);
}
#[test]
fn test_sort_strings() {
let mut v = vec!["banana", "apple", "cherry"];
sort(&mut v);
assert_eq!(v, vec!["apple", "banana", "cherry"]);
}
#[test]
fn test_sort_by_custom() {
let mut v = vec![30, 10, 20];
sort_by(&mut v, |a, b| b.cmp(a)); assert_eq!(v, vec![30, 20, 10]);
}
#[test]
fn test_stable_sort() {
let mut v = vec![3, 1, 4, 1, 5];
stable_sort(&mut v);
assert_eq!(v, vec![1, 1, 3, 4, 5]);
}
#[test]
fn test_find_algorithm() {
let v = vec![1, 2, 3, 4, 5];
assert_eq!(find(&v, &3), Some(2));
assert_eq!(find(&v, &99), None);
}
#[test]
fn test_find_if_algorithm() {
let v = vec![1, 2, 3, 4, 5];
assert_eq!(find_if(&v, |x| *x > 3), Some(3));
assert_eq!(find_if(&v, |x| *x > 10), None);
}
#[test]
fn test_count_algorithm() {
let v = vec![1, 2, 2, 3, 2, 4];
assert_eq!(count(&v, &2), 3);
assert_eq!(count(&v, &99), 0);
}
#[test]
fn test_count_if_algorithm() {
let v = vec![1, 2, 3, 4, 5];
assert_eq!(count_if(&v, |x| *x % 2 == 0), 2);
}
#[test]
fn test_copy_algorithm() {
let src = vec![1, 2, 3];
let mut dst = vec![0, 0, 0];
let n = copy(&src, &mut dst);
assert_eq!(n, 3);
assert_eq!(dst, vec![1, 2, 3]);
}
#[test]
fn test_transform_algorithm() {
let src = vec![1, 2, 3];
let mut dst = vec![0, 0, 0];
transform(&src, &mut dst, |x| x * 2);
assert_eq!(dst, vec![2, 4, 6]);
}
#[test]
fn test_accumulate_algorithm() {
let v = vec![1, 2, 3, 4, 5];
assert_eq!(accumulate(&v, 0), 15);
assert_eq!(accumulate(&v, 10), 25);
}
#[test]
fn test_max_min_element() {
let v = vec![3, 1, 4, 1, 5, 9, 2];
let (idx, val) = max_element(&v).unwrap();
assert_eq!(*val, 9);
assert_eq!(idx, 5);
let (idx, val) = min_element(&v).unwrap();
assert_eq!(*val, 1);
assert_eq!(idx, 1);
}
#[test]
fn test_binary_search_algorithm() {
let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
assert_eq!(binary_search(&v, &5), Some(4));
assert_eq!(binary_search(&v, &10), None);
}
#[test]
fn test_lower_bound_algorithm() {
let v = vec![10, 20, 20, 30, 40];
assert_eq!(lower_bound(&v, &20), 1);
assert_eq!(lower_bound(&v, &25), 3);
}
#[test]
fn test_upper_bound_algorithm() {
let v = vec![10, 20, 20, 30, 40];
assert_eq!(upper_bound(&v, &20), 3);
assert_eq!(upper_bound(&v, &30), 4);
}
#[test]
fn test_unique_algorithm() {
let mut v = vec![1, 1, 2, 2, 2, 3, 3, 4];
let n = unique(&mut v);
assert_eq!(n, 4);
v.truncate(n);
assert_eq!(v, vec![1, 2, 3, 4]);
}
#[test]
fn test_reverse_algorithm() {
let mut v = vec![1, 2, 3, 4, 5];
reverse(&mut v);
assert_eq!(v, vec![5, 4, 3, 2, 1]);
}
#[test]
fn test_rotate_algorithm() {
let mut v = vec![1, 2, 3, 4, 5];
rotate(&mut v, 2);
assert_eq!(v, vec![3, 4, 5, 1, 2]);
}
#[test]
fn test_partition_algorithm() {
let mut v = vec![1, 2, 3, 4, 5, 6];
let pivot = partition(&mut v, |x| *x % 2 == 0);
for i in 0..pivot {
assert!(v[i] % 2 == 0);
}
}
#[test]
fn test_next_permutation() {
let mut v = vec![1, 2, 3];
assert!(next_permutation(&mut v));
assert_eq!(v, vec![1, 3, 2]);
assert!(next_permutation(&mut v));
assert_eq!(v, vec![2, 1, 3]);
let mut count = 2;
while next_permutation(&mut v) {
count += 1;
}
assert_eq!(count, 6); assert_eq!(v, vec![1, 2, 3]);
}
#[test]
fn test_for_each_algorithm() {
let v = vec![1, 2, 3];
let mut sum = 0;
for_each(&v, |x| sum += x);
assert_eq!(sum, 6);
}
#[test]
fn test_reverse_iterator_new() {
let _ri = ReverseIterator::new(vec![1, 2, 3].into_iter());
}
#[test]
fn test_back_inserter_new() {
let bi = BackInserter::new(Vector::<i32>::new());
let _ = bi.into_inner();
}
#[test]
fn test_unique_ptr_new() {
let up = UniquePtr::new(42);
assert!(up.is_valid());
assert_eq!(*up, 42);
}
#[test]
fn test_unique_ptr_deref() {
let up = UniquePtr::new(100);
assert_eq!(*up, 100);
}
#[test]
fn test_make_unique() {
let up = make_unique("hello");
assert_eq!(*up, "hello");
}
#[test]
fn test_unique_ptr_release() {
let up = UniquePtr::new(42);
let raw = up.release();
unsafe {
assert_eq!(*raw, 42);
drop(Box::from_raw(raw));
}
}
#[test]
fn test_shared_ptr_new() {
let sp = SharedPtr::new(42);
assert_eq!(sp.use_count(), 1);
}
#[test]
fn test_shared_ptr_clone() {
let sp1 = SharedPtr::new(42);
let sp2 = sp1.clone();
assert_eq!(sp1.use_count(), 2);
assert_eq!(sp2.use_count(), 2);
}
#[test]
fn test_shared_ptr_reset() {
let mut sp = SharedPtr::new(42);
sp.reset();
assert_eq!(sp.use_count(), 0);
}
#[test]
fn test_make_shared() {
let sp = make_shared(99);
assert_eq!(*sp, 99);
assert_eq!(sp.use_count(), 1);
}
#[test]
fn test_weak_ptr_new() {
let wp: WeakPtr<i32> = WeakPtr::new();
assert!(wp.expired());
}
#[test]
fn test_weak_ptr_default() {
let wp = WeakPtr::<i32>::default();
assert!(wp.expired());
}
#[test]
fn test_allocator_new() {
let alloc = Allocator::new();
assert!(alloc.max_size() > 0);
}
#[test]
fn test_allocator_allocate_deallocate() {
let alloc = Allocator::new();
let ptr = alloc.allocate::<i32>(1);
assert!(!ptr.is_null());
alloc.deallocate(ptr, 1);
}
#[test]
fn test_allocator_construct_destroy() {
let alloc = Allocator::new();
let ptr = alloc.allocate::<i32>(1);
alloc.construct(ptr, 42);
unsafe {
assert_eq!(*ptr, 42);
}
alloc.destroy(ptr);
alloc.deallocate(ptr, 1);
}
#[test]
fn test_numeric_accumulate() {
let v = vec![1, 2, 3, 4, 5];
assert_eq!(numeric_accumulate(&v, 0), 15);
}
#[test]
fn test_inner_product() {
let a = vec![1, 2, 3];
let b = vec![4, 5, 6];
assert_eq!(inner_product(&a, &b, 0), 32);
}
#[test]
fn test_adjacent_difference() {
let src = vec![1, 2, 4, 7];
let mut dst = vec![0; 4];
let n = adjacent_difference(&src, &mut dst);
assert_eq!(n, 4);
assert_eq!(dst[0], 1);
assert_eq!(dst[1], 1); assert_eq!(dst[2], 2); assert_eq!(dst[3], 3); }
#[test]
fn test_partial_sum() {
let src = vec![1, 2, 3, 4];
let mut dst = vec![0; 4];
let n = partial_sum(&src, &mut dst);
assert_eq!(n, 4);
assert_eq!(dst, vec![1, 3, 6, 10]);
}
#[test]
fn test_iota() {
let mut v = vec![0u32; 5];
iota(&mut v, 10u32);
assert_eq!(v, vec![10, 11, 12, 13, 14]);
}
#[test]
fn test_gcd_lcm() {
assert_eq!(gcd(12u32, 8u32), 4);
assert_eq!(gcd(17u32, 13u32), 1);
assert_eq!(lcm(4u32, 6u32), 12);
assert_eq!(lcm(21u32, 6u32), 42);
}
#[test]
fn test_exception_what() {
let e = Exception::new("test error");
assert_eq!(e.what(), "test error");
}
#[test]
fn test_logic_error() {
let e = LogicError::new("bad logic");
assert!(e.what().contains("bad logic"));
}
#[test]
fn test_runtime_error() {
let e = RuntimeError::new("bad runtime");
assert!(e.what().contains("bad runtime"));
}
#[test]
fn test_out_of_range() {
let e = OutOfRange::new("index out of range");
assert!(e.what().contains("index out of range"));
}
#[test]
fn test_invalid_argument() {
let e = InvalidArgument::new("invalid input");
assert!(e.what().contains("invalid input"));
}
#[test]
fn test_length_error() {
let e = LengthError::new("too long");
assert!(e.what().contains("too long"));
}
#[test]
fn test_overflow_error() {
let e = OverflowError::new("overflow");
assert!(e.what().contains("overflow"));
}
#[test]
fn test_exception_display() {
let e = Exception::new("test");
assert_eq!(format!("{}", e), "test");
let le = LogicError::new("test");
assert!(format!("{}", le).contains("logic_error"));
}
#[test]
fn test_iosfwd_types_exist() {
let _cin = CIN;
let _cout = COUT;
let _cerr = CERR;
let _clog = CLOG;
}
}