repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/length_conversion.rs
src/conversions/length_conversion.rs
/// Author : https://github.com/ali77gh /// Conversion of length units. /// /// Available Units: /// -> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter /// -> Wikipedia reference: https://en.wikipedia.org/wiki/Centimeter /// -> Wikipedia reference: https://en.wikipedia.org/wiki/Meter /// -> Wikipedia reference: https://en.wikipedia.org/wiki/Kilometer /// -> Wikipedia reference: https://en.wikipedia.org/wiki/Inch /// -> Wikipedia reference: https://en.wikipedia.org/wiki/Foot /// -> Wikipedia reference: https://en.wikipedia.org/wiki/Yard /// -> Wikipedia reference: https://en.wikipedia.org/wiki/Mile #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub enum LengthUnit { Millimeter, Centimeter, Meter, Kilometer, Inch, Foot, Yard, Mile, } fn unit_to_meter_multiplier(from: LengthUnit) -> f64 { match from { LengthUnit::Millimeter => 0.001, LengthUnit::Centimeter => 0.01, LengthUnit::Meter => 1.0, LengthUnit::Kilometer => 1000.0, LengthUnit::Inch => 0.0254, LengthUnit::Foot => 0.3048, LengthUnit::Yard => 0.9144, LengthUnit::Mile => 1609.34, } } fn unit_to_meter(input: f64, from: LengthUnit) -> f64 { input * unit_to_meter_multiplier(from) } fn meter_to_unit(input: f64, to: LengthUnit) -> f64 { input / unit_to_meter_multiplier(to) } /// This function will convert a value in unit of [from] to value in unit of [to] /// by first converting it to meter and than convert it to destination unit pub fn length_conversion(input: f64, from: LengthUnit, to: LengthUnit) -> f64 { meter_to_unit(unit_to_meter(input, from), to) } #[cfg(test)] mod length_conversion_tests { use std::collections::HashMap; use super::LengthUnit::*; use super::*; #[test] fn zero_to_zero() { let units = vec![ Millimeter, Centimeter, Meter, Kilometer, Inch, Foot, Yard, Mile, ]; for u1 in units.clone() { for u2 in units.clone() { assert_eq!(length_conversion(0f64, u1, u2), 0f64); } } } #[test] fn length_of_one_meter() { let meter_in_different_units = HashMap::from([ (Millimeter, 1000f64), (Centimeter, 100f64), (Kilometer, 0.001f64), (Inch, 39.37007874015748f64), (Foot, 3.280839895013123f64), (Yard, 1.0936132983377078f64), (Mile, 0.0006213727366498068f64), ]); for (input_unit, input_value) in &meter_in_different_units { for (target_unit, target_value) in &meter_in_different_units { assert!( num_traits::abs( length_conversion(*input_value, *input_unit, *target_unit) - *target_value ) < 0.0000001 ); } } } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/hexadecimal_to_octal.rs
src/conversions/hexadecimal_to_octal.rs
// Author: NithinU2802 // Hexadecimal to Octal Converter: Converts Hexadecimal to Octal // Wikipedia References: // 1. https://en.wikipedia.org/wiki/Hexadecimal // 2. https://en.wikipedia.org/wiki/Octal pub fn hexadecimal_to_octal(hex_str: &str) -> Result<String, &'static str> { let hex_str = hex_str.trim(); if hex_str.is_empty() { return Err("Empty string"); } // Validate hexadecimal string if !hex_str.chars().all(|c| c.is_ascii_hexdigit()) { return Err("Invalid hexadecimal string"); } // Convert hex to decimal first let decimal = u64::from_str_radix(hex_str, 16).map_err(|_| "Conversion error")?; // Then convert decimal to octal if decimal == 0 { return Ok("0".to_string()); } let mut num = decimal; let mut octal = String::new(); while num > 0 { let remainder = num % 8; octal.push_str(&remainder.to_string()); num /= 8; } // Reverse the string to get the correct octal representation Ok(octal.chars().rev().collect()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_hexadecimal_to_octal() { assert_eq!(hexadecimal_to_octal("A"), Ok("12".to_string())); assert_eq!(hexadecimal_to_octal("FF"), Ok("377".to_string())); assert_eq!(hexadecimal_to_octal("64"), Ok("144".to_string())); assert_eq!(hexadecimal_to_octal("0"), Ok("0".to_string())); } #[test] fn test_invalid_input() { assert_eq!(hexadecimal_to_octal(""), Err("Empty string")); assert_eq!( hexadecimal_to_octal("GG"), Err("Invalid hexadecimal string") ); assert_eq!( hexadecimal_to_octal("XYZ"), Err("Invalid hexadecimal string") ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/octal_to_binary.rs
src/conversions/octal_to_binary.rs
// Author : cyrixninja // Octal to Binary Converter : Converts Octal to Binary // Wikipedia References : 1. https://en.wikipedia.org/wiki/Octal // 2. https://en.wikipedia.org/wiki/Binary_number pub fn octal_to_binary(octal_str: &str) -> Result<String, &'static str> { let octal_str = octal_str.trim(); if octal_str.is_empty() { return Err("Empty"); } if !octal_str.chars().all(|c| ('0'..'7').contains(&c)) { return Err("Non-octal Value"); } // Convert octal to binary let binary = octal_str .chars() .map(|c| match c { '0' => "000", '1' => "001", '2' => "010", '3' => "011", '4' => "100", '5' => "101", '6' => "110", '7' => "111", _ => unreachable!(), }) .collect::<String>(); Ok(binary) } #[cfg(test)] mod tests { use super::*; #[test] fn test_empty_string() { let input = ""; let expected = Err("Empty"); assert_eq!(octal_to_binary(input), expected); } #[test] fn test_invalid_octal() { let input = "89"; let expected = Err("Non-octal Value"); assert_eq!(octal_to_binary(input), expected); } #[test] fn test_valid_octal() { let input = "123"; let expected = Ok("001010011".to_string()); assert_eq!(octal_to_binary(input), expected); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/binary_to_octal.rs
src/conversions/binary_to_octal.rs
// Author: NithinU2802 // Binary to Octal Converter: Converts Binary to Octal // Wikipedia References: // 1. https://en.wikipedia.org/wiki/Binary_number // 2. https://en.wikipedia.org/wiki/Octal pub fn binary_to_octal(binary_str: &str) -> Result<String, &'static str> { // Validate input let binary_str = binary_str.trim(); if binary_str.is_empty() { return Err("Empty string"); } if !binary_str.chars().all(|c| c == '0' || c == '1') { return Err("Invalid binary string"); } // Pad the binary string with zeros to make its length a multiple of 3 let padding_length = (3 - (binary_str.len() % 3)) % 3; let padded_binary = "0".repeat(padding_length) + binary_str; // Convert every 3 binary digits to one octal digit let mut octal = String::new(); for chunk in padded_binary.chars().collect::<Vec<char>>().chunks(3) { let binary_group: String = chunk.iter().collect(); let decimal = u8::from_str_radix(&binary_group, 2).map_err(|_| "Conversion error")?; octal.push_str(&decimal.to_string()); } Ok(octal) } #[cfg(test)] mod tests { use super::*; #[test] fn test_binary_to_octal() { assert_eq!(binary_to_octal("1010"), Ok("12".to_string())); assert_eq!(binary_to_octal("1111"), Ok("17".to_string())); assert_eq!(binary_to_octal("11111111"), Ok("377".to_string())); assert_eq!(binary_to_octal("1100100"), Ok("144".to_string())); } #[test] fn test_invalid_input() { assert_eq!(binary_to_octal(""), Err("Empty string")); assert_eq!(binary_to_octal("12"), Err("Invalid binary string")); assert_eq!(binary_to_octal("abc"), Err("Invalid binary string")); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/hexadecimal_to_decimal.rs
src/conversions/hexadecimal_to_decimal.rs
pub fn hexadecimal_to_decimal(hexadecimal_str: &str) -> Result<u64, &'static str> { if hexadecimal_str.is_empty() { return Err("Empty input"); } for hexadecimal_str in hexadecimal_str.chars() { if !hexadecimal_str.is_ascii_hexdigit() { return Err("Input was not a hexadecimal number"); } } match u64::from_str_radix(hexadecimal_str, 16) { Ok(decimal) => Ok(decimal), Err(_e) => Err("Failed to convert octal to hexadecimal"), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_hexadecimal_to_decimal_empty() { assert_eq!(hexadecimal_to_decimal(""), Err("Empty input")); } #[test] fn test_hexadecimal_to_decimal_invalid() { assert_eq!( hexadecimal_to_decimal("xyz"), Err("Input was not a hexadecimal number") ); assert_eq!( hexadecimal_to_decimal("0xabc"), Err("Input was not a hexadecimal number") ); } #[test] fn test_hexadecimal_to_decimal_valid1() { assert_eq!(hexadecimal_to_decimal("45"), Ok(69)); assert_eq!(hexadecimal_to_decimal("2b3"), Ok(691)); assert_eq!(hexadecimal_to_decimal("4d2"), Ok(1234)); assert_eq!(hexadecimal_to_decimal("1267a"), Ok(75386)); } #[test] fn test_hexadecimal_to_decimal_valid2() { assert_eq!(hexadecimal_to_decimal("1a"), Ok(26)); assert_eq!(hexadecimal_to_decimal("ff"), Ok(255)); assert_eq!(hexadecimal_to_decimal("a1b"), Ok(2587)); assert_eq!(hexadecimal_to_decimal("7fffffff"), Ok(2147483647)); } #[test] fn test_hexadecimal_to_decimal_valid3() { assert_eq!(hexadecimal_to_decimal("0"), Ok(0)); assert_eq!(hexadecimal_to_decimal("7f"), Ok(127)); assert_eq!(hexadecimal_to_decimal("80000000"), Ok(2147483648)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/rgb_cmyk_conversion.rs
src/conversions/rgb_cmyk_conversion.rs
/// Author : https://github.com/ali77gh\ /// References:\ /// RGB: https://en.wikipedia.org/wiki/RGB_color_model\ /// CMYK: https://en.wikipedia.org/wiki/CMYK_color_model\ /// This function Converts RGB to CMYK format /// /// ### Params /// * `r` - red /// * `g` - green /// * `b` - blue /// /// ### Returns /// (C, M, Y, K) pub fn rgb_to_cmyk(rgb: (u8, u8, u8)) -> (u8, u8, u8, u8) { // Safety: no need to check if input is positive and less than 255 because it's u8 // change scale from [0,255] to [0,1] let (r, g, b) = ( rgb.0 as f64 / 255f64, rgb.1 as f64 / 255f64, rgb.2 as f64 / 255f64, ); match 1f64 - r.max(g).max(b) { 1f64 => (0, 0, 0, 100), // pure black k => ( (100f64 * (1f64 - r - k) / (1f64 - k)) as u8, // c (100f64 * (1f64 - g - k) / (1f64 - k)) as u8, // m (100f64 * (1f64 - b - k) / (1f64 - k)) as u8, // y (100f64 * k) as u8, // k ), } } #[cfg(test)] mod tests { use super::*; macro_rules! test_rgb_to_cmyk { ($($name:ident: $tc:expr,)*) => { $( #[test] fn $name() { let (rgb, cmyk) = $tc; assert_eq!(rgb_to_cmyk(rgb), cmyk); } )* } } test_rgb_to_cmyk! { white: ((255, 255, 255), (0, 0, 0, 0)), gray: ((128, 128, 128), (0, 0, 0, 49)), black: ((0, 0, 0), (0, 0, 0, 100)), red: ((255, 0, 0), (0, 100, 100, 0)), green: ((0, 255, 0), (100, 0, 100, 0)), blue: ((0, 0, 255), (100, 100, 0, 0)), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/mod.rs
src/conversions/mod.rs
mod binary_to_decimal; mod binary_to_hexadecimal; mod binary_to_octal; mod decimal_to_binary; mod decimal_to_hexadecimal; mod decimal_to_octal; mod hexadecimal_to_binary; mod hexadecimal_to_decimal; mod hexadecimal_to_octal; mod length_conversion; mod octal_to_binary; mod octal_to_decimal; mod octal_to_hexadecimal; mod order_of_magnitude_conversion; mod rgb_cmyk_conversion; pub use self::binary_to_decimal::binary_to_decimal; pub use self::binary_to_hexadecimal::binary_to_hexadecimal; pub use self::binary_to_octal::binary_to_octal; pub use self::decimal_to_binary::decimal_to_binary; pub use self::decimal_to_hexadecimal::decimal_to_hexadecimal; pub use self::decimal_to_octal::decimal_to_octal; pub use self::hexadecimal_to_binary::hexadecimal_to_binary; pub use self::hexadecimal_to_decimal::hexadecimal_to_decimal; pub use self::hexadecimal_to_octal::hexadecimal_to_octal; pub use self::length_conversion::length_conversion; pub use self::octal_to_binary::octal_to_binary; pub use self::octal_to_decimal::octal_to_decimal; pub use self::octal_to_hexadecimal::octal_to_hexadecimal; pub use self::order_of_magnitude_conversion::{ convert_metric_length, metric_length_conversion, MetricLengthUnit, }; pub use self::rgb_cmyk_conversion::rgb_to_cmyk;
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/hexadecimal_to_binary.rs
src/conversions/hexadecimal_to_binary.rs
// Author : cyrixninja // Hexadecimal to Binary Converter : Converts Hexadecimal to Binary // Wikipedia References : 1. https://en.wikipedia.org/wiki/Hexadecimal // 2. https://en.wikipedia.org/wiki/Binary_number // Other References for Testing : https://www.rapidtables.com/convert/number/hex-to-binary.html pub fn hexadecimal_to_binary(hex_str: &str) -> Result<String, String> { let hex_chars = hex_str.chars().collect::<Vec<char>>(); let mut binary = String::new(); for c in hex_chars { let bin_rep = match c { '0' => "0000", '1' => "0001", '2' => "0010", '3' => "0011", '4' => "0100", '5' => "0101", '6' => "0110", '7' => "0111", '8' => "1000", '9' => "1001", 'a' | 'A' => "1010", 'b' | 'B' => "1011", 'c' | 'C' => "1100", 'd' | 'D' => "1101", 'e' | 'E' => "1110", 'f' | 'F' => "1111", _ => return Err("Invalid".to_string()), }; binary.push_str(bin_rep); } Ok(binary) } #[cfg(test)] mod tests { use super::*; #[test] fn test_empty_string() { let input = ""; let expected = Ok("".to_string()); assert_eq!(hexadecimal_to_binary(input), expected); } #[test] fn test_hexadecimal() { let input = "1a2"; let expected = Ok("000110100010".to_string()); assert_eq!(hexadecimal_to_binary(input), expected); } #[test] fn test_hexadecimal2() { let input = "1b3"; let expected = Ok("000110110011".to_string()); assert_eq!(hexadecimal_to_binary(input), expected); } #[test] fn test_invalid_hexadecimal() { let input = "1g3"; let expected = Err("Invalid".to_string()); assert_eq!(hexadecimal_to_binary(input), expected); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/decimal_to_binary.rs
src/conversions/decimal_to_binary.rs
pub fn decimal_to_binary(base_num: u64) -> String { let mut num = base_num; let mut binary_num = String::new(); loop { let bit = (num % 2).to_string(); binary_num.push_str(&bit); num /= 2; if num == 0 { break; } } let bits = binary_num.chars(); bits.rev().collect() } #[cfg(test)] mod tests { use super::*; #[test] fn converting_decimal_to_binary() { assert_eq!(decimal_to_binary(542), "1000011110"); assert_eq!(decimal_to_binary(92), "1011100"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/octal_to_decimal.rs
src/conversions/octal_to_decimal.rs
// Author: cyrixninja // Octal to Decimal Converter: Converts Octal to Decimal // Wikipedia References: // 1. https://en.wikipedia.org/wiki/Octal // 2. https://en.wikipedia.org/wiki/Decimal pub fn octal_to_decimal(octal_str: &str) -> Result<u64, &'static str> { let octal_str = octal_str.trim(); if octal_str.is_empty() { return Err("Empty"); } if !octal_str.chars().all(|c| ('0'..='7').contains(&c)) { return Err("Non-octal Value"); } // Convert octal to decimal and directly return the Result u64::from_str_radix(octal_str, 8).map_err(|_| "Conversion error") } #[cfg(test)] mod tests { use super::*; #[test] fn test_empty_string() { let input = ""; let expected = Err("Empty"); assert_eq!(octal_to_decimal(input), expected); } #[test] fn test_invalid_octal() { let input = "89"; let expected = Err("Non-octal Value"); assert_eq!(octal_to_decimal(input), expected); } #[test] fn test_valid_octal() { let input = "123"; let expected = Ok(83); assert_eq!(octal_to_decimal(input), expected); } #[test] fn test_valid_octal2() { let input = "1234"; let expected = Ok(668); assert_eq!(octal_to_decimal(input), expected); } #[test] fn test_valid_octal3() { let input = "12345"; let expected = Ok(5349); assert_eq!(octal_to_decimal(input), expected); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/decimal_to_hexadecimal.rs
src/conversions/decimal_to_hexadecimal.rs
pub fn decimal_to_hexadecimal(base_num: u64) -> String { let mut num = base_num; let mut hexadecimal_num = String::new(); loop { let remainder = num % 16; let hex_char = if remainder < 10 { (remainder as u8 + b'0') as char } else { (remainder as u8 - 10 + b'A') as char }; hexadecimal_num.insert(0, hex_char); num /= 16; if num == 0 { break; } } hexadecimal_num } #[cfg(test)] mod tests { use super::*; #[test] fn test_zero() { assert_eq!(decimal_to_hexadecimal(0), "0"); } #[test] fn test_single_digit_decimal() { assert_eq!(decimal_to_hexadecimal(9), "9"); } #[test] fn test_single_digit_hexadecimal() { assert_eq!(decimal_to_hexadecimal(12), "C"); } #[test] fn test_multiple_digit_hexadecimal() { assert_eq!(decimal_to_hexadecimal(255), "FF"); } #[test] fn test_big() { assert_eq!(decimal_to_hexadecimal(u64::MAX), "FFFFFFFFFFFFFFFF"); } #[test] fn test_random() { assert_eq!(decimal_to_hexadecimal(123456), "1E240"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/find_unique_number.rs
src/bit_manipulation/find_unique_number.rs
/// Finds the unique number in a slice where every other element appears twice. /// /// This function uses the XOR bitwise operation. Since XOR has the property that /// `a ^ a = 0` and `a ^ 0 = a`, all paired numbers cancel out, leaving only the /// unique number. /// /// # Arguments /// /// * `arr` - A slice of integers where all elements except one appear exactly twice /// /// # Returns /// /// * `Ok(i32)` - The unique number that appears only once /// * `Err(String)` - An error message if the input is empty /// /// # Examples /// /// ``` /// # use the_algorithms_rust::bit_manipulation::find_unique_number; /// assert_eq!(find_unique_number(&[1, 1, 2, 2, 3]).unwrap(), 3); /// assert_eq!(find_unique_number(&[4, 5, 4, 6, 6]).unwrap(), 5); /// assert_eq!(find_unique_number(&[7]).unwrap(), 7); /// assert_eq!(find_unique_number(&[10, 20, 10]).unwrap(), 20); /// assert!(find_unique_number(&[]).is_err()); /// ``` pub fn find_unique_number(arr: &[i32]) -> Result<i32, String> { if arr.is_empty() { return Err("input list must not be empty".to_string()); } let result = arr.iter().fold(0, |acc, &num| acc ^ num); Ok(result) } #[cfg(test)] mod tests { use super::*; #[test] fn test_basic_case() { assert_eq!(find_unique_number(&[1, 1, 2, 2, 3]).unwrap(), 3); } #[test] fn test_different_order() { assert_eq!(find_unique_number(&[4, 5, 4, 6, 6]).unwrap(), 5); } #[test] fn test_single_element() { assert_eq!(find_unique_number(&[7]).unwrap(), 7); } #[test] fn test_three_elements() { assert_eq!(find_unique_number(&[10, 20, 10]).unwrap(), 20); } #[test] fn test_empty_array() { assert!(find_unique_number(&[]).is_err()); assert_eq!( find_unique_number(&[]).unwrap_err(), "input list must not be empty" ); } #[test] fn test_negative_numbers() { assert_eq!(find_unique_number(&[-1, -1, -2, -2, -3]).unwrap(), -3); } #[test] fn test_large_numbers() { assert_eq!( find_unique_number(&[1000, 2000, 1000, 3000, 3000]).unwrap(), 2000 ); } #[test] fn test_zero() { assert_eq!(find_unique_number(&[0, 1, 1]).unwrap(), 0); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/find_previous_power_of_two.rs
src/bit_manipulation/find_previous_power_of_two.rs
//! Previous Power of Two //! //! This module provides a function to find the largest power of two that is less than //! or equal to a given non-negative integer. //! //! # Algorithm //! //! The algorithm works by repeatedly left-shifting (doubling) a power value starting //! from 1 until it exceeds the input number, then returning the previous power (by //! right-shifting once). //! //! For more information: <https://stackoverflow.com/questions/1322510> /// Finds the largest power of two that is less than or equal to a given integer. /// /// The function uses bit shifting to efficiently find the power of two. It starts /// with 1 and keeps doubling (left shift) until it exceeds the input, then returns /// the previous value (right shift). /// /// # Arguments /// /// * `number` - A non-negative integer /// /// # Returns /// /// A `Result` containing: /// - `Ok(u32)` - The largest power of two ≤ the input number /// - `Err(String)` - An error message if the input is negative /// /// # Examples /// /// ``` /// use the_algorithms_rust::bit_manipulation::find_previous_power_of_two; /// /// assert_eq!(find_previous_power_of_two(0).unwrap(), 0); /// assert_eq!(find_previous_power_of_two(1).unwrap(), 1); /// assert_eq!(find_previous_power_of_two(2).unwrap(), 2); /// assert_eq!(find_previous_power_of_two(3).unwrap(), 2); /// assert_eq!(find_previous_power_of_two(4).unwrap(), 4); /// assert_eq!(find_previous_power_of_two(5).unwrap(), 4); /// assert_eq!(find_previous_power_of_two(8).unwrap(), 8); /// assert_eq!(find_previous_power_of_two(15).unwrap(), 8); /// assert_eq!(find_previous_power_of_two(16).unwrap(), 16); /// assert_eq!(find_previous_power_of_two(17).unwrap(), 16); /// /// // Negative numbers return an error /// assert!(find_previous_power_of_two(-5).is_err()); /// ``` /// /// # Errors /// /// Returns an error if the input number is negative. pub fn find_previous_power_of_two(number: i32) -> Result<u32, String> { if number < 0 { return Err("Input must be a non-negative integer".to_string()); } let number = number as u32; if number == 0 { return Ok(0); } let mut power = 1u32; while power <= number { power <<= 1; // Equivalent to multiplying by 2 } Ok(if number > 1 { power >> 1 } else { 1 }) } #[cfg(test)] mod tests { use super::*; #[test] fn test_zero() { assert_eq!(find_previous_power_of_two(0).unwrap(), 0); } #[test] fn test_one() { assert_eq!(find_previous_power_of_two(1).unwrap(), 1); } #[test] fn test_powers_of_two() { assert_eq!(find_previous_power_of_two(2).unwrap(), 2); assert_eq!(find_previous_power_of_two(4).unwrap(), 4); assert_eq!(find_previous_power_of_two(8).unwrap(), 8); assert_eq!(find_previous_power_of_two(16).unwrap(), 16); assert_eq!(find_previous_power_of_two(32).unwrap(), 32); assert_eq!(find_previous_power_of_two(64).unwrap(), 64); assert_eq!(find_previous_power_of_two(128).unwrap(), 128); assert_eq!(find_previous_power_of_two(256).unwrap(), 256); assert_eq!(find_previous_power_of_two(512).unwrap(), 512); assert_eq!(find_previous_power_of_two(1024).unwrap(), 1024); } #[test] fn test_numbers_between_powers() { // Between 2 and 4 assert_eq!(find_previous_power_of_two(3).unwrap(), 2); // Between 4 and 8 assert_eq!(find_previous_power_of_two(5).unwrap(), 4); assert_eq!(find_previous_power_of_two(6).unwrap(), 4); assert_eq!(find_previous_power_of_two(7).unwrap(), 4); // Between 8 and 16 assert_eq!(find_previous_power_of_two(9).unwrap(), 8); assert_eq!(find_previous_power_of_two(10).unwrap(), 8); assert_eq!(find_previous_power_of_two(11).unwrap(), 8); assert_eq!(find_previous_power_of_two(12).unwrap(), 8); assert_eq!(find_previous_power_of_two(13).unwrap(), 8); assert_eq!(find_previous_power_of_two(14).unwrap(), 8); assert_eq!(find_previous_power_of_two(15).unwrap(), 8); // Between 16 and 32 assert_eq!(find_previous_power_of_two(17).unwrap(), 16); assert_eq!(find_previous_power_of_two(20).unwrap(), 16); assert_eq!(find_previous_power_of_two(31).unwrap(), 16); } #[test] fn test_range_0_to_17() { // Test the exact output from the Python docstring let expected = vec![0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16]; let results: Vec<u32> = (0..18) .map(|i| find_previous_power_of_two(i).unwrap()) .collect(); assert_eq!(results, expected); } #[test] fn test_large_numbers() { assert_eq!(find_previous_power_of_two(100).unwrap(), 64); assert_eq!(find_previous_power_of_two(500).unwrap(), 256); assert_eq!(find_previous_power_of_two(1000).unwrap(), 512); assert_eq!(find_previous_power_of_two(2000).unwrap(), 1024); assert_eq!(find_previous_power_of_two(10000).unwrap(), 8192); } #[test] fn test_max_safe_values() { assert_eq!(find_previous_power_of_two(1023).unwrap(), 512); assert_eq!(find_previous_power_of_two(2047).unwrap(), 1024); assert_eq!(find_previous_power_of_two(4095).unwrap(), 2048); } #[test] fn test_negative_number_returns_error() { let result = find_previous_power_of_two(-1); assert!(result.is_err()); assert_eq!(result.unwrap_err(), "Input must be a non-negative integer"); } #[test] fn test_negative_numbers_return_errors() { assert!(find_previous_power_of_two(-5).is_err()); assert!(find_previous_power_of_two(-10).is_err()); assert!(find_previous_power_of_two(-100).is_err()); } #[test] fn test_edge_cases() { // One less than powers of two assert_eq!(find_previous_power_of_two(127).unwrap(), 64); assert_eq!(find_previous_power_of_two(255).unwrap(), 128); assert_eq!(find_previous_power_of_two(511).unwrap(), 256); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/highest_set_bit.rs
src/bit_manipulation/highest_set_bit.rs
//! This module provides a function to find the position of the most significant bit (MSB) //! set to 1 in a given positive integer. /// Finds the position of the highest (most significant) set bit in a positive integer. /// /// # Arguments /// /// * `num` - An integer value for which the highest set bit will be determined. /// /// # Returns /// /// * Returns `Some(position)` if a set bit exists or `None` if no bit is set. pub fn find_highest_set_bit(num: usize) -> Option<usize> { if num == 0 { return None; } let mut position = 0; let mut n = num; while n > 0 { n >>= 1; position += 1; } Some(position - 1) } #[cfg(test)] mod tests { use super::*; macro_rules! test_find_highest_set_bit { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (input, expected) = $test_case; assert_eq!(find_highest_set_bit(input), expected); } )* }; } test_find_highest_set_bit! { test_positive_number: (18, Some(4)), test_0: (0, None), test_1: (1, Some(0)), test_2: (2, Some(1)), test_3: (3, Some(1)), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/n_bits_gray_code.rs
src/bit_manipulation/n_bits_gray_code.rs
/// Custom error type for Gray code generation. #[derive(Debug, PartialEq)] pub enum GrayCodeError { ZeroBitCount, } /// Generates an n-bit Gray code sequence using the direct Gray code formula. /// /// # Arguments /// /// * `n` - The number of bits for the Gray code. /// /// # Returns /// /// A vector of Gray code sequences as strings. pub fn generate_gray_code(n: usize) -> Result<Vec<String>, GrayCodeError> { if n == 0 { return Err(GrayCodeError::ZeroBitCount); } let num_codes = 1 << n; let mut result = Vec::with_capacity(num_codes); for i in 0..num_codes { let gray = i ^ (i >> 1); let gray_code = (0..n) .rev() .map(|bit| if gray & (1 << bit) != 0 { '1' } else { '0' }) .collect::<String>(); result.push(gray_code); } Ok(result) } #[cfg(test)] mod tests { use super::*; macro_rules! gray_code_tests { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (input, expected) = $test_case; assert_eq!(generate_gray_code(input), expected); } )* }; } gray_code_tests! { zero_bit_count: (0, Err(GrayCodeError::ZeroBitCount)), gray_code_1_bit: (1, Ok(vec![ "0".to_string(), "1".to_string(), ])), gray_code_2_bit: (2, Ok(vec![ "00".to_string(), "01".to_string(), "11".to_string(), "10".to_string(), ])), gray_code_3_bit: (3, Ok(vec![ "000".to_string(), "001".to_string(), "011".to_string(), "010".to_string(), "110".to_string(), "111".to_string(), "101".to_string(), "100".to_string(), ])), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/rightmost_set_bit.rs
src/bit_manipulation/rightmost_set_bit.rs
/// Finds the index (position) of the rightmost set bit in a number. /// /// The index is 1-based, where position 1 is the least significant bit (rightmost). /// This function uses the bitwise trick `n & -n` to isolate the rightmost set bit, /// then calculates its position using logarithm base 2. /// /// # Algorithm /// /// 1. Use `n & -n` to isolate the rightmost set bit /// 2. Calculate log2 of the result to get the 0-based position /// 3. Add 1 to convert to 1-based indexing /// /// # Arguments /// /// * `num` - A positive integer /// /// # Returns /// /// * `Ok(u32)` - The 1-based position of the rightmost set bit /// * `Err(String)` - An error message if the input is invalid /// /// # Examples /// /// ``` /// # use the_algorithms_rust::bit_manipulation::index_of_rightmost_set_bit; /// // 18 in binary: 10010, rightmost set bit is at position 2 /// assert_eq!(index_of_rightmost_set_bit(18).unwrap(), 2); /// /// // 12 in binary: 1100, rightmost set bit is at position 3 /// assert_eq!(index_of_rightmost_set_bit(12).unwrap(), 3); /// /// // 5 in binary: 101, rightmost set bit is at position 1 /// assert_eq!(index_of_rightmost_set_bit(5).unwrap(), 1); /// /// // 16 in binary: 10000, rightmost set bit is at position 5 /// assert_eq!(index_of_rightmost_set_bit(16).unwrap(), 5); /// /// // 0 has no set bits /// assert!(index_of_rightmost_set_bit(0).is_err()); /// ``` pub fn index_of_rightmost_set_bit(num: i32) -> Result<u32, String> { if num <= 0 { return Err("input must be a positive integer".to_string()); } // Isolate the rightmost set bit using n & -n let rightmost_bit = num & -num; // Calculate position: log2(rightmost_bit) + 1 // We use trailing_zeros which gives us the 0-based position // and add 1 to make it 1-based let position = rightmost_bit.trailing_zeros() + 1; Ok(position) } /// Alternative implementation using a different algorithm approach. /// /// This version demonstrates the mathematical relationship between /// the rightmost set bit position and log2. /// /// # Examples /// /// ``` /// # use the_algorithms_rust::bit_manipulation::index_of_rightmost_set_bit_log; /// assert_eq!(index_of_rightmost_set_bit_log(18).unwrap(), 2); /// assert_eq!(index_of_rightmost_set_bit_log(12).unwrap(), 3); /// ``` pub fn index_of_rightmost_set_bit_log(num: i32) -> Result<u32, String> { if num <= 0 { return Err("input must be a positive integer".to_string()); } // Isolate the rightmost set bit let rightmost_bit = num & -num; // Use f64 log2 and convert to position let position = (rightmost_bit as f64).log2() as u32 + 1; Ok(position) } #[cfg(test)] mod tests { use super::*; #[test] fn test_basic_cases() { // 18 = 10010 in binary, rightmost set bit at position 2 assert_eq!(index_of_rightmost_set_bit(18).unwrap(), 2); // 12 = 1100 in binary, rightmost set bit at position 3 assert_eq!(index_of_rightmost_set_bit(12).unwrap(), 3); // 5 = 101 in binary, rightmost set bit at position 1 assert_eq!(index_of_rightmost_set_bit(5).unwrap(), 1); } #[test] fn test_powers_of_two() { // 1 = 1 in binary, position 1 assert_eq!(index_of_rightmost_set_bit(1).unwrap(), 1); // 2 = 10 in binary, position 2 assert_eq!(index_of_rightmost_set_bit(2).unwrap(), 2); // 4 = 100 in binary, position 3 assert_eq!(index_of_rightmost_set_bit(4).unwrap(), 3); // 8 = 1000 in binary, position 4 assert_eq!(index_of_rightmost_set_bit(8).unwrap(), 4); // 16 = 10000 in binary, position 5 assert_eq!(index_of_rightmost_set_bit(16).unwrap(), 5); // 32 = 100000 in binary, position 6 assert_eq!(index_of_rightmost_set_bit(32).unwrap(), 6); } #[test] fn test_odd_numbers() { // All odd numbers have rightmost set bit at position 1 assert_eq!(index_of_rightmost_set_bit(1).unwrap(), 1); assert_eq!(index_of_rightmost_set_bit(3).unwrap(), 1); assert_eq!(index_of_rightmost_set_bit(7).unwrap(), 1); assert_eq!(index_of_rightmost_set_bit(15).unwrap(), 1); assert_eq!(index_of_rightmost_set_bit(31).unwrap(), 1); } #[test] fn test_even_numbers() { // 6 = 110 in binary, rightmost set bit at position 2 assert_eq!(index_of_rightmost_set_bit(6).unwrap(), 2); // 10 = 1010 in binary, rightmost set bit at position 2 assert_eq!(index_of_rightmost_set_bit(10).unwrap(), 2); // 20 = 10100 in binary, rightmost set bit at position 3 assert_eq!(index_of_rightmost_set_bit(20).unwrap(), 3); } #[test] fn test_zero() { assert!(index_of_rightmost_set_bit(0).is_err()); assert_eq!( index_of_rightmost_set_bit(0).unwrap_err(), "input must be a positive integer" ); } #[test] fn test_negative_numbers() { assert!(index_of_rightmost_set_bit(-1).is_err()); assert!(index_of_rightmost_set_bit(-10).is_err()); assert_eq!( index_of_rightmost_set_bit(-5).unwrap_err(), "input must be a positive integer" ); } #[test] fn test_large_numbers() { // 1024 = 10000000000 in binary, position 11 assert_eq!(index_of_rightmost_set_bit(1024).unwrap(), 11); // 1023 = 1111111111 in binary, position 1 assert_eq!(index_of_rightmost_set_bit(1023).unwrap(), 1); // 2048 = 100000000000 in binary, position 12 assert_eq!(index_of_rightmost_set_bit(2048).unwrap(), 12); } #[test] fn test_consecutive_numbers() { // Testing a range to ensure correctness assert_eq!(index_of_rightmost_set_bit(14).unwrap(), 2); // 1110 assert_eq!(index_of_rightmost_set_bit(15).unwrap(), 1); // 1111 assert_eq!(index_of_rightmost_set_bit(16).unwrap(), 5); // 10000 assert_eq!(index_of_rightmost_set_bit(17).unwrap(), 1); // 10001 } #[test] fn test_log_version() { // Test the alternative log-based implementation assert_eq!(index_of_rightmost_set_bit_log(18).unwrap(), 2); assert_eq!(index_of_rightmost_set_bit_log(12).unwrap(), 3); assert_eq!(index_of_rightmost_set_bit_log(5).unwrap(), 1); assert_eq!(index_of_rightmost_set_bit_log(16).unwrap(), 5); } #[test] fn test_both_implementations_match() { // Verify both implementations give the same results for i in 1..=100 { assert_eq!( index_of_rightmost_set_bit(i).unwrap(), index_of_rightmost_set_bit_log(i).unwrap() ); } } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/counting_bits.rs
src/bit_manipulation/counting_bits.rs
//! This module implements a function to count the number of set bits (1s) //! in the binary representation of an unsigned integer. //! It uses Brian Kernighan's algorithm, which efficiently clears the least significant //! set bit in each iteration until all bits are cleared. //! The algorithm runs in O(k), where k is the number of set bits. /// Counts the number of set bits in an unsigned integer. /// /// # Arguments /// /// * `n` - An unsigned 32-bit integer whose set bits will be counted. /// /// # Returns /// /// * `usize` - The number of set bits (1s) in the binary representation of the input number. pub fn count_set_bits(mut n: usize) -> usize { // Initialize a variable to keep track of the count of set bits let mut count = 0; while n > 0 { // Clear the least significant set bit by // performing a bitwise AND operation with (n - 1) n &= n - 1; // Increment the count for each set bit found count += 1; } count } #[cfg(test)] mod tests { use super::*; macro_rules! test_count_set_bits { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (input, expected) = $test_case; assert_eq!(count_set_bits(input), expected); } )* }; } test_count_set_bits! { test_count_set_bits_zero: (0, 0), test_count_set_bits_one: (1, 1), test_count_set_bits_power_of_two: (16, 1), test_count_set_bits_all_set_bits: (usize::MAX, std::mem::size_of::<usize>() * 8), test_count_set_bits_alternating_bits: (0b10101010, 4), test_count_set_bits_mixed_bits: (0b11011011, 6), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/find_missing_number.rs
src/bit_manipulation/find_missing_number.rs
/// Finds the missing number in a slice of consecutive integers. /// /// This function uses XOR bitwise operation to find the missing number. /// It XORs all expected numbers in the range [min, max] with the actual /// numbers present in the array. Since XOR has the property that `a ^ a = 0`, /// all present numbers cancel out, leaving only the missing number. /// /// # Arguments /// /// * `nums` - A slice of integers forming a sequence with one missing number /// /// # Returns /// /// * `Ok(i32)` - The missing number in the sequence /// * `Err(String)` - An error message if the input is invalid /// /// # Examples /// /// ``` /// # use the_algorithms_rust::bit_manipulation::find_missing_number; /// assert_eq!(find_missing_number(&[0, 1, 3, 4]).unwrap(), 2); /// assert_eq!(find_missing_number(&[4, 3, 1, 0]).unwrap(), 2); /// assert_eq!(find_missing_number(&[-4, -3, -1, 0]).unwrap(), -2); /// assert_eq!(find_missing_number(&[-2, 2, 1, 3, 0]).unwrap(), -1); /// assert_eq!(find_missing_number(&[1, 3, 4, 5, 6]).unwrap(), 2); /// ``` pub fn find_missing_number(nums: &[i32]) -> Result<i32, String> { if nums.is_empty() { return Err("input array must not be empty".to_string()); } if nums.len() == 1 { return Err("array must have at least 2 elements to find a missing number".to_string()); } let low = *nums.iter().min().unwrap(); let high = *nums.iter().max().unwrap(); let mut missing_number = high; for i in low..high { let index = (i - low) as usize; missing_number ^= i ^ nums[index]; } Ok(missing_number) } #[cfg(test)] mod tests { use super::*; #[test] fn test_missing_in_middle() { assert_eq!(find_missing_number(&[0, 1, 3, 4]).unwrap(), 2); } #[test] fn test_unordered_array() { assert_eq!(find_missing_number(&[4, 3, 1, 0]).unwrap(), 2); } #[test] fn test_negative_numbers() { assert_eq!(find_missing_number(&[-4, -3, -1, 0]).unwrap(), -2); } #[test] fn test_negative_and_positive() { assert_eq!(find_missing_number(&[-2, 2, 1, 3, 0]).unwrap(), -1); } #[test] fn test_missing_at_start() { assert_eq!(find_missing_number(&[1, 3, 4, 5, 6]).unwrap(), 2); } #[test] fn test_unordered_missing_middle() { assert_eq!(find_missing_number(&[6, 5, 4, 2, 1]).unwrap(), 3); } #[test] fn test_another_unordered() { assert_eq!(find_missing_number(&[6, 1, 5, 3, 4]).unwrap(), 2); } #[test] fn test_empty_array() { assert!(find_missing_number(&[]).is_err()); assert_eq!( find_missing_number(&[]).unwrap_err(), "input array must not be empty" ); } #[test] fn test_single_element() { assert!(find_missing_number(&[5]).is_err()); assert_eq!( find_missing_number(&[5]).unwrap_err(), "array must have at least 2 elements to find a missing number" ); } #[test] fn test_two_elements() { assert_eq!(find_missing_number(&[0, 2]).unwrap(), 1); assert_eq!(find_missing_number(&[2, 0]).unwrap(), 1); } #[test] fn test_large_range() { assert_eq!(find_missing_number(&[100, 101, 103, 104]).unwrap(), 102); } #[test] fn test_missing_at_boundaries() { // Missing is the second to last element assert_eq!(find_missing_number(&[1, 2, 3, 5]).unwrap(), 4); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/twos_complement.rs
src/bit_manipulation/twos_complement.rs
//! Two's Complement Representation //! //! Two's complement is a mathematical operation on binary numbers and a binary signed //! number representation. It is widely used in computing as the most common method of //! representing signed integers on computers. //! //! For more information: <https://en.wikipedia.org/wiki/Two%27s_complement> /// Takes a negative integer and returns its two's complement binary representation. /// /// The two's complement of a negative number is calculated by finding the binary /// representation that, when added to the positive value with the same magnitude, /// equals 2^n (where n is the number of bits). /// /// # Arguments /// /// * `number` - A non-positive integer (0 or negative) /// /// # Returns /// /// A `Result` containing: /// - `Ok(String)` - The two's complement representation with "0b" prefix /// - `Err(String)` - An error message if the input is positive /// /// # Examples /// /// ``` /// use the_algorithms_rust::bit_manipulation::twos_complement; /// /// assert_eq!(twos_complement(0).unwrap(), "0b0"); /// assert_eq!(twos_complement(-1).unwrap(), "0b11"); /// assert_eq!(twos_complement(-5).unwrap(), "0b1011"); /// assert_eq!(twos_complement(-17).unwrap(), "0b101111"); /// assert_eq!(twos_complement(-207).unwrap(), "0b100110001"); /// /// // Positive numbers return an error /// assert!(twos_complement(1).is_err()); /// ``` /// /// # Errors /// /// Returns an error if the input number is positive. pub fn twos_complement(number: i32) -> Result<String, String> { if number > 0 { return Err("input must be a negative integer".to_string()); } if number == 0 { return Ok("0b0".to_string()); } // Calculate the number of bits needed for the binary representation // (excluding the sign bit in the original representation) let binary_number_length = format!("{:b}", number.abs()).len(); // Calculate two's complement value // This is equivalent to: abs(number) - 2^binary_number_length let twos_complement_value = (number.abs() as i64) - (1_i64 << binary_number_length); // Format as binary string (removing the negative sign) let mut twos_complement_str = format!("{:b}", twos_complement_value.abs()); // Add leading zeros if necessary let padding_zeros = binary_number_length.saturating_sub(twos_complement_str.len()); if padding_zeros > 0 { twos_complement_str = format!("{}{twos_complement_str}", "0".repeat(padding_zeros)); } // Add leading '1' to indicate negative number in two's complement Ok(format!("0b1{twos_complement_str}")) } #[cfg(test)] mod tests { use super::*; #[test] fn test_zero() { assert_eq!(twos_complement(0).unwrap(), "0b0"); } #[test] fn test_negative_one() { assert_eq!(twos_complement(-1).unwrap(), "0b11"); } #[test] fn test_negative_five() { assert_eq!(twos_complement(-5).unwrap(), "0b1011"); } #[test] fn test_negative_seventeen() { assert_eq!(twos_complement(-17).unwrap(), "0b101111"); } #[test] fn test_negative_two_hundred_seven() { assert_eq!(twos_complement(-207).unwrap(), "0b100110001"); } #[test] fn test_negative_small_values() { assert_eq!(twos_complement(-2).unwrap(), "0b110"); assert_eq!(twos_complement(-3).unwrap(), "0b101"); assert_eq!(twos_complement(-4).unwrap(), "0b1100"); } #[test] fn test_negative_larger_values() { assert_eq!(twos_complement(-128).unwrap(), "0b110000000"); assert_eq!(twos_complement(-255).unwrap(), "0b100000001"); assert_eq!(twos_complement(-1000).unwrap(), "0b10000011000"); } #[test] fn test_positive_number_returns_error() { let result = twos_complement(1); assert!(result.is_err()); assert_eq!(result.unwrap_err(), "input must be a negative integer"); } #[test] fn test_large_positive_number_returns_error() { let result = twos_complement(100); assert!(result.is_err()); assert_eq!(result.unwrap_err(), "input must be a negative integer"); } #[test] fn test_edge_case_negative_powers_of_two() { assert_eq!(twos_complement(-8).unwrap(), "0b11000"); assert_eq!(twos_complement(-16).unwrap(), "0b110000"); assert_eq!(twos_complement(-32).unwrap(), "0b1100000"); assert_eq!(twos_complement(-64).unwrap(), "0b11000000"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/reverse_bits.rs
src/bit_manipulation/reverse_bits.rs
//! This module provides a function to reverse the bits of a 32-bit unsigned integer. //! //! The algorithm works by iterating through each of the 32 bits from least //! significant to most significant, extracting each bit and placing it in the //! reverse position. //! //! # Algorithm //! //! For each of the 32 bits: //! 1. Shift the result left by 1 to make room for the next bit //! 2. Extract the least significant bit of the input using bitwise AND with 1 //! 3. OR that bit into the result //! 4. Shift the input right by 1 to process the next bit //! //! # Time Complexity //! //! O(1) - Always processes exactly 32 bits //! //! # Space Complexity //! //! O(1) - Uses a constant amount of extra space //! //! # Example //! //! ``` //! use the_algorithms_rust::bit_manipulation::reverse_bits; //! //! let n = 43261596; // Binary: 00000010100101000001111010011100 //! let reversed = reverse_bits(n); //! assert_eq!(reversed, 964176192); // Binary: 00111001011110000010100101000000 //! ``` /// Reverses the bits of a 32-bit unsigned integer. /// /// # Arguments /// /// * `n` - A 32-bit unsigned integer whose bits are to be reversed /// /// # Returns /// /// A 32-bit unsigned integer with bits in reverse order /// /// # Examples /// /// ``` /// use the_algorithms_rust::bit_manipulation::reverse_bits; /// /// let n = 43261596; // 00000010100101000001111010011100 in binary /// let result = reverse_bits(n); /// assert_eq!(result, 964176192); // 00111001011110000010100101000000 in binary /// ``` /// /// ``` /// use the_algorithms_rust::bit_manipulation::reverse_bits; /// /// let n = 1; // 00000000000000000000000000000001 in binary /// let result = reverse_bits(n); /// assert_eq!(result, 2147483648); // 10000000000000000000000000000000 in binary /// ``` pub fn reverse_bits(n: u32) -> u32 { let mut result: u32 = 0; let mut num = n; // Process all 32 bits for _ in 0..32 { // Shift result left to make room for next bit result <<= 1; // Extract the least significant bit of num and add it to result result |= num & 1; // Shift num right to process the next bit num >>= 1; } result } #[cfg(test)] mod tests { use super::*; #[test] fn test_reverse_bits_basic() { // Test case 1: 43261596 (00000010100101000001111010011100) // Expected: 964176192 (00111001011110000010100101000000) assert_eq!(reverse_bits(43261596), 964176192); } #[test] fn test_reverse_bits_one() { // Test case 2: 1 (00000000000000000000000000000001) // Expected: 2147483648 (10000000000000000000000000000000) assert_eq!(reverse_bits(1), 2147483648); } #[test] fn test_reverse_bits_all_ones() { // Test case 3: 4294967293 (11111111111111111111111111111101) // Expected: 3221225471 (10111111111111111111111111111111) assert_eq!(reverse_bits(4294967293), 3221225471); } #[test] fn test_reverse_bits_zero() { // Test case 4: 0 (00000000000000000000000000000000) // Expected: 0 (00000000000000000000000000000000) assert_eq!(reverse_bits(0), 0); } #[test] fn test_reverse_bits_max() { // Test case 5: u32::MAX (11111111111111111111111111111111) // Expected: u32::MAX (11111111111111111111111111111111) assert_eq!(reverse_bits(u32::MAX), u32::MAX); } #[test] fn test_reverse_bits_alternating() { // Test case 6: 2863311530 (10101010101010101010101010101010) // Expected: 1431655765 (01010101010101010101010101010101) assert_eq!(reverse_bits(2863311530), 1431655765); } #[test] fn test_reverse_bits_symmetric() { // Test case 7: reversing twice should give original number let n = 12345678; assert_eq!(reverse_bits(reverse_bits(n)), n); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/swap_odd_even_bits.rs
src/bit_manipulation/swap_odd_even_bits.rs
/// Swaps odd and even bits in an integer. /// /// This function separates the even bits (0, 2, 4, 6, etc.) and odd bits (1, 3, 5, 7, etc.) /// using bitwise AND operations, then swaps them by shifting and combining with OR. /// /// # Arguments /// /// * `num` - A 32-bit unsigned integer /// /// # Returns /// /// A new integer with odd and even bits swapped /// /// # Examples /// /// ``` /// use the_algorithms_rust::bit_manipulation::swap_odd_even_bits; /// /// assert_eq!(swap_odd_even_bits(0), 0); /// assert_eq!(swap_odd_even_bits(1), 2); /// assert_eq!(swap_odd_even_bits(2), 1); /// assert_eq!(swap_odd_even_bits(3), 3); /// assert_eq!(swap_odd_even_bits(4), 8); /// assert_eq!(swap_odd_even_bits(5), 10); /// assert_eq!(swap_odd_even_bits(6), 9); /// assert_eq!(swap_odd_even_bits(23), 43); /// ``` pub fn swap_odd_even_bits(num: u32) -> u32 { // Get all even bits - 0xAAAAAAAA is a 32-bit number with all even bits set to 1 let even_bits = num & 0xAAAAAAAA; // Get all odd bits - 0x55555555 is a 32-bit number with all odd bits set to 1 let odd_bits = num & 0x55555555; // Right shift even bits and left shift odd bits and swap them (even_bits >> 1) | (odd_bits << 1) } #[cfg(test)] mod tests { use super::*; #[test] fn test_swap_odd_even_bits() { assert_eq!(swap_odd_even_bits(0), 0); assert_eq!(swap_odd_even_bits(1), 2); assert_eq!(swap_odd_even_bits(2), 1); assert_eq!(swap_odd_even_bits(3), 3); assert_eq!(swap_odd_even_bits(4), 8); assert_eq!(swap_odd_even_bits(5), 10); assert_eq!(swap_odd_even_bits(6), 9); assert_eq!(swap_odd_even_bits(23), 43); assert_eq!(swap_odd_even_bits(24), 36); } #[test] fn test_edge_cases() { // All bits set assert_eq!(swap_odd_even_bits(0xFFFFFFFF), 0xFFFFFFFF); // Alternating patterns assert_eq!(swap_odd_even_bits(0xAAAAAAAA), 0x55555555); assert_eq!(swap_odd_even_bits(0x55555555), 0xAAAAAAAA); } #[test] fn test_power_of_two() { assert_eq!(swap_odd_even_bits(16), 32); assert_eq!(swap_odd_even_bits(32), 16); assert_eq!(swap_odd_even_bits(64), 128); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/binary_count_trailing_zeros.rs
src/bit_manipulation/binary_count_trailing_zeros.rs
/// Counts the number of trailing zeros in the binary representation of a number /// /// # Arguments /// /// * `num` - The input number /// /// # Returns /// /// The number of trailing zeros in the binary representation /// /// # Examples /// /// ``` /// use the_algorithms_rust::bit_manipulation::binary_count_trailing_zeros; /// /// assert_eq!(binary_count_trailing_zeros(25), 0); /// assert_eq!(binary_count_trailing_zeros(36), 2); /// assert_eq!(binary_count_trailing_zeros(16), 4); /// assert_eq!(binary_count_trailing_zeros(58), 1); /// ``` pub fn binary_count_trailing_zeros(num: u64) -> u32 { if num == 0 { return 0; } num.trailing_zeros() } /// Alternative implementation using bit manipulation /// /// Uses the bit manipulation trick: log2(num & -num) /// /// # Examples /// /// ``` /// // This function uses bit manipulation: log2(num & -num) /// // where num & -num isolates the rightmost set bit /// # fn binary_count_trailing_zeros_bitwise(num: u64) -> u32 { /// # if num == 0 { return 0; } /// # let rightmost_set_bit = num & (num.wrapping_neg()); /// # 63 - rightmost_set_bit.leading_zeros() /// # } /// assert_eq!(binary_count_trailing_zeros_bitwise(25), 0); /// assert_eq!(binary_count_trailing_zeros_bitwise(36), 2); /// assert_eq!(binary_count_trailing_zeros_bitwise(16), 4); /// ``` #[allow(dead_code)] pub fn binary_count_trailing_zeros_bitwise(num: u64) -> u32 { if num == 0 { return 0; } let rightmost_set_bit = num & (num.wrapping_neg()); 63 - rightmost_set_bit.leading_zeros() } #[cfg(test)] mod tests { use super::*; #[test] fn test_basic_cases() { assert_eq!(binary_count_trailing_zeros(25), 0); assert_eq!(binary_count_trailing_zeros(36), 2); assert_eq!(binary_count_trailing_zeros(16), 4); assert_eq!(binary_count_trailing_zeros(58), 1); assert_eq!(binary_count_trailing_zeros(4294967296), 32); } #[test] fn test_zero() { assert_eq!(binary_count_trailing_zeros(0), 0); } #[test] fn test_powers_of_two() { assert_eq!(binary_count_trailing_zeros(1), 0); assert_eq!(binary_count_trailing_zeros(2), 1); assert_eq!(binary_count_trailing_zeros(4), 2); assert_eq!(binary_count_trailing_zeros(8), 3); assert_eq!(binary_count_trailing_zeros(1024), 10); } #[test] fn test_bitwise_vs_builtin() { // Test that bitwise implementation matches built-in trailing_zeros() let test_cases = vec![ 0, 1, 2, 3, 4, 5, 6, 7, 8, 16, 25, 36, 58, 64, 100, 128, 256, 512, 1024, 4294967296, u64::MAX - 1, u64::MAX, ]; for num in test_cases { assert_eq!( binary_count_trailing_zeros(num), binary_count_trailing_zeros_bitwise(num), "Mismatch for input: {num}" ); } } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/binary_coded_decimal.rs
src/bit_manipulation/binary_coded_decimal.rs
//! Binary Coded Decimal (BCD) conversion //! //! This module provides a function to convert decimal integers to Binary Coded Decimal (BCD) format. //! In BCD, each decimal digit is represented by its 4-bit binary equivalent. //! //! # Examples //! //! ``` //! use the_algorithms_rust::bit_manipulation::binary_coded_decimal; //! //! assert_eq!(binary_coded_decimal(12), "0b00010010"); //! assert_eq!(binary_coded_decimal(987), "0b100110000111"); //! ``` use std::fmt::Write; /// Converts a decimal integer to Binary Coded Decimal (BCD) format. /// /// Each digit of the input number is represented by a 4-bit binary value. /// Negative numbers are treated as 0. /// /// # Arguments /// /// * `number` - An integer to be converted to BCD format /// /// # Returns /// /// A `String` representing the BCD encoding with "0b" prefix /// /// # Examples /// /// ``` /// use the_algorithms_rust::bit_manipulation::binary_coded_decimal; /// /// assert_eq!(binary_coded_decimal(0), "0b0000"); /// assert_eq!(binary_coded_decimal(3), "0b0011"); /// assert_eq!(binary_coded_decimal(12), "0b00010010"); /// assert_eq!(binary_coded_decimal(987), "0b100110000111"); /// assert_eq!(binary_coded_decimal(-5), "0b0000"); /// ``` /// /// # Algorithm /// /// 1. Convert the number to its absolute value (negative numbers become 0) /// 2. For each decimal digit: /// - Convert the digit to binary /// - Pad to 4 bits with leading zeros /// - Concatenate to the result /// 3. Prepend "0b" to the final binary string pub fn binary_coded_decimal(number: i32) -> String { // Handle negative numbers by converting to 0 let num = if number < 0 { 0 } else { number }; // Convert to string to process each digit let digits = num.to_string(); // Build the BCD string using fold for efficiency let bcd = digits.chars().fold(String::new(), |mut acc, digit| { // Convert char to digit value and format as 4-bit binary let digit_value = digit.to_digit(10).unwrap(); write!(acc, "{digit_value:04b}").unwrap(); acc }); format!("0b{bcd}") } #[cfg(test)] mod tests { use super::*; #[test] fn test_zero() { assert_eq!(binary_coded_decimal(0), "0b0000"); } #[test] fn test_single_digit() { assert_eq!(binary_coded_decimal(1), "0b0001"); assert_eq!(binary_coded_decimal(2), "0b0010"); assert_eq!(binary_coded_decimal(3), "0b0011"); assert_eq!(binary_coded_decimal(4), "0b0100"); assert_eq!(binary_coded_decimal(5), "0b0101"); assert_eq!(binary_coded_decimal(6), "0b0110"); assert_eq!(binary_coded_decimal(7), "0b0111"); assert_eq!(binary_coded_decimal(8), "0b1000"); assert_eq!(binary_coded_decimal(9), "0b1001"); } #[test] fn test_two_digits() { assert_eq!(binary_coded_decimal(10), "0b00010000"); assert_eq!(binary_coded_decimal(12), "0b00010010"); assert_eq!(binary_coded_decimal(25), "0b00100101"); assert_eq!(binary_coded_decimal(99), "0b10011001"); } #[test] fn test_three_digits() { assert_eq!(binary_coded_decimal(100), "0b000100000000"); assert_eq!(binary_coded_decimal(123), "0b000100100011"); assert_eq!(binary_coded_decimal(456), "0b010001010110"); assert_eq!(binary_coded_decimal(987), "0b100110000111"); } #[test] fn test_large_numbers() { assert_eq!(binary_coded_decimal(1234), "0b0001001000110100"); assert_eq!(binary_coded_decimal(9999), "0b1001100110011001"); } #[test] fn test_negative_numbers() { // Negative numbers should be treated as 0 assert_eq!(binary_coded_decimal(-1), "0b0000"); assert_eq!(binary_coded_decimal(-2), "0b0000"); assert_eq!(binary_coded_decimal(-100), "0b0000"); } #[test] fn test_each_digit_encoding() { // Verify that each digit is encoded correctly in a multi-digit number // 67 should be: 6 (0110) and 7 (0111) assert_eq!(binary_coded_decimal(67), "0b01100111"); // 305 should be: 3 (0011), 0 (0000), 5 (0101) assert_eq!(binary_coded_decimal(305), "0b001100000101"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/mod.rs
src/bit_manipulation/mod.rs
mod binary_coded_decimal; mod binary_count_trailing_zeros; mod counting_bits; mod find_missing_number; mod find_previous_power_of_two; mod find_unique_number; mod hamming_distance; mod highest_set_bit; mod is_power_of_two; mod n_bits_gray_code; mod reverse_bits; mod rightmost_set_bit; mod sum_of_two_integers; mod swap_odd_even_bits; mod twos_complement; pub use self::binary_coded_decimal::binary_coded_decimal; pub use self::binary_count_trailing_zeros::binary_count_trailing_zeros; pub use self::counting_bits::count_set_bits; pub use self::find_missing_number::find_missing_number; pub use self::find_previous_power_of_two::find_previous_power_of_two; pub use self::find_unique_number::find_unique_number; pub use self::hamming_distance::{hamming_distance, hamming_distance_str}; pub use self::highest_set_bit::find_highest_set_bit; pub use self::is_power_of_two::is_power_of_two; pub use self::n_bits_gray_code::generate_gray_code; pub use self::reverse_bits::reverse_bits; pub use self::rightmost_set_bit::{index_of_rightmost_set_bit, index_of_rightmost_set_bit_log}; pub use self::sum_of_two_integers::add_two_integers; pub use self::swap_odd_even_bits::swap_odd_even_bits; pub use self::twos_complement::twos_complement;
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/sum_of_two_integers.rs
src/bit_manipulation/sum_of_two_integers.rs
//! This module provides a function to add two integers without using the `+` operator. //! It relies on bitwise operations (XOR and AND) to compute the sum, simulating the addition process. /// Adds two integers using bitwise operations. /// /// # Arguments /// /// * `a` - The first integer to be added. /// * `b` - The second integer to be added. /// /// # Returns /// /// * `isize` - The result of adding the two integers. pub fn add_two_integers(mut a: isize, mut b: isize) -> isize { let mut carry; while b != 0 { let sum = a ^ b; carry = (a & b) << 1; a = sum; b = carry; } a } #[cfg(test)] mod tests { use super::*; macro_rules! test_add_two_integers { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (a, b) = $test_case; assert_eq!(add_two_integers(a, b), a + b); assert_eq!(add_two_integers(b, a), a + b); } )* }; } test_add_two_integers! { test_add_two_integers_positive: (3, 5), test_add_two_integers_large_positive: (100, 200), test_add_two_integers_edge_positive: (65535, 1), test_add_two_integers_negative: (-10, 6), test_add_two_integers_both_negative: (-50, -30), test_add_two_integers_edge_negative: (-1, -1), test_add_two_integers_zero: (0, 0), test_add_two_integers_zero_with_positive: (0, 42), test_add_two_integers_zero_with_negative: (0, -42), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/is_power_of_two.rs
src/bit_manipulation/is_power_of_two.rs
//! Power of Two Check //! //! This module provides a function to determine if a given positive integer is a power of two //! using efficient bit manipulation. //! //! # Algorithm //! //! The algorithm uses the property that powers of two have exactly one bit set in their //! binary representation. When we subtract 1 from a power of two, all bits after the single //! set bit become 1, and the set bit becomes 0: //! //! ```text //! n = 0..100..00 (power of 2) //! n - 1 = 0..011..11 //! n & (n - 1) = 0 (no intersections) //! ``` //! //! For example: //! - 8 in binary: 1000 //! - 7 in binary: 0111 //! - 8 & 7 = 0000 = 0 ✓ //! //! Author: Alexander Pantyukhin //! Date: November 1, 2022 /// Determines if a given number is a power of two. /// /// This function uses bit manipulation to efficiently check if a number is a power of two. /// A number is a power of two if it has exactly one bit set in its binary representation. /// The check `number & (number - 1) == 0` leverages this property. /// /// # Arguments /// /// * `number` - An integer to check (must be non-negative) /// /// # Returns /// /// A `Result` containing: /// - `Ok(true)` - If the number is a power of two (including 0 and 1) /// - `Ok(false)` - If the number is not a power of two /// - `Err(String)` - If the number is negative /// /// # Examples /// /// ``` /// use the_algorithms_rust::bit_manipulation::is_power_of_two; /// /// assert_eq!(is_power_of_two(0).unwrap(), true); /// assert_eq!(is_power_of_two(1).unwrap(), true); /// assert_eq!(is_power_of_two(2).unwrap(), true); /// assert_eq!(is_power_of_two(4).unwrap(), true); /// assert_eq!(is_power_of_two(8).unwrap(), true); /// assert_eq!(is_power_of_two(16).unwrap(), true); /// /// assert_eq!(is_power_of_two(3).unwrap(), false); /// assert_eq!(is_power_of_two(6).unwrap(), false); /// assert_eq!(is_power_of_two(17).unwrap(), false); /// /// // Negative numbers return an error /// assert!(is_power_of_two(-1).is_err()); /// ``` /// /// # Errors /// /// Returns an error if the input number is negative. /// /// # Time Complexity /// /// O(1) - The function performs a constant number of operations regardless of input size. pub fn is_power_of_two(number: i32) -> Result<bool, String> { if number < 0 { return Err("number must not be negative".to_string()); } // Convert to u32 for safe bit operations let num = number as u32; // Check if number & (number - 1) == 0 // For powers of 2, this will always be true Ok(num & num.wrapping_sub(1) == 0) } #[cfg(test)] mod tests { use super::*; #[test] fn test_zero() { // 0 is considered a power of 2 by the algorithm (2^(-∞) interpretation) assert!(is_power_of_two(0).unwrap()); } #[test] fn test_one() { // 1 = 2^0 assert!(is_power_of_two(1).unwrap()); } #[test] fn test_powers_of_two() { assert!(is_power_of_two(2).unwrap()); // 2^1 assert!(is_power_of_two(4).unwrap()); // 2^2 assert!(is_power_of_two(8).unwrap()); // 2^3 assert!(is_power_of_two(16).unwrap()); // 2^4 assert!(is_power_of_two(32).unwrap()); // 2^5 assert!(is_power_of_two(64).unwrap()); // 2^6 assert!(is_power_of_two(128).unwrap()); // 2^7 assert!(is_power_of_two(256).unwrap()); // 2^8 assert!(is_power_of_two(512).unwrap()); // 2^9 assert!(is_power_of_two(1024).unwrap()); // 2^10 assert!(is_power_of_two(2048).unwrap()); // 2^11 assert!(is_power_of_two(4096).unwrap()); // 2^12 assert!(is_power_of_two(8192).unwrap()); // 2^13 assert!(is_power_of_two(16384).unwrap()); // 2^14 assert!(is_power_of_two(32768).unwrap()); // 2^15 assert!(is_power_of_two(65536).unwrap()); // 2^16 } #[test] fn test_non_powers_of_two() { assert!(!is_power_of_two(3).unwrap()); assert!(!is_power_of_two(5).unwrap()); assert!(!is_power_of_two(6).unwrap()); assert!(!is_power_of_two(7).unwrap()); assert!(!is_power_of_two(9).unwrap()); assert!(!is_power_of_two(10).unwrap()); assert!(!is_power_of_two(11).unwrap()); assert!(!is_power_of_two(12).unwrap()); assert!(!is_power_of_two(13).unwrap()); assert!(!is_power_of_two(14).unwrap()); assert!(!is_power_of_two(15).unwrap()); assert!(!is_power_of_two(17).unwrap()); assert!(!is_power_of_two(18).unwrap()); } #[test] fn test_specific_non_powers() { assert!(!is_power_of_two(6).unwrap()); assert!(!is_power_of_two(17).unwrap()); assert!(!is_power_of_two(100).unwrap()); assert!(!is_power_of_two(1000).unwrap()); } #[test] fn test_large_powers_of_two() { assert!(is_power_of_two(131072).unwrap()); // 2^17 assert!(is_power_of_two(262144).unwrap()); // 2^18 assert!(is_power_of_two(524288).unwrap()); // 2^19 assert!(is_power_of_two(1048576).unwrap()); // 2^20 } #[test] fn test_numbers_near_powers_of_two() { // One less than powers of 2 assert!(!is_power_of_two(3).unwrap()); // 2^2 - 1 assert!(!is_power_of_two(7).unwrap()); // 2^3 - 1 assert!(!is_power_of_two(15).unwrap()); // 2^4 - 1 assert!(!is_power_of_two(31).unwrap()); // 2^5 - 1 assert!(!is_power_of_two(63).unwrap()); // 2^6 - 1 assert!(!is_power_of_two(127).unwrap()); // 2^7 - 1 assert!(!is_power_of_two(255).unwrap()); // 2^8 - 1 // One more than powers of 2 assert!(!is_power_of_two(3).unwrap()); // 2^1 + 1 assert!(!is_power_of_two(5).unwrap()); // 2^2 + 1 assert!(!is_power_of_two(9).unwrap()); // 2^3 + 1 assert!(!is_power_of_two(17).unwrap()); // 2^4 + 1 assert!(!is_power_of_two(33).unwrap()); // 2^5 + 1 assert!(!is_power_of_two(65).unwrap()); // 2^6 + 1 assert!(!is_power_of_two(129).unwrap()); // 2^7 + 1 } #[test] fn test_negative_number_returns_error() { let result = is_power_of_two(-1); assert!(result.is_err()); assert_eq!(result.unwrap_err(), "number must not be negative"); } #[test] fn test_multiple_negative_numbers() { assert!(is_power_of_two(-1).is_err()); assert!(is_power_of_two(-2).is_err()); assert!(is_power_of_two(-4).is_err()); assert!(is_power_of_two(-8).is_err()); assert!(is_power_of_two(-100).is_err()); } #[test] fn test_all_powers_of_two_up_to_30() { // Test 2^0 through 2^30 for i in 0..=30 { let power = 1u32 << i; // 2^i assert!( is_power_of_two(power as i32).unwrap(), "2^{i} = {power} should be a power of 2" ); } } #[test] fn test_range_verification() { // Test that between consecutive powers of 2, only the powers return true for i in 1..10 { let power = 1 << i; // 2^i assert!(is_power_of_two(power).unwrap()); // Check numbers between this power and the next let next_power = 1 << (i + 1); for num in (power + 1)..next_power { assert!( !is_power_of_two(num).unwrap(), "{num} should not be a power of 2" ); } } } #[test] fn test_bit_manipulation_correctness() { // Verify the bit manipulation logic for specific examples // For 8: 1000 & 0111 = 0000 ✓ assert_eq!(8 & 7, 0); assert!(is_power_of_two(8).unwrap()); // For 16: 10000 & 01111 = 00000 ✓ assert_eq!(16 & 15, 0); assert!(is_power_of_two(16).unwrap()); // For 6: 110 & 101 = 100 ✗ assert_ne!(6 & 5, 0); assert!(!is_power_of_two(6).unwrap()); } #[test] fn test_edge_case_max_i32_power_of_two() { // Largest power of 2 that fits in i32: 2^30 = 1073741824 assert!(is_power_of_two(1073741824).unwrap()); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/hamming_distance.rs
src/bit_manipulation/hamming_distance.rs
//! Hamming Distance //! //! This module implements the [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) //! algorithm for both integers and strings. //! //! The Hamming distance between two values is the number of positions at which //! the corresponding symbols differ. /// Counts the number of set bits (1s) in a 64-bit unsigned integer. /// /// # Arguments /// /// * `value` - The number to count set bits in /// /// # Returns /// /// The number of set bits in the value /// /// # Example /// /// ``` /// // This is a private helper function /// let value: u64 = 11; // 1011 in binary has 3 set bits /// ``` fn bit_count(mut value: u64) -> u64 { let mut count = 0; while value != 0 { if value & 1 == 1 { count += 1; } value >>= 1; } count } /// Calculates the Hamming distance between two unsigned 64-bit integers. /// /// The Hamming distance is the number of bit positions at which the /// corresponding bits differ. This is computed by taking the XOR of the /// two numbers and counting the set bits. /// /// # Arguments /// /// * `a` - The first integer /// * `b` - The second integer /// /// # Returns /// /// The number of differing bits between `a` and `b` /// /// # Example /// /// ``` /// use the_algorithms_rust::bit_manipulation::hamming_distance; /// /// let distance = hamming_distance(11, 2); /// assert_eq!(distance, 2); /// ``` pub fn hamming_distance(a: u64, b: u64) -> u64 { bit_count(a ^ b) } /// Calculates the Hamming distance between two strings of equal length. /// /// The Hamming distance is the number of positions at which the /// corresponding characters differ. /// /// # Arguments /// /// * `a` - The first string /// * `b` - The second string /// /// # Returns /// /// The number of differing characters between `a` and `b` /// /// # Panics /// /// Panics if the strings have different lengths /// /// # Example /// /// ``` /// use the_algorithms_rust::bit_manipulation::hamming_distance_str; /// /// let distance = hamming_distance_str("1101", "1111"); /// assert_eq!(distance, 1); /// ``` pub fn hamming_distance_str(a: &str, b: &str) -> u64 { assert_eq!( a.len(), b.len(), "Strings must have the same length for Hamming distance calculation" ); a.chars() .zip(b.chars()) .filter(|(ch_a, ch_b)| ch_a != ch_b) .count() as u64 } #[cfg(test)] mod tests { use super::*; #[test] fn test_bit_count() { assert_eq!(bit_count(0), 0); assert_eq!(bit_count(11), 3); // 1011 in binary assert_eq!(bit_count(15), 4); // 1111 in binary } #[test] fn test_hamming_distance_integers() { assert_eq!(hamming_distance(11, 2), 2); assert_eq!(hamming_distance(2, 0), 1); assert_eq!(hamming_distance(11, 0), 3); assert_eq!(hamming_distance(0, 0), 0); } #[test] fn test_hamming_distance_strings() { assert_eq!(hamming_distance_str("1101", "1111"), 1); assert_eq!(hamming_distance_str("1111", "1111"), 0); assert_eq!(hamming_distance_str("0000", "1111"), 4); assert_eq!(hamming_distance_str("alpha", "alphb"), 1); assert_eq!(hamming_distance_str("abcd", "abcd"), 0); assert_eq!(hamming_distance_str("dcba", "abcd"), 4); } #[test] #[should_panic(expected = "Strings must have the same length")] fn test_hamming_distance_strings_different_lengths() { hamming_distance_str("abc", "abcd"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/compression/move_to_front.rs
src/compression/move_to_front.rs
// https://en.wikipedia.org/wiki/Move-to-front_transform fn blank_char_table() -> Vec<char> { (0..=255).map(|ch| ch as u8 as char).collect() } pub fn move_to_front_encode(text: &str) -> Vec<u8> { let mut char_table = blank_char_table(); let mut result = Vec::new(); for ch in text.chars() { if let Some(position) = char_table.iter().position(|&x| x == ch) { result.push(position as u8); char_table.remove(position); char_table.insert(0, ch); } } result } pub fn move_to_front_decode(encoded: &[u8]) -> String { let mut char_table = blank_char_table(); let mut result = String::new(); for &pos in encoded { let ch = char_table[pos as usize]; result.push(ch); char_table.remove(pos as usize); char_table.insert(0, ch); } result } #[cfg(test)] mod test { use super::*; macro_rules! test_mtf { ($($name:ident: ($text:expr, $encoded:expr),)*) => { $( #[test] fn $name() { assert_eq!(move_to_front_encode($text), $encoded); assert_eq!(move_to_front_decode($encoded), $text); } )* } } test_mtf! { empty: ("", &[]), single_char: ("@", &[64]), repeated_chars: ("aaba", &[97, 0, 98, 1]), mixed_chars: ("aZ!", &[97, 91, 35]), word: ("banana", &[98, 98, 110, 1, 1, 1]), special_chars: ("\0\n\t", &[0, 10, 10]), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/compression/huffman_encoding.rs
src/compression/huffman_encoding.rs
//! Huffman Encoding implementation //! //! Huffman coding is a lossless data compression algorithm that assigns variable-length codes //! to characters based on their frequency of occurrence. Characters that occur more frequently //! are assigned shorter codes, while less frequent characters get longer codes. //! //! # Algorithm Overview //! //! 1. Count the frequency of each character in the input //! 2. Build a min-heap (priority queue) of nodes based on frequency //! 3. Build the Huffman tree by repeatedly: //! - Remove two nodes with minimum frequency //! - Create a parent node with combined frequency //! - Insert the parent back into the heap //! 4. Traverse the tree to assign binary codes to each character //! 5. Encode the input using the generated codes //! //! # Time Complexity //! //! - Building frequency map: O(n) where n is input length //! - Building Huffman tree: O(m log m) where m is number of unique characters //! - Encoding: O(n) //! //! # Usage //! //! As a library: //! ```no_run //! use the_algorithms_rust::compression::huffman_encode; //! //! let text = "hello world"; //! let (encoded, codes) = huffman_encode(text); //! println!("Original: {}", text); //! println!("Encoded: {}", encoded); //! ``` //! //! As a command-line tool: //! ```bash //! rustc huffman_encoding.rs -o huffman //! ./huffman input.txt //! ``` use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap}; use std::fs; #[cfg(not(test))] use std::env; /// Represents a node in the Huffman tree #[derive(Debug, Eq, PartialEq)] enum HuffmanNode { /// Leaf node containing a character and its frequency Leaf { character: char, frequency: usize }, /// Internal node with combined frequency and left/right children Internal { frequency: usize, left: Box<HuffmanNode>, right: Box<HuffmanNode>, }, } impl HuffmanNode { /// Returns the frequency of this node fn frequency(&self) -> usize { match self { HuffmanNode::Leaf { frequency, .. } | HuffmanNode::Internal { frequency, .. } => { *frequency } } } /// Creates a new leaf node fn new_leaf(character: char, frequency: usize) -> Self { HuffmanNode::Leaf { character, frequency, } } /// Creates a new internal node from two children fn new_internal(left: HuffmanNode, right: HuffmanNode) -> Self { let frequency = left.frequency() + right.frequency(); HuffmanNode::Internal { frequency, left: Box::new(left), right: Box::new(right), } } } /// Wrapper for HuffmanNode to implement Ord for BinaryHeap (min-heap) #[derive(Eq, PartialEq)] struct HeapNode(HuffmanNode); impl Ord for HeapNode { fn cmp(&self, other: &Self) -> Ordering { // Reverse ordering for min-heap other.0.frequency().cmp(&self.0.frequency()) } } impl PartialOrd for HeapNode { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } /// Counts the frequency of each character in the input string /// /// # Arguments /// /// * `text` - The input string to analyze /// /// # Returns /// /// A HashMap mapping each character to its frequency count fn build_frequency_map(text: &str) -> HashMap<char, usize> { let mut frequencies = HashMap::new(); for ch in text.chars() { *frequencies.entry(ch).or_insert(0) += 1; } frequencies } /// Builds the Huffman tree from a frequency map /// /// # Arguments /// /// * `frequencies` - HashMap of character frequencies /// /// # Returns /// /// The root node of the Huffman tree, or None if input is empty fn build_huffman_tree(frequencies: HashMap<char, usize>) -> Option<HuffmanNode> { if frequencies.is_empty() { return None; } let mut heap: BinaryHeap<HeapNode> = frequencies .into_iter() .map(|(ch, freq)| HeapNode(HuffmanNode::new_leaf(ch, freq))) .collect(); // Special case: only one unique character if heap.len() == 1 { return heap.pop().map(|node| node.0); } // Build the tree by combining nodes while heap.len() > 1 { let left = heap.pop().unwrap().0; let right = heap.pop().unwrap().0; let parent = HuffmanNode::new_internal(left, right); heap.push(HeapNode(parent)); } heap.pop().map(|node| node.0) } /// Traverses the Huffman tree to generate binary codes for each character /// /// # Arguments /// /// * `node` - The current node being traversed /// * `code` - The current binary code string /// * `codes` - HashMap to store the generated codes fn generate_codes(node: &HuffmanNode, code: String, codes: &mut HashMap<char, String>) { match node { HuffmanNode::Leaf { character, .. } => { // Use "0" for single character case codes.insert( *character, if code.is_empty() { "0".to_string() } else { code }, ); } HuffmanNode::Internal { left, right, .. } => { generate_codes(left, format!("{code}0"), codes); generate_codes(right, format!("{code}1"), codes); } } } /// Encodes text using Huffman coding /// /// # Arguments /// /// * `text` - The input string to encode /// /// # Returns /// /// A tuple containing: /// - The encoded binary string /// - A HashMap of character to binary code mappings /// /// # Examples /// /// ``` /// # use std::collections::HashMap; /// # use the_algorithms_rust::compression::huffman_encode; /// let (encoded, codes) = huffman_encode("hello"); /// assert!(!encoded.is_empty()); /// assert!(codes.contains_key(&'h')); /// ``` pub fn huffman_encode(text: &str) -> (String, HashMap<char, String>) { if text.is_empty() { return (String::new(), HashMap::new()); } let frequencies = build_frequency_map(text); let tree = build_huffman_tree(frequencies).expect("Failed to build Huffman tree"); let mut codes = HashMap::new(); generate_codes(&tree, String::new(), &mut codes); let encoded: String = text.chars().map(|ch| codes[&ch].as_str()).collect(); (encoded, codes) } /// Decodes a Huffman-encoded string /// /// # Arguments /// /// * `encoded` - The binary string to decode /// * `codes` - HashMap of character to binary code mappings /// /// # Returns /// /// The decoded original string /// /// # Examples /// /// ``` /// # use std::collections::HashMap; /// # use the_algorithms_rust::compression::{huffman_encode, huffman_decode}; /// let text = "hello world"; /// let (encoded, codes) = huffman_encode(text); /// let decoded = huffman_decode(&encoded, &codes); /// assert_eq!(text, decoded); /// ``` pub fn huffman_decode(encoded: &str, codes: &HashMap<char, String>) -> String { if encoded.is_empty() { return String::new(); } // Reverse the code map for decoding let reverse_codes: HashMap<&str, char> = codes .iter() .map(|(ch, code)| (code.as_str(), *ch)) .collect(); let mut decoded = String::new(); let mut current_code = String::new(); for bit in encoded.chars() { current_code.push(bit); if let Some(&character) = reverse_codes.get(current_code.as_str()) { decoded.push(character); current_code.clear(); } } decoded } /// Demonstrates Huffman encoding by processing a file and displaying detailed results /// /// This function reads a file, encodes it using Huffman coding, and displays: /// - Character code mappings /// - Compression statistics /// - Encoded output (with smart truncation for large files) /// - Decoding verification /// /// # Arguments /// /// * `file_path` - Path to the file to encode /// /// # Returns /// /// Result indicating success or IO error /// /// # Examples /// /// ```ignore /// // Note: This function is not re-exported in the public API /// // Access it via: the_algorithms_rust::compression::huffman_encoding::demonstrate_huffman_from_file /// use std::fs::File; /// use std::io::Write; /// /// // Create a test file /// let mut file = File::create("test.txt").unwrap(); /// file.write_all(b"hello world").unwrap(); /// /// // Demonstrate Huffman encoding /// // In your code, use the full path or import from huffman_encoding module /// demonstrate_huffman_from_file("test.txt").unwrap(); /// ``` #[allow(dead_code)] pub fn demonstrate_huffman_from_file(file_path: &str) -> std::io::Result<()> { // Read the file contents let text = fs::read_to_string(file_path)?; if text.is_empty() { println!("File is empty!"); return Ok(()); } // Encode using Huffman coding let (encoded, codes) = huffman_encode(&text); // Display the results println!("Huffman Coding of {file_path}: "); println!(); // Show the code table println!("Character Codes:"); println!("{:-<40}", ""); let mut sorted_codes: Vec<_> = codes.iter().collect(); sorted_codes.sort_by_key(|(ch, _)| *ch); for (ch, code) in sorted_codes { let display_char = if ch.is_whitespace() { format!("'{}' (space/whitespace)", ch.escape_default()) } else { format!("'{ch}'") }; println!("{display_char:20} -> {code}"); } println!("{:-<40}", ""); println!(); // Show encoding statistics let original_bits = text.len() * 8; // Assuming 8-bit characters let compressed_bits = encoded.len(); let compression_ratio = if original_bits > 0 { (1.0 - (compressed_bits as f64 / original_bits as f64)) * 100.0 } else { 0.0 }; println!("Statistics:"); println!( " Original size: {} characters ({} bits)", text.len(), original_bits ); println!(" Encoded size: {compressed_bits} bits"); println!(" Compression: {compression_ratio:.2}%"); println!(); // Show the encoded output (limited to avoid overwhelming the terminal) println!("Encoded output:"); if encoded.len() <= 500 { // Split into chunks of 50 for readability for (i, chunk) in encoded.as_bytes().chunks(50).enumerate() { print!("{:4}: ", i * 50); for &byte in chunk { print!("{}", byte as char); } println!(); } } else { // Show first and last portions for very long outputs println!(" (showing first and last 200 bits)"); print!(" Start: "); for &byte in &encoded.as_bytes()[..200] { print!("{}", byte as char); } println!(); print!(" End: "); for &byte in &encoded.as_bytes()[encoded.len() - 200..] { print!("{}", byte as char); } println!(); } println!(); // Verify decoding let decoded = huffman_decode(&encoded, &codes); if decoded == text { println!("✓ Decoding verification: SUCCESS"); } else { println!("✗ Decoding verification: FAILED"); } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_empty_string() { let (encoded, codes) = huffman_encode(""); assert_eq!(encoded, ""); assert!(codes.is_empty()); } #[test] fn test_single_character() { let (encoded, codes) = huffman_encode("aaaa"); assert_eq!(encoded, "0000"); assert_eq!(codes.get(&'a'), Some(&"0".to_string())); } #[test] fn test_simple_string() { let text = "hello"; let (encoded, codes) = huffman_encode(text); // Verify all characters have codes for ch in text.chars() { assert!(codes.contains_key(&ch), "Missing code for '{ch}'"); } // Verify decoding returns original text let decoded = huffman_decode(&encoded, &codes); assert_eq!(decoded, text); } #[test] fn test_encode_decode_roundtrip() { let test_cases = vec![ "a", "ab", "hello world", "the quick brown fox jumps over the lazy dog", "aaaaabbbbbcccccdddddeeeeefffffggggghhhhhiiiii", ]; for text in test_cases { let (encoded, codes) = huffman_encode(text); let decoded = huffman_decode(&encoded, &codes); assert_eq!(decoded, text, "Failed roundtrip for: '{text}'"); } } #[test] fn test_frequency_based_encoding() { // In "aaabbc", 'a' should have shorter code than 'b' or 'c' let (_, codes) = huffman_encode("aaabbc"); let a_len = codes[&'a'].len(); let b_len = codes[&'b'].len(); let c_len = codes[&'c'].len(); // 'a' appears most frequently, so should have shortest or equal code assert!(a_len <= b_len); assert!(a_len <= c_len); } #[test] fn test_compression_ratio() { let text = "aaaaaaaaaa"; // 10 'a's let (encoded, _) = huffman_encode(text); // Original: 10 chars * 8 bits = 80 bits (in UTF-8) // Huffman: 10 * 1 bit = 10 bits (single character gets code "0") assert_eq!(encoded.len(), 10); assert!(encoded.chars().all(|c| c == '0')); } #[test] fn test_all_unique_characters() { let text = "abcdefg"; let (encoded, codes) = huffman_encode(text); // All characters should have codes assert_eq!(codes.len(), 7); // Verify roundtrip let decoded = huffman_decode(&encoded, &codes); assert_eq!(decoded, text); } #[test] fn test_build_frequency_map() { let frequencies = build_frequency_map("hello"); assert_eq!(frequencies.get(&'h'), Some(&1)); assert_eq!(frequencies.get(&'e'), Some(&1)); assert_eq!(frequencies.get(&'l'), Some(&2)); assert_eq!(frequencies.get(&'o'), Some(&1)); } #[test] fn test_unicode_characters() { let text = "Hello, 世界! 🌍"; let (encoded, codes) = huffman_encode(text); let decoded = huffman_decode(&encoded, &codes); assert_eq!(decoded, text); } #[test] fn test_demonstrate_huffman_from_file() { use std::fs::File; use std::io::Write; // Create a temporary test file let test_file = "/tmp/huffman_test.txt"; let test_content = "The quick brown fox jumps over the lazy dog"; { let mut file = File::create(test_file).unwrap(); file.write_all(test_content.as_bytes()).unwrap(); } // Test the demonstrate function let result = demonstrate_huffman_from_file(test_file); assert!(result.is_ok()); } #[test] fn test_demonstrate_empty_file() { use std::fs::File; // Create an empty test file let test_file = "/tmp/huffman_empty.txt"; File::create(test_file).unwrap(); // Test with empty file let result = demonstrate_huffman_from_file(test_file); assert!(result.is_ok()); } } /// Main function for command-line usage /// /// Allows this file to be compiled as a standalone binary: /// ```bash /// rustc huffman_encoding.rs -o huffman /// ./huffman input.txt /// ``` #[cfg(not(test))] #[allow(dead_code)] fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 { eprintln!("Huffman Encoding - Lossless Data Compression"); eprintln!(); eprintln!("Usage: {} <file_path>", args[0]); eprintln!(); eprintln!("Example:"); eprintln!(" {} sample.txt", args[0]); eprintln!(); eprintln!("This will encode the file and display:"); eprintln!(" - Character code mappings"); eprintln!(" - Compression statistics"); eprintln!(" - Encoded binary output"); eprintln!(" - Verification of successful decoding"); std::process::exit(1); } let file_path = &args[1]; match demonstrate_huffman_from_file(file_path) { Ok(()) => {} Err(e) => { eprintln!("Error processing file '{file_path}': {e}"); std::process::exit(1); } } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/compression/run_length_encoding.rs
src/compression/run_length_encoding.rs
// https://en.wikipedia.org/wiki/Run-length_encoding pub fn run_length_encode(text: &str) -> Vec<(char, i32)> { let mut count = 1; let mut encoded: Vec<(char, i32)> = vec![]; for (i, c) in text.chars().enumerate() { if i + 1 < text.len() && c == text.chars().nth(i + 1).unwrap() { count += 1; } else { encoded.push((c, count)); count = 1; } } encoded } pub fn run_length_decode(encoded: &[(char, i32)]) -> String { let res = encoded .iter() .map(|x| (x.0).to_string().repeat(x.1 as usize)) .collect::<String>(); res } #[cfg(test)] mod test { use super::*; #[test] fn test_run_length_decode() { let res = run_length_decode(&[('A', 0)]); assert_eq!(res, ""); let res = run_length_decode(&[('B', 1)]); assert_eq!(res, "B"); let res = run_length_decode(&[('A', 5), ('z', 3), ('B', 1)]); assert_eq!(res, "AAAAAzzzB"); } #[test] fn test_run_length_encode() { let res = run_length_encode(""); assert_eq!(res, []); let res = run_length_encode("A"); assert_eq!(res, [('A', 1)]); let res = run_length_encode("AA"); assert_eq!(res, [('A', 2)]); let res = run_length_encode("AAAABBBCCDAA"); assert_eq!(res, [('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)]); let res = run_length_encode("Rust-Trends"); assert_eq!( res, [ ('R', 1), ('u', 1), ('s', 1), ('t', 1), ('-', 1), ('T', 1), ('r', 1), ('e', 1), ('n', 1), ('d', 1), ('s', 1) ] ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/compression/lz77.rs
src/compression/lz77.rs
//! LZ77 Compression Algorithm //! //! LZ77 is a lossless data compression algorithm published by Abraham Lempel and Jacob Ziv in 1977. //! Also known as LZ1 or sliding-window compression, it forms the basis for many variations //! including LZW, LZSS, LZMA and others. //! //! # Algorithm Overview //! //! It uses a "sliding window" method where the window contains: //! - Search buffer: previously seen data that can be referenced //! - Look-ahead buffer: data currently being encoded //! //! LZ77 encodes data using triplets (tokens) composed of: //! - **Offset**: distance from the current position to the start of a match in the search buffer //! - **Length**: number of characters that match //! - **Indicator**: the next character to be encoded //! //! # Examples //! //! ``` //! use the_algorithms_rust::compression::LZ77Compressor; //! //! let compressor = LZ77Compressor::new(13, 6); //! let text = "ababcbababaa"; //! let compressed = compressor.compress(text); //! let decompressed = compressor.decompress(&compressed); //! assert_eq!(text, decompressed); //! ``` //! //! # References //! //! - [Wikipedia: LZ77 and LZ78](https://en.wikipedia.org/wiki/LZ77_and_LZ78) use std::fmt; /// Represents a compression token (triplet) used in LZ77 compression. /// /// A token consists of: /// - `offset`: distance to the start of the match in the search buffer /// - `length`: number of matching characters /// - `indicator`: the next character to be encoded #[derive(Debug, Clone, PartialEq, Eq)] pub struct Token { pub offset: usize, pub length: usize, pub indicator: char, } impl Token { /// Creates a new Token. pub fn new(offset: usize, length: usize, indicator: char) -> Self { Self { offset, length, indicator, } } } impl fmt::Display for Token { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}, {}, {})", self.offset, self.length, self.indicator) } } /// LZ77 Compressor with configurable window and lookahead buffer sizes. #[derive(Debug, Clone)] pub struct LZ77Compressor { search_buffer_size: usize, } impl LZ77Compressor { /// Creates a new LZ77Compressor with the specified parameters. /// /// # Arguments /// /// * `window_size` - Total size of the sliding window /// * `lookahead_buffer_size` - Size of the lookahead buffer /// /// # Panics /// /// Panics if `lookahead_buffer_size` is greater than or equal to `window_size`. /// /// # Examples /// /// ``` /// use the_algorithms_rust::compression::LZ77Compressor; /// /// let compressor = LZ77Compressor::new(13, 6); /// ``` pub fn new(window_size: usize, lookahead_buffer_size: usize) -> Self { assert!( lookahead_buffer_size < window_size, "lookahead_buffer_size must be less than window_size" ); Self { search_buffer_size: window_size - lookahead_buffer_size, } } /// Compresses the given text using the LZ77 algorithm. /// /// # Arguments /// /// * `text` - The string to be compressed /// /// # Returns /// /// A vector of `Token`s representing the compressed data /// /// # Examples /// /// ``` /// use the_algorithms_rust::compression::LZ77Compressor; /// /// let compressor = LZ77Compressor::new(13, 6); /// let compressed = compressor.compress("ababcbababaa"); /// assert_eq!(compressed.len(), 5); /// ``` pub fn compress(&self, text: &str) -> Vec<Token> { let mut output = Vec::new(); let mut search_buffer = String::new(); let mut remaining_text = text.to_string(); while !remaining_text.is_empty() { // Find the next encoding token let token = self.find_encoding_token(&remaining_text, &search_buffer); // Update the search buffer with the newly processed characters let chars_to_add = token.length + 1; let new_chars: String = remaining_text.chars().take(chars_to_add).collect(); search_buffer.push_str(&new_chars); // Trim search buffer if it exceeds the maximum size if search_buffer.len() > self.search_buffer_size { let trim_amount = search_buffer.len() - self.search_buffer_size; search_buffer = search_buffer.chars().skip(trim_amount).collect(); } // Remove processed characters from remaining text remaining_text = remaining_text.chars().skip(chars_to_add).collect(); // Add token to output output.push(token); } output } /// Decompresses a list of tokens back into the original text. /// /// # Arguments /// /// * `tokens` - A slice of `Token`s representing compressed data /// /// # Returns /// /// The decompressed string /// /// # Examples /// /// ``` /// use the_algorithms_rust::compression::{LZ77Compressor, Token}; /// /// let compressor = LZ77Compressor::new(13, 6); /// let tokens = vec![ /// Token::new(0, 0, 'a'), /// Token::new(0, 0, 'b'), /// Token::new(2, 2, 'c'), /// Token::new(4, 3, 'a'), /// Token::new(2, 2, 'a'), /// ]; /// let decompressed = compressor.decompress(&tokens); /// assert_eq!(decompressed, "ababcbababaa"); /// ``` pub fn decompress(&self, tokens: &[Token]) -> String { let mut output = String::new(); for token in tokens { // Copy characters from the existing output based on offset and length for _ in 0..token.length { let index = output.len() - token.offset; let ch = output.chars().nth(index).unwrap(); output.push(ch); } // Add the indicator character output.push(token.indicator); } output } /// Finds the encoding token for the current position in the text. /// /// This method searches the search buffer for the longest match with the /// beginning of the text and returns the corresponding token. fn find_encoding_token(&self, text: &str, search_buffer: &str) -> Token { if text.is_empty() { panic!("Cannot encode empty text"); } let mut length = 0; let mut offset = 0; if search_buffer.is_empty() { return Token::new(offset, length, text.chars().next().unwrap()); } let search_chars: Vec<char> = search_buffer.chars().collect(); let text_chars: Vec<char> = text.chars().collect(); // We must keep at least one character for the indicator let max_match_length = text_chars.len() - 1; // Search for matches in the search buffer for (i, &ch) in search_chars.iter().enumerate() { let found_offset = search_chars.len() - i; if ch == text_chars[0] { let found_length = Self::match_length_from_index(&text_chars, &search_chars, 0, i); // Limit match length to ensure we have an indicator character let found_length = found_length.min(max_match_length); // Update if we found a longer match (or same length with smaller offset) if found_length >= length { offset = found_offset; length = found_length; } } } Token::new(offset, length, text_chars[length]) } /// Calculates the length of the longest match between text and window /// starting from the given indices. /// /// This is a helper function that recursively finds matching characters. fn match_length_from_index( text: &[char], window: &[char], text_index: usize, window_index: usize, ) -> usize { // Base cases if text_index >= text.len() || window_index >= window.len() { return 0; } if text[text_index] != window[window_index] { return 0; } // Recursive case: characters match, continue checking let mut extended_window = window.to_vec(); extended_window.push(text[text_index]); 1 + Self::match_length_from_index(text, &extended_window, text_index + 1, window_index + 1) } } impl Default for LZ77Compressor { /// Creates a default LZ77Compressor with window_size=13 and lookahead_buffer_size=6. fn default() -> Self { Self::new(13, 6) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_token_display() { let token = Token::new(1, 2, 'c'); assert_eq!(token.to_string(), "(1, 2, c)"); } #[test] fn test_compress_ababcbababaa() { let compressor = LZ77Compressor::new(13, 6); let compressed = compressor.compress("ababcbababaa"); let expected = vec![ Token::new(0, 0, 'a'), Token::new(0, 0, 'b'), Token::new(2, 2, 'c'), Token::new(4, 3, 'a'), Token::new(2, 2, 'a'), ]; assert_eq!(compressed, expected); } #[test] fn test_compress_aacaacabcabaaac() { let compressor = LZ77Compressor::new(13, 6); let compressed = compressor.compress("aacaacabcabaaac"); let expected = vec![ Token::new(0, 0, 'a'), Token::new(1, 1, 'c'), Token::new(3, 4, 'b'), Token::new(3, 3, 'a'), Token::new(1, 2, 'c'), ]; assert_eq!(compressed, expected); } #[test] fn test_decompress_cabracadabrarrarrad() { let compressor = LZ77Compressor::new(13, 6); let tokens = vec![ Token::new(0, 0, 'c'), Token::new(0, 0, 'a'), Token::new(0, 0, 'b'), Token::new(0, 0, 'r'), Token::new(3, 1, 'c'), Token::new(2, 1, 'd'), Token::new(7, 4, 'r'), Token::new(3, 5, 'd'), ]; let decompressed = compressor.decompress(&tokens); assert_eq!(decompressed, "cabracadabrarrarrad"); } #[test] fn test_decompress_ababcbababaa() { let compressor = LZ77Compressor::new(13, 6); let tokens = vec![ Token::new(0, 0, 'a'), Token::new(0, 0, 'b'), Token::new(2, 2, 'c'), Token::new(4, 3, 'a'), Token::new(2, 2, 'a'), ]; let decompressed = compressor.decompress(&tokens); assert_eq!(decompressed, "ababcbababaa"); } #[test] fn test_decompress_aacaacabcabaaac() { let compressor = LZ77Compressor::new(13, 6); let tokens = vec![ Token::new(0, 0, 'a'), Token::new(1, 1, 'c'), Token::new(3, 4, 'b'), Token::new(3, 3, 'a'), Token::new(1, 2, 'c'), ]; let decompressed = compressor.decompress(&tokens); assert_eq!(decompressed, "aacaacabcabaaac"); } #[test] fn test_round_trip_compression() { let compressor = LZ77Compressor::new(13, 6); let texts = vec![ "cabracadabrarrarrad", "ababcbababaa", "aacaacabcabaaac", "hello world", "aaaaaaa", "abcdefghijk", ]; for text in texts { let compressed = compressor.compress(text); let decompressed = compressor.decompress(&compressed); assert_eq!(text, decompressed, "Round trip failed for text: {text}"); } } #[test] fn test_empty_search_buffer() { let compressor = LZ77Compressor::new(13, 6); let token = compressor.find_encoding_token("abc", ""); assert_eq!(token, Token::new(0, 0, 'a')); } #[test] #[should_panic(expected = "Cannot encode empty text")] fn test_empty_text_panics() { let compressor = LZ77Compressor::new(13, 6); compressor.find_encoding_token("", "xyz"); } #[test] fn test_default_compressor() { let compressor = LZ77Compressor::default(); let text = "test"; let compressed = compressor.compress(text); let decompressed = compressor.decompress(&compressed); assert_eq!(text, decompressed); } #[test] #[should_panic(expected = "lookahead_buffer_size must be less than window_size")] fn test_invalid_buffer_sizes() { LZ77Compressor::new(10, 10); } #[test] fn test_single_character() { let compressor = LZ77Compressor::new(13, 6); let compressed = compressor.compress("a"); assert_eq!(compressed, vec![Token::new(0, 0, 'a')]); let decompressed = compressor.decompress(&compressed); assert_eq!(decompressed, "a"); } #[test] fn test_repeated_pattern() { let compressor = LZ77Compressor::new(13, 6); let text = "abababab"; let compressed = compressor.compress(text); let decompressed = compressor.decompress(&compressed); assert_eq!(text, decompressed); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/compression/mod.rs
src/compression/mod.rs
mod burrows_wheeler_transform; mod huffman_encoding; mod lz77; mod move_to_front; mod run_length_encoding; pub use self::burrows_wheeler_transform::{all_rotations, bwt_transform, reverse_bwt, BwtResult}; pub use self::huffman_encoding::{huffman_decode, huffman_encode}; pub use self::lz77::{LZ77Compressor, Token}; pub use self::move_to_front::{move_to_front_decode, move_to_front_encode}; pub use self::run_length_encoding::{run_length_decode, run_length_encode};
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/compression/burrows_wheeler_transform.rs
src/compression/burrows_wheeler_transform.rs
//! Burrows-Wheeler Transform //! //! The Burrows-Wheeler transform (BWT, also called block-sorting compression) //! rearranges a character string into runs of similar characters. This is useful //! for compression, since it tends to be easy to compress a string that has runs //! of repeated characters by techniques such as move-to-front transform and //! run-length encoding. More importantly, the transformation is reversible, //! without needing to store any additional data except the position of the first //! original character. The BWT is thus a "free" method of improving the efficiency //! of text compression algorithms, costing only some extra computation. //! //! More info: <https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform> /// Result of the Burrows-Wheeler transform containing the transformed string /// and the index of the original string in the sorted rotations. #[derive(Debug, Clone, PartialEq, Eq)] pub struct BwtResult { /// The BWT-transformed string pub bwt_string: String, /// The index of the original string in the sorted rotations (0-based) pub idx_original_string: usize, } /// Generates all rotations of a string. /// /// # Arguments /// /// * `s` - The string to rotate /// /// # Returns /// /// A vector containing all rotations of the input string /// /// # Examples /// /// ``` /// # use the_algorithms_rust::compression::all_rotations; /// let rotations = all_rotations("^BANANA|"); /// assert_eq!(rotations.len(), 8); /// assert_eq!(rotations[0], "^BANANA|"); /// assert_eq!(rotations[1], "BANANA|^"); /// ``` pub fn all_rotations(s: &str) -> Vec<String> { (0..s.len()) .map(|i| format!("{}{}", &s[i..], &s[..i])) .collect() } /// Performs the Burrows-Wheeler transform on a string. /// /// # Arguments /// /// * `s` - The string to transform (must not be empty) /// /// # Returns /// /// A `BwtResult` containing the transformed string and the index of the original string /// /// # Panics /// /// Panics if the input string is empty /// /// # Examples /// /// ``` /// # use the_algorithms_rust::compression::bwt_transform; /// let result = bwt_transform("^BANANA"); /// assert_eq!(result.bwt_string, "BNN^AAA"); /// assert_eq!(result.idx_original_string, 6); /// /// let result = bwt_transform("panamabanana"); /// assert_eq!(result.bwt_string, "mnpbnnaaaaaa"); /// assert_eq!(result.idx_original_string, 11); /// ``` pub fn bwt_transform(s: &str) -> BwtResult { assert!(!s.is_empty(), "Input string must not be empty"); let mut rotations = all_rotations(s); rotations.sort(); // Find the index of the original string in sorted rotations let idx_original_string = rotations .iter() .position(|r| r == s) .expect("Original string must be in rotations"); // Build BWT string from last character of each rotation let bwt_string: String = rotations .iter() .map(|r| r.chars().last().unwrap()) .collect(); BwtResult { bwt_string, idx_original_string, } } /// Reverses the Burrows-Wheeler transform to recover the original string. /// /// # Arguments /// /// * `bwt_string` - The BWT-transformed string /// * `idx_original_string` - The 0-based index of the original string in sorted rotations /// /// # Returns /// /// The original string before BWT transformation /// /// # Panics /// /// * If `bwt_string` is empty /// * If `idx_original_string` is out of bounds (>= length of `bwt_string`) /// /// # Examples /// /// ``` /// # use the_algorithms_rust::compression::reverse_bwt; /// assert_eq!(reverse_bwt("BNN^AAA", 6), "^BANANA"); /// assert_eq!(reverse_bwt("aaaadss_c__aa", 3), "a_asa_da_casa"); /// assert_eq!(reverse_bwt("mnpbnnaaaaaa", 11), "panamabanana"); /// ``` pub fn reverse_bwt(bwt_string: &str, idx_original_string: usize) -> String { assert!(!bwt_string.is_empty(), "BWT string must not be empty"); assert!( idx_original_string < bwt_string.len(), "Index must be less than BWT string length" ); let len = bwt_string.len(); let bwt_chars: Vec<char> = bwt_string.chars().collect(); let mut ordered_rotations: Vec<String> = vec![String::new(); len]; // Iteratively prepend characters and sort to reconstruct rotations for _ in 0..len { for i in 0..len { ordered_rotations[i] = format!("{}{}", bwt_chars[i], ordered_rotations[i]); } ordered_rotations.sort(); } ordered_rotations[idx_original_string].clone() } #[cfg(test)] mod tests { use super::*; #[test] fn test_all_rotations_banana() { let rotations = all_rotations("^BANANA|"); assert_eq!(rotations.len(), 8); assert_eq!( rotations, vec![ "^BANANA|", "BANANA|^", "ANANA|^B", "NANA|^BA", "ANA|^BAN", "NA|^BANA", "A|^BANAN", "|^BANANA" ] ); } #[test] fn test_all_rotations_casa() { let rotations = all_rotations("a_asa_da_casa"); assert_eq!(rotations.len(), 13); assert_eq!(rotations[0], "a_asa_da_casa"); assert_eq!(rotations[1], "_asa_da_casaa"); assert_eq!(rotations[12], "aa_asa_da_cas"); } #[test] fn test_all_rotations_panama() { let rotations = all_rotations("panamabanana"); assert_eq!(rotations.len(), 12); assert_eq!(rotations[0], "panamabanana"); assert_eq!(rotations[11], "apanamabanan"); } #[test] fn test_bwt_transform_banana() { let result = bwt_transform("^BANANA"); assert_eq!(result.bwt_string, "BNN^AAA"); assert_eq!(result.idx_original_string, 6); } #[test] fn test_bwt_transform_casa() { let result = bwt_transform("a_asa_da_casa"); assert_eq!(result.bwt_string, "aaaadss_c__aa"); assert_eq!(result.idx_original_string, 3); } #[test] fn test_bwt_transform_panama() { let result = bwt_transform("panamabanana"); assert_eq!(result.bwt_string, "mnpbnnaaaaaa"); assert_eq!(result.idx_original_string, 11); } #[test] #[should_panic(expected = "Input string must not be empty")] fn test_bwt_transform_empty() { bwt_transform(""); } #[test] fn test_reverse_bwt_banana() { let original = reverse_bwt("BNN^AAA", 6); assert_eq!(original, "^BANANA"); } #[test] fn test_reverse_bwt_casa() { let original = reverse_bwt("aaaadss_c__aa", 3); assert_eq!(original, "a_asa_da_casa"); } #[test] fn test_reverse_bwt_panama() { let original = reverse_bwt("mnpbnnaaaaaa", 11); assert_eq!(original, "panamabanana"); } #[test] #[should_panic(expected = "BWT string must not be empty")] fn test_reverse_bwt_empty_string() { reverse_bwt("", 0); } #[test] #[should_panic(expected = "Index must be less than BWT string length")] fn test_reverse_bwt_index_too_high() { reverse_bwt("mnpbnnaaaaaa", 12); } #[test] fn test_bwt_roundtrip() { // Test that transform -> reverse gives back original string let test_strings = vec![ "^BANANA", "a_asa_da_casa", "panamabanana", "ABRACADABRA", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", ]; for s in test_strings { let result = bwt_transform(s); let recovered = reverse_bwt(&result.bwt_string, result.idx_original_string); assert_eq!(recovered, s, "Roundtrip failed for '{s}'"); } } #[test] fn test_single_character() { let result = bwt_transform("A"); assert_eq!(result.bwt_string, "A"); assert_eq!(result.idx_original_string, 0); let recovered = reverse_bwt(&result.bwt_string, result.idx_original_string); assert_eq!(recovered, "A"); } #[test] fn test_repeated_characters() { let result = bwt_transform("AAAA"); assert_eq!(result.bwt_string, "AAAA"); let recovered = reverse_bwt(&result.bwt_string, result.idx_original_string); assert_eq!(recovered, "AAAA"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/number_theory/mod.rs
src/number_theory/mod.rs
mod compute_totient; mod euler_totient; mod kth_factor; pub use self::compute_totient::compute_totient; pub use self::euler_totient::euler_totient; pub use self::kth_factor::kth_factor;
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/number_theory/euler_totient.rs
src/number_theory/euler_totient.rs
pub fn euler_totient(n: u64) -> u64 { let mut result = n; let mut num = n; let mut p = 2; // Find all prime factors and apply formula while p * p <= num { // Check if p is a divisor of n if num.is_multiple_of(p) { // If yes, then it is a prime factor // Apply the formula: result = result * (1 - 1/p) while num.is_multiple_of(p) { num /= p; } result -= result / p; } p += 1; } // If num > 1, then it is a prime factor if num > 1 { result -= result / num; } result } #[cfg(test)] mod tests { use super::*; macro_rules! test_euler_totient { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (input, expected) = $test_case; assert_eq!(euler_totient(input), expected) } )* }; } test_euler_totient! { prime_2: (2, 1), prime_3: (3, 2), prime_5: (5, 4), prime_7: (7, 6), prime_11: (11, 10), prime_13: (13, 12), prime_17: (17, 16), prime_19: (19, 18), composite_6: (6, 2), // 2 * 3 composite_10: (10, 4), // 2 * 5 composite_15: (15, 8), // 3 * 5 composite_12: (12, 4), // 2^2 * 3 composite_18: (18, 6), // 2 * 3^2 composite_20: (20, 8), // 2^2 * 5 composite_30: (30, 8), // 2 * 3 * 5 prime_power_2_to_2: (4, 2), prime_power_2_to_3: (8, 4), prime_power_3_to_2: (9, 6), prime_power_2_to_4: (16, 8), prime_power_5_to_2: (25, 20), prime_power_3_to_3: (27, 18), prime_power_2_to_5: (32, 16), // Large numbers large_50: (50, 20), // 2 * 5^2 large_100: (100, 40), // 2^2 * 5^2 large_1000: (1000, 400), // 2^3 * 5^3 } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/number_theory/compute_totient.rs
src/number_theory/compute_totient.rs
// Totient function for // all numbers smaller than // or equal to n. // Computes and prints // totient of all numbers // smaller than or equal to n use std::vec; pub fn compute_totient(n: i32) -> vec::Vec<i32> { let mut phi: Vec<i32> = Vec::new(); // initialize phi[i] = i for i in 0..=n { phi.push(i); } // Compute other Phi values for p in 2..=n { // If phi[p] is not computed already, // then number p is prime if phi[(p) as usize] == p { // Phi of a prime number p is // always equal to p-1. phi[(p) as usize] = p - 1; // Update phi values of all // multiples of p for i in ((2 * p)..=n).step_by(p as usize) { phi[(i) as usize] = (phi[i as usize] / p) * (p - 1); } } } phi[1..].to_vec() } #[cfg(test)] mod tests { use super::*; #[test] fn test_1() { assert_eq!( compute_totient(12), vec![1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10, 4] ); } #[test] fn test_2() { assert_eq!(compute_totient(7), vec![1, 1, 2, 2, 4, 2, 6]); } #[test] fn test_3() { assert_eq!(compute_totient(4), vec![1, 1, 2, 2]); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/number_theory/kth_factor.rs
src/number_theory/kth_factor.rs
// Kth Factor of N // The idea is to check for each number in the range [N, 1], and print the Kth number that divides N completely. pub fn kth_factor(n: i32, k: i32) -> i32 { let mut factors: Vec<i32> = Vec::new(); let k = (k as usize) - 1; for i in 1..=n { if n % i == 0 { factors.push(i); } if let Some(number) = factors.get(k) { return *number; } } -1 } #[cfg(test)] mod tests { use super::*; #[test] fn test_1() { assert_eq!(kth_factor(12, 3), 3); } #[test] fn test_2() { assert_eq!(kth_factor(7, 2), 7); } #[test] fn test_3() { assert_eq!(kth_factor(4, 4), -1); } #[test] fn test_4() { assert_eq!(kth_factor(950, 5), 19); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/big_integer/poly1305.rs
src/big_integer/poly1305.rs
use num_bigint::BigUint; use num_traits::Num; use num_traits::Zero; macro_rules! hex_uint { ($a:literal) => { BigUint::from_str_radix($a, 16).unwrap() }; } /** * Poly1305 Message Authentication Code: * This implementation is based on RFC8439. * Note that the Big Integer library we are using may not be suitable for * cryptographic applications due to non constant time operations. */ pub struct Poly1305 { p: BigUint, r: BigUint, s: BigUint, /// The accumulator pub acc: BigUint, } impl Default for Poly1305 { fn default() -> Self { Self::new() } } impl Poly1305 { pub fn new() -> Self { Poly1305 { p: hex_uint!("3fffffffffffffffffffffffffffffffb"), // 2^130 - 5 r: Zero::zero(), s: Zero::zero(), acc: Zero::zero(), } } pub fn clamp_r(&mut self) { self.r &= hex_uint!("0ffffffc0ffffffc0ffffffc0fffffff"); } pub fn set_key(&mut self, key: &[u8; 32]) { self.r = BigUint::from_bytes_le(&key[..16]); self.s = BigUint::from_bytes_le(&key[16..]); self.clamp_r(); } /// process a 16-byte-long message block. If message is not long enough, /// fill the `msg` array with zeros, but set `msg_bytes` to the original /// chunk length in bytes. See `basic_tv1` for example usage. pub fn add_msg(&mut self, msg: &[u8; 16], msg_bytes: u64) { let mut n = BigUint::from_bytes_le(msg); n.set_bit(msg_bytes * 8, true); self.acc += n; self.acc *= &self.r; self.acc %= &self.p; } /// The result is guaranteed to be 16 bytes long pub fn get_tag(&self) -> Vec<u8> { let result = &self.acc + &self.s; let mut bytes = result.to_bytes_le(); bytes.resize(16, 0); bytes } } #[cfg(test)] mod tests { use super::*; use std::fmt::Write; fn get_tag_hex(tag: &[u8]) -> String { let mut result = String::new(); for &x in tag { write!(result, "{x:02x}").unwrap(); } result } #[test] fn basic_tv1() { let mut mac = Poly1305::default(); let key: [u8; 32] = [ 0x85, 0xd6, 0xbe, 0x78, 0x57, 0x55, 0x6d, 0x33, 0x7f, 0x44, 0x52, 0xfe, 0x42, 0xd5, 0x06, 0xa8, 0x01, 0x03, 0x80, 0x8a, 0xfb, 0x0d, 0xb2, 0xfd, 0x4a, 0xbf, 0xf6, 0xaf, 0x41, 0x49, 0xf5, 0x1b, ]; let mut tmp_buffer = [0_u8; 16]; mac.set_key(&key); mac.add_msg(b"Cryptographic Fo", 16); mac.add_msg(b"rum Research Gro", 16); tmp_buffer[..2].copy_from_slice(b"up"); mac.add_msg(&tmp_buffer, 2); let result = mac.get_tag(); assert_eq!( get_tag_hex(result.as_slice()), "a8061dc1305136c6c22b8baf0c0127a9" ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/big_integer/mod.rs
src/big_integer/mod.rs
#![cfg(feature = "big-math")] mod fast_factorial; mod multiply; mod poly1305; pub use self::fast_factorial::fast_factorial; pub use self::multiply::multiply; pub use self::poly1305::Poly1305;
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/big_integer/fast_factorial.rs
src/big_integer/fast_factorial.rs
// Algorithm created by Peter Borwein in 1985 // https://doi.org/10.1016/0196-6774(85)90006-9 use crate::math::sieve_of_eratosthenes; use num_bigint::BigUint; use num_traits::One; use std::collections::BTreeMap; /// Calculate the sum of n / p^i with integer division for all values of i fn index(p: usize, n: usize) -> usize { let mut index = 0; let mut i = 1; let mut quot = n / p; while quot > 0 { index += quot; i += 1; quot = n / p.pow(i); } index } /// Calculate the factorial with time complexity O(log(log(n)) * M(n * log(n))) where M(n) is the time complexity of multiplying two n-digit numbers together. pub fn fast_factorial(n: usize) -> BigUint { if n < 2 { return BigUint::one(); } // get list of primes that will be factors of n! let primes = sieve_of_eratosthenes(n); // Map the primes with their index let p_indices = primes .into_iter() .map(|p| (p, index(p, n))) .collect::<BTreeMap<_, _>>(); let max_bits = p_indices[&2].next_power_of_two().ilog2() + 1; // Create a Vec of 1's let mut a = vec![BigUint::one(); max_bits as usize]; // For every prime p, multiply a[i] by p if the ith bit of p's index is 1 for (p, i) in p_indices { let mut bit = 1usize; while bit.ilog2() < max_bits { if (bit & i) > 0 { a[bit.ilog2() as usize] *= p; } bit <<= 1; } } a.into_iter() .enumerate() .map(|(i, a_i)| a_i.pow(2u32.pow(i as u32))) // raise every a[i] to the 2^ith power .product() // we get our answer by multiplying the result } #[cfg(test)] mod tests { use super::*; use crate::math::factorial::factorial_bigmath; #[test] fn fact() { assert_eq!(fast_factorial(0), BigUint::one()); assert_eq!(fast_factorial(1), BigUint::one()); assert_eq!(fast_factorial(2), factorial_bigmath(2)); assert_eq!(fast_factorial(3), factorial_bigmath(3)); assert_eq!(fast_factorial(6), factorial_bigmath(6)); assert_eq!(fast_factorial(7), factorial_bigmath(7)); assert_eq!(fast_factorial(10), factorial_bigmath(10)); assert_eq!(fast_factorial(11), factorial_bigmath(11)); assert_eq!(fast_factorial(18), factorial_bigmath(18)); assert_eq!(fast_factorial(19), factorial_bigmath(19)); assert_eq!(fast_factorial(30), factorial_bigmath(30)); assert_eq!(fast_factorial(34), factorial_bigmath(34)); assert_eq!(fast_factorial(35), factorial_bigmath(35)); assert_eq!(fast_factorial(52), factorial_bigmath(52)); assert_eq!(fast_factorial(100), factorial_bigmath(100)); assert_eq!(fast_factorial(1000), factorial_bigmath(1000)); assert_eq!(fast_factorial(5000), factorial_bigmath(5000)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/big_integer/multiply.rs
src/big_integer/multiply.rs
/// Performs long multiplication on string representations of non-negative numbers. pub fn multiply(num1: &str, num2: &str) -> String { if !is_valid_nonnegative(num1) || !is_valid_nonnegative(num2) { panic!("String does not conform to specification") } if num1 == "0" || num2 == "0" { return "0".to_string(); } let output_size = num1.len() + num2.len(); let mut mult = vec![0; output_size]; for (i, c1) in num1.chars().rev().enumerate() { for (j, c2) in num2.chars().rev().enumerate() { let mul = c1.to_digit(10).unwrap() * c2.to_digit(10).unwrap(); // It could be a two-digit number here. mult[i + j + 1] += (mult[i + j] + mul) / 10; // Handling rounding. Here's a single digit. mult[i + j] = (mult[i + j] + mul) % 10; } } if mult[output_size - 1] == 0 { mult.pop(); } mult.iter().rev().map(|&n| n.to_string()).collect() } pub fn is_valid_nonnegative(num: &str) -> bool { num.chars().all(char::is_numeric) && !num.is_empty() && (!num.starts_with('0') || num == "0") } #[cfg(test)] mod tests { use super::*; macro_rules! test_multiply { ($($name:ident: $inputs:expr,)*) => { $( #[test] fn $name() { let (s, t, expected) = $inputs; assert_eq!(multiply(s, t), expected); assert_eq!(multiply(t, s), expected); } )* } } test_multiply! { multiply0: ("2", "3", "6"), multiply1: ("123", "456", "56088"), multiply_zero: ("0", "222", "0"), other_1: ("99", "99", "9801"), other_2: ("999", "99", "98901"), other_3: ("9999", "99", "989901"), other_4: ("192939", "9499596", "1832842552644"), } macro_rules! test_multiply_with_wrong_input { ($($name:ident: $inputs:expr,)*) => { $( #[test] #[should_panic] fn $name() { let (s, t) = $inputs; multiply(s, t); } )* } } test_multiply_with_wrong_input! { empty_input: ("", "121"), leading_zero: ("01", "3"), wrong_characters: ("2", "12d4"), wrong_input_and_zero_1: ("0", "x"), wrong_input_and_zero_2: ("y", "0"), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/rail_fence.rs
src/ciphers/rail_fence.rs
// wiki: https://en.wikipedia.org/wiki/Rail_fence_cipher pub fn rail_fence_encrypt(plain_text: &str, key: usize) -> String { let mut cipher = vec![Vec::new(); key]; for (c, i) in plain_text.chars().zip(zigzag(key)) { cipher[i].push(c); } return cipher.iter().flatten().collect::<String>(); } pub fn rail_fence_decrypt(cipher: &str, key: usize) -> String { let mut indices: Vec<_> = zigzag(key).zip(1..).take(cipher.len()).collect(); indices.sort(); let mut cipher_text: Vec<_> = cipher .chars() .zip(indices) .map(|(c, (_, i))| (i, c)) .collect(); cipher_text.sort(); return cipher_text.iter().map(|(_, c)| c).collect(); } fn zigzag(n: usize) -> impl Iterator<Item = usize> { (0..n - 1).chain((1..n).rev()).cycle() } #[cfg(test)] mod test { use super::*; #[test] fn rails_basic() { assert_eq!(rail_fence_encrypt("attack at once", 2), "atc toctaka ne"); assert_eq!(rail_fence_decrypt("atc toctaka ne", 2), "attack at once"); assert_eq!(rail_fence_encrypt("rust is cool", 3), "r cuti olsso"); assert_eq!(rail_fence_decrypt("r cuti olsso", 3), "rust is cool"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/diffie_hellman.rs
src/ciphers/diffie_hellman.rs
// Based on the TheAlgorithms/Python // RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for // Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 use num_bigint::BigUint; use num_traits::{Num, Zero}; use std::{ collections::HashMap, sync::LazyLock, time::{SystemTime, UNIX_EPOCH}, }; // A map of predefined prime numbers for different bit lengths, as specified in RFC 3526 static PRIMES: LazyLock<HashMap<u8, BigUint>> = LazyLock::new(|| { let mut m: HashMap<u8, BigUint> = HashMap::new(); m.insert( // 1536-bit 5, BigUint::parse_bytes( b"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\ 29024E088A67CC74020BBEA63B139B22514A08798E3404DD\ EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\ E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\ EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\ C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\ 83655D23DCA3AD961C62F356208552BB9ED529077096966D\ 670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", 16, ) .unwrap(), ); m.insert( // 2048-bit 14, BigUint::parse_bytes( b"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\ 29024E088A67CC74020BBEA63B139B22514A08798E3404DD\ EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\ E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\ EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\ C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\ 83655D23DCA3AD961C62F356208552BB9ED529077096966D\ 670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\ E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\ DE2BCBF6955817183995497CEA956AE515D2261898FA0510\ 15728E5A8AACAA68FFFFFFFFFFFFFFFF", 16, ) .unwrap(), ); m.insert( // 3072-bit 15, BigUint::parse_bytes( b"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\ 29024E088A67CC74020BBEA63B139B22514A08798E3404DD\ EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\ E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\ EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\ C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\ 83655D23DCA3AD961C62F356208552BB9ED529077096966D\ 670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\ E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\ DE2BCBF6955817183995497CEA956AE515D2261898FA0510\ 15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64\ ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7\ ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B\ F12FFA06D98A0864D87602733EC86A64521F2B18177B200C\ BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31\ 43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF", 16, ) .unwrap(), ); m.insert( // 4096-bit 16, BigUint::parse_bytes( b"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\ 29024E088A67CC74020BBEA63B139B22514A08798E3404DD\ EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\ E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\ EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\ C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\ 83655D23DCA3AD961C62F356208552BB9ED529077096966D\ 670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\ E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\ DE2BCBF6955817183995497CEA956AE515D2261898FA0510\ 15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64\ ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7\ ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B\ F12FFA06D98A0864D87602733EC86A64521F2B18177B200C\ BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31\ 43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7\ 88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA\ 2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6\ 287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED\ 1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9\ 93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199\ FFFFFFFFFFFFFFFF", 16, ) .unwrap(), ); m.insert( // 6144-bit 17, BigUint::parse_bytes( b"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08\ 8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B\ 302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9\ A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6\ 49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8\ FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D\ 670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C\ 180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718\ 3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D\ 04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D\ B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226\ 1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C\ BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC\ E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26\ 99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB\ 04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2\ 233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127\ D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492\ 36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406\ AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918\ DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151\ 2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03\ F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F\ BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA\ CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B\ B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632\ 387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E\ 6DCC4024FFFFFFFFFFFFFFFF", 16, ) .unwrap(), ); m.insert( // 8192-bit 18, BigUint::parse_bytes( b"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\ 29024E088A67CC74020BBEA63B139B22514A08798E3404DD\ EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\ E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\ EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\ C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\ 83655D23DCA3AD961C62F356208552BB9ED529077096966D\ 670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\ E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\ DE2BCBF6955817183995497CEA956AE515D2261898FA0510\ 15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64\ ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7\ ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B\ F12FFA06D98A0864D87602733EC86A64521F2B18177B200C\ BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31\ 43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7\ 88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA\ 2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6\ 287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED\ 1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9\ 93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492\ 36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD\ F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831\ 179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B\ DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF\ 5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6\ D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3\ 23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA\ CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328\ 06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C\ DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE\ 12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4\ 38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300\ 741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568\ 3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9\ 22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B\ 4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A\ 062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36\ 4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1\ B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92\ 4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47\ 9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71\ 60C980DD98EDD3DFFFFFFFFFFFFFFFFF", 16, ) .unwrap(), ); m }); /// Generating random number, should use num_bigint::RandomBits if possible. fn rand() -> usize { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .subsec_nanos() as usize } pub struct DiffieHellman { prime: BigUint, private_key: BigUint, public_key: BigUint, generator: u8, } impl DiffieHellman { // Diffie-Hellman key exchange algorithm is based on the following mathematical concepts: // - A large prime number p (known as the prime modulus) is chosen and shared by both parties. // - A base number g (known as the generator) is chosen and shared by both parties. // - Each party generates a private key a or b (which are secret and only known to that party) and calculates a corresponding public key A or B using the following formulas: // - A = g^a mod p // - B = g^b mod p // - Each party then exchanges their public keys with each other. // - Each party then calculates the shared secret key s using the following formula: // - s = B^a mod p or s = A^b mod p // Both parties now have the same shared secret key s which can be used for encryption or authentication. pub fn new(group: Option<u8>) -> Self { let _group = group.unwrap_or(14); if !PRIMES.contains_key(&_group) { panic!("group not in primes") } // generate private key let private_key: BigUint = BigUint::from(rand()); Self { prime: PRIMES[&_group].clone(), private_key, generator: 2, // the generator is 2 for all the primes if this would not be the case it can be added to hashmap public_key: BigUint::default(), } } /// get private key as hexadecimal String pub fn get_private_key(&self) -> String { self.private_key.to_str_radix(16) } /// Generate public key A = g**a mod p pub fn generate_public_key(&mut self) -> String { self.public_key = BigUint::from(self.generator).modpow(&self.private_key, &self.prime); self.public_key.to_str_radix(16) } pub fn is_valid_public_key(&self, key_str: &str) -> bool { // the unwrap_or_else will make sure it is false, because 2 <= 0 and therefor False is returned let key = BigUint::from_str_radix(key_str, 16) .unwrap_or_else(|_| BigUint::parse_bytes(b"0", 16).unwrap()); // Check if the other public key is valid based on NIST SP800-56 if BigUint::from(2_u8) <= key && key <= &self.prime - BigUint::from(2_u8) && !key .modpow( &((&self.prime - BigUint::from(1_u8)) / BigUint::from(2_u8)), &self.prime, ) .is_zero() { return true; } false } /// Generate the shared key pub fn generate_shared_key(self, other_key_str: &str) -> Option<String> { let other_key = BigUint::from_str_radix(other_key_str, 16) .unwrap_or_else(|_| BigUint::parse_bytes(b"0", 16).unwrap()); if !self.is_valid_public_key(&other_key.to_str_radix(16)) { return None; } let shared_key = other_key.modpow(&self.private_key, &self.prime); Some(shared_key.to_str_radix(16)) } } #[cfg(test)] mod tests { use super::*; #[test] fn verify_invalid_pub_key() { let diffie = DiffieHellman::new(Some(14)); assert!(!diffie.is_valid_public_key("0000")); } #[test] fn verify_valid_pub_key() { let diffie = DiffieHellman::new(Some(14)); assert!(diffie.is_valid_public_key("EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245")); } #[test] fn verify_invalid_pub_key_same_as_prime() { let diffie = DiffieHellman::new(Some(14)); assert!(!diffie.is_valid_public_key( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\ 29024E088A67CC74020BBEA63B139B22514A08798E3404DD\ EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\ E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\ EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\ C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\ 83655D23DCA3AD961C62F356208552BB9ED529077096966D\ 670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\ E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\ DE2BCBF6955817183995497CEA956AE515D2261898FA0510\ 15728E5A8AACAA68FFFFFFFFFFFFFFFF" )); } #[test] fn verify_key_exchange() { let mut alice = DiffieHellman::new(Some(16)); let mut bob = DiffieHellman::new(Some(16)); // Private key not used, showed for illustrative purpose let _alice_private = alice.get_private_key(); let alice_public = alice.generate_public_key(); // Private key not used, showed for illustrative purpose let _bob_private = bob.get_private_key(); let bob_public = bob.generate_public_key(); // generating shared key using the struct implemenations let alice_shared = alice.generate_shared_key(bob_public.as_str()).unwrap(); let bob_shared = bob.generate_shared_key(alice_public.as_str()).unwrap(); assert_eq!(alice_shared, bob_shared); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/morse_code.rs
src/ciphers/morse_code.rs
use std::collections::HashMap; use std::io; const UNKNOWN_CHARACTER: &str = "........"; const _UNKNOWN_MORSE_CHARACTER: &str = "_"; pub fn encode(message: &str) -> String { let dictionary = _morse_dictionary(); message .chars() .map(|char| char.to_uppercase().to_string()) .map(|letter| dictionary.get(letter.as_str())) .map(|option| (*option.unwrap_or(&UNKNOWN_CHARACTER)).to_string()) .collect::<Vec<String>>() .join(" ") } // Declarative macro for creating readable map declarations, for more info see https://doc.rust-lang.org/book/ch19-06-macros.html macro_rules! map { ($($key:expr => $value:expr),* $(,)?) => { std::iter::Iterator::collect(IntoIterator::into_iter([$(($key, $value),)*])) }; } fn _morse_dictionary() -> HashMap<&'static str, &'static str> { map! { "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.--", "Z" => "--..", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", "0" => "-----", "&" => ".-...", "@" => ".--.-.", ":" => "---...", "," => "--..--", "." => ".-.-.-", "'" => ".----.", "\"" => ".-..-.", "?" => "..--..", "/" => "-..-.", "=" => "-...-", "+" => ".-.-.", "-" => "-....-", "(" => "-.--.", ")" => "-.--.-", " " => "/", "!" => "-.-.--", } } fn _morse_to_alphanumeric_dictionary() -> HashMap<&'static str, &'static str> { map! { ".-" => "A", "-..." => "B", "-.-." => "C", "-.." => "D", "." => "E", "..-." => "F", "--." => "G", "...." => "H", ".." => "I", ".---" => "J", "-.-" => "K", ".-.." => "L", "--" => "M", "-." => "N", "---" => "O", ".--." => "P", "--.-" => "Q", ".-." => "R", "..." => "S", "-" => "T", "..-" => "U", "...-" => "V", ".--" => "W", "-..-" => "X", "-.--" => "Y", "--.." => "Z", ".----" => "1", "..---" => "2", "...--" => "3", "....-" => "4", "....." => "5", "-...." => "6", "--..." => "7", "---.." => "8", "----." => "9", "-----" => "0", ".-..." => "&", ".--.-." => "@", "---..." => ":", "--..--" => ",", ".-.-.-" => ".", ".----." => "'", ".-..-." => "\"", "..--.." => "?", "-..-." => "/", "-...-" => "=", ".-.-." => "+", "-....-" => "-", "-.--." => "(", "-.--.-" => ")", "/" => " ", "-.-.--" => "!", " " => " ", "" => "" } } fn _check_part(string: &str) -> bool { for c in string.chars() { match c { '.' | '-' | ' ' => (), _ => return false, } } true } fn _check_all_parts(string: &str) -> bool { string.split('/').all(_check_part) } fn _decode_token(string: &str) -> String { (*_morse_to_alphanumeric_dictionary() .get(string) .unwrap_or(&_UNKNOWN_MORSE_CHARACTER)) .to_string() } fn _decode_part(string: &str) -> String { string.split(' ').map(_decode_token).collect::<String>() } /// Convert morse code to ascii. /// /// Given a morse code, return the corresponding message. /// If the code is invalid, the undecipherable part of the code is replaced by `_`. pub fn decode(string: &str) -> Result<String, io::Error> { if !_check_all_parts(string) { return Err(io::Error::new( io::ErrorKind::InvalidData, "Invalid morse code", )); } let mut partitions: Vec<String> = vec![]; for part in string.split('/') { partitions.push(_decode_part(part)); } Ok(partitions.join(" ")) } #[cfg(test)] mod tests { use super::*; #[test] fn encrypt_only_letters() { let message = "Hello Morse"; let cipher = encode(message); assert_eq!( cipher, ".... . .-.. .-.. --- / -- --- .-. ... .".to_string() ) } #[test] fn encrypt_letters_and_special_characters() { let message = "What's a great day!"; let cipher = encode(message); assert_eq!( cipher, ".-- .... .- - .----. ... / .- / --. .-. . .- - / -.. .- -.-- -.-.--".to_string() ) } #[test] fn encrypt_message_with_unsupported_character() { let message = "Error?? {}"; let cipher = encode(message); assert_eq!( cipher, ". .-. .-. --- .-. ..--.. ..--.. / ........ ........".to_string() ) } #[test] fn decrypt_valid_morsecode_with_spaces() { let expected = "Hello Morse! How's it goin, \"eh\"?" .to_string() .to_uppercase(); let encypted = encode(&expected); let result = decode(&encypted).unwrap(); assert_eq!(expected, result); } #[test] fn decrypt_valid_character_set_invalid_morsecode() { let expected = format!( "{_UNKNOWN_MORSE_CHARACTER}{_UNKNOWN_MORSE_CHARACTER}{_UNKNOWN_MORSE_CHARACTER}{_UNKNOWN_MORSE_CHARACTER} {_UNKNOWN_MORSE_CHARACTER}", ); let encypted = ".-.-.--.-.-. --------. ..---.-.-. .-.-.--.-.-. / .-.-.--.-.-.".to_string(); let result = decode(&encypted).unwrap(); assert_eq!(expected, result); } #[test] fn decrypt_invalid_morsecode_with_spaces() { let encypted = "1... . .-.. .-.. --- / -- --- .-. ... ."; let result = decode(encypted).map_err(|e| e.kind()); let expected = Err(io::ErrorKind::InvalidData); assert_eq!(expected, result); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/transposition.rs
src/ciphers/transposition.rs
//! Transposition Cipher //! //! The Transposition Cipher is a method of encryption by which a message is shifted //! according to a regular system, so that the ciphertext is a rearrangement of the //! original message. The most commonly referred to Transposition Cipher is the //! COLUMNAR TRANSPOSITION cipher, which is demonstrated below. use std::ops::RangeInclusive; /// Encrypts or decrypts a message, using multiple keys. The /// encryption is based on the columnar transposition method. pub fn transposition(decrypt_mode: bool, msg: &str, key: &str) -> String { let key_uppercase = key.to_uppercase(); let mut cipher_msg: String = msg.to_string(); let keys: Vec<&str> = if decrypt_mode { key_uppercase.split_whitespace().rev().collect() } else { key_uppercase.split_whitespace().collect() }; for cipher_key in keys.iter() { let mut key_order: Vec<usize> = Vec::new(); // Removes any non-alphabet characters from 'msg' cipher_msg = cipher_msg .to_uppercase() .chars() .filter(|&c| c.is_ascii_alphabetic()) .collect(); // Determines the sequence of the columns, as dictated by the // alphabetical order of the keyword's letters let mut key_ascii: Vec<(usize, u8)> = cipher_key.bytes().enumerate().collect::<Vec<(usize, u8)>>(); key_ascii.sort_by_key(|&(_, key)| key); for (counter, (_, key)) in key_ascii.iter_mut().enumerate() { *key = counter as u8; } key_ascii.sort_by_key(|&(index, _)| index); for (_, key) in key_ascii { key_order.push(key.into()); } // Determines whether to encrypt or decrypt the message, // and returns the result cipher_msg = if decrypt_mode { decrypt(cipher_msg, key_order) } else { encrypt(cipher_msg, key_order) }; } cipher_msg } /// Performs the columnar transposition encryption fn encrypt(mut msg: String, key_order: Vec<usize>) -> String { let mut encrypted_msg: String = String::from(""); let mut encrypted_vec: Vec<String> = Vec::new(); let msg_len = msg.len(); let key_len: usize = key_order.len(); let mut msg_index: usize = msg_len; let mut key_index: usize = key_len; // Loop each column, pushing it to a Vec<T> while !msg.is_empty() { let mut chars: String = String::from(""); let mut index: usize = 0; key_index -= 1; // Loop every nth character, determined by key length, to create a column while index < msg_index { let ch = msg.remove(index); chars.push(ch); index += key_index; msg_index -= 1; } encrypted_vec.push(chars); } // Concatenate the columns into a string, determined by the // alphabetical order of the keyword's characters let mut indexed_vec: Vec<(usize, &String)> = Vec::new(); let mut indexed_msg: String = String::from(""); for (counter, key_index) in key_order.into_iter().enumerate() { indexed_vec.push((key_index, &encrypted_vec[counter])); } indexed_vec.sort(); for (_, column) in indexed_vec { indexed_msg.push_str(column); } // Split the message by a space every nth character, determined by // 'message length divided by keyword length' to the next highest integer. let msg_div: usize = (msg_len as f32 / key_len as f32).ceil() as usize; let mut counter: usize = 0; indexed_msg.chars().for_each(|c| { encrypted_msg.push(c); counter += 1; if counter == msg_div { encrypted_msg.push(' '); counter = 0; } }); encrypted_msg.trim_end().to_string() } /// Performs the columnar transposition decryption fn decrypt(mut msg: String, key_order: Vec<usize>) -> String { let mut decrypted_msg: String = String::from(""); let mut decrypted_vec: Vec<String> = Vec::new(); let mut indexed_vec: Vec<(usize, String)> = Vec::new(); let msg_len = msg.len(); let key_len: usize = key_order.len(); // Split the message into columns, determined by 'message length divided by keyword length'. // Some columns are larger by '+1', where the prior calculation leaves a remainder. let split_size: usize = (msg_len as f64 / key_len as f64) as usize; let msg_mod: usize = msg_len % key_len; let mut counter: usize = msg_mod; let mut key_split: Vec<usize> = key_order.clone(); let (split_large, split_small) = key_split.split_at_mut(msg_mod); split_large.sort_unstable(); split_small.sort_unstable(); split_large.iter_mut().rev().for_each(|key_index| { counter -= 1; let range: RangeInclusive<usize> = ((*key_index * split_size) + counter)..=(((*key_index + 1) * split_size) + counter); let slice: String = msg[range.clone()].to_string(); indexed_vec.push((*key_index, slice)); msg.replace_range(range, ""); }); for key_index in split_small.iter_mut() { let (slice, rest_of_msg) = msg.split_at(split_size); indexed_vec.push((*key_index, (slice.to_string()))); msg = rest_of_msg.to_string(); } indexed_vec.sort(); for key in key_order { if let Some((_, column)) = indexed_vec.iter().find(|(key_index, _)| key_index == &key) { decrypted_vec.push(column.clone()); } } // Concatenate the columns into a string, determined by the // alphabetical order of the keyword's characters for _ in 0..split_size { decrypted_vec.iter_mut().for_each(|column| { decrypted_msg.push(column.remove(0)); }) } if !decrypted_vec.is_empty() { decrypted_vec.into_iter().for_each(|chars| { decrypted_msg.push_str(&chars); }) } decrypted_msg } #[cfg(test)] mod tests { use super::*; #[test] fn encryption() { assert_eq!( transposition( false, "The quick brown fox jumps over the lazy dog", "Archive", ), "TKOOL ERJEZ CFSEG QOURY UWMTD HBXVA INPHO" ); assert_eq!( transposition( false, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,/;'[]{}:|_+=-`~() ", "Tenacious" ), "DMVENW ENWFOX BKTCLU FOXGPY CLUDMV GPYHQZ IRAJSA JSBKTH QZIR" ); assert_eq!( transposition(false, "WE ARE DISCOVERED. FLEE AT ONCE.", "ZEBRAS"), "EVLNA CDTES EAROF ODEEC WIREE" ); } #[test] fn decryption() { assert_eq!( transposition(true, "TKOOL ERJEZ CFSEG QOURY UWMTD HBXVA INPHO", "Archive"), "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG" ); assert_eq!( transposition( true, "DMVENW ENWFOX BKTCLU FOXGPY CLUDMV GPYHQZ IRAJSA JSBKTH QZIR", "Tenacious" ), "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" ); assert_eq!( transposition(true, "EVLNA CDTES EAROF ODEEC WIREE", "ZEBRAS"), "WEAREDISCOVEREDFLEEATONCE" ); } #[test] fn double_encryption() { assert_eq!( transposition( false, "The quick brown fox jumps over the lazy dog", "Archive Snow" ), "KEZEUWHAH ORCGRMBIO TLESOUDVP OJFQYTXN" ); assert_eq!( transposition( false, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,/;'[]{}:|_+=-`~() ", "Tenacious Drink" ), "DWOCXLGZSKI VNBUPDYRJHN FTOCVQJBZEW KFYMHASQMEX LGUPIATR" ); assert_eq!( transposition(false, "WE ARE DISCOVERED. FLEE AT ONCE.", "ZEBRAS STRIPE"), "CAEEN SOIAE DRLEF WEDRE EVTOC" ); } #[test] fn double_decryption() { assert_eq!( transposition( true, "KEZEUWHAH ORCGRMBIO TLESOUDVP OJFQYTXN", "Archive Snow" ), "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG" ); assert_eq!( transposition( true, "DWOCXLGZSKI VNBUPDYRJHN FTOCVQJBZEW KFYMHASQMEX LGUPIATR", "Tenacious Drink", ), "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" ); assert_eq!( transposition(true, "CAEEN SOIAE DRLEF WEDRE EVTOC", "ZEBRAS STRIPE"), "WEAREDISCOVEREDFLEEATONCE" ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/xor.rs
src/ciphers/xor.rs
pub fn xor_bytes(text: &[u8], key: u8) -> Vec<u8> { text.iter().map(|c| c ^ key).collect() } pub fn xor(text: &str, key: u8) -> Vec<u8> { xor_bytes(text.as_bytes(), key) } #[cfg(test)] mod tests { use super::*; #[test] fn test_simple() { let test_string = "test string"; let ciphered_text = xor(test_string, 32); assert_eq!(test_string.as_bytes(), xor_bytes(&ciphered_text, 32)); } #[test] fn test_every_alphabet_with_space() { let test_string = "The quick brown fox jumps over the lazy dog"; let ciphered_text = xor(test_string, 64); assert_eq!(test_string.as_bytes(), xor_bytes(&ciphered_text, 64)); } #[test] fn test_multi_byte() { let test_string = "日本語"; let key = 42; let ciphered_text = xor(test_string, key); assert_eq!(test_string.as_bytes(), xor_bytes(&ciphered_text, key)); } #[test] fn test_zero_byte() { let test_string = "The quick brown fox jumps over the lazy dog"; let key = b' '; let ciphered_text = xor(test_string, key); assert_eq!(test_string.as_bytes(), xor_bytes(&ciphered_text, key)); } #[test] fn test_invalid_byte() { let test_string = "The quick brown fox jumps over the lazy dog"; let key = !0; let ciphered_text = xor(test_string, key); assert_eq!(test_string.as_bytes(), xor_bytes(&ciphered_text, key)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/hashing_traits.rs
src/ciphers/hashing_traits.rs
pub trait Hasher<const DIGEST_BYTES: usize> { /// return a new instance with default parameters fn new_default() -> Self; /// Add new data fn update(&mut self, data: &[u8]); /// Returns the hash of current data. If it is necessary does finalization /// work on the instance, thus it may no longer make sense to do `update` /// after calling this. fn get_hash(&mut self) -> [u8; DIGEST_BYTES]; } /// HMAC based on RFC2104, applicable to many cryptographic hash functions pub struct HMAC<const KEY_BYTES: usize, const DIGEST_BYTES: usize, H: Hasher<DIGEST_BYTES>> { pub inner_internal_state: H, pub outer_internal_state: H, } impl<const KEY_BYTES: usize, const DIGEST_BYTES: usize, H: Hasher<DIGEST_BYTES>> HMAC<KEY_BYTES, DIGEST_BYTES, H> { pub fn new_default() -> Self { HMAC { inner_internal_state: H::new_default(), outer_internal_state: H::new_default(), } } /// Note that `key` must be no longer than `KEY_BYTES`. According to RFC, /// if it is so, you should replace it with its hash. We do not do this /// automatically due to fear of `DIGEST_BYTES` not being the same as /// `KEY_BYTES` or even being longer than it pub fn add_key(&mut self, key: &[u8]) -> Result<(), &'static str> { match key.len().cmp(&KEY_BYTES) { std::cmp::Ordering::Less | std::cmp::Ordering::Equal => { let mut tmp_key = [0u8; KEY_BYTES]; for (d, s) in tmp_key.iter_mut().zip(key.iter()) { *d = *s; } // key ^ 0x363636.. should be used as inner key for b in tmp_key.iter_mut() { *b ^= 0x36; } self.inner_internal_state.update(&tmp_key); // key ^ 0x5c5c5c.. should be used as outer key, but the key is // already XORed with 0x363636.. , so it must now be XORed with // 0x6a6a6a.. for b in tmp_key.iter_mut() { *b ^= 0x6a; } self.outer_internal_state.update(&tmp_key); Ok(()) } _ => Err("Key is longer than `KEY_BYTES`."), } } pub fn update(&mut self, data: &[u8]) { self.inner_internal_state.update(data); } pub fn finalize(&mut self) -> [u8; DIGEST_BYTES] { self.outer_internal_state .update(&self.inner_internal_state.get_hash()); self.outer_internal_state.get_hash() } } #[cfg(test)] mod tests { use super::super::sha256::tests::get_hash_string; use super::super::SHA256; use super::HMAC; #[test] fn sha256_basic() { // To test this, use the following command on linux: // echo -n "Hello World" | openssl sha256 -hex -mac HMAC -macopt hexkey:"deadbeef" let mut hmac: HMAC<64, 32, SHA256> = HMAC::new_default(); hmac.add_key(&[0xde, 0xad, 0xbe, 0xef]).unwrap(); hmac.update(b"Hello World"); let hash = hmac.finalize(); assert_eq!( get_hash_string(&hash), "f585fc4536e8e7f378437465b65b6c2eb79036409b18a7d28b6d4c46d3a156f8" ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/kernighan.rs
src/ciphers/kernighan.rs
pub fn kernighan(n: u32) -> i32 { let mut count = 0; let mut n = n; while n > 0 { n = n & (n - 1); count += 1; } count } #[cfg(test)] mod tests { use super::*; #[test] fn count_set_bits() { assert_eq!(kernighan(0b0000_0000_0000_0000_0000_0000_0000_1011), 3); assert_eq!(kernighan(0b0000_0000_0000_0000_0000_0000_1000_0000), 1); assert_eq!(kernighan(0b1111_1111_1111_1111_1111_1111_1111_1101), 31); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/sha3.rs
src/ciphers/sha3.rs
/// Size of the state array in bits const B: usize = 1600; const W: usize = B / 25; const L: usize = W.ilog2() as usize; const U8BITS: usize = u8::BITS as usize; // Macro for looping through the whole state array macro_rules! iterate { ( $x:ident, $y:ident, $z:ident => $b:block ) => { for $y in 0..5 { for $x in 0..5 { for $z in 0..W { $b } } } }; } /// A function that produces a padding string such that the length of the padding + the length of /// the string to be padded (2nd parameter) is divisible by the 1st parameter type PadFn = fn(isize, isize) -> Vec<bool>; type SpongeFn = fn(&[bool]) -> [bool; B]; type State = [[[bool; W]; 5]; 5]; fn state_new() -> State { [[[false; W]; 5]; 5] } fn state_fill(dest: &mut State, bits: &[bool]) { let mut i = 0usize; iterate!(x, y, z => { if i >= bits.len() { return; } dest[x][y][z] = bits[i]; i += 1; }); } fn state_copy(dest: &mut State, src: &State) { iterate!(x, y, z => { dest[x][y][z] = src[x][y][z]; }); } fn state_dump(state: &State) -> [bool; B] { let mut bits = [false; B]; let mut i = 0usize; iterate!(x, y, z => { bits[i] = state[x][y][z]; i += 1; }); bits } /// XORs the state with the parities of two columns in the state array fn theta(state: &mut State) { let mut c = [[false; W]; 5]; let mut d = [[false; W]; 5]; // Assign values of C[x,z] for x in 0..5 { for z in 0..W { c[x][z] = state[x][0][z]; for y in 1..5 { c[x][z] ^= state[x][y][z]; } } } // Assign values of D[x,z] for x in 0..5 { for z in 0..W { let x1 = (x as isize - 1).rem_euclid(5) as usize; let z2 = (z as isize - 1).rem_euclid(W as isize) as usize; d[x][z] = c[x1][z] ^ c[(x + 1) % 5][z2]; } } // Xor values of D[x,z] into our state array iterate!(x, y, z => { state[x][y][z] ^= d[x][z]; }); } /// Rotates each lane by an offset depending of the x and y indeces fn rho(state: &mut State) { let mut new_state = state_new(); for z in 0..W { new_state[0][0][z] = state[0][0][z]; } let mut x = 1; let mut y = 0; for t in 0..=23isize { for z in 0..W { let z_offset: isize = ((t + 1) * (t + 2)) / 2; let new_z = (z as isize - z_offset).rem_euclid(W as isize) as usize; new_state[x][y][z] = state[x][y][new_z]; } let old_y = y; y = ((2 * x) + (3 * y)) % 5; x = old_y; } state_copy(state, &new_state); } /// Rearrange the positions of the lanes of the state array fn pi(state: &mut State) { let mut new_state = state_new(); iterate!(x, y, z => { new_state[x][y][z] = state[(x + (3 * y)) % 5][x][z]; }); state_copy(state, &new_state); } fn chi(state: &mut State) { let mut new_state = state_new(); iterate!(x, y, z => { new_state[x][y][z] = state[x][y][z] ^ ((state[(x + 1) % 5][y][z] ^ true) & state[(x + 2) % 5][y][z]); }); state_copy(state, &new_state); } /// Calculates the round constant depending on what the round number is fn rc(t: u8) -> bool { let mut b1: u16; let mut b2: u16; let mut r: u16 = 0x80; // tread r as an array of bits //if t % 0xFF == 0 { return true; } for _i in 0..(t % 255) { b1 = r >> 8; b2 = r & 1; r |= (b1 ^ b2) << 8; b1 = (r >> 4) & 1; r &= 0x1EF; // clear r[4] r |= (b1 ^ b2) << 4; b1 = (r >> 3) & 1; r &= 0x1F7; // clear r[3] r |= (b1 ^ b2) << 3; b1 = (r >> 2) & 1; r &= 0x1FB; // clear r[2] r |= (b1 ^ b2) << 2; r >>= 1; } (r >> 7) != 0 } /// Applies the round constant to the first lane of the state array fn iota(state: &mut State, i_r: u8) { let mut rc_arr = [false; W]; for j in 0..=L { rc_arr[(1 << j) - 1] = rc((j as u8) + (7 * i_r)); } for (z, bit) in rc_arr.iter().enumerate() { state[0][0][z] ^= *bit; } } fn rnd(state: &mut State, i_r: u8) { theta(state); rho(state); pi(state); chi(state); iota(state, i_r); } fn keccak_f(bits: &[bool]) -> [bool; B] { let n_r = 12 + (2 * L); let mut state = state_new(); state_fill(&mut state, bits); for i_r in 0..n_r { rnd(&mut state, i_r as u8); } state_dump(&state) } fn pad101(x: isize, m: isize) -> Vec<bool> { let mut j = -m - 2; while j < 0 { j += x; } j %= x; let mut ret = vec![false; (j as usize) + 2]; *ret.first_mut().unwrap() = true; *ret.last_mut().unwrap() = true; ret } /// Sponge construction is a method of compression needing 1) a function on fixed-length bit /// strings( here we use keccak_f), 2) a padding function (pad10*1), and 3) a rate. The input and /// output of this method can be arbitrarily long fn sponge(f: SpongeFn, pad: PadFn, r: usize, n: &[bool], d: usize) -> Vec<bool> { let mut p = Vec::from(n); p.append(&mut pad(r as isize, n.len() as isize)); assert!(r < B); let mut s = [false; B]; for chunk in p.chunks(r) { for (s_i, c_i) in s.iter_mut().zip(chunk) { *s_i ^= c_i; } s = f(&s); } let mut z = Vec::<bool>::new(); while z.len() < d { z.extend(&s); s = f(&s); } z.truncate(d); z } fn keccak(c: usize, n: &[bool], d: usize) -> Vec<bool> { sponge(keccak_f, pad101, B - c, n, d) } fn h2b(h: &[u8], n: usize) -> Vec<bool> { let mut bits = Vec::with_capacity(h.len() * U8BITS); for byte in h { for i in 0..u8::BITS { let mask: u8 = 1 << i; bits.push((byte & mask) != 0); } } assert!(bits.len() == h.len() * U8BITS); bits.truncate(n); bits } fn b2h(s: &[bool]) -> Vec<u8> { let m = if s.len().is_multiple_of(U8BITS) { s.len() / 8 } else { (s.len() / 8) + 1 }; let mut bytes = vec![0u8; m]; for (i, bit) in s.iter().enumerate() { let byte_index = i / U8BITS; let mask = (*bit as u8) << (i % U8BITS); bytes[byte_index] |= mask; } bytes } /// Macro to implement all sha3 hash functions as they only differ in digest size macro_rules! sha3 { ($name:ident, $n:literal) => { pub fn $name(m: &[u8]) -> [u8; ($n / U8BITS)] { let mut temp = h2b(m, m.len() * U8BITS); temp.append(&mut vec![false, true]); temp = keccak($n * 2, &temp, $n); let mut ret = [0u8; ($n / U8BITS)]; let temp = b2h(&temp); assert!(temp.len() == $n / U8BITS); for (i, byte) in temp.iter().enumerate() { ret[i] = *byte; } ret } }; } sha3!(sha3_224, 224); sha3!(sha3_256, 256); sha3!(sha3_384, 384); sha3!(sha3_512, 512); #[cfg(test)] mod tests { use super::*; macro_rules! digest_test { ($fname:ident, $hash:ident, $size:literal, $message:expr, $expected:expr) => { #[test] fn $fname() { let digest = $hash(&$message); let expected: [u8; $size / U8BITS] = $expected; assert_eq!(digest, expected); } }; } digest_test!( sha3_224_0, sha3_224, 224, [0; 0], [ 0x6b, 0x4e, 0x03, 0x42, 0x36, 0x67, 0xdb, 0xb7, 0x3b, 0x6e, 0x15, 0x45, 0x4f, 0x0e, 0xb1, 0xab, 0xd4, 0x59, 0x7f, 0x9a, 0x1b, 0x07, 0x8e, 0x3f, 0x5b, 0x5a, 0x6b, 0xc7, ] ); digest_test!( sha3_224_8, sha3_224, 224, [1u8], [ 0x48, 0x82, 0x86, 0xd9, 0xd3, 0x27, 0x16, 0xe5, 0x88, 0x1e, 0xa1, 0xee, 0x51, 0xf3, 0x6d, 0x36, 0x60, 0xd7, 0x0f, 0x0d, 0xb0, 0x3b, 0x3f, 0x61, 0x2c, 0xe9, 0xed, 0xa4, ] ); // Done on large input to verify sponge function is working properly digest_test!( sha3_224_2312, sha3_224, 224, [ 0x31, 0xc8, 0x2d, 0x71, 0x78, 0x5b, 0x7c, 0xa6, 0xb6, 0x51, 0xcb, 0x6c, 0x8c, 0x9a, 0xd5, 0xe2, 0xac, 0xeb, 0x0b, 0x06, 0x33, 0xc0, 0x88, 0xd3, 0x3a, 0xa2, 0x47, 0xad, 0xa7, 0xa5, 0x94, 0xff, 0x49, 0x36, 0xc0, 0x23, 0x25, 0x13, 0x19, 0x82, 0x0a, 0x9b, 0x19, 0xfc, 0x6c, 0x48, 0xde, 0x8a, 0x6f, 0x7a, 0xda, 0x21, 0x41, 0x76, 0xcc, 0xda, 0xad, 0xae, 0xef, 0x51, 0xed, 0x43, 0x71, 0x4a, 0xc0, 0xc8, 0x26, 0x9b, 0xbd, 0x49, 0x7e, 0x46, 0xe7, 0x8b, 0xb5, 0xe5, 0x81, 0x96, 0x49, 0x4b, 0x24, 0x71, 0xb1, 0x68, 0x0e, 0x2d, 0x4c, 0x6d, 0xbd, 0x24, 0x98, 0x31, 0xbd, 0x83, 0xa4, 0xd3, 0xbe, 0x06, 0xc8, 0xa2, 0xe9, 0x03, 0x93, 0x39, 0x74, 0xaa, 0x05, 0xee, 0x74, 0x8b, 0xfe, 0x6e, 0xf3, 0x59, 0xf7, 0xa1, 0x43, 0xed, 0xf0, 0xd4, 0x91, 0x8d, 0xa9, 0x16, 0xbd, 0x6f, 0x15, 0xe2, 0x6a, 0x79, 0x0c, 0xff, 0x51, 0x4b, 0x40, 0xa5, 0xda, 0x7f, 0x72, 0xe1, 0xed, 0x2f, 0xe6, 0x3a, 0x05, 0xb8, 0x14, 0x95, 0x87, 0xbe, 0xa0, 0x56, 0x53, 0x71, 0x8c, 0xc8, 0x98, 0x0e, 0xad, 0xbf, 0xec, 0xa8, 0x5b, 0x7c, 0x9c, 0x28, 0x6d, 0xd0, 0x40, 0x93, 0x65, 0x85, 0x93, 0x8b, 0xe7, 0xf9, 0x82, 0x19, 0x70, 0x0c, 0x83, 0xa9, 0x44, 0x3c, 0x28, 0x56, 0xa8, 0x0f, 0xf4, 0x68, 0x52, 0xb2, 0x6d, 0x1b, 0x1e, 0xdf, 0x72, 0xa3, 0x02, 0x03, 0xcf, 0x6c, 0x44, 0xa1, 0x0f, 0xa6, 0xea, 0xf1, 0x92, 0x01, 0x73, 0xce, 0xdf, 0xb5, 0xc4, 0xcf, 0x3a, 0xc6, 0x65, 0xb3, 0x7a, 0x86, 0xed, 0x02, 0x15, 0x5b, 0xbb, 0xf1, 0x7d, 0xc2, 0xe7, 0x86, 0xaf, 0x94, 0x78, 0xfe, 0x08, 0x89, 0xd8, 0x6c, 0x5b, 0xfa, 0x85, 0xa2, 0x42, 0xeb, 0x08, 0x54, 0xb1, 0x48, 0x2b, 0x7b, 0xd1, 0x6f, 0x67, 0xf8, 0x0b, 0xef, 0x9c, 0x7a, 0x62, 0x8f, 0x05, 0xa1, 0x07, 0x93, 0x6a, 0x64, 0x27, 0x3a, 0x97, 0xb0, 0x08, 0x8b, 0x0e, 0x51, 0x54, 0x51, 0xf9, 0x16, 0xb5, 0x65, 0x62, 0x30, 0xa1, 0x2b, 0xa6, 0xdc, 0x78 ], [ 0xaa, 0xb2, 0x3c, 0x9e, 0x7f, 0xb9, 0xd7, 0xda, 0xce, 0xfd, 0xfd, 0x0b, 0x1a, 0xe8, 0x5a, 0xb1, 0x37, 0x4a, 0xbf, 0xf7, 0xc4, 0xe3, 0xf7, 0x55, 0x6e, 0xca, 0xe4, 0x12 ] ); digest_test!( sha3_256_0, sha3_256, 256, [0; 0], [ 0xa7, 0xff, 0xc6, 0xf8, 0xbf, 0x1e, 0xd7, 0x66, 0x51, 0xc1, 0x47, 0x56, 0xa0, 0x61, 0xd6, 0x62, 0xf5, 0x80, 0xff, 0x4d, 0xe4, 0x3b, 0x49, 0xfa, 0x82, 0xd8, 0x0a, 0x4b, 0x80, 0xf8, 0x43, 0x4a, ] ); digest_test!( sha3_256_8, sha3_256, 256, [0xe9u8], [ 0xf0, 0xd0, 0x4d, 0xd1, 0xe6, 0xcf, 0xc2, 0x9a, 0x44, 0x60, 0xd5, 0x21, 0x79, 0x68, 0x52, 0xf2, 0x5d, 0x9e, 0xf8, 0xd2, 0x8b, 0x44, 0xee, 0x91, 0xff, 0x5b, 0x75, 0x9d, 0x72, 0xc1, 0xe6, 0xd6, ] ); digest_test!( sha3_256_2184, sha3_256, 256, [ 0xb1, 0xca, 0xa3, 0x96, 0x77, 0x1a, 0x09, 0xa1, 0xdb, 0x9b, 0xc2, 0x05, 0x43, 0xe9, 0x88, 0xe3, 0x59, 0xd4, 0x7c, 0x2a, 0x61, 0x64, 0x17, 0xbb, 0xca, 0x1b, 0x62, 0xcb, 0x02, 0x79, 0x6a, 0x88, 0x8f, 0xc6, 0xee, 0xff, 0x5c, 0x0b, 0x5c, 0x3d, 0x50, 0x62, 0xfc, 0xb4, 0x25, 0x6f, 0x6a, 0xe1, 0x78, 0x2f, 0x49, 0x2c, 0x1c, 0xf0, 0x36, 0x10, 0xb4, 0xa1, 0xfb, 0x7b, 0x81, 0x4c, 0x05, 0x78, 0x78, 0xe1, 0x19, 0x0b, 0x98, 0x35, 0x42, 0x5c, 0x7a, 0x4a, 0x0e, 0x18, 0x2a, 0xd1, 0xf9, 0x15, 0x35, 0xed, 0x2a, 0x35, 0x03, 0x3a, 0x5d, 0x8c, 0x67, 0x0e, 0x21, 0xc5, 0x75, 0xff, 0x43, 0xc1, 0x94, 0xa5, 0x8a, 0x82, 0xd4, 0xa1, 0xa4, 0x48, 0x81, 0xdd, 0x61, 0xf9, 0xf8, 0x16, 0x1f, 0xc6, 0xb9, 0x98, 0x86, 0x0c, 0xbe, 0x49, 0x75, 0x78, 0x0b, 0xe9, 0x3b, 0x6f, 0x87, 0x98, 0x0b, 0xad, 0x0a, 0x99, 0xaa, 0x2c, 0xb7, 0x55, 0x6b, 0x47, 0x8c, 0xa3, 0x5d, 0x1f, 0x37, 0x46, 0xc3, 0x3e, 0x2b, 0xb7, 0xc4, 0x7a, 0xf4, 0x26, 0x64, 0x1c, 0xc7, 0xbb, 0xb3, 0x42, 0x5e, 0x21, 0x44, 0x82, 0x03, 0x45, 0xe1, 0xd0, 0xea, 0x5b, 0x7d, 0xa2, 0xc3, 0x23, 0x6a, 0x52, 0x90, 0x6a, 0xcd, 0xc3, 0xb4, 0xd3, 0x4e, 0x47, 0x4d, 0xd7, 0x14, 0xc0, 0xc4, 0x0b, 0xf0, 0x06, 0xa3, 0xa1, 0xd8, 0x89, 0xa6, 0x32, 0x98, 0x38, 0x14, 0xbb, 0xc4, 0xa1, 0x4f, 0xe5, 0xf1, 0x59, 0xaa, 0x89, 0x24, 0x9e, 0x7c, 0x73, 0x8b, 0x3b, 0x73, 0x66, 0x6b, 0xac, 0x2a, 0x61, 0x5a, 0x83, 0xfd, 0x21, 0xae, 0x0a, 0x1c, 0xe7, 0x35, 0x2a, 0xde, 0x7b, 0x27, 0x8b, 0x58, 0x71, 0x58, 0xfd, 0x2f, 0xab, 0xb2, 0x17, 0xaa, 0x1f, 0xe3, 0x1d, 0x0b, 0xda, 0x53, 0x27, 0x20, 0x45, 0x59, 0x80, 0x15, 0xa8, 0xae, 0x4d, 0x8c, 0xec, 0x22, 0x6f, 0xef, 0xa5, 0x8d, 0xaa, 0x05, 0x50, 0x09, 0x06, 0xc4, 0xd8, 0x5e, 0x75, 0x67 ], [ 0xcb, 0x56, 0x48, 0xa1, 0xd6, 0x1c, 0x6c, 0x5b, 0xda, 0xcd, 0x96, 0xf8, 0x1c, 0x95, 0x91, 0xde, 0xbc, 0x39, 0x50, 0xdc, 0xf6, 0x58, 0x14, 0x5b, 0x8d, 0x99, 0x65, 0x70, 0xba, 0x88, 0x1a, 0x05 ] ); digest_test!( sha3_384_0, sha3_384, 384, [0; 0], [ 0x0c, 0x63, 0xa7, 0x5b, 0x84, 0x5e, 0x4f, 0x7d, 0x01, 0x10, 0x7d, 0x85, 0x2e, 0x4c, 0x24, 0x85, 0xc5, 0x1a, 0x50, 0xaa, 0xaa, 0x94, 0xfc, 0x61, 0x99, 0x5e, 0x71, 0xbb, 0xee, 0x98, 0x3a, 0x2a, 0xc3, 0x71, 0x38, 0x31, 0x26, 0x4a, 0xdb, 0x47, 0xfb, 0x6b, 0xd1, 0xe0, 0x58, 0xd5, 0xf0, 0x04, ] ); digest_test!( sha3_384_8, sha3_384, 384, [0x80u8], [ 0x75, 0x41, 0x38, 0x48, 0x52, 0xe1, 0x0f, 0xf1, 0x0d, 0x5f, 0xb6, 0xa7, 0x21, 0x3a, 0x4a, 0x6c, 0x15, 0xcc, 0xc8, 0x6d, 0x8b, 0xc1, 0x06, 0x8a, 0xc0, 0x4f, 0x69, 0x27, 0x71, 0x42, 0x94, 0x4f, 0x4e, 0xe5, 0x0d, 0x91, 0xfd, 0xc5, 0x65, 0x53, 0xdb, 0x06, 0xb2, 0xf5, 0x03, 0x9c, 0x8a, 0xb7, ] ); digest_test!( sha3_384_2512, sha3_384, 384, [ 0x03, 0x5a, 0xdc, 0xb6, 0x39, 0xe5, 0xf2, 0x8b, 0xb5, 0xc8, 0x86, 0x58, 0xf4, 0x5c, 0x1c, 0xe0, 0xbe, 0x16, 0xe7, 0xda, 0xfe, 0x08, 0x3b, 0x98, 0xd0, 0xab, 0x45, 0xe8, 0xdc, 0xdb, 0xfa, 0x38, 0xe3, 0x23, 0x4d, 0xfd, 0x97, 0x3b, 0xa5, 0x55, 0xb0, 0xcf, 0x8e, 0xea, 0x3c, 0x82, 0xae, 0x1a, 0x36, 0x33, 0xfc, 0x56, 0x5b, 0x7f, 0x2c, 0xc8, 0x39, 0x87, 0x6d, 0x39, 0x89, 0xf3, 0x57, 0x31, 0xbe, 0x37, 0x1f, 0x60, 0xde, 0x14, 0x0e, 0x3c, 0x91, 0x62, 0x31, 0xec, 0x78, 0x0e, 0x51, 0x65, 0xbf, 0x5f, 0x25, 0xd3, 0xf6, 0x7d, 0xc7, 0x3a, 0x1c, 0x33, 0x65, 0x5d, 0xfd, 0xf4, 0x39, 0xdf, 0xbf, 0x1c, 0xbb, 0xa8, 0xb7, 0x79, 0x15, 0x8a, 0x81, 0x0a, 0xd7, 0x24, 0x4f, 0x06, 0xec, 0x07, 0x81, 0x20, 0xcd, 0x18, 0x76, 0x0a, 0xf4, 0x36, 0xa2, 0x38, 0x94, 0x1c, 0xe1, 0xe6, 0x87, 0x88, 0x0b, 0x5c, 0x87, 0x9d, 0xc9, 0x71, 0xa2, 0x85, 0xa7, 0x4e, 0xe8, 0x5c, 0x6a, 0x74, 0x67, 0x49, 0xa3, 0x01, 0x59, 0xee, 0x84, 0x2e, 0x9b, 0x03, 0xf3, 0x1d, 0x61, 0x3d, 0xdd, 0xd2, 0x29, 0x75, 0xcd, 0x7f, 0xed, 0x06, 0xbd, 0x04, 0x9d, 0x77, 0x2c, 0xb6, 0xcc, 0x5a, 0x70, 0x5f, 0xaa, 0x73, 0x4e, 0x87, 0x32, 0x1d, 0xc8, 0xf2, 0xa4, 0xea, 0x36, 0x6a, 0x36, 0x8a, 0x98, 0xbf, 0x06, 0xee, 0x2b, 0x0b, 0x54, 0xac, 0x3a, 0x3a, 0xee, 0xa6, 0x37, 0xca, 0xeb, 0xe7, 0x0a, 0xd0, 0x9c, 0xcd, 0xa9, 0x3c, 0xc0, 0x6d, 0xe9, 0x5d, 0xf7, 0x33, 0x94, 0xa8, 0x7a, 0xc9, 0xbb, 0xb5, 0x08, 0x3a, 0x4d, 0x8a, 0x24, 0x58, 0xe9, 0x1c, 0x7d, 0x5b, 0xf1, 0x13, 0xae, 0xca, 0xe0, 0xce, 0x27, 0x9f, 0xdd, 0xa7, 0x6b, 0xa6, 0x90, 0x78, 0x7d, 0x26, 0x34, 0x5e, 0x94, 0xc3, 0xed, 0xbc, 0x16, 0xa3, 0x5c, 0x83, 0xc4, 0xd0, 0x71, 0xb1, 0x32, 0xdd, 0x81, 0x18, 0x7b, 0xcd, 0x99, 0x61, 0x32, 0x30, 0x11, 0x50, 0x9c, 0x8f, 0x64, 0x4a, 0x1c, 0x0a, 0x3f, 0x14, 0xee, 0x40, 0xd7, 0xdd, 0x18, 0x6f, 0x80, 0x7f, 0x9e, 0xdc, 0x7c, 0x02, 0xf6, 0x76, 0x10, 0x61, 0xbb, 0xb6, 0xdd, 0x91, 0xa6, 0xc9, 0x6e, 0xc0, 0xb9, 0xf1, 0x0e, 0xdb, 0xbd, 0x29, 0xdc, 0x52 ], [ 0x02, 0x53, 0x5d, 0x86, 0xcc, 0x75, 0x18, 0x48, 0x4a, 0x2a, 0x23, 0x8c, 0x92, 0x1b, 0x73, 0x9b, 0x17, 0x04, 0xa5, 0x03, 0x70, 0xa2, 0x92, 0x4a, 0xbf, 0x39, 0x95, 0x8c, 0x59, 0x76, 0xe6, 0x58, 0xdc, 0x5e, 0x87, 0x44, 0x00, 0x63, 0x11, 0x24, 0x59, 0xbd, 0xdb, 0x40, 0x30, 0x8b, 0x1c, 0x70 ] ); digest_test!( sha3_512_0, sha3_512, 512, [0u8; 0], [ 0xa6, 0x9f, 0x73, 0xcc, 0xa2, 0x3a, 0x9a, 0xc5, 0xc8, 0xb5, 0x67, 0xdc, 0x18, 0x5a, 0x75, 0x6e, 0x97, 0xc9, 0x82, 0x16, 0x4f, 0xe2, 0x58, 0x59, 0xe0, 0xd1, 0xdc, 0xc1, 0x47, 0x5c, 0x80, 0xa6, 0x15, 0xb2, 0x12, 0x3a, 0xf1, 0xf5, 0xf9, 0x4c, 0x11, 0xe3, 0xe9, 0x40, 0x2c, 0x3a, 0xc5, 0x58, 0xf5, 0x00, 0x19, 0x9d, 0x95, 0xb6, 0xd3, 0xe3, 0x01, 0x75, 0x85, 0x86, 0x28, 0x1d, 0xcd, 0x26, ] ); digest_test!( sha3_512_8, sha3_512, 512, [0xe5u8], [ 0x15, 0x02, 0x40, 0xba, 0xf9, 0x5f, 0xb3, 0x6f, 0x8c, 0xcb, 0x87, 0xa1, 0x9a, 0x41, 0x76, 0x7e, 0x7a, 0xed, 0x95, 0x12, 0x50, 0x75, 0xa2, 0xb2, 0xdb, 0xba, 0x6e, 0x56, 0x5e, 0x1c, 0xe8, 0x57, 0x5f, 0x2b, 0x04, 0x2b, 0x62, 0xe2, 0x9a, 0x04, 0xe9, 0x44, 0x03, 0x14, 0xa8, 0x21, 0xc6, 0x22, 0x41, 0x82, 0x96, 0x4d, 0x8b, 0x55, 0x7b, 0x16, 0xa4, 0x92, 0xb3, 0x80, 0x6f, 0x4c, 0x39, 0xc1 ] ); digest_test!( sha3_512_4080, sha3_512, 512, [ 0x43, 0x02, 0x56, 0x15, 0x52, 0x1d, 0x66, 0xfe, 0x8e, 0xc3, 0xa3, 0xf8, 0xcc, 0xc5, 0xab, 0xfa, 0xb8, 0x70, 0xa4, 0x62, 0xc6, 0xb3, 0xd1, 0x39, 0x6b, 0x84, 0x62, 0xb9, 0x8c, 0x7f, 0x91, 0x0c, 0x37, 0xd0, 0xea, 0x57, 0x91, 0x54, 0xea, 0xf7, 0x0f, 0xfb, 0xcc, 0x0b, 0xe9, 0x71, 0xa0, 0x32, 0xcc, 0xfd, 0x9d, 0x96, 0xd0, 0xa9, 0xb8, 0x29, 0xa9, 0xa3, 0x76, 0x2e, 0x21, 0xe3, 0xfe, 0xfc, 0xc6, 0x0e, 0x72, 0xfe, 0xdf, 0x9a, 0x7f, 0xff, 0xa5, 0x34, 0x33, 0xa4, 0xb0, 0x5e, 0x0f, 0x3a, 0xb0, 0x5d, 0x5e, 0xb2, 0x5d, 0x52, 0xc5, 0xea, 0xb1, 0xa7, 0x1a, 0x2f, 0x54, 0xac, 0x79, 0xff, 0x58, 0x82, 0x95, 0x13, 0x26, 0x39, 0x4d, 0x9d, 0xb8, 0x35, 0x80, 0xce, 0x09, 0xd6, 0x21, 0x9b, 0xca, 0x58, 0x8e, 0xc1, 0x57, 0xf7, 0x1d, 0x06, 0xe9, 0x57, 0xf8, 0xc2, 0x0d, 0x24, 0x2c, 0x9f, 0x55, 0xf5, 0xfc, 0x9d, 0x4d, 0x77, 0x7b, 0x59, 0xb0, 0xc7, 0x5a, 0x8e, 0xdc, 0x1f, 0xfe, 0xdc, 0x84, 0xb5, 0xd5, 0xc8, 0xa5, 0xe0, 0xeb, 0x05, 0xbb, 0x7d, 0xb8, 0xf2, 0x34, 0x91, 0x3d, 0x63, 0x25, 0x30, 0x4f, 0xa4, 0x3c, 0x9d, 0x32, 0xbb, 0xf6, 0xb2, 0x69, 0xee, 0x11, 0x82, 0xcd, 0x85, 0x45, 0x3e, 0xdd, 0xd1, 0x2f, 0x55, 0x55, 0x6d, 0x8e, 0xdf, 0x02, 0xc4, 0xb1, 0x3c, 0xd4, 0xd3, 0x30, 0xf8, 0x35, 0x31, 0xdb, 0xf2, 0x99, 0x4c, 0xf0, 0xbe, 0x56, 0xf5, 0x91, 0x47, 0xb7, 0x1f, 0x74, 0xb9, 0x4b, 0xe3, 0xdd, 0x9e, 0x83, 0xc8, 0xc9, 0x47, 0x7c, 0x42, 0x6c, 0x6d, 0x1a, 0x78, 0xde, 0x18, 0x56, 0x4a, 0x12, 0xc0, 0xd9, 0x93, 0x07, 0xb2, 0xc9, 0xab, 0x42, 0xb6, 0xe3, 0x31, 0x7b, 0xef, 0xca, 0x07, 0x97, 0x02, 0x9e, 0x9d, 0xd6, 0x7b, 0xd1, 0x73, 0x4e, 0x6c, 0x36, 0xd9, 0x98, 0x56, 0x5b, 0xfa, 0xc9, 0x4d, 0x19, 0x18, 0xa3, 0x58, 0x69, 0x19, 0x0d, 0x17, 0x79, 0x43, 0xc1, 0xa8, 0x00, 0x44, 0x45, 0xca, 0xce, 0x75, 0x1c, 0x43, 0xa7, 0x5f, 0x3d, 0x80, 0x51, 0x7f, 0xc4, 0x7c, 0xec, 0x46, 0xe8, 0xe3, 0x82, 0x64, 0x2d, 0x76, 0xdf, 0x46, 0xda, 0xb1, 0xa3, 0xdd, 0xae, 0xab, 0x95, 0xa2, 0xcf, 0x3f, 0x3a, 0xd7, 0x03, 0x69, 0xa7, 0x0f, 0x22, 0xf2, 0x93, 0xf0, 0xcc, 0x50, 0xb0, 0x38, 0x57, 0xc8, 0x3c, 0xfe, 0x0b, 0xd5, 0xd2, 0x3b, 0x92, 0xcd, 0x87, 0x88, 0xaa, 0xc2, 0x32, 0x29, 0x1d, 0xa6, 0x0b, 0x4b, 0xf3, 0xb3, 0x78, 0x8a, 0xe6, 0x0a, 0x23, 0xb6, 0x16, 0x9b, 0x50, 0xd7, 0xfe, 0x44, 0x6e, 0x6e, 0xa7, 0x3d, 0xeb, 0xfe, 0x1b, 0xb3, 0x4d, 0xcb, 0x1d, 0xb3, 0x7f, 0xe2, 0x17, 0x4a, 0x68, 0x59, 0x54, 0xeb, 0xc2, 0xd8, 0x6f, 0x10, 0x2a, 0x59, 0x0c, 0x24, 0x73, 0x2b, 0xc5, 0xa1, 0x40, 0x3d, 0x68, 0x76, 0xd2, 0x99, 0x5f, 0xab, 0x1e, 0x2f, 0x6f, 0x47, 0x23, 0xd4, 0xa6, 0x72, 0x7a, 0x8a, 0x8e, 0xd7, 0x2f, 0x02, 0xa7, 0x4c, 0xcf, 0x5f, 0x14, 0xb5, 0xc2, 0x3d, 0x95, 0x25, 0xdb, 0xf2, 0xb5, 0x47, 0x2e, 0x13, 0x45, 0xfd, 0x22, 0x3b, 0x08, 0x46, 0xc7, 0x07, 0xb0, 0x65, 0x69, 0x65, 0x09, 0x40, 0x65, 0x0f, 0x75, 0x06, 0x3b, 0x52, 0x98, 0x14, 0xe5, 0x14, 0x54, 0x1a, 0x67, 0x15, 0xf8, 0x79, 0xa8, 0x75, 0xb4, 0xf0, 0x80, 0x77, 0x51, 0x78, 0x12, 0x84, 0x1e, 0x6c, 0x5c, 0x73, 0x2e, 0xed, 0x0c, 0x07, 0xc0, 0x85, 0x95, 0xb9, 0xff, 0x0a, 0x83, 0xb8, 0xec, 0xc6, 0x0b, 0x2f, 0x98, 0xd4, 0xe7, 0xc6, 0x96, 0xcd, 0x61, 0x6b, 0xb0, 0xa5, 0xad, 0x52, 0xd9, 0xcf, 0x7b, 0x3a, 0x63, 0xa8, 0xcd, 0xf3, 0x72, 0x12 ], [ 0xe7, 0xba, 0x73, 0x40, 0x7a, 0xa4, 0x56, 0xae, 0xce, 0x21, 0x10, 0x77, 0xd9, 0x20, 0x87, 0xd5, 0xcd, 0x28, 0x3e, 0x38, 0x68, 0xd2, 0x84, 0xe0, 0x7e, 0xd1, 0x24, 0xb2, 0x7c, 0xbc, 0x66, 0x4a, 0x6a, 0x47, 0x5a, 0x8d, 0x7b, 0x4c, 0xf6, 0xa8, 0xa4, 0x92, 0x7e, 0xe0, 0x59, 0xa2, 0x62, 0x6a, 0x4f, 0x98, 0x39, 0x23, 0x36, 0x01, 0x45, 0xb2, 0x65, 0xeb, 0xfd, 0x4f, 0x5b, 0x3c, 0x44, 0xfd ] ); }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/chacha.rs
src/ciphers/chacha.rs
macro_rules! quarter_round { ($a:expr,$b:expr,$c:expr,$d:expr) => { $a = $a.wrapping_add($b); $d = ($d ^ $a).rotate_left(16); $c = $c.wrapping_add($d); $b = ($b ^ $c).rotate_left(12); $a = $a.wrapping_add($b); $d = ($d ^ $a).rotate_left(8); $c = $c.wrapping_add($d); $b = ($b ^ $c).rotate_left(7); }; } #[allow(dead_code)] // "expand 32-byte k", written in little-endian order pub const C: [u32; 4] = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574]; /// ChaCha20 implementation based on RFC8439 /// /// ChaCha20 is a stream cipher developed independently by Daniel J. Bernstein.\ /// To use it, the `chacha20` function should be called with appropriate /// parameters and the output of the function should be XORed with plain text. /// /// `chacha20` function takes as input an array of 16 32-bit integers (512 bits) /// of which 128 bits is the constant 'expand 32-byte k', 256 bits is the key, /// and 128 bits are nonce and counter. According to RFC8439, the nonce should /// be 96 bits long, which leaves 32 bits for the counter. Given that the block /// length is 512 bits, this leaves enough counter values to encrypt 256GB of /// data. /// /// The 16 input numbers can be thought of as the elements of a 4x4 matrix like /// the one below, on which we do the main operations of the cipher. /// /// ```text /// +----+----+----+----+ /// | 00 | 01 | 02 | 03 | /// +----+----+----+----+ /// | 04 | 05 | 06 | 07 | /// +----+----+----+----+ /// | 08 | 09 | 10 | 11 | /// +----+----+----+----+ /// | 12 | 13 | 14 | 15 | /// +----+----+----+----+ /// ``` /// /// As per the diagram below, `input[0, 1, 2, 3]` are the constants mentioned /// above, `input[4..=11]` is filled with the key, and `input[6..=9]` should be /// filled with nonce and counter values. The output of the function is stored /// in `output` variable and can be XORed with the plain text to produce the /// cipher text. /// /// ```text /// +------+------+------+------+ /// | | | | | /// | C[0] | C[1] | C[2] | C[3] | /// | | | | | /// +------+------+------+------+ /// | | | | | /// | key0 | key1 | key2 | key3 | /// | | | | | /// +------+------+------+------+ /// | | | | | /// | key4 | key5 | key6 | key7 | /// | | | | | /// +------+------+------+------+ /// | | | | | /// | ctr0 | no.0 | no.1 | no.2 | /// | | | | | /// +------+------+------+------+ /// ``` /// /// Note that the constants, the key, and the nonce should be written in /// little-endian order, meaning that for example if the key is 01:02:03:04 /// (in hex), it corresponds to the integer `0x04030201`. It is important to /// know that the hex value of the counter is meaningless, and only its integer /// value matters, and it should start with (for example) `0x00000000`, and then /// `0x00000001` and so on until `0xffffffff`. Keep in mind that as soon as we get /// from bytes to words, we stop caring about their representation in memory, /// and we only need the math to be correct. /// /// The output of the function can be used without any change, as long as the /// plain text has the same endianness. For example if the plain text is /// "hello world", and the first word of the output is `0x01020304`, then the /// first byte of plain text ('h') should be XORed with the least-significant /// byte of `0x01020304`, which is `0x04`. pub fn chacha20(input: &[u32; 16], output: &mut [u32; 16]) { output.copy_from_slice(&input[..]); for _ in 0..10 { // Odd round (column round) quarter_round!(output[0], output[4], output[8], output[12]); // column 1 quarter_round!(output[1], output[5], output[9], output[13]); // column 2 quarter_round!(output[2], output[6], output[10], output[14]); // column 3 quarter_round!(output[3], output[7], output[11], output[15]); // column 4 // Even round (diagonal round) quarter_round!(output[0], output[5], output[10], output[15]); // diag 1 quarter_round!(output[1], output[6], output[11], output[12]); // diag 2 quarter_round!(output[2], output[7], output[8], output[13]); // diag 3 quarter_round!(output[3], output[4], output[9], output[14]); // diag 4 } for (a, &b) in output.iter_mut().zip(input.iter()) { *a = a.wrapping_add(b); } } #[cfg(test)] mod tests { use super::*; use std::fmt::Write; fn output_hex(inp: &[u32; 16]) -> String { let mut res = String::new(); res.reserve(512 / 4); for &x in inp { write!(&mut res, "{x:08x}").unwrap(); } res } #[test] // test vector 1 fn basic_tv1() { let mut inp = [0u32; 16]; let mut out = [0u32; 16]; inp[0] = C[0]; inp[1] = C[1]; inp[2] = C[2]; inp[3] = C[3]; inp[4] = 0x03020100; // The key is 00:01:02:..:1f (hex) inp[5] = 0x07060504; inp[6] = 0x0b0a0908; inp[7] = 0x0f0e0d0c; inp[8] = 0x13121110; inp[9] = 0x17161514; inp[10] = 0x1b1a1918; inp[11] = 0x1f1e1d1c; inp[12] = 0x00000001; // The value of counter is 1 (an integer). Nonce: inp[13] = 0x09000000; // 00:00:00:09 inp[14] = 0x4a000000; // 00:00:00:4a inp[15] = 0x00000000; // 00:00:00:00 chacha20(&inp, &mut out); assert_eq!( output_hex(&out), concat!( "e4e7f11015593bd11fdd0f50c47120a3c7f4d1c70368c0339aaa22044e6cd4c3", "466482d209aa9f0705d7c214a2028bd9d19c12b5b94e16dee883d0cb4e3c50a2" ) ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/rsa_cipher.rs
src/ciphers/rsa_cipher.rs
//! RSA Cipher Implementation //! //! This module provides a basic implementation of the RSA (Rivest-Shamir-Adleman) encryption algorithm. //! RSA is an asymmetric cryptographic algorithm that uses a pair of keys: public and private. //! //! # Warning //! //! This is an educational implementation and should NOT be used for production cryptography. //! Use established cryptographic libraries like `ring` or `rust-crypto` for real-world applications. //! //! # Examples //! //! ``` //! use the_algorithms_rust::ciphers::{generate_keypair, encrypt, decrypt}; //! //! let (public_key, private_key) = generate_keypair(61, 53); //! let message = 65; //! let encrypted = encrypt(message, &public_key); //! let decrypted = decrypt(encrypted, &private_key); //! assert_eq!(message, decrypted); //! ``` /// Represents an RSA public key containing (n, e) #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PublicKey { pub n: u64, pub e: u64, } /// Represents an RSA private key containing (n, d) #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PrivateKey { pub n: u64, pub d: u64, } /// Computes the greatest common divisor using Euclid's algorithm /// /// # Arguments /// /// * `a` - First number /// * `b` - Second number /// /// # Returns /// /// The GCD of `a` and `b` fn gcd(mut a: u64, mut b: u64) -> u64 { while b != 0 { let temp = b; b = a % b; a = temp; } a } /// Computes the modular multiplicative inverse using the Extended Euclidean Algorithm /// /// Finds `x` such that `(a * x) % m == 1` /// /// # Arguments /// /// * `a` - The number to find the inverse of /// * `m` - The modulus /// /// # Returns /// /// The modular multiplicative inverse of `a` modulo `m`, or `None` if it doesn't exist fn mod_inverse(a: i64, m: i64) -> Option<u64> { let (mut old_r, mut r) = (a, m); let (mut old_s, mut s) = (1_i64, 0_i64); while r != 0 { let quotient = old_r / r; (old_r, r) = (r, old_r - quotient * r); (old_s, s) = (s, old_s - quotient * s); } if old_r > 1 { return None; // a is not invertible } if old_s < 0 { Some((old_s + m) as u64) } else { Some(old_s as u64) } } /// Performs modular exponentiation: (base^exp) % modulus /// /// Uses the square-and-multiply algorithm for efficiency /// /// # Arguments /// /// * `base` - The base number /// * `exp` - The exponent /// * `modulus` - The modulus /// /// # Returns /// /// The result of (base^exp) % modulus fn mod_pow(mut base: u64, mut exp: u64, modulus: u64) -> u64 { if modulus == 1 { return 0; } let mut result = 1; base %= modulus; while exp > 0 { if exp % 2 == 1 { result = ((result as u128 * base as u128) % modulus as u128) as u64; } exp >>= 1; base = ((base as u128 * base as u128) % modulus as u128) as u64; } result } /// Generates an RSA keypair from two prime numbers /// /// # Arguments /// /// * `p` - First prime number /// * `q` - Second prime number (should be different from p) /// /// # Returns /// /// A tuple containing (PublicKey, PrivateKey) /// /// # Examples /// /// ``` /// use the_algorithms_rust::ciphers::generate_keypair; /// /// let (public, private) = generate_keypair(61, 53); /// // n = p * q /// assert_eq!(public.n, 3233); /// assert_eq!(private.n, 3233); /// // Both keys share the same n /// assert_eq!(public.n, private.n); /// ``` /// /// # Panics /// /// Panics if the modular inverse cannot be computed pub fn generate_keypair(p: u64, q: u64) -> (PublicKey, PrivateKey) { let n = p * q; let phi = (p - 1) * (q - 1); // Choose e such that 1 < e < phi and gcd(e, phi) = 1 let mut e = 2; while e < phi { if gcd(e, phi) == 1 { break; } e += 1; } // Compute d, the modular multiplicative inverse of e mod phi let d = mod_inverse(e as i64, phi as i64).expect("Failed to compute modular inverse"); let public_key = PublicKey { n, e }; let private_key = PrivateKey { n, d }; (public_key, private_key) } /// Encrypts a message using the RSA public key /// /// # Arguments /// /// * `message` - The plaintext message (must be less than n) /// * `public_key` - The public key to use for encryption /// /// # Returns /// /// The encrypted ciphertext /// /// # Examples /// /// ``` /// use the_algorithms_rust::ciphers::{generate_keypair, encrypt, decrypt}; /// /// let (public_key, private_key) = generate_keypair(61, 53); /// let message = 65; /// let ciphertext = encrypt(message, &public_key); /// let decrypted = decrypt(ciphertext, &private_key); /// assert_eq!(decrypted, message); /// ``` pub fn encrypt(message: u64, public_key: &PublicKey) -> u64 { mod_pow(message, public_key.e, public_key.n) } /// Decrypts a ciphertext using the RSA private key /// /// # Arguments /// /// * `ciphertext` - The encrypted message /// * `private_key` - The private key to use for decryption /// /// # Returns /// /// The decrypted plaintext message /// /// # Examples /// /// ``` /// use the_algorithms_rust::ciphers::{generate_keypair, encrypt, decrypt}; /// /// let (public_key, private_key) = generate_keypair(61, 53); /// let message = 65; /// let ciphertext = encrypt(message, &public_key); /// let plaintext = decrypt(ciphertext, &private_key); /// assert_eq!(plaintext, message); /// ``` pub fn decrypt(ciphertext: u64, private_key: &PrivateKey) -> u64 { mod_pow(ciphertext, private_key.d, private_key.n) } /// Encrypts a text message by converting each character to its ASCII value /// /// # Arguments /// /// * `message` - The plaintext string /// * `public_key` - The public key to use for encryption /// /// # Returns /// /// A vector of encrypted values, one for each character /// /// # Examples /// /// ``` /// use the_algorithms_rust::ciphers::{generate_keypair, encrypt_text, decrypt_text}; /// /// let (public, private) = generate_keypair(61, 53); /// let encrypted = encrypt_text("HI", &public); /// let decrypted = decrypt_text(&encrypted, &private); /// assert_eq!(decrypted, "HI"); /// ``` pub fn encrypt_text(message: &str, public_key: &PublicKey) -> Vec<u64> { message .chars() .map(|c| encrypt(c as u64, public_key)) .collect() } /// Decrypts a vector of encrypted values back to text /// /// # Arguments /// /// * `ciphertext` - The vector of encrypted character values /// * `private_key` - The private key to use for decryption /// /// # Returns /// /// The decrypted string /// /// # Examples /// /// ``` /// use the_algorithms_rust::ciphers::{generate_keypair, encrypt_text, decrypt_text}; /// /// let (public, private) = generate_keypair(61, 53); /// let encrypted = encrypt_text("HELLO", &public); /// let decrypted = decrypt_text(&encrypted, &private); /// assert_eq!(decrypted, "HELLO"); /// ``` pub fn decrypt_text(ciphertext: &[u64], private_key: &PrivateKey) -> String { ciphertext .iter() .map(|&c| { let decrypted = decrypt(c, private_key); char::from_u32(decrypted as u32).unwrap_or('?') }) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn test_gcd() { assert_eq!(gcd(48, 18), 6); assert_eq!(gcd(17, 13), 1); assert_eq!(gcd(100, 50), 50); assert_eq!(gcd(7, 7), 7); } #[test] fn test_mod_inverse() { assert_eq!(mod_inverse(17, 3120), Some(2753)); assert_eq!(mod_inverse(7, 40), Some(23)); assert!(mod_inverse(4, 8).is_none()); // No inverse exists } #[test] fn test_mod_pow() { assert_eq!(mod_pow(4, 13, 497), 445); assert_eq!(mod_pow(2, 10, 1000), 24); assert_eq!(mod_pow(3, 5, 7), 5); } #[test] fn test_generate_keypair() { let (public, private) = generate_keypair(61, 53); // n should be p * q assert_eq!(public.n, 3233); assert_eq!(private.n, 3233); // e should be coprime with phi let phi = (61 - 1) * (53 - 1); assert_eq!(gcd(public.e, phi), 1); // Verify that (e * d) % phi == 1 assert_eq!((public.e * private.d) % phi, 1); } #[test] fn test_encrypt_decrypt_number() { let (public, private) = generate_keypair(61, 53); let message = 65; let encrypted = encrypt(message, &public); // Encrypted value will vary based on e, so we just check it's different assert_ne!(encrypted, message); let decrypted = decrypt(encrypted, &private); assert_eq!(decrypted, message); } #[test] fn test_encrypt_decrypt_various_numbers() { let (public, private) = generate_keypair(61, 53); for message in [1, 42, 100, 255, 1000, 3000] { let encrypted = encrypt(message, &public); let decrypted = decrypt(encrypted, &private); assert_eq!(decrypted, message, "Failed for message: {message}"); } } #[test] fn test_encrypt_decrypt_text() { let (public, private) = generate_keypair(61, 53); let message = "HI"; let encrypted = encrypt_text(message, &public); let decrypted = decrypt_text(&encrypted, &private); assert_eq!(decrypted, message); } #[test] fn test_encrypt_decrypt_longer_text() { let (public, private) = generate_keypair(61, 53); let message = "HELLO"; let encrypted = encrypt_text(message, &public); let decrypted = decrypt_text(&encrypted, &private); assert_eq!(decrypted, message); } #[test] fn test_different_primes() { let (public, private) = generate_keypair(17, 19); let message = 42; let encrypted = encrypt(message, &public); let decrypted = decrypt(encrypted, &private); assert_eq!(decrypted, message); } #[test] fn test_encrypt_decrypt_alphabet() { let (public, private) = generate_keypair(61, 53); let message = "ABC"; let encrypted = encrypt_text(message, &public); let decrypted = decrypt_text(&encrypted, &private); assert_eq!(decrypted, message); } #[test] fn test_key_properties() { let (public, private) = generate_keypair(61, 53); // Both keys should have the same n assert_eq!(public.n, private.n); // e and d should be different assert_ne!(public.e, private.d); // Verify that (e * d) % phi == 1 let phi = (61 - 1) * (53 - 1); assert_eq!((public.e * private.d) % phi, 1); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/caesar.rs
src/ciphers/caesar.rs
const ERROR_MESSAGE: &str = "Rotation must be in the range [0, 25]"; const ALPHABET_LENGTH: u8 = b'z' - b'a' + 1; /// Encrypts a given text using the Caesar cipher technique. /// /// In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code, /// or Caesar shift, is one of the simplest and most widely known encryption techniques. /// It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter /// some fixed number of positions down the alphabet. /// /// # Arguments /// /// * `text` - The text to be encrypted. /// * `rotation` - The number of rotations (shift) to be applied. It should be within the range [0, 25]. /// /// # Returns /// /// Returns a `Result` containing the encrypted string if successful, or an error message if the rotation /// is out of the valid range. /// /// # Errors /// /// Returns an error if the rotation value is out of the valid range [0, 25] pub fn caesar(text: &str, rotation: isize) -> Result<String, &'static str> { if !(0..ALPHABET_LENGTH as isize).contains(&rotation) { return Err(ERROR_MESSAGE); } let result = text .chars() .map(|c| { if c.is_ascii_alphabetic() { shift_char(c, rotation) } else { c } }) .collect(); Ok(result) } /// Shifts a single ASCII alphabetic character by a specified number of positions in the alphabet. /// /// # Arguments /// /// * `c` - The ASCII alphabetic character to be shifted. /// * `rotation` - The number of positions to shift the character. Should be within the range [0, 25]. /// /// # Returns /// /// Returns the shifted ASCII alphabetic character. fn shift_char(c: char, rotation: isize) -> char { let first = if c.is_ascii_lowercase() { b'a' } else { b'A' }; let rotation = rotation as u8; // Safe cast as rotation is within [0, 25] (((c as u8 - first) + rotation) % ALPHABET_LENGTH + first) as char } #[cfg(test)] mod tests { use super::*; macro_rules! test_caesar_happy_path { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (text, rotation, expected) = $test_case; assert_eq!(caesar(&text, rotation).unwrap(), expected); let backward_rotation = if rotation == 0 { 0 } else { ALPHABET_LENGTH as isize - rotation }; assert_eq!(caesar(&expected, backward_rotation).unwrap(), text); } )* }; } macro_rules! test_caesar_error_cases { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (text, rotation) = $test_case; assert_eq!(caesar(&text, rotation), Err(ERROR_MESSAGE)); } )* }; } #[test] fn alphabet_length_should_be_26() { assert_eq!(ALPHABET_LENGTH, 26); } test_caesar_happy_path! { empty_text: ("", 13, ""), rot_13: ("rust", 13, "ehfg"), unicode: ("attack at dawn 攻", 5, "fyyfhp fy ifbs 攻"), rotation_within_alphabet_range: ("Hello, World!", 3, "Khoor, Zruog!"), no_rotation: ("Hello, World!", 0, "Hello, World!"), rotation_at_alphabet_end: ("Hello, World!", 25, "Gdkkn, Vnqkc!"), longer: ("The quick brown fox jumps over the lazy dog.", 5, "Ymj vznhp gwtbs ktc ozrux tajw ymj qfed itl."), non_alphabetic_characters: ("12345!@#$%", 3, "12345!@#$%"), uppercase_letters: ("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1, "BCDEFGHIJKLMNOPQRSTUVWXYZA"), mixed_case: ("HeLlO WoRlD", 7, "OlSsV DvYsK"), with_whitespace: ("Hello, World!", 13, "Uryyb, Jbeyq!"), with_special_characters: ("Hello!@#$%^&*()_+World", 4, "Lipps!@#$%^&*()_+Asvph"), with_numbers: ("Abcd1234XYZ", 10, "Klmn1234HIJ"), } test_caesar_error_cases! { negative_rotation: ("Hello, World!", -5), empty_input_negative_rotation: ("", -1), empty_input_large_rotation: ("", 27), large_rotation: ("Large rotation", 139), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/blake2b.rs
src/ciphers/blake2b.rs
// For specification go to https://www.rfc-editor.org/rfc/rfc7693 use std::cmp::{max, min}; use std::convert::{TryFrom, TryInto}; type Word = u64; const BB: usize = 128; const U64BYTES: usize = (u64::BITS as usize) / 8; type Block = [Word; BB / U64BYTES]; const KK_MAX: usize = 64; const NN_MAX: u8 = 64; // Array of round constants used in mixing function G const RC: [u32; 4] = [32, 24, 16, 63]; // IV[i] = floor(2**64 * frac(sqrt(prime(i+1)))) where prime(i) is the ith prime number const IV: [Word; 8] = [ 0x6A09E667F3BCC908, 0xBB67AE8584CAA73B, 0x3C6EF372FE94F82B, 0xA54FF53A5F1D36F1, 0x510E527FADE682D1, 0x9B05688C2B3E6C1F, 0x1F83D9ABFB41BD6B, 0x5BE0CD19137E2179, ]; const SIGMA: [[usize; 16]; 10] = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8], [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9], [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11], [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10], [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5], [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0], ]; #[inline] const fn blank_block() -> Block { [0u64; BB / U64BYTES] } // Overflowing addition #[inline] fn add(a: &mut Word, b: Word) { *a = a.overflowing_add(b).0; } #[inline] const fn ceil(dividend: usize, divisor: usize) -> usize { (dividend / divisor) + (!dividend.is_multiple_of(divisor) as usize) } fn g(v: &mut [Word; 16], a: usize, b: usize, c: usize, d: usize, x: Word, y: Word) { for (m, r) in [x, y].into_iter().zip(RC.chunks(2)) { let v_b = v[b]; add(&mut v[a], v_b); add(&mut v[a], m); v[d] = (v[d] ^ v[a]).rotate_right(r[0]); let v_d = v[d]; add(&mut v[c], v_d); v[b] = (v[b] ^ v[c]).rotate_right(r[1]); } } fn f(h: &mut [Word; 8], m: Block, t: u128, flag: bool) { let mut v: [Word; 16] = [0; 16]; for (i, (h_i, iv_i)) in h.iter().zip(IV.iter()).enumerate() { v[i] = *h_i; v[i + 8] = *iv_i; } v[12] ^= (t % (u64::MAX as u128)) as u64; v[13] ^= (t >> 64) as u64; if flag { v[14] = !v[14]; } for i in 0..12 { let s = SIGMA[i % 10]; let mut s_index = 0; for j in 0..4 { g( &mut v, j, j + 4, j + 8, j + 12, m[s[s_index]], m[s[s_index + 1]], ); s_index += 2; } let i1d = |col, row| { let col = col % 4; let row = row % 4; (row * 4) + col }; for j in 0..4 { // Produces indeces for diagonals of a 4x4 matrix starting at 0,j let idx: Vec<usize> = (0..4).map(|n| i1d(j + n, n) as usize).collect(); g( &mut v, idx[0], idx[1], idx[2], idx[3], m[s[s_index]], m[s[s_index + 1]], ); s_index += 2; } } for (i, n) in h.iter_mut().enumerate() { *n ^= v[i] ^ v[i + 8]; } } fn blake2(d: Vec<Block>, ll: u128, kk: Word, nn: Word) -> Vec<u8> { let mut h: [Word; 8] = IV .iter() .take(8) .copied() .collect::<Vec<Word>>() .try_into() .unwrap(); h[0] ^= 0x01010000u64 ^ (kk << 8) ^ nn; if d.len() > 1 { for (i, w) in d.iter().enumerate().take(d.len() - 1) { f(&mut h, *w, (i as u128 + 1) * BB as u128, false); } } let ll = if kk > 0 { ll + BB as u128 } else { ll }; f(&mut h, d[d.len() - 1], ll, true); h.iter() .flat_map(|n| n.to_le_bytes()) .take(nn as usize) .collect() } // Take arbitrarily long slice of u8's and turn up to 8 bytes into u64 fn bytes_to_word(bytes: &[u8]) -> Word { if let Ok(arr) = <[u8; U64BYTES]>::try_from(bytes) { Word::from_le_bytes(arr) } else { let mut arr = [0u8; 8]; for (a_i, b_i) in arr.iter_mut().zip(bytes) { *a_i = *b_i; } Word::from_le_bytes(arr) } } pub fn blake2b(m: &[u8], k: &[u8], nn: u8) -> Vec<u8> { let kk = min(k.len(), KK_MAX); let nn = min(nn, NN_MAX); // Prevent user from giving a key that is too long let k = &k[..kk]; let dd = max(ceil(kk, BB) + ceil(m.len(), BB), 1); let mut blocks: Vec<Block> = vec![blank_block(); dd]; // Copy key into blocks for (w, c) in blocks[0].iter_mut().zip(k.chunks(U64BYTES)) { *w = bytes_to_word(c); } let first_index = (kk > 0) as usize; // Copy bytes from message into blocks for (i, c) in m.chunks(U64BYTES).enumerate() { let block_index = first_index + (i / (BB / U64BYTES)); let word_in_block = i % (BB / U64BYTES); blocks[block_index][word_in_block] = bytes_to_word(c); } blake2(blocks, m.len() as u128, kk as u64, nn as Word) } #[cfg(test)] mod test { use super::*; macro_rules! digest_test { ($fname:ident, $message:expr, $key:expr, $nn:literal, $expected:expr) => { #[test] fn $fname() { let digest = blake2b($message, $key, $nn); let expected = Vec::from($expected); assert_eq!(digest, expected); } }; } digest_test!( blake2b_from_rfc, &[0x61, 0x62, 0x63], &[0; 0], 64, [ 0xBA, 0x80, 0xA5, 0x3F, 0x98, 0x1C, 0x4D, 0x0D, 0x6A, 0x27, 0x97, 0xB6, 0x9F, 0x12, 0xF6, 0xE9, 0x4C, 0x21, 0x2F, 0x14, 0x68, 0x5A, 0xC4, 0xB7, 0x4B, 0x12, 0xBB, 0x6F, 0xDB, 0xFF, 0xA2, 0xD1, 0x7D, 0x87, 0xC5, 0x39, 0x2A, 0xAB, 0x79, 0x2D, 0xC2, 0x52, 0xD5, 0xDE, 0x45, 0x33, 0xCC, 0x95, 0x18, 0xD3, 0x8A, 0xA8, 0xDB, 0xF1, 0x92, 0x5A, 0xB9, 0x23, 0x86, 0xED, 0xD4, 0x00, 0x99, 0x23 ] ); digest_test!( blake2b_empty, &[0; 0], &[0; 0], 64, [ 0x78, 0x6a, 0x02, 0xf7, 0x42, 0x01, 0x59, 0x03, 0xc6, 0xc6, 0xfd, 0x85, 0x25, 0x52, 0xd2, 0x72, 0x91, 0x2f, 0x47, 0x40, 0xe1, 0x58, 0x47, 0x61, 0x8a, 0x86, 0xe2, 0x17, 0xf7, 0x1f, 0x54, 0x19, 0xd2, 0x5e, 0x10, 0x31, 0xaf, 0xee, 0x58, 0x53, 0x13, 0x89, 0x64, 0x44, 0x93, 0x4e, 0xb0, 0x4b, 0x90, 0x3a, 0x68, 0x5b, 0x14, 0x48, 0xb7, 0x55, 0xd5, 0x6f, 0x70, 0x1a, 0xfe, 0x9b, 0xe2, 0xce ] ); digest_test!( blake2b_empty_with_key, &[0; 0], &[ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f ], 64, [ 0x10, 0xeb, 0xb6, 0x77, 0x00, 0xb1, 0x86, 0x8e, 0xfb, 0x44, 0x17, 0x98, 0x7a, 0xcf, 0x46, 0x90, 0xae, 0x9d, 0x97, 0x2f, 0xb7, 0xa5, 0x90, 0xc2, 0xf0, 0x28, 0x71, 0x79, 0x9a, 0xaa, 0x47, 0x86, 0xb5, 0xe9, 0x96, 0xe8, 0xf0, 0xf4, 0xeb, 0x98, 0x1f, 0xc2, 0x14, 0xb0, 0x05, 0xf4, 0x2d, 0x2f, 0xf4, 0x23, 0x34, 0x99, 0x39, 0x16, 0x53, 0xdf, 0x7a, 0xef, 0xcb, 0xc1, 0x3f, 0xc5, 0x15, 0x68 ] ); digest_test!( blake2b_key_shortin, &[0], &[ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f ], 64, [ 0x96, 0x1f, 0x6d, 0xd1, 0xe4, 0xdd, 0x30, 0xf6, 0x39, 0x01, 0x69, 0x0c, 0x51, 0x2e, 0x78, 0xe4, 0xb4, 0x5e, 0x47, 0x42, 0xed, 0x19, 0x7c, 0x3c, 0x5e, 0x45, 0xc5, 0x49, 0xfd, 0x25, 0xf2, 0xe4, 0x18, 0x7b, 0x0b, 0xc9, 0xfe, 0x30, 0x49, 0x2b, 0x16, 0xb0, 0xd0, 0xbc, 0x4e, 0xf9, 0xb0, 0xf3, 0x4c, 0x70, 0x03, 0xfa, 0xc0, 0x9a, 0x5e, 0xf1, 0x53, 0x2e, 0x69, 0x43, 0x02, 0x34, 0xce, 0xbd ] ); digest_test!( blake2b_keyed_filled, &[ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f ], &[ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f ], 64, [ 0x65, 0x67, 0x6d, 0x80, 0x06, 0x17, 0x97, 0x2f, 0xbd, 0x87, 0xe4, 0xb9, 0x51, 0x4e, 0x1c, 0x67, 0x40, 0x2b, 0x7a, 0x33, 0x10, 0x96, 0xd3, 0xbf, 0xac, 0x22, 0xf1, 0xab, 0xb9, 0x53, 0x74, 0xab, 0xc9, 0x42, 0xf1, 0x6e, 0x9a, 0xb0, 0xea, 0xd3, 0x3b, 0x87, 0xc9, 0x19, 0x68, 0xa6, 0xe5, 0x09, 0xe1, 0x19, 0xff, 0x07, 0x78, 0x7b, 0x3e, 0xf4, 0x83, 0xe1, 0xdc, 0xdc, 0xcf, 0x6e, 0x30, 0x22 ] ); }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/base64.rs
src/ciphers/base64.rs
/* A Rust implementation of a base64 encoder and decoder. Written from scratch. */ // The charset and padding used for en- and decoding. const CHARSET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const PADDING: char = '='; /* Combines the two provided bytes into an u16, and collects 6 bits from it using an AND mask: Example: Bytes: X and Y (Bits of those bytes will be signified using the names of their byte) Offset: 4 `combined` = 0bXXXXXXXXYYYYYYYY AND mask: 0b1111110000000000 >> offset (4) = 0b0000111111000000 `combined` with mask applied: 0b0000XXYYYY000000 Shift the value right by (16 bit number) - (6 bit mask) - (4 offset) = 6: 0b0000000000XXYYYY And then turn it into an u8: 0b00XXYYYY (Return value) */ fn collect_six_bits(from: (u8, u8), offset: u8) -> u8 { let combined: u16 = ((from.0 as u16) << 8) | (from.1 as u16); ((combined & (0b1111110000000000u16 >> offset)) >> (10 - offset)) as u8 } pub fn base64_encode(data: &[u8]) -> String { let mut bits_encoded = 0usize; let mut encoded_string = String::new(); // Using modulo twice to prevent an underflow, Wolfram|Alpha says this is optimal let padding_needed = ((6 - (data.len() * 8) % 6) / 2) % 3; loop { let lower_byte_index_to_encode = bits_encoded / 8usize; // Integer division if lower_byte_index_to_encode == data.len() { break; } let lower_byte_to_encode = data[lower_byte_index_to_encode]; let upper_byte_to_encode = if (lower_byte_index_to_encode + 1) == data.len() { 0u8 // Padding } else { data[lower_byte_index_to_encode + 1] }; let bytes_to_encode = (lower_byte_to_encode, upper_byte_to_encode); let offset: u8 = (bits_encoded % 8) as u8; encoded_string.push(CHARSET[collect_six_bits(bytes_to_encode, offset) as usize] as char); bits_encoded += 6; } for _ in 0..padding_needed { encoded_string.push(PADDING); } encoded_string } /* Performs the exact inverse of the above description of `base64_encode` */ pub fn base64_decode(data: &str) -> Result<Vec<u8>, (&str, u8)> { let mut collected_bits = 0; let mut byte_buffer = 0u16; let mut databytes = data.bytes(); let mut outputbytes = Vec::<u8>::new(); 'decodeloop: loop { while collected_bits < 8 { if let Some(nextbyte) = databytes.next() { // Finds the first occurrence of the latest byte if let Some(idx) = CHARSET.iter().position(|&x| x == nextbyte) { byte_buffer |= ((idx & 0b00111111) as u16) << (10 - collected_bits); collected_bits += 6; } else if nextbyte == (PADDING as u8) { collected_bits -= 2; // Padding only comes at the end so this works } else { return Err(( "Failed to decode base64: Expected byte from charset, found invalid byte.", nextbyte, )); } } else { break 'decodeloop; } } outputbytes.push(((0b1111111100000000 & byte_buffer) >> 8) as u8); byte_buffer &= 0b0000000011111111; byte_buffer <<= 8; collected_bits -= 8; } if collected_bits != 0 { return Err(("Failed to decode base64: Invalid padding.", collected_bits)); } Ok(outputbytes) } #[cfg(test)] mod tests { use super::*; #[test] fn pregenerated_random_bytes_encode() { macro_rules! test_encode { ($left: expr, $right: expr) => { assert_eq!(base64_encode(&$left.to_vec()), $right); }; } test_encode!( b"\xd31\xc9\x87D\xfe\xaa\xb3\xff\xef\x8c\x0eoD", "0zHJh0T+qrP/74wOb0Q=" ); test_encode!( b"\x9f\x0e8\xbc\xf5\xd0-\xb4.\xd4\xf0?\x8f\xe7\t{.\xff/6\xcbTY!\xae9\x82", "nw44vPXQLbQu1PA/j+cJey7/LzbLVFkhrjmC" ); test_encode!(b"\x7f3\x15\x1a\xd3\xf91\x9bS\xa44=", "fzMVGtP5MZtTpDQ9"); test_encode!( b"7:\xf5\xd1[\xbfV/P\x18\x03\x00\xdc\xcd\xa1\xecG", "Nzr10Vu/Vi9QGAMA3M2h7Ec=" ); test_encode!( b"\xc3\xc9\x18={\xc4\x08\x97wN\xda\x81\x84?\x94\xe6\x9e", "w8kYPXvECJd3TtqBhD+U5p4=" ); test_encode!( b"\x8cJ\xf8e\x13\r\x8fw\xa8\xe6G\xce\x93c*\xe7M\xb6\xd7", "jEr4ZRMNj3eo5kfOk2Mq50221w==" ); test_encode!( b"\xde\xc4~\xb2}\xb1\x14F.~\xa1z|s\x90\x8dd\x9b\x04\x81\xf2\x92{", "3sR+sn2xFEYufqF6fHOQjWSbBIHykns=" ); test_encode!( b"\xf0y\t\x14\xd161n\x03e\xed\x0e\x05\xdf\xc1\xb9\xda", "8HkJFNE2MW4DZe0OBd/Budo=" ); test_encode!( b"*.\x8e\x1d@\x1ac\xdd;\x9a\xcc \x0c\xc2KI", "Ki6OHUAaY907mswgDMJLSQ==" ); test_encode!(b"\xd6\x829\x82\xbc\x00\xc9\xfe\x03", "1oI5grwAyf4D"); test_encode!( b"\r\xf2\xb4\xd4\xa1g\x8fhl\xaa@\x98\x00\xda\x95", "DfK01KFnj2hsqkCYANqV" ); test_encode!( b"\x1a\xfaV\x1a\xc2e\xc0\xad\xef|\x07\xcf\xa9\xb7O", "GvpWGsJlwK3vfAfPqbdP" ); test_encode!(b"\xc20{_\x81\xac", "wjB7X4Gs"); test_encode!( b"B\xa85\xac\xe9\x0ev-\x8bT\xb3|\xde", "Qqg1rOkOdi2LVLN83g==" ); test_encode!( b"\x05\xe0\xeeSs\xfdY9\x0b7\x84\xfc-\xec", "BeDuU3P9WTkLN4T8Lew=" ); test_encode!( b"Qj\x92\xfa?\xa5\xe3_[\xde\x82\x97{$\xb2\xf9\xd5\x98\x0cy\x15\xe4R\x8d", "UWqS+j+l419b3oKXeySy+dWYDHkV5FKN" ); test_encode!(b"\x853\xe0\xc0\x1d\xc1", "hTPgwB3B"); test_encode!(b"}2\xd0\x13m\x8d\x8f#\x9c\xf5,\xc7", "fTLQE22NjyOc9SzH"); } #[test] fn pregenerated_random_bytes_decode() { macro_rules! test_decode { ($left: expr, $right: expr) => { assert_eq!( base64_decode(&String::from($left)).unwrap(), $right.to_vec() ); }; } test_decode!( "0zHJh0T+qrP/74wOb0Q=", b"\xd31\xc9\x87D\xfe\xaa\xb3\xff\xef\x8c\x0eoD" ); test_decode!( "nw44vPXQLbQu1PA/j+cJey7/LzbLVFkhrjmC", b"\x9f\x0e8\xbc\xf5\xd0-\xb4.\xd4\xf0?\x8f\xe7\t{.\xff/6\xcbTY!\xae9\x82" ); test_decode!("fzMVGtP5MZtTpDQ9", b"\x7f3\x15\x1a\xd3\xf91\x9bS\xa44="); test_decode!( "Nzr10Vu/Vi9QGAMA3M2h7Ec=", b"7:\xf5\xd1[\xbfV/P\x18\x03\x00\xdc\xcd\xa1\xecG" ); test_decode!( "w8kYPXvECJd3TtqBhD+U5p4=", b"\xc3\xc9\x18={\xc4\x08\x97wN\xda\x81\x84?\x94\xe6\x9e" ); test_decode!( "jEr4ZRMNj3eo5kfOk2Mq50221w==", b"\x8cJ\xf8e\x13\r\x8fw\xa8\xe6G\xce\x93c*\xe7M\xb6\xd7" ); test_decode!( "3sR+sn2xFEYufqF6fHOQjWSbBIHykns=", b"\xde\xc4~\xb2}\xb1\x14F.~\xa1z|s\x90\x8dd\x9b\x04\x81\xf2\x92{" ); test_decode!( "8HkJFNE2MW4DZe0OBd/Budo=", b"\xf0y\t\x14\xd161n\x03e\xed\x0e\x05\xdf\xc1\xb9\xda" ); test_decode!( "Ki6OHUAaY907mswgDMJLSQ==", b"*.\x8e\x1d@\x1ac\xdd;\x9a\xcc \x0c\xc2KI" ); test_decode!("1oI5grwAyf4D", b"\xd6\x829\x82\xbc\x00\xc9\xfe\x03"); test_decode!( "DfK01KFnj2hsqkCYANqV", b"\r\xf2\xb4\xd4\xa1g\x8fhl\xaa@\x98\x00\xda\x95" ); test_decode!( "GvpWGsJlwK3vfAfPqbdP", b"\x1a\xfaV\x1a\xc2e\xc0\xad\xef|\x07\xcf\xa9\xb7O" ); test_decode!("wjB7X4Gs", b"\xc20{_\x81\xac"); test_decode!( "Qqg1rOkOdi2LVLN83g==", b"B\xa85\xac\xe9\x0ev-\x8bT\xb3|\xde" ); test_decode!( "BeDuU3P9WTkLN4T8Lew=", b"\x05\xe0\xeeSs\xfdY9\x0b7\x84\xfc-\xec" ); test_decode!( "UWqS+j+l419b3oKXeySy+dWYDHkV5FKN", b"Qj\x92\xfa?\xa5\xe3_[\xde\x82\x97{$\xb2\xf9\xd5\x98\x0cy\x15\xe4R\x8d" ); test_decode!("hTPgwB3B", b"\x853\xe0\xc0\x1d\xc1"); test_decode!("fTLQE22NjyOc9SzH", b"}2\xd0\x13m\x8d\x8f#\x9c\xf5,\xc7"); } #[test] fn encode_decode() { macro_rules! test_e_d { ($text: expr) => { assert_eq!( base64_decode(&base64_encode(&$text.to_vec())).unwrap(), $text ); }; } test_e_d!(b"green"); test_e_d!(b"The quick brown fox jumped over the lazy dog."); test_e_d!(b"Lorem Ipsum sit dolor amet."); test_e_d!(b"0"); test_e_d!(b"01"); test_e_d!(b"012"); test_e_d!(b"0123"); test_e_d!(b"0123456789"); } #[test] fn decode_encode() { macro_rules! test_d_e { ($data: expr) => { assert_eq!( base64_encode(&base64_decode(&String::from($data)).unwrap()), String::from($data) ); }; } test_d_e!("TG9uZyBsaXZlIGVhc3RlciBlZ2dzIDop"); test_d_e!("SGFwcHkgSGFja3RvYmVyZmVzdCE="); test_d_e!("PVRoZSBBbGdvcml0aG1zPQ=="); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/salsa.rs
src/ciphers/salsa.rs
macro_rules! quarter_round { ($v1:expr,$v2:expr,$v3:expr,$v4:expr) => { $v2 ^= ($v1.wrapping_add($v4).rotate_left(7)); $v3 ^= ($v2.wrapping_add($v1).rotate_left(9)); $v4 ^= ($v3.wrapping_add($v2).rotate_left(13)); $v1 ^= ($v4.wrapping_add($v3).rotate_left(18)); }; } /// This is a `Salsa20` implementation based on <https://en.wikipedia.org/wiki/Salsa20>\ /// `Salsa20` is a stream cipher developed by Daniel J. Bernstein.\ /// To use it, the `salsa20` function should be called with appropriate parameters and the /// output of the function should be XORed with plain text. /// /// `salsa20` function takes as input an array of 16 32-bit integers (512 bits) /// of which 128 bits is the constant 'expand 32-byte k', 256 bits is the key, /// and 128 bits are nonce and counter. It is up to the user to determine how /// many bits each of nonce and counter take, but a default of 64 bits each /// seems to be a sane choice. /// /// The 16 input numbers can be thought of as the elements of a 4x4 matrix like /// the one below, on which we do the main operations of the cipher. /// /// ```text /// +----+----+----+----+ /// | 00 | 01 | 02 | 03 | /// +----+----+----+----+ /// | 04 | 05 | 06 | 07 | /// +----+----+----+----+ /// | 08 | 09 | 10 | 11 | /// +----+----+----+----+ /// | 12 | 13 | 14 | 15 | /// +----+----+----+----+ /// ``` /// /// As per the diagram below, `input[0, 5, 10, 15]` are the constants mentioned /// above, `input[1, 2, 3, 4, 11, 12, 13, 14]` is filled with the key, and /// `input[6, 7, 8, 9]` should be filled with nonce and counter values. The output /// of the function is stored in `output` variable and can be XORed with the /// plain text to produce the cipher text. /// /// ```text /// +------+------+------+------+ /// | | | | | /// | C[0] | key1 | key2 | key3 | /// | | | | | /// +------+------+------+------+ /// | | | | | /// | key4 | C[1] | no1 | no2 | /// | | | | | /// +------+------+------+------+ /// | | | | | /// | ctr1 | ctr2 | C[2] | key5 | /// | | | | | /// +------+------+------+------+ /// | | | | | /// | key6 | key7 | key8 | C[3] | /// | | | | | /// +------+------+------+------+ /// ``` pub fn salsa20(input: &[u32; 16], output: &mut [u32; 16]) { output.copy_from_slice(&input[..]); for _ in 0..10 { // Odd round quarter_round!(output[0], output[4], output[8], output[12]); // column 1 quarter_round!(output[5], output[9], output[13], output[1]); // column 2 quarter_round!(output[10], output[14], output[2], output[6]); // column 3 quarter_round!(output[15], output[3], output[7], output[11]); // column 4 // Even round quarter_round!(output[0], output[1], output[2], output[3]); // row 1 quarter_round!(output[5], output[6], output[7], output[4]); // row 2 quarter_round!(output[10], output[11], output[8], output[9]); // row 3 quarter_round!(output[15], output[12], output[13], output[14]); // row 4 } for (a, &b) in output.iter_mut().zip(input.iter()) { *a = a.wrapping_add(b); } } #[cfg(test)] mod tests { use super::*; use std::fmt::Write; const C: [u32; 4] = [0x65787061, 0x6e642033, 0x322d6279, 0x7465206b]; fn output_hex(inp: &[u32; 16]) -> String { let mut res = String::new(); res.reserve(512 / 4); for &x in inp { write!(&mut res, "{x:08x}").unwrap(); } res } #[test] // test vector 1 fn basic_tv1() { let mut inp = [0u32; 16]; let mut out = [0u32; 16]; inp[0] = C[0]; inp[1] = 0x01020304; // 1, 2, 3, 4 inp[2] = 0x05060708; // 5, 6, 7, 8, ... inp[3] = 0x090a0b0c; inp[4] = 0x0d0e0f10; inp[5] = C[1]; inp[6] = 0x65666768; // 101, 102, 103, 104 inp[7] = 0x696a6b6c; // 105, 106, 107, 108, ... inp[8] = 0x6d6e6f70; inp[9] = 0x71727374; inp[10] = C[2]; inp[11] = 0xc9cacbcc; // 201, 202, 203, 204 inp[12] = 0xcdcecfd0; // 205, 206, 207, 208, ... inp[13] = 0xd1d2d3d4; inp[14] = 0xd5d6d7d8; inp[15] = C[3]; salsa20(&inp, &mut out); // Checked with wikipedia implementation, does not agree with // "https://cr.yp.to/snuffle/spec.pdf" assert_eq!( output_hex(&out), concat!( "de1d6f8d91dbf69d0db4b70c8b4320d236694432896d98b05aa7b76d5738ca13", "04e5a170c8e479af1542ed2f30f26ba57da20203cfe955c66f4cc7a06dd34359" ) ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/another_rot13.rs
src/ciphers/another_rot13.rs
pub fn another_rot13(text: &str) -> String { let input = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; let output = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"; text.chars() .map(|c| match input.find(c) { Some(i) => output.chars().nth(i).unwrap(), None => c, }) .collect() } #[cfg(test)] mod tests { // Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; #[test] fn test_simple() { assert_eq!(another_rot13("ABCzyx"), "NOPmlk"); } #[test] fn test_every_alphabet_with_space() { assert_eq!( another_rot13("The quick brown fox jumps over the lazy dog"), "Gur dhvpx oebja sbk whzcf bire gur ynml qbt" ); } #[test] fn test_non_alphabet() { assert_eq!(another_rot13("🎃 Jack-o'-lantern"), "🎃 Wnpx-b'-ynagrea"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/rot13.rs
src/ciphers/rot13.rs
pub fn rot13(text: &str) -> String { let to_enc = text.to_uppercase(); to_enc .chars() .map(|c| match c { 'A'..='M' => ((c as u8) + 13) as char, 'N'..='Z' => ((c as u8) - 13) as char, _ => c, }) .collect() } #[cfg(test)] mod test { use super::*; #[test] fn test_single_letter() { assert_eq!("N", rot13("A")); } #[test] fn test_bunch_of_letters() { assert_eq!("NOP", rot13("ABC")); } #[test] fn test_non_ascii() { assert_eq!("😀NO", rot13("😀AB")); } #[test] fn test_twice() { assert_eq!("ABCD", rot13(&rot13("ABCD"))); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/sha256.rs
src/ciphers/sha256.rs
/*! * SHA-2 256 bit implementation * This implementation is based on RFC6234 * Keep in mind that the amount of data (in bits) processed should always be an * integer multiple of 8 */ // The constants are tested to make sure they are correct pub const H0: [u32; 8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ]; pub const K: [u32; 64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ]; // The following functions are implemented according to page 10 of RFC6234 #[inline] fn ch(x: u32, y: u32, z: u32) -> u32 { (x & y) ^ ((!x) & z) } #[inline] fn maj(x: u32, y: u32, z: u32) -> u32 { (x & y) ^ (x & z) ^ (y & z) } #[inline] fn bsig0(x: u32) -> u32 { x.rotate_right(2) ^ x.rotate_right(13) ^ x.rotate_right(22) } #[inline] fn bsig1(x: u32) -> u32 { x.rotate_right(6) ^ x.rotate_right(11) ^ x.rotate_right(25) } #[inline] fn ssig0(x: u32) -> u32 { x.rotate_right(7) ^ x.rotate_right(18) ^ (x >> 3) } #[inline] fn ssig1(x: u32) -> u32 { x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10) } pub struct SHA256 { /// The current block to be processed, 512 bits long buffer: [u32; 16], /// Length (bits) of the message, should always be a multiple of 8 length: u64, /// The current hash value. Note: this value is invalid unless `finalize` /// is called pub h: [u32; 8], /// Message schedule w: [u32; 64], pub finalized: bool, // Temporary values: round: [u32; 8], } fn process_block(h: &mut [u32; 8], w: &mut [u32; 64], round: &mut [u32; 8], buf: &[u32; 16]) { // Prepare the message schedule: w[..buf.len()].copy_from_slice(&buf[..]); for i in buf.len()..w.len() { w[i] = ssig1(w[i - 2]) .wrapping_add(w[i - 7]) .wrapping_add(ssig0(w[i - 15])) .wrapping_add(w[i - 16]); } round.copy_from_slice(h); for i in 0..w.len() { let t1 = round[7] .wrapping_add(bsig1(round[4])) .wrapping_add(ch(round[4], round[5], round[6])) .wrapping_add(K[i]) .wrapping_add(w[i]); let t2 = bsig0(round[0]).wrapping_add(maj(round[0], round[1], round[2])); round[7] = round[6]; round[6] = round[5]; round[5] = round[4]; round[4] = round[3].wrapping_add(t1); round[3] = round[2]; round[2] = round[1]; round[1] = round[0]; round[0] = t1.wrapping_add(t2); } for i in 0..h.len() { h[i] = h[i].wrapping_add(round[i]); } } impl SHA256 { pub fn new_default() -> Self { SHA256 { buffer: [0u32; 16], length: 0, h: H0, w: [0u32; 64], round: [0u32; 8], finalized: false, } } /// Note: buffer should be empty before calling this! pub fn process_block(&mut self, buf: &[u32; 16]) { process_block(&mut self.h, &mut self.w, &mut self.round, buf); self.length += 512; } pub fn update(&mut self, data: &[u8]) { if data.is_empty() { return; } let offset = (((32 - (self.length & 31)) & 31) >> 3) as usize; let mut buf_ind = ((self.length & 511) >> 5) as usize; for (i, &byte) in data.iter().enumerate().take(offset) { self.buffer[buf_ind] ^= (byte as u32) << ((offset - i - 1) << 3); } self.length += (data.len() as u64) << 3; if offset > data.len() { return; } if offset > 0 { buf_ind += 1; } if data.len() > 3 { for i in (offset..(data.len() - 3)).step_by(4) { if buf_ind & 16 == 16 { process_block(&mut self.h, &mut self.w, &mut self.round, &self.buffer); buf_ind = 0; } self.buffer[buf_ind] = ((data[i] as u32) << 24) ^ ((data[i + 1] as u32) << 16) ^ ((data[i + 2] as u32) << 8) ^ data[i + 3] as u32; buf_ind += 1; } } if buf_ind & 16 == 16 { process_block(&mut self.h, &mut self.w, &mut self.round, &self.buffer); buf_ind = 0; } self.buffer[buf_ind] = 0; let rem_ind = offset + ((data.len() - offset) & !0b11); for (i, &byte) in data[rem_ind..].iter().enumerate() { self.buffer[buf_ind] ^= (byte as u32) << ((3 - i) << 3); } } pub fn get_hash(&mut self) -> [u8; 32] { // we should first add a `1` bit to the end of the buffer, then we will // add enough 0s so that the length becomes (512k + 448). After that we // will append the binary representation of length to the data if !self.finalized { self.finalized = true; let clen = (self.length + 8) & 511; let num_0 = match clen.cmp(&448) { std::cmp::Ordering::Greater => (448 + 512 - clen) >> 3, _ => (448 - clen) >> 3, }; let mut padding: Vec<u8> = vec![0_u8; (num_0 + 9) as usize]; let len = padding.len(); padding[0] = 0x80; padding[len - 8] = (self.length >> 56) as u8; padding[len - 7] = (self.length >> 48) as u8; padding[len - 6] = (self.length >> 40) as u8; padding[len - 5] = (self.length >> 32) as u8; padding[len - 4] = (self.length >> 24) as u8; padding[len - 3] = (self.length >> 16) as u8; padding[len - 2] = (self.length >> 8) as u8; padding[len - 1] = self.length as u8; self.update(&padding); } assert_eq!(self.length & 511, 0); let mut result = [0u8; 32]; for i in (0..32).step_by(4) { result[i] = (self.h[i >> 2] >> 24) as u8; result[i + 1] = (self.h[i >> 2] >> 16) as u8; result[i + 2] = (self.h[i >> 2] >> 8) as u8; result[i + 3] = self.h[i >> 2] as u8; } result } } impl super::Hasher<32> for SHA256 { fn new_default() -> Self { SHA256::new_default() } fn update(&mut self, data: &[u8]) { self.update(data); } fn get_hash(&mut self) -> [u8; 32] { self.get_hash() } } #[cfg(test)] pub mod tests { use super::*; use crate::math::LinearSieve; use std::fmt::Write; // Let's keep this utility function pub fn get_hash_string(hash: &[u8; 32]) -> String { let mut result = String::new(); result.reserve(64); for &ch in hash { write!(&mut result, "{ch:02x}").unwrap(); } result } #[test] fn test_constants() { let mut ls = LinearSieve::new(); ls.prepare(311).unwrap(); assert_eq!(64, ls.primes.len()); assert_eq!(311, ls.primes[63]); let float_len = 52; let constant_len = 32; for (pos, &k) in K.iter().enumerate() { let a: f64 = ls.primes[pos] as f64; let bits = a.cbrt().to_bits(); let exp = bits >> float_len; // The sign bit is already 0 //(exp - 1023) can be bigger than 0, we must include more bits. let k_ref = ((bits & ((1_u64 << float_len) - 1)) >> (float_len - constant_len + 1023 - exp)) as u32; assert_eq!(k, k_ref); } for (pos, &h) in H0.iter().enumerate() { let a: f64 = ls.primes[pos] as f64; let bits = a.sqrt().to_bits(); let exp = bits >> float_len; let h_ref = ((bits & ((1_u64 << float_len) - 1)) >> (float_len - constant_len + 1023 - exp)) as u32; assert_eq!(h, h_ref); } } // To test the hashes, you can use the following command on linux: // echo -n 'STRING' | sha256sum // the `-n` is because by default, echo adds a `\n` to its output #[test] fn empty() { let mut res = SHA256::new_default(); assert_eq!( res.get_hash(), [ 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55 ] ); } #[test] fn ascii() { let mut res = SHA256::new_default(); res.update(b"The quick brown fox jumps over the lazy dog"); assert_eq!( res.get_hash(), [ 0xD7, 0xA8, 0xFB, 0xB3, 0x07, 0xD7, 0x80, 0x94, 0x69, 0xCA, 0x9A, 0xBC, 0xB0, 0x08, 0x2E, 0x4F, 0x8D, 0x56, 0x51, 0xE4, 0x6D, 0x3C, 0xDB, 0x76, 0x2D, 0x02, 0xD0, 0xBF, 0x37, 0xC9, 0xE5, 0x92 ] ) } #[test] fn ascii_avalanche() { let mut res = SHA256::new_default(); res.update(b"The quick brown fox jumps over the lazy dog."); assert_eq!( res.get_hash(), [ 0xEF, 0x53, 0x7F, 0x25, 0xC8, 0x95, 0xBF, 0xA7, 0x82, 0x52, 0x65, 0x29, 0xA9, 0xB6, 0x3D, 0x97, 0xAA, 0x63, 0x15, 0x64, 0xD5, 0xD7, 0x89, 0xC2, 0xB7, 0x65, 0x44, 0x8C, 0x86, 0x35, 0xFB, 0x6C ] ); // Test if finalization is not repeated twice assert_eq!( res.get_hash(), [ 0xEF, 0x53, 0x7F, 0x25, 0xC8, 0x95, 0xBF, 0xA7, 0x82, 0x52, 0x65, 0x29, 0xA9, 0xB6, 0x3D, 0x97, 0xAA, 0x63, 0x15, 0x64, 0xD5, 0xD7, 0x89, 0xC2, 0xB7, 0x65, 0x44, 0x8C, 0x86, 0x35, 0xFB, 0x6C ] ) } #[test] fn long_ascii() { let mut res = SHA256::new_default(); let val = b"The quick brown fox jumps over the lazy dog."; for _ in 0..1000 { res.update(val); } let hash = res.get_hash(); assert_eq!( &get_hash_string(&hash), "c264fca077807d391df72fadf39dd63be21f1823f65ca530c9637760eabfc18c" ); let mut res = SHA256::new_default(); let val = b"a"; for _ in 0..999 { res.update(val); } let hash = res.get_hash(); assert_eq!( &get_hash_string(&hash), "d9fe27f3d807a7c46467325f7189495e82b099ce2e14c5b16cc76697fa909f81" ) } #[test] fn short_ascii() { let mut res = SHA256::new_default(); let val = b"a"; res.update(val); let hash = res.get_hash(); assert_eq!( &get_hash_string(&hash), "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb" ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/polybius.rs
src/ciphers/polybius.rs
/// Encode an ASCII string into its location in a Polybius square. /// Only alphabetical characters are encoded. pub fn encode_ascii(string: &str) -> String { string .chars() .map(|c| match c { 'a' | 'A' => "11", 'b' | 'B' => "12", 'c' | 'C' => "13", 'd' | 'D' => "14", 'e' | 'E' => "15", 'f' | 'F' => "21", 'g' | 'G' => "22", 'h' | 'H' => "23", 'i' | 'I' | 'j' | 'J' => "24", 'k' | 'K' => "25", 'l' | 'L' => "31", 'm' | 'M' => "32", 'n' | 'N' => "33", 'o' | 'O' => "34", 'p' | 'P' => "35", 'q' | 'Q' => "41", 'r' | 'R' => "42", 's' | 'S' => "43", 't' | 'T' => "44", 'u' | 'U' => "45", 'v' | 'V' => "51", 'w' | 'W' => "52", 'x' | 'X' => "53", 'y' | 'Y' => "54", 'z' | 'Z' => "55", _ => "", }) .collect() } /// Decode a string of ints into their corresponding /// letters in a Polybius square. /// /// Any invalid characters, or whitespace will be ignored. pub fn decode_ascii(string: &str) -> String { string .chars() .filter(|c| !c.is_whitespace()) .collect::<String>() .as_bytes() .chunks(2) .map(|s| match std::str::from_utf8(s) { Ok(v) => v.parse::<i32>().unwrap_or(0), Err(_) => 0, }) .map(|i| match i { 11 => 'A', 12 => 'B', 13 => 'C', 14 => 'D', 15 => 'E', 21 => 'F', 22 => 'G', 23 => 'H', 24 => 'I', 25 => 'K', 31 => 'L', 32 => 'M', 33 => 'N', 34 => 'O', 35 => 'P', 41 => 'Q', 42 => 'R', 43 => 'S', 44 => 'T', 45 => 'U', 51 => 'V', 52 => 'W', 53 => 'X', 54 => 'Y', 55 => 'Z', _ => ' ', }) .collect::<String>() .replace(' ', "") } #[cfg(test)] mod tests { use super::{decode_ascii, encode_ascii}; #[test] fn encode_empty() { assert_eq!(encode_ascii(""), ""); } #[test] fn encode_valid_string() { assert_eq!(encode_ascii("This is a test"), "4423244324431144154344"); } #[test] fn encode_emoji() { assert_eq!(encode_ascii("🙂"), ""); } #[test] fn decode_empty() { assert_eq!(decode_ascii(""), ""); } #[test] fn decode_valid_string() { assert_eq!( decode_ascii("44 23 24 43 24 43 11 44 15 43 44 "), "THISISATEST" ); } #[test] fn decode_emoji() { assert_eq!(decode_ascii("🙂"), ""); } #[test] fn decode_string_with_whitespace() { assert_eq!( decode_ascii("44\n23\t\r24\r\n43 2443\n 11 \t 44\r \r15 \n43 44"), "THISISATEST" ); } #[test] fn decode_unknown_string() { assert_eq!(decode_ascii("94 63 64 83 64 48 77 00 05 47 48 "), ""); } #[test] fn decode_odd_length() { assert_eq!(decode_ascii("11 22 33 4"), "AGN"); } #[test] fn encode_and_decode() { let string = "Do you ever wonder why we're here?"; let encode = encode_ascii(string); assert_eq!( "1434543445155115425234331415425223545215421523154215", encode, ); assert_eq!("DOYOUEVERWONDERWHYWEREHERE", decode_ascii(&encode)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/aes.rs
src/ciphers/aes.rs
const AES_WORD_SIZE: usize = 4; const AES_BLOCK_SIZE: usize = 16; const AES_NUM_BLOCK_WORDS: usize = AES_BLOCK_SIZE / AES_WORD_SIZE; type Byte = u8; type Word = u32; type AesWord = [Byte; AES_WORD_SIZE]; /// Precalculated values for x to the power of 2 in Rijndaels galois field. /// Used as 'RCON' during the key expansion. const RCON: [Word; 256] = [ // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, ]; /// Rijndael S-box Substitution table used for encryption in the subBytes /// step, as well as the key expansion. const SBOX: [Byte; 256] = [ // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16, ]; /// Inverse Rijndael S-box Substitution table used for decryption in the /// subBytesDec step. const INV_SBOX: [Byte; 256] = [ // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D, ]; #[rustfmt::skip] const GF_MUL_TABLE: [[Byte; 256]; 16] = [ /* 0 */ [0u8; 256], /* 1 */ [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, ], /* 2 */ [ 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e, 0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e, 0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e, 0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c, 0x8e, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e, 0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa, 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe, 0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde, 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe, 0x1b, 0x19, 0x1f, 0x1d, 0x13, 0x11, 0x17, 0x15, 0x0b, 0x09, 0x0f, 0x0d, 0x03, 0x01, 0x07, 0x05, 0x3b, 0x39, 0x3f, 0x3d, 0x33, 0x31, 0x37, 0x35, 0x2b, 0x29, 0x2f, 0x2d, 0x23, 0x21, 0x27, 0x25, 0x5b, 0x59, 0x5f, 0x5d, 0x53, 0x51, 0x57, 0x55, 0x4b, 0x49, 0x4f, 0x4d, 0x43, 0x41, 0x47, 0x45, 0x7b, 0x79, 0x7f, 0x7d, 0x73, 0x71, 0x77, 0x75, 0x6b, 0x69, 0x6f, 0x6d, 0x63, 0x61, 0x67, 0x65, 0x9b, 0x99, 0x9f, 0x9d, 0x93, 0x91, 0x97, 0x95, 0x8b, 0x89, 0x8f, 0x8d, 0x83, 0x81, 0x87, 0x85, 0xbb, 0xb9, 0xbf, 0xbd, 0xb3, 0xb1, 0xb7, 0xb5, 0xab, 0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5, 0xdb, 0xd9, 0xdf, 0xdd, 0xd3, 0xd1, 0xd7, 0xd5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5, 0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, 0xf5, 0xeb, 0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5 ], /* 3 */ [ 0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, 0x17, 0x12, 0x11, 0x30, 0x33, 0x36, 0x35, 0x3c, 0x3f, 0x3a, 0x39, 0x28, 0x2b, 0x2e, 0x2d, 0x24, 0x27, 0x22, 0x21, 0x60, 0x63, 0x66, 0x65, 0x6c, 0x6f, 0x6a, 0x69, 0x78, 0x7b, 0x7e, 0x7d, 0x74, 0x77, 0x72, 0x71, 0x50, 0x53, 0x56, 0x55, 0x5c, 0x5f, 0x5a, 0x59, 0x48, 0x4b, 0x4e, 0x4d, 0x44, 0x47, 0x42, 0x41, 0xc0, 0xc3, 0xc6, 0xc5, 0xcc, 0xcf, 0xca, 0xc9, 0xd8, 0xdb, 0xde, 0xdd, 0xd4, 0xd7, 0xd2, 0xd1, 0xf0, 0xf3, 0xf6, 0xf5, 0xfc, 0xff, 0xfa, 0xf9, 0xe8, 0xeb, 0xee, 0xed, 0xe4, 0xe7, 0xe2, 0xe1, 0xa0, 0xa3, 0xa6, 0xa5, 0xac, 0xaf, 0xaa, 0xa9, 0xb8, 0xbb, 0xbe, 0xbd, 0xb4, 0xb7, 0xb2, 0xb1, 0x90, 0x93, 0x96, 0x95, 0x9c, 0x9f, 0x9a, 0x99, 0x88, 0x8b, 0x8e, 0x8d, 0x84, 0x87, 0x82, 0x81, 0x9b, 0x98, 0x9d, 0x9e, 0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, 0x86, 0x8f, 0x8c, 0x89, 0x8a, 0xab, 0xa8, 0xad, 0xae, 0xa7, 0xa4, 0xa1, 0xa2, 0xb3, 0xb0, 0xb5, 0xb6, 0xbf, 0xbc, 0xb9, 0xba, 0xfb, 0xf8, 0xfd, 0xfe, 0xf7, 0xf4, 0xf1, 0xf2, 0xe3, 0xe0, 0xe5, 0xe6, 0xef, 0xec, 0xe9, 0xea, 0xcb, 0xc8, 0xcd, 0xce, 0xc7, 0xc4, 0xc1, 0xc2, 0xd3, 0xd0, 0xd5, 0xd6, 0xdf, 0xdc, 0xd9, 0xda, 0x5b, 0x58, 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4f, 0x4c, 0x49, 0x4a, 0x6b, 0x68, 0x6d, 0x6e, 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a, 0x3b, 0x38, 0x3d, 0x3e, 0x37, 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a, 0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a, ], /* 4 */ [0u8; 256], /* 5 */ [0u8; 256], /* 6 */ [0u8; 256], /* 7 */ [0u8; 256], /* 8 */ [0u8; 256], /* 9 */ [ 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77, 0x90, 0x99, 0x82, 0x8b, 0xb4, 0xbd, 0xa6, 0xaf, 0xd8, 0xd1, 0xca, 0xc3, 0xfc, 0xf5, 0xee, 0xe7, 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, 0xab, 0xa2, 0xb9, 0xb0, 0x8f, 0x86, 0x9d, 0x94, 0xe3, 0xea, 0xf1, 0xf8, 0xc7, 0xce, 0xd5, 0xdc, 0x76, 0x7f, 0x64, 0x6d, 0x52, 0x5b, 0x40, 0x49, 0x3e, 0x37, 0x2c, 0x25, 0x1a, 0x13, 0x08, 0x01, 0xe6, 0xef, 0xf4, 0xfd, 0xc2, 0xcb, 0xd0, 0xd9, 0xae, 0xa7, 0xbc, 0xb5, 0x8a, 0x83, 0x98, 0x91, 0x4d, 0x44, 0x5f, 0x56, 0x69, 0x60, 0x7b, 0x72, 0x05, 0x0c, 0x17, 0x1e, 0x21, 0x28, 0x33, 0x3a, 0xdd, 0xd4, 0xcf, 0xc6, 0xf9, 0xf0, 0xeb, 0xe2, 0x95, 0x9c, 0x87, 0x8e, 0xb1, 0xb8, 0xa3, 0xaa, 0xec, 0xe5, 0xfe, 0xf7, 0xc8, 0xc1, 0xda, 0xd3, 0xa4, 0xad, 0xb6, 0xbf, 0x80, 0x89, 0x92, 0x9b, 0x7c, 0x75, 0x6e, 0x67, 0x58, 0x51, 0x4a, 0x43, 0x34, 0x3d, 0x26, 0x2f, 0x10, 0x19, 0x02, 0x0b, 0xd7, 0xde, 0xc5, 0xcc, 0xf3, 0xfa, 0xe1, 0xe8, 0x9f, 0x96, 0x8d, 0x84, 0xbb, 0xb2, 0xa9, 0xa0, 0x47, 0x4e, 0x55, 0x5c, 0x63, 0x6a, 0x71, 0x78, 0x0f, 0x06, 0x1d, 0x14, 0x2b, 0x22, 0x39, 0x30, 0x9a, 0x93, 0x88, 0x81, 0xbe, 0xb7, 0xac, 0xa5, 0xd2, 0xdb, 0xc0, 0xc9, 0xf6, 0xff, 0xe4, 0xed, 0x0a, 0x03, 0x18, 0x11, 0x2e, 0x27, 0x3c, 0x35, 0x42, 0x4b, 0x50, 0x59, 0x66, 0x6f, 0x74, 0x7d, 0xa1, 0xa8, 0xb3, 0xba, 0x85, 0x8c, 0x97, 0x9e, 0xe9, 0xe0, 0xfb, 0xf2, 0xcd, 0xc4, 0xdf, 0xd6, 0x31, 0x38, 0x23, 0x2a, 0x15, 0x1c, 0x07, 0x0e, 0x79, 0x70, 0x6b, 0x62, 0x5d, 0x54, 0x4f, 0x46, ], /* A */ [0u8; 256], /* B */ [ 0x00, 0x0b, 0x16, 0x1d, 0x2c, 0x27, 0x3a, 0x31, 0x58, 0x53, 0x4e, 0x45, 0x74, 0x7f, 0x62, 0x69, 0xb0, 0xbb, 0xa6, 0xad, 0x9c, 0x97, 0x8a, 0x81, 0xe8, 0xe3, 0xfe, 0xf5, 0xc4, 0xcf, 0xd2, 0xd9, 0x7b, 0x70, 0x6d, 0x66, 0x57, 0x5c, 0x41, 0x4a, 0x23, 0x28, 0x35, 0x3e, 0x0f, 0x04, 0x19, 0x12, 0xcb, 0xc0, 0xdd, 0xd6, 0xe7, 0xec, 0xf1, 0xfa, 0x93, 0x98, 0x85, 0x8e, 0xbf, 0xb4, 0xa9, 0xa2, 0xf6, 0xfd, 0xe0, 0xeb, 0xda, 0xd1, 0xcc, 0xc7, 0xae, 0xa5, 0xb8, 0xb3, 0x82, 0x89, 0x94, 0x9f, 0x46, 0x4d, 0x50, 0x5b, 0x6a, 0x61, 0x7c, 0x77, 0x1e, 0x15, 0x08, 0x03, 0x32, 0x39, 0x24, 0x2f, 0x8d, 0x86, 0x9b, 0x90, 0xa1, 0xaa, 0xb7, 0xbc, 0xd5, 0xde, 0xc3, 0xc8, 0xf9, 0xf2, 0xef, 0xe4, 0x3d, 0x36, 0x2b, 0x20, 0x11, 0x1a, 0x07, 0x0c, 0x65, 0x6e, 0x73, 0x78, 0x49, 0x42, 0x5f, 0x54, 0xf7, 0xfc, 0xe1, 0xea, 0xdb, 0xd0, 0xcd, 0xc6, 0xaf, 0xa4, 0xb9, 0xb2, 0x83, 0x88, 0x95, 0x9e, 0x47, 0x4c, 0x51, 0x5a, 0x6b, 0x60, 0x7d, 0x76, 0x1f, 0x14, 0x09, 0x02, 0x33, 0x38, 0x25, 0x2e, 0x8c, 0x87, 0x9a, 0x91, 0xa0, 0xab, 0xb6, 0xbd, 0xd4, 0xdf, 0xc2, 0xc9, 0xf8, 0xf3, 0xee, 0xe5, 0x3c, 0x37, 0x2a, 0x21, 0x10, 0x1b, 0x06, 0x0d, 0x64, 0x6f, 0x72, 0x79, 0x48, 0x43, 0x5e, 0x55, 0x01, 0x0a, 0x17, 0x1c, 0x2d, 0x26, 0x3b, 0x30, 0x59, 0x52, 0x4f, 0x44, 0x75, 0x7e, 0x63, 0x68, 0xb1, 0xba, 0xa7, 0xac, 0x9d, 0x96, 0x8b, 0x80, 0xe9, 0xe2, 0xff, 0xf4, 0xc5, 0xce, 0xd3, 0xd8, 0x7a, 0x71, 0x6c, 0x67, 0x56, 0x5d, 0x40, 0x4b, 0x22, 0x29, 0x34, 0x3f, 0x0e, 0x05, 0x18, 0x13, 0xca, 0xc1, 0xdc, 0xd7, 0xe6, 0xed, 0xf0, 0xfb, 0x92, 0x99, 0x84, 0x8f, 0xbe, 0xb5, 0xa8, 0xa3, ], /* C */ [0u8; 256], /* D */ [ 0x00, 0x0d, 0x1a, 0x17, 0x34, 0x39, 0x2e, 0x23, 0x68, 0x65, 0x72, 0x7f, 0x5c, 0x51, 0x46, 0x4b, 0xd0, 0xdd, 0xca, 0xc7, 0xe4, 0xe9, 0xfe, 0xf3, 0xb8, 0xb5, 0xa2, 0xaf, 0x8c, 0x81, 0x96, 0x9b, 0xbb, 0xb6, 0xa1, 0xac, 0x8f, 0x82, 0x95, 0x98, 0xd3, 0xde, 0xc9, 0xc4, 0xe7, 0xea, 0xfd, 0xf0, 0x6b, 0x66, 0x71, 0x7c, 0x5f, 0x52, 0x45, 0x48, 0x03, 0x0e, 0x19, 0x14, 0x37, 0x3a, 0x2d, 0x20, 0x6d, 0x60, 0x77, 0x7a, 0x59, 0x54, 0x43, 0x4e, 0x05, 0x08, 0x1f, 0x12, 0x31, 0x3c, 0x2b, 0x26, 0xbd, 0xb0, 0xa7, 0xaa, 0x89, 0x84, 0x93, 0x9e, 0xd5, 0xd8, 0xcf, 0xc2, 0xe1, 0xec, 0xfb, 0xf6, 0xd6, 0xdb, 0xcc, 0xc1, 0xe2, 0xef, 0xf8, 0xf5, 0xbe, 0xb3, 0xa4, 0xa9, 0x8a, 0x87, 0x90, 0x9d, 0x06, 0x0b, 0x1c, 0x11, 0x32, 0x3f, 0x28, 0x25, 0x6e, 0x63, 0x74, 0x79, 0x5a, 0x57, 0x40, 0x4d, 0xda, 0xd7, 0xc0, 0xcd, 0xee, 0xe3, 0xf4, 0xf9, 0xb2, 0xbf, 0xa8, 0xa5, 0x86, 0x8b, 0x9c, 0x91, 0x0a, 0x07, 0x10, 0x1d, 0x3e, 0x33, 0x24, 0x29, 0x62, 0x6f, 0x78, 0x75, 0x56, 0x5b, 0x4c, 0x41, 0x61, 0x6c, 0x7b, 0x76, 0x55, 0x58, 0x4f, 0x42, 0x09, 0x04, 0x13, 0x1e, 0x3d, 0x30, 0x27, 0x2a, 0xb1, 0xbc, 0xab, 0xa6, 0x85, 0x88, 0x9f, 0x92, 0xd9, 0xd4, 0xc3, 0xce, 0xed, 0xe0, 0xf7, 0xfa, 0xb7, 0xba, 0xad, 0xa0, 0x83, 0x8e, 0x99, 0x94, 0xdf, 0xd2, 0xc5, 0xc8, 0xeb, 0xe6, 0xf1, 0xfc, 0x67, 0x6a, 0x7d, 0x70, 0x53, 0x5e, 0x49, 0x44, 0x0f, 0x02, 0x15, 0x18, 0x3b, 0x36, 0x21, 0x2c, 0x0c, 0x01, 0x16, 0x1b, 0x38, 0x35, 0x22, 0x2f, 0x64, 0x69, 0x7e, 0x73, 0x50, 0x5d, 0x4a, 0x47, 0xdc, 0xd1, 0xc6, 0xcb, 0xe8, 0xe5, 0xf2, 0xff, 0xb4, 0xb9, 0xae, 0xa3, 0x80, 0x8d, 0x9a, 0x97 ], /* E */ [ 0x00, 0x0e, 0x1c, 0x12, 0x38, 0x36, 0x24, 0x2a, 0x70, 0x7e, 0x6c, 0x62, 0x48, 0x46, 0x54, 0x5a, 0xe0, 0xee, 0xfc, 0xf2, 0xd8, 0xd6, 0xc4, 0xca, 0x90, 0x9e, 0x8c, 0x82, 0xa8, 0xa6, 0xb4, 0xba, 0xdb, 0xd5, 0xc7, 0xc9, 0xe3, 0xed, 0xff, 0xf1, 0xab, 0xa5, 0xb7, 0xb9, 0x93, 0x9d, 0x8f, 0x81, 0x3b, 0x35, 0x27, 0x29, 0x03, 0x0d, 0x1f, 0x11, 0x4b, 0x45, 0x57, 0x59, 0x73, 0x7d, 0x6f, 0x61, 0xad, 0xa3, 0xb1, 0xbf, 0x95, 0x9b, 0x89, 0x87, 0xdd, 0xd3, 0xc1, 0xcf, 0xe5, 0xeb, 0xf9, 0xf7, 0x4d, 0x43, 0x51, 0x5f, 0x75, 0x7b, 0x69, 0x67, 0x3d, 0x33, 0x21, 0x2f, 0x05, 0x0b, 0x19, 0x17, 0x76, 0x78, 0x6a, 0x64, 0x4e, 0x40, 0x52, 0x5c, 0x06, 0x08, 0x1a, 0x14, 0x3e, 0x30, 0x22, 0x2c, 0x96, 0x98, 0x8a, 0x84, 0xae, 0xa0, 0xb2, 0xbc, 0xe6, 0xe8, 0xfa, 0xf4, 0xde, 0xd0, 0xc2, 0xcc, 0x41, 0x4f, 0x5d, 0x53, 0x79, 0x77, 0x65, 0x6b, 0x31, 0x3f, 0x2d, 0x23, 0x09, 0x07, 0x15, 0x1b, 0xa1, 0xaf, 0xbd, 0xb3, 0x99, 0x97, 0x85, 0x8b, 0xd1, 0xdf, 0xcd, 0xc3, 0xe9, 0xe7, 0xf5, 0xfb, 0x9a, 0x94, 0x86, 0x88, 0xa2, 0xac, 0xbe, 0xb0, 0xea, 0xe4, 0xf6, 0xf8, 0xd2, 0xdc, 0xce, 0xc0, 0x7a, 0x74, 0x66, 0x68, 0x42, 0x4c, 0x5e, 0x50, 0x0a, 0x04, 0x16, 0x18, 0x32, 0x3c, 0x2e, 0x20, 0xec, 0xe2, 0xf0, 0xfe, 0xd4, 0xda, 0xc8, 0xc6, 0x9c, 0x92, 0x80, 0x8e, 0xa4, 0xaa, 0xb8, 0xb6, 0x0c, 0x02, 0x10, 0x1e, 0x34, 0x3a, 0x28, 0x26, 0x7c, 0x72, 0x60, 0x6e, 0x44, 0x4a, 0x58, 0x56, 0x37, 0x39, 0x2b, 0x25, 0x0f, 0x01, 0x13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d, 0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd, 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d ], /* F */ [0u8; 256], ]; pub enum AesKey { AesKey128([Byte; 16]), AesKey192([Byte; 24]), AesKey256([Byte; 32]), } #[derive(Clone, Copy)] enum AesMode { Encryption, Decryption, } pub fn aes_encrypt(plain_text: &[Byte], key: AesKey) -> Vec<Byte> { let (key, num_rounds) = match key { AesKey::AesKey128(key) => (Vec::from(key), 10), AesKey::AesKey192(key) => (Vec::from(key), 12), AesKey::AesKey256(key) => (Vec::from(key), 14), }; let round_keys = key_expansion(&key, num_rounds); let mut data = padding::<Byte>(plain_text, AES_BLOCK_SIZE); let round_key = &round_keys[0..AES_BLOCK_SIZE]; add_round_key(&mut data, round_key); for round in 1..num_rounds { sub_bytes_blocks(&mut data, AesMode::Encryption); shift_rows_blocks(&mut data, AesMode::Encryption); mix_column_blocks(&mut data, AesMode::Encryption); let round_key = &round_keys[round * AES_BLOCK_SIZE..(round + 1) * AES_BLOCK_SIZE]; add_round_key(&mut data, round_key); } sub_bytes_blocks(&mut data, AesMode::Encryption); shift_rows_blocks(&mut data, AesMode::Encryption); let round_key = &round_keys[num_rounds * AES_BLOCK_SIZE..(num_rounds + 1) * AES_BLOCK_SIZE]; add_round_key(&mut data, round_key); data } pub fn aes_decrypt(cipher_text: &[Byte], key: AesKey) -> Vec<Byte> { let (key, num_rounds) = match key { AesKey::AesKey128(key) => (Vec::from(key), 10), AesKey::AesKey192(key) => (Vec::from(key), 12), AesKey::AesKey256(key) => (Vec::from(key), 14), }; let round_keys = key_expansion(&key, num_rounds); let mut data = padding::<Byte>(cipher_text, AES_BLOCK_SIZE); let round_key = &round_keys[num_rounds * AES_BLOCK_SIZE..(num_rounds + 1) * AES_BLOCK_SIZE]; add_round_key(&mut data, round_key); shift_rows_blocks(&mut data, AesMode::Decryption); sub_bytes_blocks(&mut data, AesMode::Decryption); for round in (1..num_rounds).rev() { let round_key = &round_keys[round * AES_BLOCK_SIZE..(round + 1) * AES_BLOCK_SIZE]; add_round_key(&mut data, round_key); mix_column_blocks(&mut data, AesMode::Decryption); shift_rows_blocks(&mut data, AesMode::Decryption); sub_bytes_blocks(&mut data, AesMode::Decryption); } let round_key = &round_keys[0..AES_BLOCK_SIZE]; add_round_key(&mut data, round_key); data } fn key_expansion(init_key: &[Byte], num_rounds: usize) -> Vec<Byte> { let nr = num_rounds; // number of words in initial key let nk = init_key.len() / AES_WORD_SIZE; let nb = AES_NUM_BLOCK_WORDS; let key = init_key .chunks(AES_WORD_SIZE) .map(bytes_to_word) .collect::<Vec<Word>>(); let mut key = padding::<Word>(&key, nk * (nr + 1)); for i in nk..nb * (nr + 1) { let mut temp_word = key[i - 1]; if i % nk == 0 { temp_word = sub_word(rot_word(temp_word), AesMode::Encryption) ^ RCON[i / nk]; } else if nk > 6 && i % nk == 4 { temp_word = sub_word(temp_word, AesMode::Encryption); } key[i] = key[i - nk] ^ temp_word; } key.iter() .map(|&w| word_to_bytes(w)) .collect::<Vec<AesWord>>() .concat() } fn add_round_key(data: &mut [Byte], round_key: &[Byte]) { assert!(data.len().is_multiple_of(AES_BLOCK_SIZE) && round_key.len() == AES_BLOCK_SIZE); let num_blocks = data.len() / AES_BLOCK_SIZE; data.iter_mut() .zip(round_key.repeat(num_blocks)) .for_each(|(s, k)| *s ^= k); } fn sub_bytes_blocks(data: &mut [Byte], mode: AesMode) { for block in data.chunks_mut(AES_BLOCK_SIZE) { sub_bytes(block, mode); } } fn shift_rows_blocks(blocks: &mut [Byte], mode: AesMode) { for block in blocks.chunks_mut(AES_BLOCK_SIZE) { transpose_block(block); shift_rows(block, mode); transpose_block(block); } } fn mix_column_blocks(data: &mut [Byte], mode: AesMode) { for block in data.chunks_mut(AES_BLOCK_SIZE) { transpose_block(block); mix_column(block, mode); transpose_block(block); } } fn padding<T: Clone + Default>(data: &[T], block_size: usize) -> Vec<T> { if data.len().is_multiple_of(block_size) { Vec::from(data) } else { let num_blocks = data.len() / block_size + 1; let mut padded = Vec::from(data); padded.append(&mut vec![ T::default(); num_blocks * block_size - data.len() ]); padded } } fn sub_word(word: Word, mode: AesMode) -> Word { let mut bytes = word_to_bytes(word); sub_bytes(&mut bytes, mode); bytes_to_word(&bytes) } fn sub_bytes(data: &mut [Byte], mode: AesMode) { let sbox = match mode { AesMode::Encryption => &SBOX, AesMode::Decryption => &INV_SBOX, }; for data_byte in data { *data_byte = sbox[*data_byte as usize]; } } fn shift_rows(block: &mut [Byte], mode: AesMode) { // skip the first row, index begin from 1 for row in 1..4 { let mut row_word: AesWord = [0u8; 4]; row_word.copy_from_slice(&block[row * 4..row * 4 + 4]); for col in 0..4 { block[row * 4 + col] = match mode { AesMode::Encryption => row_word[(col + row) % 4], AesMode::Decryption => row_word[(col + 4 - row) % 4], } } } } fn mix_column(block: &mut [Byte], mode: AesMode) { let mix_col_mat = match mode { AesMode::Encryption => [ [0x02, 0x03, 0x01, 0x01], [0x01, 0x02, 0x03, 0x01], [0x01, 0x01, 0x02, 0x03], [0x03, 0x01, 0x01, 0x02], ], AesMode::Decryption => [ [0x0e, 0x0b, 0x0d, 0x09], [0x09, 0x0e, 0x0b, 0x0d], [0x0d, 0x09, 0x0e, 0x0b], [0x0b, 0x0d, 0x09, 0x0e], ], }; for col in 0..4 { let col_word = block .iter() .zip(0..AES_BLOCK_SIZE) .filter_map(|(&x, i)| if i % 4 == col { Some(x) } else { None }) .collect::<Vec<u8>>(); for row in 0..4 { let mut word = 0; for i in 0..4 { word ^= GF_MUL_TABLE[mix_col_mat[row][i]][col_word[i] as usize] as Word } block[row * 4 + col] = word as Byte; } } } fn transpose_block(block: &mut [u8]) { let mut src_block = [0u8; AES_BLOCK_SIZE]; src_block.copy_from_slice(block); for row in 0..4 { for col in 0..4 { block[row * 4 + col] = src_block[col * 4 + row]; } } } fn bytes_to_word(bytes: &[Byte]) -> Word { assert!(bytes.len() == AES_WORD_SIZE); let mut word = 0; for (i, &byte) in bytes.iter().enumerate() { word |= (byte as Word) << (8 * i); } word } fn word_to_bytes(word: Word) -> AesWord { let mut bytes = [0; AES_WORD_SIZE]; for (i, byte) in bytes.iter_mut().enumerate() { let bits_shift = 8 * i; *byte = ((word & (0xff << bits_shift)) >> bits_shift) as Byte; } bytes } fn rot_word(word: Word) -> Word { let mut bytes = word_to_bytes(word); let init = bytes[0]; bytes[0] = bytes[1]; bytes[1] = bytes[2]; bytes[2] = bytes[3]; bytes[3] = init; bytes_to_word(&bytes) } #[cfg(test)] mod tests { use super::*; #[test] fn test_aes_128() { let plain: [u8; 16] = [ 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34, ]; let key: [u8; 16] = [ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c, ]; let cipher: [u8; 16] = [ 0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, 0x32, ]; let encrypted = aes_encrypt(&plain, AesKey::AesKey128(key)); assert_eq!(cipher, encrypted[..]); let decrypted = aes_decrypt(&encrypted, AesKey::AesKey128(key)); assert_eq!(plain, decrypted[..]); } #[test] fn test_aes_192() { let plain: [u8; 16] = [ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, ]; let key: [u8; 24] = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, ]; let cipher: [u8; 16] = [ 0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0, 0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71, 0x91, ]; let encrypted = aes_encrypt(&plain, AesKey::AesKey192(key)); assert_eq!(cipher, encrypted[..]); let decrypted = aes_decrypt(&encrypted, AesKey::AesKey192(key)); assert_eq!(plain, decrypted[..]); } #[test] fn test_aes_256() { let plain: [u8; 16] = [ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, ]; let key: [u8; 32] = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, ]; let cipher: [u8; 16] = [ 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89, ]; let encrypted = aes_encrypt(&plain, AesKey::AesKey256(key)); assert_eq!(cipher, encrypted[..]); let decrypted = aes_decrypt(&encrypted, AesKey::AesKey256(key)); assert_eq!(plain, decrypted[..]); } #[test] fn test_str() { let str = "Hello, cipher world!"; let plain = str.as_bytes(); let key = [ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c, ]; let encrypted = aes_encrypt(plain, AesKey::AesKey128(key)); let decrypted = aes_decrypt(&encrypted, AesKey::AesKey128(key)); assert_eq!( str, String::from_utf8(decrypted).unwrap().trim_end_matches('\0') ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/mod.rs
src/ciphers/mod.rs
mod aes; mod another_rot13; mod baconian_cipher; mod base64; mod blake2b; mod caesar; mod chacha; mod diffie_hellman; mod hashing_traits; mod kernighan; mod morse_code; mod polybius; mod rail_fence; mod rot13; mod rsa_cipher; mod salsa; mod sha256; mod sha3; mod tea; mod theoretical_rot13; mod transposition; mod vernam; mod vigenere; mod xor; pub use self::aes::{aes_decrypt, aes_encrypt, AesKey}; pub use self::another_rot13::another_rot13; pub use self::baconian_cipher::{baconian_decode, baconian_encode}; pub use self::base64::{base64_decode, base64_encode}; pub use self::blake2b::blake2b; pub use self::caesar::caesar; pub use self::chacha::chacha20; pub use self::diffie_hellman::DiffieHellman; pub use self::hashing_traits::Hasher; pub use self::hashing_traits::HMAC; pub use self::kernighan::kernighan; pub use self::morse_code::{decode, encode}; pub use self::polybius::{decode_ascii, encode_ascii}; pub use self::rail_fence::{rail_fence_decrypt, rail_fence_encrypt}; pub use self::rot13::rot13; pub use self::rsa_cipher::{ decrypt, decrypt_text, encrypt, encrypt_text, generate_keypair, PrivateKey, PublicKey, }; pub use self::salsa::salsa20; pub use self::sha256::SHA256; pub use self::sha3::{sha3_224, sha3_256, sha3_384, sha3_512}; pub use self::tea::{tea_decrypt, tea_encrypt}; pub use self::theoretical_rot13::theoretical_rot13; pub use self::transposition::transposition; pub use self::vernam::{vernam_decrypt, vernam_encrypt}; pub use self::vigenere::vigenere; pub use self::xor::xor;
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/vernam.rs
src/ciphers/vernam.rs
//! Vernam Cipher //! //! The Vernam cipher is a symmetric stream cipher where plaintext is combined //! with a random or pseudorandom stream of data (the key) of the same length. //! This implementation uses the alphabet A-Z with modular arithmetic. //! //! # Algorithm //! //! For encryption: C = (P + K) mod 26 //! For decryption: P = (C - K) mod 26 //! //! Where P is plaintext, K is key, and C is ciphertext (all converted to 0-25 range) /// Encrypts a plaintext string using the Vernam cipher. /// /// The function converts all input to uppercase and works only with letters A-Z. /// The key is repeated cyclically if it's shorter than the plaintext. /// /// # Arguments /// /// * `plaintext` - The text to encrypt (will be converted to uppercase) /// * `key` - The encryption key (will be converted to uppercase, must not be empty) /// /// # Returns /// /// The encrypted ciphertext as an uppercase string /// /// # Panics /// /// Panics if the key is empty /// /// # Example /// /// ``` /// use the_algorithms_rust::ciphers::vernam_encrypt; /// /// let ciphertext = vernam_encrypt("HELLO", "KEY"); /// assert_eq!(ciphertext, "RIJVS"); /// ``` pub fn vernam_encrypt(plaintext: &str, key: &str) -> String { assert!(!key.is_empty(), "Key cannot be empty"); let plaintext = plaintext.to_uppercase(); let key = key.to_uppercase(); let plaintext_bytes: Vec<u8> = plaintext .chars() .filter(|c| c.is_ascii_alphabetic()) .map(|c| (c as u8) - b'A') .collect(); let key_bytes: Vec<u8> = key .chars() .filter(|c| c.is_ascii_alphabetic()) .map(|c| (c as u8) - b'A') .collect(); assert!( !key_bytes.is_empty(), "Key must contain at least one letter" ); plaintext_bytes .iter() .enumerate() .map(|(i, &p)| { let k = key_bytes[i % key_bytes.len()]; let encrypted = (p + k) % 26; (encrypted + b'A') as char }) .collect() } /// Decrypts a ciphertext string using the Vernam cipher. /// /// The function converts all input to uppercase and works only with letters A-Z. /// The key is repeated cyclically if it's shorter than the ciphertext. /// /// # Arguments /// /// * `ciphertext` - The text to decrypt (will be converted to uppercase) /// * `key` - The decryption key (will be converted to uppercase, must not be empty) /// /// # Returns /// /// The decrypted plaintext as an uppercase string /// /// # Panics /// /// Panics if the key is empty /// /// # Example /// /// ``` /// use the_algorithms_rust::ciphers::vernam_decrypt; /// /// let plaintext = vernam_decrypt("RIJVS", "KEY"); /// assert_eq!(plaintext, "HELLO"); /// ``` pub fn vernam_decrypt(ciphertext: &str, key: &str) -> String { assert!(!key.is_empty(), "Key cannot be empty"); let ciphertext = ciphertext.to_uppercase(); let key = key.to_uppercase(); let ciphertext_bytes: Vec<u8> = ciphertext .chars() .filter(|c| c.is_ascii_alphabetic()) .map(|c| (c as u8) - b'A') .collect(); let key_bytes: Vec<u8> = key .chars() .filter(|c| c.is_ascii_alphabetic()) .map(|c| (c as u8) - b'A') .collect(); assert!( !key_bytes.is_empty(), "Key must contain at least one letter" ); ciphertext_bytes .iter() .enumerate() .map(|(i, &c)| { let k = key_bytes[i % key_bytes.len()]; // Add 26 before modulo to handle negative numbers properly let decrypted = (c + 26 - k) % 26; (decrypted + b'A') as char }) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn test_encrypt_basic() { assert_eq!(vernam_encrypt("HELLO", "KEY"), "RIJVS"); } #[test] fn test_decrypt_basic() { assert_eq!(vernam_decrypt("RIJVS", "KEY"), "HELLO"); } #[test] fn test_encrypt_decrypt_roundtrip() { let plaintext = "HELLO"; let key = "KEY"; let encrypted = vernam_encrypt(plaintext, key); let decrypted = vernam_decrypt(&encrypted, key); assert_eq!(decrypted, plaintext); } #[test] fn test_encrypt_decrypt_long_text() { let plaintext = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG"; let key = "SECRET"; let encrypted = vernam_encrypt(plaintext, key); let decrypted = vernam_decrypt(&encrypted, key); assert_eq!(decrypted, plaintext); } #[test] fn test_lowercase_input() { // Should convert to uppercase assert_eq!(vernam_encrypt("hello", "key"), "RIJVS"); assert_eq!(vernam_decrypt("rijvs", "key"), "HELLO"); } #[test] fn test_mixed_case_input() { assert_eq!(vernam_encrypt("HeLLo", "KeY"), "RIJVS"); assert_eq!(vernam_decrypt("RiJvS", "kEy"), "HELLO"); } #[test] fn test_single_character() { assert_eq!(vernam_encrypt("A", "B"), "B"); assert_eq!(vernam_decrypt("B", "B"), "A"); } #[test] fn test_key_wrapping() { // Key shorter than plaintext, should wrap around let encrypted = vernam_encrypt("AAAA", "BC"); assert_eq!(encrypted, "BCBC"); let decrypted = vernam_decrypt(&encrypted, "BC"); assert_eq!(decrypted, "AAAA"); } #[test] fn test_alphabet_boundary() { // Test wrapping at alphabet boundaries assert_eq!(vernam_encrypt("Z", "B"), "A"); // 25 + 1 = 26 -> 0 assert_eq!(vernam_decrypt("A", "B"), "Z"); // 0 - 1 = -1 -> 25 } #[test] fn test_same_key_as_plaintext() { let text = "HELLO"; let encrypted = vernam_encrypt(text, text); assert_eq!(encrypted, "OIWWC"); } #[test] fn test_with_spaces_and_numbers() { // Non-alphabetic characters should be filtered out let encrypted = vernam_encrypt("HELLO 123 WORLD", "KEY"); let expected = vernam_encrypt("HELLOWORLD", "KEY"); assert_eq!(encrypted, expected); } #[test] #[should_panic(expected = "Key cannot be empty")] fn test_empty_key_encrypt() { vernam_encrypt("HELLO", ""); } #[test] #[should_panic(expected = "Key cannot be empty")] fn test_empty_key_decrypt() { vernam_decrypt("HELLO", ""); } #[test] #[should_panic(expected = "Key must contain at least one letter")] fn test_key_with_only_numbers() { vernam_encrypt("HELLO", "12345"); } #[test] fn test_empty_plaintext() { assert_eq!(vernam_encrypt("", "KEY"), ""); } #[test] fn test_plaintext_with_only_numbers() { assert_eq!(vernam_encrypt("12345", "KEY"), ""); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/vigenere.rs
src/ciphers/vigenere.rs
//! Vigenère Cipher //! //! # Algorithm //! //! Rotate each ascii character by the offset of the corresponding key character. //! When we reach the last key character, we start over from the first one. //! This implementation does not rotate unicode characters. /// Vigenère cipher to rotate plain_text text by key and return an owned String. pub fn vigenere(plain_text: &str, key: &str) -> String { // Remove all unicode and non-ascii characters from key let key: String = key.chars().filter(|&c| c.is_ascii_alphabetic()).collect(); let key = key.to_ascii_lowercase(); let key_len = key.len(); if key_len == 0 { return String::from(plain_text); } let mut index = 0; plain_text .chars() .map(|c| { if c.is_ascii_alphabetic() { let first = if c.is_ascii_lowercase() { b'a' } else { b'A' }; let shift = key.as_bytes()[index % key_len] - b'a'; index += 1; // modulo the distance to keep character range (first + (c as u8 + shift - first) % 26) as char } else { c } }) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn empty() { assert_eq!(vigenere("", "test"), ""); } #[test] fn vigenere_base() { assert_eq!( vigenere("LoremIpsumDolorSitAmet", "base"), "MojinIhwvmVsmojWjtSqft" ); } #[test] fn vigenere_with_spaces() { assert_eq!( vigenere( "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "spaces" ), "Ddrgq ahhuo hgddr uml sbev, ggfheexwljr chahxsemfy tlkx." ); } #[test] fn vigenere_unicode_and_numbers() { assert_eq!( vigenere("1 Lorem ⏳ ipsum dolor sit amet Ѡ", "unicode"), "1 Fbzga ⏳ ltmhu fcosl fqv opin Ѡ" ); } #[test] fn vigenere_unicode_key() { assert_eq!( vigenere("Lorem ipsum dolor sit amet", "😉 key!"), "Vspoq gzwsw hmvsp cmr kqcd" ); } #[test] fn vigenere_empty_key() { assert_eq!(vigenere("Lorem ipsum", ""), "Lorem ipsum"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/tea.rs
src/ciphers/tea.rs
use std::num::Wrapping as W; struct TeaContext { key0: u64, key1: u64, } impl TeaContext { pub fn new(key: &[u64; 2]) -> TeaContext { TeaContext { key0: key[0], key1: key[1], } } pub fn encrypt_block(&self, block: u64) -> u64 { let (mut b0, mut b1) = divide_u64(block); let (k0, k1) = divide_u64(self.key0); let (k2, k3) = divide_u64(self.key1); let mut sum = W(0u32); for _ in 0..32 { sum += W(0x9E3779B9); b0 += ((b1 << 4) + k0) ^ (b1 + sum) ^ ((b1 >> 5) + k1); b1 += ((b0 << 4) + k2) ^ (b0 + sum) ^ ((b0 >> 5) + k3); } ((b1.0 as u64) << 32) | b0.0 as u64 } pub fn decrypt_block(&self, block: u64) -> u64 { let (mut b0, mut b1) = divide_u64(block); let (k0, k1) = divide_u64(self.key0); let (k2, k3) = divide_u64(self.key1); let mut sum = W(0xC6EF3720u32); for _ in 0..32 { b1 -= ((b0 << 4) + k2) ^ (b0 + sum) ^ ((b0 >> 5) + k3); b0 -= ((b1 << 4) + k0) ^ (b1 + sum) ^ ((b1 >> 5) + k1); sum -= W(0x9E3779B9); } ((b1.0 as u64) << 32) | b0.0 as u64 } } #[inline] fn divide_u64(n: u64) -> (W<u32>, W<u32>) { (W(n as u32), W((n >> 32) as u32)) } pub fn tea_encrypt(plain: &[u8], key: &[u8]) -> Vec<u8> { let tea = TeaContext::new(&[to_block(&key[..8]), to_block(&key[8..16])]); let mut result: Vec<u8> = Vec::new(); for i in (0..plain.len()).step_by(8) { let block = to_block(&plain[i..i + 8]); result.extend(from_block(tea.encrypt_block(block)).iter()); } result } pub fn tea_decrypt(cipher: &[u8], key: &[u8]) -> Vec<u8> { let tea = TeaContext::new(&[to_block(&key[..8]), to_block(&key[8..16])]); let mut result: Vec<u8> = Vec::new(); for i in (0..cipher.len()).step_by(8) { let block = to_block(&cipher[i..i + 8]); result.extend(from_block(tea.decrypt_block(block)).iter()); } result } #[inline] fn to_block(data: &[u8]) -> u64 { data[0] as u64 | (data[1] as u64) << 8 | (data[2] as u64) << 16 | (data[3] as u64) << 24 | (data[4] as u64) << 32 | (data[5] as u64) << 40 | (data[6] as u64) << 48 | (data[7] as u64) << 56 } fn from_block(block: u64) -> [u8; 8] { [ block as u8, (block >> 8) as u8, (block >> 16) as u8, (block >> 24) as u8, (block >> 32) as u8, (block >> 40) as u8, (block >> 48) as u8, (block >> 56) as u8, ] } #[cfg(test)] mod test { use super::*; #[test] fn test_block_convert() { assert_eq!( to_block(&[0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]), 0xefcdab8967452301 ); assert_eq!( from_block(0xefcdab8967452301), [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef] ); } #[test] fn test_tea_encrypt() { assert_eq!( tea_encrypt( &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], &[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] ), [0x0A, 0x3A, 0xEA, 0x41, 0x40, 0xA9, 0xBA, 0x94] ); } #[test] fn test_tea_encdec() { let plain = &[0x1b, 0xcc, 0xd4, 0x31, 0xa0, 0xf6, 0x8a, 0x55]; let key = &[ 0x20, 0x45, 0x08, 0x10, 0xb0, 0x23, 0xe2, 0x17, 0xc3, 0x81, 0xd6, 0xf2, 0xee, 0x00, 0xa4, 0x8a, ]; let cipher = tea_encrypt(plain, key); assert_eq!(tea_decrypt(&cipher[..], key), plain); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/baconian_cipher.rs
src/ciphers/baconian_cipher.rs
// Author : cyrixninja //Program to encode and decode Baconian or Bacon's Cipher //Wikipedia reference : https://en.wikipedia.org/wiki/Bacon%27s_cipher // Bacon's cipher or the Baconian cipher is a method of steganographic message encoding devised by Francis Bacon in 1605. // A message is concealed in the presentation of text, rather than its content. Bacon cipher is categorized as both a substitution cipher (in plain code) and a concealment cipher (using the two typefaces). // Encode Baconian Cipher pub fn baconian_encode(message: &str) -> String { let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; let baconian = [ "AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB", "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB", "BABAA", "BABAB", "BABBA", "BABBB", ]; message .chars() .map(|c| { if let Some(index) = alphabet.find(c.to_ascii_uppercase()) { baconian[index].to_string() } else { c.to_string() } }) .collect() } // Decode Baconian Cipher pub fn baconian_decode(encoded: &str) -> String { let baconian = [ "AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB", "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB", "BABAA", "BABAB", "BABBA", "BABBB", ]; let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; encoded .as_bytes() .chunks(5) .map(|chunk| { if let Some(index) = baconian .iter() .position(|&x| x == String::from_utf8_lossy(chunk)) { alphabet.chars().nth(index).unwrap() } else { ' ' } }) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn test_baconian_encoding() { let message = "HELLO"; let encoded = baconian_encode(message); assert_eq!(encoded, "AABBBAABAAABABBABABBABBBA"); } #[test] fn test_baconian_decoding() { let message = "AABBBAABAAABABBABABBABBBA"; let decoded = baconian_decode(message); assert_eq!(decoded, "HELLO"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/theoretical_rot13.rs
src/ciphers/theoretical_rot13.rs
// in theory rot-13 only affects the lowercase characters in a cipher pub fn theoretical_rot13(text: &str) -> String { let mut pos: u8 = 0; let mut npos: u8 = 0; text.to_owned() .chars() .map(|mut c| { if c.is_ascii_lowercase() { // ((c as u8) + 13) as char pos = c as u8 - b'a'; npos = (pos + 13) % 26; c = (npos + b'a') as char; c } else { c } }) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn test_single_letter() { assert_eq!("n", theoretical_rot13("a")); } #[test] fn test_bunch_of_letters() { assert_eq!("nop op", theoretical_rot13("abc bc")); } #[test] fn test_non_ascii() { assert_eq!("😀ab", theoretical_rot13("😀no")); } #[test] fn test_twice() { assert_eq!("abcd", theoretical_rot13(&theoretical_rot13("abcd"))); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/two_sum.rs
src/general/two_sum.rs
use std::collections::HashMap; /// Given an array of integers nums and an integer target, /// return indices of the two numbers such that they add up to target. /// /// # Parameters /// /// - `nums`: A list of numbers to check. /// - `target`: The target sum. /// /// # Returns /// /// If the target sum is found in the array, the indices of the augend and /// addend are returned as a tuple. /// /// If the target sum cannot be found in the array, `None` is returned. /// pub fn two_sum(nums: Vec<i32>, target: i32) -> Option<(usize, usize)> { // This HashMap is used to look up a corresponding index in the `nums` list. // Given that we know where we are at in the array, we can look up our // complementary value using this table and only go through the list once. // // We populate this table with distances from the target. As we go through // the list, a distance is computed like so: // // `target - current_value` // // This distance also tells us about the complementary value we're looking // for in the array. If we don't find that value, we insert `current_value` // into the table for future look-ups. As we iterate through the list, // the number we just inserted might be the perfect distance for another // number, and we've found a match! // let mut distance_table: HashMap<i32, usize> = HashMap::new(); for (i, current_value) in nums.iter().enumerate() { match distance_table.get(&(target - current_value)) { Some(j) => return Some((i, *j)), _ => distance_table.insert(*current_value, i), }; } // No match was found! None } #[cfg(test)] mod test { use super::*; #[test] fn test() { let nums = vec![2, 7, 11, 15]; assert_eq!(two_sum(nums, 9), Some((1, 0))); let nums = vec![3, 2, 4]; assert_eq!(two_sum(nums, 6), Some((2, 1))); let nums = vec![3, 3]; assert_eq!(two_sum(nums, 6), Some((1, 0))); let nums = vec![2, 7, 11, 15]; assert_eq!(two_sum(nums, 16), None); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/hanoi.rs
src/general/hanoi.rs
pub fn hanoi(n: i32, from: i32, to: i32, via: i32, moves: &mut Vec<(i32, i32)>) { if n > 0 { hanoi(n - 1, from, via, to, moves); moves.push((from, to)); hanoi(n - 1, via, to, from, moves); } } #[cfg(test)] mod tests { use super::*; #[test] fn hanoi_simple() { let correct_solution: Vec<(i32, i32)> = vec![(1, 3), (1, 2), (3, 2), (1, 3), (2, 1), (2, 3), (1, 3)]; let mut our_solution: Vec<(i32, i32)> = Vec::new(); hanoi(3, 1, 3, 2, &mut our_solution); assert_eq!(correct_solution, our_solution); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/kmeans.rs
src/general/kmeans.rs
// Macro to implement kmeans for both f64 and f32 without writing everything // twice or importing the `num` crate macro_rules! impl_kmeans { ($kind: ty, $modname: ident) => { // Since we can't overload methods in rust, we have to use namespacing pub mod $modname { /// computes sum of squared deviation between two identically sized vectors /// `x`, and `y`. fn distance(x: &[$kind], y: &[$kind]) -> $kind { x.iter() .zip(y.iter()) .fold(0.0, |dist, (&xi, &yi)| dist + (xi - yi).powi(2)) } /// Returns a vector containing the indices z<sub>i</sub> in {0, ..., K-1} of /// the centroid nearest to each datum. fn nearest_centroids(xs: &[Vec<$kind>], centroids: &[Vec<$kind>]) -> Vec<usize> { xs.iter() .map(|xi| { // Find the argmin by folding using a tuple containing the argmin // and the minimum distance. let (argmin, _) = centroids.iter().enumerate().fold( (0_usize, <$kind>::INFINITY), |(min_ix, min_dist), (ix, ci)| { let dist = distance(xi, ci); if dist < min_dist { (ix, dist) } else { (min_ix, min_dist) } }, ); argmin }) .collect() } /// Recompute the centroids given the current clustering fn recompute_centroids( xs: &[Vec<$kind>], clustering: &[usize], k: usize, ) -> Vec<Vec<$kind>> { let ndims = xs[0].len(); // NOTE: Kind of inefficient because we sweep all the data from each of the // k centroids. (0..k) .map(|cluster_ix| { let mut centroid: Vec<$kind> = vec![0.0; ndims]; let mut n_cluster: $kind = 0.0; xs.iter().zip(clustering.iter()).for_each(|(xi, &zi)| { if zi == cluster_ix { n_cluster += 1.0; xi.iter().enumerate().for_each(|(j, &x_ij)| { centroid[j] += x_ij; }); } }); centroid.iter().map(|&c_j| c_j / n_cluster).collect() }) .collect() } /// Assign the N D-dimensional data, `xs`, to `k` clusters using K-Means clustering pub fn kmeans(xs: Vec<Vec<$kind>>, k: usize) -> Vec<usize> { assert!(xs.len() >= k); // Rather than pulling in a dependency to radomly select the staring // points for the centroids, we're going to deterministally choose them by // slecting evenly spaced points in `xs` let n_per_cluster: usize = xs.len() / k; let centroids: Vec<Vec<$kind>> = (0..k).map(|j| xs[j * n_per_cluster].clone()).collect(); let mut clustering = nearest_centroids(&xs, &centroids); loop { let centroids = recompute_centroids(&xs, &clustering, k); let new_clustering = nearest_centroids(&xs, &centroids); // loop until the clustering doesn't change after the new centroids are computed if new_clustering .iter() .zip(clustering.iter()) .all(|(&za, &zb)| za == zb) { // We need to use `return` to break out of the `loop` return clustering; } clustering = new_clustering; } } } }; } // generate code for kmeans for f32 and f64 data impl_kmeans!(f64, f64); impl_kmeans!(f32, f32); #[cfg(test)] mod test { use self::super::f64::kmeans; #[test] fn easy_univariate_clustering() { let xs: Vec<Vec<f64>> = vec![ vec![-1.1], vec![-1.2], vec![-1.3], vec![-1.4], vec![1.1], vec![1.2], vec![1.3], vec![1.4], ]; let clustering = kmeans(xs, 2); assert_eq!(clustering, vec![0, 0, 0, 0, 1, 1, 1, 1]); } #[test] fn easy_univariate_clustering_odd_number_of_data() { let xs: Vec<Vec<f64>> = vec![ vec![-1.1], vec![-1.2], vec![-1.3], vec![-1.4], vec![1.1], vec![1.2], vec![1.3], vec![1.4], vec![1.5], ]; let clustering = kmeans(xs, 2); assert_eq!(clustering, vec![0, 0, 0, 0, 1, 1, 1, 1, 1]); } #[test] fn easy_bivariate_clustering() { let xs: Vec<Vec<f64>> = vec![ vec![-1.1, 0.2], vec![-1.2, 0.3], vec![-1.3, 0.1], vec![-1.4, 0.4], vec![1.1, -1.1], vec![1.2, -1.0], vec![1.3, -1.2], vec![1.4, -1.3], ]; let clustering = kmeans(xs, 2); assert_eq!(clustering, vec![0, 0, 0, 0, 1, 1, 1, 1]); } #[test] fn high_dims() { let xs: Vec<Vec<f64>> = vec![ vec![-2.7825343, -1.7604825, -5.5550113, -2.9752946, -2.7874138], vec![-2.9847919, -3.8209332, -2.1531757, -2.2710119, -2.3582877], vec![-3.0109320, -2.2366132, -2.8048492, -1.2632331, -4.5755581], vec![-2.8432186, -1.0383805, -2.2022826, -2.7435962, -2.0013399], vec![-2.6638082, -3.5520086, -1.3684702, -2.1562444, -1.3186447], vec![1.7409171, 1.9687576, 4.7162628, 4.5743537, 3.7905611], vec![3.2932369, 2.8508700, 2.5580937, 2.0437325, 4.2192562], vec![2.5843321, 2.8329818, 2.1329531, 3.2562319, 2.4878733], vec![2.1859638, 3.2880048, 3.7018615, 2.3641232, 1.6281994], vec![2.6201773, 0.9006588, 2.6774097, 1.8188620, 1.6076493], ]; let clustering = kmeans(xs, 2); assert_eq!(clustering, vec![0, 0, 0, 0, 0, 1, 1, 1, 1, 1]); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/huffman_encoding.rs
src/general/huffman_encoding.rs
use std::{ cmp::Ordering, collections::{BTreeMap, BinaryHeap}, }; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)] pub struct HuffmanValue { // For the `value` to overflow, the sum of frequencies should be bigger // than u64. So we should be safe here /// The encoded value pub value: u64, /// number of bits used (up to 64) pub bits: u32, } pub struct HuffmanNode<T> { pub left: Option<Box<HuffmanNode<T>>>, pub right: Option<Box<HuffmanNode<T>>>, pub symbol: Option<T>, pub frequency: u64, } impl<T> PartialEq for HuffmanNode<T> { fn eq(&self, other: &Self) -> bool { self.frequency == other.frequency } } impl<T> PartialOrd for HuffmanNode<T> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<T> Eq for HuffmanNode<T> {} impl<T> Ord for HuffmanNode<T> { fn cmp(&self, other: &Self) -> Ordering { self.frequency.cmp(&other.frequency).reverse() } } impl<T: Clone + Copy + Ord> HuffmanNode<T> { /// Turn the tree into the map that can be used in encoding pub fn get_alphabet( height: u32, path: u64, node: &HuffmanNode<T>, map: &mut BTreeMap<T, HuffmanValue>, ) { match node.symbol { Some(s) => { map.insert( s, HuffmanValue { value: path, bits: height, }, ); } None => { Self::get_alphabet(height + 1, path, node.left.as_ref().unwrap(), map); Self::get_alphabet( height + 1, path | (1 << height), node.right.as_ref().unwrap(), map, ); } } } } pub struct HuffmanDictionary<T> { pub alphabet: BTreeMap<T, HuffmanValue>, pub root: HuffmanNode<T>, } impl<T: Clone + Copy + Ord> HuffmanDictionary<T> { /// Creates a new Huffman dictionary from alphabet symbols and their frequencies. /// /// Returns `None` if the alphabet is empty. /// /// # Arguments /// * `alphabet` - A slice of tuples containing symbols and their frequencies /// /// # Example /// ``` /// # use the_algorithms_rust::general::HuffmanDictionary; /// let freq = vec![('a', 5), ('b', 2), ('c', 1)]; /// let dict = HuffmanDictionary::new(&freq).unwrap(); /// pub fn new(alphabet: &[(T, u64)]) -> Option<Self> { if alphabet.is_empty() { return None; } let mut alph: BTreeMap<T, HuffmanValue> = BTreeMap::new(); // Special case: single symbol if alphabet.len() == 1 { let (symbol, _freq) = alphabet[0]; alph.insert( symbol, HuffmanValue { value: 0, bits: 1, // Must use at least 1 bit per symbol }, ); let root = HuffmanNode { left: None, right: None, symbol: Some(symbol), frequency: alphabet[0].1, }; return Some(HuffmanDictionary { alphabet: alph, root, }); } let mut queue: BinaryHeap<HuffmanNode<T>> = BinaryHeap::new(); for (symbol, freq) in alphabet.iter() { queue.push(HuffmanNode { left: None, right: None, symbol: Some(*symbol), frequency: *freq, }); } for _ in 1..alphabet.len() { let left = queue.pop().unwrap(); let right = queue.pop().unwrap(); let sm_freq = left.frequency + right.frequency; queue.push(HuffmanNode { left: Some(Box::new(left)), right: Some(Box::new(right)), symbol: None, frequency: sm_freq, }); } if let Some(root) = queue.pop() { HuffmanNode::get_alphabet(0, 0, &root, &mut alph); Some(HuffmanDictionary { alphabet: alph, root, }) } else { None } } pub fn encode(&self, data: &[T]) -> HuffmanEncoding { let mut result = HuffmanEncoding::new(); for value in data.iter() { result.add_data(self.alphabet[value]); } result } } pub struct HuffmanEncoding { pub num_bits: u64, pub data: Vec<u64>, } impl Default for HuffmanEncoding { fn default() -> Self { Self::new() } } impl HuffmanEncoding { pub fn new() -> Self { HuffmanEncoding { num_bits: 0, data: vec![0], } } #[inline] pub fn add_data(&mut self, data: HuffmanValue) { let shift = (self.num_bits & 63) as u32; let val = data.value; *self.data.last_mut().unwrap() |= val.wrapping_shl(shift); if (shift + data.bits) >= 64 { self.data.push(val.wrapping_shr(64 - shift)); } self.num_bits += data.bits as u64; } #[inline] fn get_bit(&self, pos: u64) -> bool { (self.data[(pos >> 6) as usize] & (1 << (pos & 63))) != 0 } /// In case the encoding is invalid, `None` is returned pub fn decode<T: Clone + Copy + Ord>(&self, dict: &HuffmanDictionary<T>) -> Option<Vec<T>> { // Handle empty encoding if self.num_bits == 0 { return Some(vec![]); } // Special case: single symbol in dictionary if dict.alphabet.len() == 1 { //all bits represent the same symbol let symbol = dict.alphabet.keys().next()?; let result = vec![*symbol; self.num_bits as usize]; return Some(result); } // Normal case: multiple symbols let mut state = &dict.root; let mut result: Vec<T> = vec![]; for i in 0..self.num_bits { if let Some(symbol) = state.symbol { result.push(symbol); state = &dict.root; } state = if self.get_bit(i) { state.right.as_ref()? } else { state.left.as_ref()? } } // Check if we ended on a symbol if self.num_bits > 0 { result.push(state.symbol?); } Some(result) } } #[cfg(test)] mod tests { use super::*; fn get_frequency(bytes: &[u8]) -> Vec<(u8, u64)> { let mut cnts: Vec<u64> = vec![0; 256]; for &b in bytes.iter() { cnts[b as usize] += 1; } let mut result = vec![]; cnts.iter() .enumerate() .filter(|(_, &v)| v > 0) .for_each(|(b, &cnt)| result.push((b as u8, cnt))); result } #[test] fn empty_text() { let text = ""; let bytes = text.as_bytes(); let freq = get_frequency(bytes); let dict = HuffmanDictionary::new(&freq); assert!(dict.is_none()); } #[test] fn one_symbol_text() { let text = "aaaa"; let bytes = text.as_bytes(); let freq = get_frequency(bytes); let dict = HuffmanDictionary::new(&freq).unwrap(); let encoded = dict.encode(bytes); assert_eq!(encoded.num_bits, 4); let decoded = encoded.decode(&dict).unwrap(); assert_eq!(decoded, bytes); } #[test] fn test_decode_empty_encoding_struct() { // Create a minimal but VALID HuffmanDictionary. // This is required because decode() expects a dictionary, even though // the content of the dictionary doesn't matter when num_bits == 0. let freq = vec![(b'a', 1)]; let dict = HuffmanDictionary::new(&freq).unwrap(); // Manually create the target state: an encoding with 0 bits. let empty_encoding = HuffmanEncoding { data: vec![], num_bits: 0, }; let result = empty_encoding.decode(&dict); assert_eq!(result, Some(vec![])); } #[test] fn minimal_decode_end_check() { let freq = vec![(b'a', 1), (b'b', 1)]; let bytes = b"ab"; let dict = HuffmanDictionary::new(&freq).unwrap(); let encoded = dict.encode(bytes); // This decode will go through the main loop and hit the final 'if self.num_bits > 0' check. let decoded = encoded.decode(&dict).unwrap(); assert_eq!(decoded, bytes); } #[test] fn test_decode_corrupted_stream_dead_end() { // Create a dictionary with three symbols to ensure a deeper tree. // This makes hitting a dead-end (None pointer) easier. let freq = vec![(b'a', 1), (b'b', 1), (b'c', 1)]; let bytes = b"ab"; let dict = HuffmanDictionary::new(&freq).unwrap(); let encoded = dict.encode(bytes); // Manually corrupt the stream to stop mid-symbol. // We will truncate num_bits by a small amount (e.g., 1 bit). // This forces the loop to stop on an *intermediate* node. let corrupted_encoding = HuffmanEncoding { data: encoded.data, // Shorten the bit count by one. The total length of the 'ab' stream // is likely 4 or 5 bits. This forces the loop to end one bit early, // leaving the state on an internal node. num_bits: encoded .num_bits .checked_sub(1) .expect("Encoding should be > 0 bits"), }; // Assert that the decode fails gracefully. // The loop finishes, the final 'if self.num_bits > 0' executes, // and result.push(state.symbol?) fails because state.symbol is None. assert_eq!(corrupted_encoding.decode(&dict), None); } #[test] fn small_text() { let text = "Hello world"; let bytes = text.as_bytes(); let freq = get_frequency(bytes); let dict = HuffmanDictionary::new(&freq).unwrap(); let encoded = dict.encode(bytes); assert_eq!(encoded.num_bits, 32); let decoded = encoded.decode(&dict).unwrap(); assert_eq!(decoded, bytes); } #[test] fn lorem_ipsum() { let text = concat!( "The quick brown fox jumped over the lazy dog.", "Lorem ipsum dolor sit amet, consectetur ", "adipiscing elit, sed do eiusmod tempor incididunt ut labore et ", "dolore magna aliqua. Facilisis magna etiam tempor orci. Nullam ", "non nisi est sit amet facilisis magna. Commodo nulla facilisi ", "nullam vehicula. Interdum posuere lorem ipsum dolor. Elit eget ", "gravida cum sociis natoque penatibus. Dictum sit amet justo donec ", "enim. Tempor commodo ullamcorper a lacus vestibulum sed. Nisl ", "suscipit adipiscing bibendum est ultricies. Sit amet aliquam id ", "diam maecenas ultricies." ); let bytes = text.as_bytes(); let freq = get_frequency(bytes); let dict = HuffmanDictionary::new(&freq).unwrap(); let encoded = dict.encode(bytes); assert_eq!(encoded.num_bits, 2372); let decoded = encoded.decode(&dict).unwrap(); assert_eq!(decoded, bytes); let text = "The dictionary should work on other texts too"; let bytes = text.as_bytes(); let encoded = dict.encode(bytes); assert_eq!(encoded.num_bits, 215); let decoded = encoded.decode(&dict).unwrap(); assert_eq!(decoded, bytes); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/fisher_yates_shuffle.rs
src/general/fisher_yates_shuffle.rs
use std::time::{SystemTime, UNIX_EPOCH}; use crate::math::PCG32; const DEFAULT: u64 = 4294967296; fn gen_range(range: usize, generator: &mut PCG32) -> usize { generator.get_u64() as usize % range } pub fn fisher_yates_shuffle(array: &mut [i32]) { let seed = match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(duration) => duration.as_millis() as u64, Err(_) => DEFAULT, }; let mut random_generator = PCG32::new_default(seed); let len = array.len(); for i in 0..(len - 2) { let r = gen_range(len - i, &mut random_generator); array.swap(i, i + r); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/genetic.rs
src/general/genetic.rs
use std::cmp::Ordering; use std::collections::BTreeSet; use std::fmt::Debug; /// The goal is to showcase how Genetic algorithms generically work /// See: https://en.wikipedia.org/wiki/Genetic_algorithm for concepts /// This is the definition of a Chromosome for a genetic algorithm /// We can picture this as "one contending solution to our problem" /// It is generic over: /// * Eval, which could be a float, or any other totally ordered type, so that we can rank solutions to our problem /// * Rng: a random number generator (could be thread rng, etc.) pub trait Chromosome<Rng: rand::Rng, Eval> { /// Mutates this Chromosome, changing its genes fn mutate(&mut self, rng: &mut Rng); /// Mixes this chromosome with another one fn crossover(&self, other: &Self, rng: &mut Rng) -> Self; /// How well this chromosome fits the problem we're trying to solve /// **The smaller the better it fits** (we could use abs(... - expected_value) for instance fn fitness(&self) -> Eval; } pub trait SelectionStrategy<Rng: rand::Rng> { fn new(rng: Rng) -> Self; /// Selects a portion of the population for reproduction /// Could be totally random ones or the ones that fit best, etc. /// This assumes the population is sorted by how it fits the solution (the first the better) fn select<'a, Eval: Into<f64>, C: Chromosome<Rng, Eval>>( &mut self, population: &'a [C], ) -> (&'a C, &'a C); } /// A roulette wheel selection strategy /// https://en.wikipedia.org/wiki/Fitness_proportionate_selection #[allow(dead_code)] pub struct RouletteWheel<Rng: rand::Rng> { rng: Rng, } impl<Rng: rand::Rng> SelectionStrategy<Rng> for RouletteWheel<Rng> { fn new(rng: Rng) -> Self { Self { rng } } fn select<'a, Eval: Into<f64>, C: Chromosome<Rng, Eval>>( &mut self, population: &'a [C], ) -> (&'a C, &'a C) { // We will assign a probability for every item in the population, based on its proportion towards the sum of all fitness // This would work well for an increasing fitness function, but not in our case of a fitness function for which "lower is better" // We thus need to take the reciprocal let mut parents = Vec::with_capacity(2); let fitnesses: Vec<f64> = population .iter() .filter_map(|individual| { let fitness = individual.fitness().into(); if individual.fitness().into() == 0.0 { parents.push(individual); None } else { Some(1.0 / fitness) } }) .collect(); if parents.len() == 2 { return (parents[0], parents[1]); } let sum: f64 = fitnesses.iter().sum(); let mut spin = self.rng.random_range(0.0..=sum); for individual in population { let fitness: f64 = individual.fitness().into(); if spin <= fitness { parents.push(individual); if parents.len() == 2 { return (parents[0], parents[1]); } } else { spin -= fitness; } } panic!("Could not select parents"); } } #[allow(dead_code)] pub struct Tournament<const K: usize, Rng: rand::Rng> { rng: Rng, } impl<const K: usize, Rng: rand::Rng> SelectionStrategy<Rng> for Tournament<K, Rng> { fn new(rng: Rng) -> Self { Self { rng } } fn select<'a, Eval, C: Chromosome<Rng, Eval>>( &mut self, population: &'a [C], ) -> (&'a C, &'a C) { if K < 2 { panic!("K must be > 2"); } // This strategy is defined as the following: pick K chromosomes randomly, use the 2 that fits the best // We assume the population is sorted // This means we can draw K random (distinct) numbers between (0..population.len()) and return the chromosomes at the 2 lowest indices let mut picked_indices = BTreeSet::new(); // will keep indices ordered while picked_indices.len() < K { picked_indices.insert(self.rng.random_range(0..population.len())); } let mut iter = picked_indices.into_iter(); ( &population[iter.next().unwrap()], &population[iter.next().unwrap()], ) } } type Comparator<T> = Box<dyn FnMut(&T, &T) -> Ordering>; pub struct GeneticAlgorithm< Rng: rand::Rng, Eval: PartialOrd, C: Chromosome<Rng, Eval>, Selection: SelectionStrategy<Rng>, > { rng: Rng, // will be used to draw random numbers for initial population, mutations and crossovers population: Vec<C>, // the set of random solutions (chromosomes) threshold: Eval, // Any chromosome fitting over this threshold is considered a valid solution max_generations: usize, // So that we don't loop infinitely mutation_chance: f64, // what's the probability a chromosome will mutate crossover_chance: f64, // what's the probability two chromosomes will cross-over and give birth to a new chromosome compare: Comparator<Eval>, selection: Selection, // how we will select parent chromosomes for crossing over, see `SelectionStrategy` } pub struct GenericAlgorithmParams { max_generations: usize, mutation_chance: f64, crossover_chance: f64, } impl< Rng: rand::Rng, Eval: Into<f64> + PartialOrd + Debug, C: Chromosome<Rng, Eval> + Clone + Debug, Selection: SelectionStrategy<Rng>, > GeneticAlgorithm<Rng, Eval, C, Selection> { pub fn init( rng: Rng, population: Vec<C>, threshold: Eval, params: GenericAlgorithmParams, compare: Comparator<Eval>, selection: Selection, ) -> Self { let GenericAlgorithmParams { max_generations, mutation_chance, crossover_chance, } = params; Self { rng, population, threshold, max_generations, mutation_chance, crossover_chance, compare, selection, } } pub fn solve(&mut self) -> Option<C> { let mut generations = 1; // 1st generation is our initial population while generations <= self.max_generations { // 1. Sort the population by fitness score, remember: the lower the better (so natural ordering) self.population .sort_by(|c1: &C, c2: &C| (self.compare)(&c1.fitness(), &c2.fitness())); // 2. Stop condition: we might have found a good solution if let Some(solution) = self.population.first() { if solution.fitness() <= self.threshold { return Some(solution).cloned(); } } // 3. Apply random mutations to the whole population for chromosome in self.population.iter_mut() { if self.rng.random::<f64>() <= self.mutation_chance { chromosome.mutate(&mut self.rng); } } // 4. Select parents that will be mating to create new chromosomes let mut new_population = Vec::with_capacity(self.population.len() + 1); while new_population.len() < self.population.len() { let (p1, p2) = self.selection.select(&self.population); if self.rng.random::<f64>() <= self.crossover_chance { let child = p1.crossover(p2, &mut self.rng); new_population.push(child); } else { // keep parents new_population.extend([p1.clone(), p2.clone()]); } } if new_population.len() > self.population.len() { // We might have added 2 parents new_population.pop(); } self.population = new_population; // 5. Rinse & Repeat until we find a proper solution or we reach the maximum number of generations generations += 1; } None } } #[cfg(test)] mod tests { use crate::general::genetic::{ Chromosome, GenericAlgorithmParams, GeneticAlgorithm, RouletteWheel, SelectionStrategy, Tournament, }; use rand::rngs::ThreadRng; use rand::{rng, Rng}; use std::collections::HashMap; use std::fmt::{Debug, Formatter}; use std::ops::RangeInclusive; #[test] #[ignore] // Too long and not deterministic enough to be part of CI, more of an example than a test fn find_secret() { let chars = 'a'..='z'; let secret = "thisistopsecret".to_owned(); // Note: we'll pick genes (a, b, c) in the range -10, 10 #[derive(Clone)] struct TestString { chars: RangeInclusive<char>, secret: String, genes: Vec<char>, } impl TestString { fn new(rng: &mut ThreadRng, secret: String, chars: RangeInclusive<char>) -> Self { let current = (0..secret.len()) .map(|_| rng.random_range(chars.clone())) .collect::<Vec<_>>(); Self { chars, secret, genes: current, } } } impl Debug for TestString { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str(&self.genes.iter().collect::<String>()) } } impl Chromosome<ThreadRng, i32> for TestString { fn mutate(&mut self, rng: &mut ThreadRng) { // let's assume mutations happen completely randomly, one "gene" at a time (i.e. one char at a time) let gene_idx = rng.random_range(0..self.secret.len()); let new_char = rng.random_range(self.chars.clone()); self.genes[gene_idx] = new_char; } fn crossover(&self, other: &Self, rng: &mut ThreadRng) -> Self { // Let's not assume anything here, simply mixing random genes from both parents let genes = (0..self.secret.len()) .map(|idx| { if rng.random_bool(0.5) { // pick gene from self self.genes[idx] } else { // pick gene from other parent other.genes[idx] } }) .collect(); Self { chars: self.chars.clone(), secret: self.secret.clone(), genes, } } fn fitness(&self) -> i32 { // We are just counting how many chars are distinct from secret self.genes .iter() .zip(self.secret.chars()) .filter(|(char, expected)| expected != *char) .count() as i32 } } let mut rng = rng(); let pop_count = 1_000; let mut population = Vec::with_capacity(pop_count); for _ in 0..pop_count { population.push(TestString::new(&mut rng, secret.clone(), chars.clone())); } let selection: Tournament<100, ThreadRng> = Tournament::new(rng.clone()); let params = GenericAlgorithmParams { max_generations: 100, mutation_chance: 0.2, crossover_chance: 0.4, }; let mut solver = GeneticAlgorithm::init(rng, population, 0, params, Box::new(i32::cmp), selection); let res = solver.solve(); assert!(res.is_some()); assert_eq!(res.unwrap().genes, secret.chars().collect::<Vec<_>>()) } #[test] #[ignore] // Too long and not deterministic enough to be part of CI, more of an example than a test fn solve_mastermind() { #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] enum ColoredPeg { Red, Yellow, Green, Blue, White, Black, } struct GuessAnswer { right_pos: i32, // right color at the right pos wrong_pos: i32, // right color, but at wrong pos } #[derive(Clone, Debug)] struct CodeMaker { // the player coming up with a secret code code: [ColoredPeg; 4], count_by_color: HashMap<ColoredPeg, usize>, } impl CodeMaker { fn new(code: [ColoredPeg; 4]) -> Self { let mut count_by_color = HashMap::with_capacity(4); for peg in &code { *count_by_color.entry(*peg).or_insert(0) += 1; } Self { code, count_by_color, } } fn eval(&self, guess: &[ColoredPeg; 4]) -> GuessAnswer { let mut right_pos = 0; let mut wrong_pos = 0; let mut idx_by_colors = self.count_by_color.clone(); for (idx, color) in guess.iter().enumerate() { if self.code[idx] == *color { right_pos += 1; let count = idx_by_colors.get_mut(color).unwrap(); *count -= 1; // don't reuse to say "right color but wrong pos" if *count == 0 { idx_by_colors.remove(color); } } } for (idx, color) in guess.iter().enumerate() { if self.code[idx] != *color { // try to use another color if let Some(count) = idx_by_colors.get_mut(color) { *count -= 1; if *count == 0 { idx_by_colors.remove(color); } wrong_pos += 1; } } } GuessAnswer { right_pos, wrong_pos, } } } #[derive(Clone)] struct CodeBreaker { maker: CodeMaker, // so that we can ask the code maker if our guess is good or not guess: [ColoredPeg; 4], } impl Debug for CodeBreaker { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str(format!("{:?}", self.guess).as_str()) } } fn random_color(rng: &mut ThreadRng) -> ColoredPeg { match rng.random_range(0..=5) { 0 => ColoredPeg::Red, 1 => ColoredPeg::Yellow, 2 => ColoredPeg::Green, 3 => ColoredPeg::Blue, 4 => ColoredPeg::White, _ => ColoredPeg::Black, } } fn random_guess(rng: &mut ThreadRng) -> [ColoredPeg; 4] { std::array::from_fn(|_| random_color(rng)) } impl Chromosome<ThreadRng, i32> for CodeBreaker { fn mutate(&mut self, rng: &mut ThreadRng) { // change one random color let idx = rng.random_range(0..4); self.guess[idx] = random_color(rng); } fn crossover(&self, other: &Self, rng: &mut ThreadRng) -> Self { Self { maker: self.maker.clone(), guess: std::array::from_fn(|i| { if rng.random::<f64>() < 0.5 { self.guess[i] } else { other.guess[i] } }), } } fn fitness(&self) -> i32 { // Ask the code maker for the result let answer = self.maker.eval(&self.guess); // Remember: we need to have fitness return 0 if the guess is good, and the higher number we return, the further we are from a proper solution let mut res = 32; // worst case scenario, everything is wrong res -= answer.right_pos * 8; // count 8 points for the right item at the right spot res -= answer.wrong_pos; // count 1 point for having a right color res } } let code = [ ColoredPeg::Red, ColoredPeg::Red, ColoredPeg::White, ColoredPeg::Blue, ]; let maker = CodeMaker::new(code); let population_count = 10; let params = GenericAlgorithmParams { max_generations: 100, mutation_chance: 0.5, crossover_chance: 0.3, }; let mut rng = rng(); let mut initial_pop = Vec::with_capacity(population_count); for _ in 0..population_count { initial_pop.push(CodeBreaker { maker: maker.clone(), guess: random_guess(&mut rng), }); } let selection = RouletteWheel { rng: rng.clone() }; let mut solver = GeneticAlgorithm::init(rng, initial_pop, 0, params, Box::new(i32::cmp), selection); let res = solver.solve(); assert!(res.is_some()); assert_eq!(code, res.unwrap().guess); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/convex_hull.rs
src/general/convex_hull.rs
use std::cmp::Ordering::Equal; fn sort_by_min_angle(pts: &[(f64, f64)], min: &(f64, f64)) -> Vec<(f64, f64)> { let mut points: Vec<(f64, f64, (f64, f64))> = pts .iter() .map(|x| { ( (x.1 - min.1).atan2(x.0 - min.0), // angle (x.1 - min.1).hypot(x.0 - min.0), // distance (we want the closest to be first) *x, ) }) .collect(); points.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Equal)); points.into_iter().map(|x| x.2).collect() } // calculates the z coordinate of the vector product of vectors ab and ac fn calc_z_coord_vector_product(a: &(f64, f64), b: &(f64, f64), c: &(f64, f64)) -> f64 { (b.0 - a.0) * (c.1 - a.1) - (c.0 - a.0) * (b.1 - a.1) } /* If three points are aligned and are part of the convex hull then the three are kept. If one doesn't want to keep those points, it is easy to iterate the answer and remove them. The first point is the one with the lowest y-coordinate and the lowest x-coordinate. Points are then given counter-clockwise, and the closest one is given first if needed. */ pub fn convex_hull_graham(pts: &[(f64, f64)]) -> Vec<(f64, f64)> { if pts.is_empty() { return vec![]; } let mut stack: Vec<(f64, f64)> = vec![]; let min = pts .iter() .min_by(|a, b| { let ord = a.1.partial_cmp(&b.1).unwrap_or(Equal); match ord { Equal => a.0.partial_cmp(&b.0).unwrap_or(Equal), o => o, } }) .unwrap(); let points = sort_by_min_angle(pts, min); if points.len() <= 3 { return points; } for point in points { while stack.len() > 1 && calc_z_coord_vector_product(&stack[stack.len() - 2], &stack[stack.len() - 1], &point) < 0. { stack.pop(); } stack.push(point); } stack } #[cfg(test)] mod tests { use super::*; #[test] fn empty() { assert_eq!(convex_hull_graham(&[]), vec![]); } #[test] fn not_enough_points() { let list = vec![(0f64, 0f64)]; assert_eq!(convex_hull_graham(&list), list); } #[test] fn not_enough_points1() { let list = vec![(2f64, 2f64), (1f64, 1f64), (0f64, 0f64)]; let ans = vec![(0f64, 0f64), (1f64, 1f64), (2f64, 2f64)]; assert_eq!(convex_hull_graham(&list), ans); } #[test] fn not_enough_points2() { let list = vec![(2f64, 2f64), (1f64, 2f64), (0f64, 0f64)]; let ans = vec![(0f64, 0f64), (2f64, 2f64), (1f64, 2f64)]; assert_eq!(convex_hull_graham(&list), ans); } #[test] // from https://codegolf.stackexchange.com/questions/11035/find-the-convex-hull-of-a-set-of-2d-points fn lots_of_points() { let list = vec![ (4.4, 14.), (6.7, 15.25), (6.9, 12.8), (2.1, 11.1), (9.5, 14.9), (13.2, 11.9), (10.3, 12.3), (6.8, 9.5), (3.3, 7.7), (0.6, 5.1), (5.3, 2.4), (8.45, 4.7), (11.5, 9.6), (13.8, 7.3), (12.9, 3.1), (11., 1.1), ]; let ans = vec![ (11., 1.1), (12.9, 3.1), (13.8, 7.3), (13.2, 11.9), (9.5, 14.9), (6.7, 15.25), (4.4, 14.), (2.1, 11.1), (0.6, 5.1), (5.3, 2.4), ]; assert_eq!(convex_hull_graham(&list), ans); } #[test] // from https://codegolf.stackexchange.com/questions/11035/find-the-convex-hull-of-a-set-of-2d-points fn lots_of_points2() { let list = vec![ (1., 0.), (1., 1.), (1., -1.), (0.68957, 0.283647), (0.909487, 0.644276), (0.0361877, 0.803816), (0.583004, 0.91555), (-0.748169, 0.210483), (-0.553528, -0.967036), (0.316709, -0.153861), (-0.79267, 0.585945), (-0.700164, -0.750994), (0.452273, -0.604434), (-0.79134, -0.249902), (-0.594918, -0.397574), (-0.547371, -0.434041), (0.958132, -0.499614), (0.039941, 0.0990732), (-0.891471, -0.464943), (0.513187, -0.457062), (-0.930053, 0.60341), (0.656995, 0.854205), ]; let ans = vec![ (1., -1.), (1., 0.), (1., 1.), (0.583004, 0.91555), (0.0361877, 0.803816), (-0.930053, 0.60341), (-0.891471, -0.464943), (-0.700164, -0.750994), (-0.553528, -0.967036), ]; assert_eq!(convex_hull_graham(&list), ans); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/mod.rs
src/general/mod.rs
mod convex_hull; mod fisher_yates_shuffle; mod genetic; mod hanoi; mod huffman_encoding; mod kadane_algorithm; mod kmeans; mod mex; mod permutations; mod two_sum; pub use self::convex_hull::convex_hull_graham; pub use self::fisher_yates_shuffle::fisher_yates_shuffle; pub use self::genetic::GeneticAlgorithm; pub use self::hanoi::hanoi; pub use self::huffman_encoding::{HuffmanDictionary, HuffmanEncoding}; pub use self::kadane_algorithm::max_sub_array; pub use self::kmeans::f32::kmeans as kmeans_f32; pub use self::kmeans::f64::kmeans as kmeans_f64; pub use self::mex::mex_using_set; pub use self::mex::mex_using_sort; pub use self::permutations::{ heap_permute, permute, permute_unique, steinhaus_johnson_trotter_permute, }; pub use self::two_sum::two_sum;
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/kadane_algorithm.rs
src/general/kadane_algorithm.rs
/** * @file * @brief Find the maximum subarray sum using Kadane's algorithm.(https://en.wikipedia.org/wiki/Maximum_subarray_problem) * * @details * This program provides a function to find the maximum subarray sum in an array of integers * using Kadane's algorithm. * * @param arr A slice of integers representing the array. * @return The maximum subarray sum. * * @author [Gyandeep] (https://github.com/Gyan172004) * @see Wikipedia - Maximum subarray problem */ /** * Find the maximum subarray sum using Kadane's algorithm. * @param arr A slice of integers representing the array. * @return The maximum subarray sum. */ pub fn max_sub_array(nums: Vec<i32>) -> i32 { if nums.is_empty() { return 0; } let mut max_current = nums[0]; let mut max_global = nums[0]; nums.iter().skip(1).for_each(|&item| { max_current = std::cmp::max(item, max_current + item); if max_current > max_global { max_global = max_current; } }); max_global } #[cfg(test)] mod tests { use super::*; /** * Test case for Kadane's algorithm with positive numbers. */ #[test] fn test_kadanes_algorithm_positive() { let arr = [1, 2, 3, 4, 5]; assert_eq!(max_sub_array(arr.to_vec()), 15); } /** * Test case for Kadane's algorithm with negative numbers. */ #[test] fn test_kadanes_algorithm_negative() { let arr = [-2, -3, -4, -1, -2]; assert_eq!(max_sub_array(arr.to_vec()), -1); } /** * Test case for Kadane's algorithm with mixed numbers. */ #[test] fn test_kadanes_algorithm_mixed() { let arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]; assert_eq!(max_sub_array(arr.to_vec()), 6); } /** * Test case for Kadane's algorithm with an empty array. */ #[test] fn test_kadanes_algorithm_empty() { let arr: [i32; 0] = []; assert_eq!(max_sub_array(arr.to_vec()), 0); } /** * Test case for Kadane's algorithm with a single positive number. */ #[test] fn test_kadanes_algorithm_single_positive() { let arr = [10]; assert_eq!(max_sub_array(arr.to_vec()), 10); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/mex.rs
src/general/mex.rs
use std::collections::BTreeSet; // Find minimum excluded number from a set of given numbers using a set /// Finds the MEX of the values provided in `arr` /// Uses [`BTreeSet`](std::collections::BTreeSet) /// O(nlog(n)) implementation pub fn mex_using_set(arr: &[i64]) -> i64 { let mut s: BTreeSet<i64> = BTreeSet::new(); for i in 0..=arr.len() { s.insert(i as i64); } for x in arr { s.remove(x); } // TODO: change the next 10 lines to *s.first().unwrap() when merged into stable // set should never have 0 elements if let Some(x) = s.into_iter().next() { x } else { panic!("Some unknown error in mex_using_set") } } /// Finds the MEX of the values provided in `arr` /// Uses sorting /// O(nlog(n)) implementation pub fn mex_using_sort(arr: &[i64]) -> i64 { let mut arr = arr.to_vec(); arr.sort(); let mut mex = 0; for x in arr { if x == mex { mex += 1; } } mex } #[cfg(test)] mod tests { use super::*; struct MexTests { test_arrays: Vec<Vec<i64>>, outputs: Vec<i64>, } impl MexTests { fn new() -> Self { Self { test_arrays: vec![ vec![-1, 0, 1, 2, 3], vec![-100, 0, 1, 2, 3, 5], vec![-1000000, 0, 1, 2, 5], vec![2, 0, 1, 2, 4], vec![1, 2, 3, 0, 4], vec![0, 1, 5, 2, 4, 3], vec![0, 1, 2, 3, 4, 5, 6], vec![0, 1, 2, 3, 4, 5, 6, 7], vec![0, 1, 2, 3, 4, 5, 6, 7, 8], ], outputs: vec![4, 4, 3, 3, 5, 6, 7, 8, 9], } } fn test_function(&self, f: fn(&[i64]) -> i64) { for (nums, output) in self.test_arrays.iter().zip(self.outputs.iter()) { assert_eq!(f(nums), *output); } } } #[test] fn test_mex_using_set() { let tests = MexTests::new(); mex_using_set(&[1, 23, 3]); tests.test_function(mex_using_set); } #[test] fn test_mex_using_sort() { let tests = MexTests::new(); tests.test_function(mex_using_sort); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/permutations/steinhaus_johnson_trotter.rs
src/general/permutations/steinhaus_johnson_trotter.rs
/// <https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm> pub fn steinhaus_johnson_trotter_permute<T: Clone>(array: &[T]) -> Vec<Vec<T>> { let len = array.len(); let mut array = array.to_owned(); let mut inversion_vector = vec![0; len]; let mut i = 1; let mut res = Vec::with_capacity((1..=len).product()); res.push(array.clone()); while i < len { if inversion_vector[i] < i { if i % 2 == 0 { array.swap(0, i); } else { array.swap(inversion_vector[i], i); } res.push(array.to_vec()); inversion_vector[i] += 1; i = 1; } else { inversion_vector[i] = 0; i += 1; } } res } #[cfg(test)] mod tests { use quickcheck_macros::quickcheck; use crate::general::permutations::steinhaus_johnson_trotter::steinhaus_johnson_trotter_permute; use crate::general::permutations::tests::{ assert_permutations, assert_valid_permutation, NotTooBigVec, }; #[test] fn test_3_different_values() { let original = vec![1, 2, 3]; let res = steinhaus_johnson_trotter_permute(&original); assert_eq!(res.len(), 6); // 3! for permut in res { assert_valid_permutation(&original, &permut) } } #[test] fn test_3_times_the_same_value() { let original = vec![1, 1, 1]; let res = steinhaus_johnson_trotter_permute(&original); assert_eq!(res.len(), 6); // 3! for permut in res { assert_valid_permutation(&original, &permut) } } #[quickcheck] fn test_some_elements(NotTooBigVec { inner: original }: NotTooBigVec) { let permutations = steinhaus_johnson_trotter_permute(&original); assert_permutations(&original, &permutations) } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/permutations/naive.rs
src/general/permutations/naive.rs
use std::collections::HashSet; use std::fmt::Debug; use std::hash::Hash; /// Here's a basic (naive) implementation for generating permutations pub fn permute<T: Clone + Debug>(arr: &[T]) -> Vec<Vec<T>> { if arr.is_empty() { return vec![vec![]]; } let n = arr.len(); let count = (1..=n).product(); // n! permutations let mut collector = Vec::with_capacity(count); // collects the permuted arrays let mut arr = arr.to_owned(); // we'll need to mutate the array // the idea is the following: imagine [a, b, c] // always swap an item with the last item, then generate all permutations from the first k characters // permute_recurse(arr, k - 1, collector); // leave the last character alone, and permute the first k-1 characters permute_recurse(&mut arr, n, &mut collector); collector } fn permute_recurse<T: Clone + Debug>(arr: &mut Vec<T>, k: usize, collector: &mut Vec<Vec<T>>) { if k == 1 { collector.push(arr.to_owned()); return; } for i in 0..k { arr.swap(i, k - 1); // swap i with the last character permute_recurse(arr, k - 1, collector); // collect the permutations of the rest arr.swap(i, k - 1); // swap back to original } } /// A common variation of generating permutations is to generate only unique permutations /// Of course, we could use the version above together with a Set as collector instead of a Vec. /// But let's try something different: how can we avoid to generate duplicated permutations in the first place, can we tweak the algorithm above? pub fn permute_unique<T: Clone + Debug + Eq + Hash + Copy>(arr: &[T]) -> Vec<Vec<T>> { if arr.is_empty() { return vec![vec![]]; } let n = arr.len(); let count = (1..=n).product(); // n! permutations let mut collector = Vec::with_capacity(count); // collects the permuted arrays let mut arr = arr.to_owned(); // Heap's algorithm needs to mutate the array permute_recurse_unique(&mut arr, n, &mut collector); collector } fn permute_recurse_unique<T: Clone + Debug + Eq + Hash + Copy>( arr: &mut Vec<T>, k: usize, collector: &mut Vec<Vec<T>>, ) { // We have the same base-case as previously, whenever we reach the first element in the array, collect the result if k == 1 { collector.push(arr.to_owned()); return; } // We'll keep the same idea (swap with last item, and generate all permutations for the first k - 1) // But we'll have to be careful though: how would we generate duplicates? // Basically if, when swapping i with k-1, we generate the exact same array as in a previous iteration // Imagine [a, a, b] // i = 0: // Swap (a, b) => [b, a, a], fix 'a' as last, and generate all permutations of [b, a] => [b, a, a], [a, b, a] // Swap Back to [a, a, b] // i = 1: // Swap(a, b) => [b, a, a], we've done that already!! let mut swapped = HashSet::with_capacity(k); for i in 0..k { if swapped.contains(&arr[i]) { continue; } swapped.insert(arr[i]); arr.swap(i, k - 1); // swap i with the last character permute_recurse_unique(arr, k - 1, collector); // collect the permutations arr.swap(i, k - 1); // go back to original } } #[cfg(test)] mod tests { use crate::general::permutations::naive::{permute, permute_unique}; use crate::general::permutations::tests::{ assert_permutations, assert_valid_permutation, NotTooBigVec, }; use quickcheck_macros::quickcheck; use std::collections::HashSet; #[test] fn test_3_different_values() { let original = vec![1, 2, 3]; let res = permute(&original); assert_eq!(res.len(), 6); // 3! for permut in res { assert_valid_permutation(&original, &permut) } } #[test] fn empty_array() { let empty: std::vec::Vec<u8> = vec![]; assert_eq!(permute(&empty), vec![vec![]]); assert_eq!(permute_unique(&empty), vec![vec![]]); } #[test] fn test_3_times_the_same_value() { let original = vec![1, 1, 1]; let res = permute(&original); assert_eq!(res.len(), 6); // 3! for permut in res { assert_valid_permutation(&original, &permut) } } #[quickcheck] fn test_some_elements(NotTooBigVec { inner: original }: NotTooBigVec) { let permutations = permute(&original); assert_permutations(&original, &permutations) } #[test] fn test_unique_values() { let original = vec![1, 1, 2, 2]; let unique_permutations = permute_unique(&original); let every_permutation = permute(&original); for unique_permutation in &unique_permutations { assert!(every_permutation.contains(unique_permutation)); } assert_eq!( unique_permutations.len(), every_permutation.iter().collect::<HashSet<_>>().len() ) } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/permutations/mod.rs
src/general/permutations/mod.rs
mod heap; mod naive; mod steinhaus_johnson_trotter; pub use self::heap::heap_permute; pub use self::naive::{permute, permute_unique}; pub use self::steinhaus_johnson_trotter::steinhaus_johnson_trotter_permute; #[cfg(test)] mod tests { use quickcheck::{Arbitrary, Gen}; use std::collections::HashMap; pub fn assert_permutations(original: &[i32], permutations: &[Vec<i32>]) { if original.is_empty() { assert_eq!(vec![vec![] as Vec<i32>], permutations); return; } let n = original.len(); assert_eq!((1..=n).product::<usize>(), permutations.len()); // n! for permut in permutations { assert_valid_permutation(original, permut); } } pub fn assert_valid_permutation(original: &[i32], permuted: &[i32]) { assert_eq!(original.len(), permuted.len()); let mut indices = HashMap::with_capacity(original.len()); for value in original { *indices.entry(*value).or_insert(0) += 1; } for permut_value in permuted { let count = indices.get_mut(permut_value).unwrap_or_else(|| { panic!("Value {permut_value} appears too many times in permutation") }); *count -= 1; // use this value if *count == 0 { indices.remove(permut_value); // so that we can simply check every value has been removed properly } } assert!(indices.is_empty()) } #[test] fn test_valid_permutations() { assert_valid_permutation(&[1, 2, 3], &[1, 2, 3]); assert_valid_permutation(&[1, 2, 3], &[1, 3, 2]); assert_valid_permutation(&[1, 2, 3], &[2, 1, 3]); assert_valid_permutation(&[1, 2, 3], &[2, 3, 1]); assert_valid_permutation(&[1, 2, 3], &[3, 1, 2]); assert_valid_permutation(&[1, 2, 3], &[3, 2, 1]); } #[test] #[should_panic] fn test_invalid_permutation_1() { assert_valid_permutation(&[1, 2, 3], &[4, 2, 3]); } #[test] #[should_panic] fn test_invalid_permutation_2() { assert_valid_permutation(&[1, 2, 3], &[1, 4, 3]); } #[test] #[should_panic] fn test_invalid_permutation_3() { assert_valid_permutation(&[1, 2, 3], &[1, 2, 4]); } #[test] #[should_panic] fn test_invalid_permutation_repeat() { assert_valid_permutation(&[1, 2, 3], &[1, 2, 2]); } /// A Data Structure for testing permutations /// Holds a Vec<i32> with just a few items, so that it's not too long to compute permutations #[derive(Debug, Clone)] pub struct NotTooBigVec { pub(crate) inner: Vec<i32>, // opaque type alias so that we can implement Arbitrary } const MAX_SIZE: usize = 8; // 8! ~= 40k permutations already impl Arbitrary for NotTooBigVec { fn arbitrary(g: &mut Gen) -> Self { let size = usize::arbitrary(g) % MAX_SIZE; let res = (0..size).map(|_| i32::arbitrary(g)).collect(); NotTooBigVec { inner: res } } } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/permutations/heap.rs
src/general/permutations/heap.rs
use std::fmt::Debug; /// Computes all permutations of an array using Heap's algorithm /// Read `recurse_naive` first, since we're building on top of the same intuition pub fn heap_permute<T: Clone + Debug>(arr: &[T]) -> Vec<Vec<T>> { if arr.is_empty() { return vec![vec![]]; } let n = arr.len(); let mut collector = Vec::with_capacity((1..=n).product()); // collects the permuted arrays let mut arr = arr.to_owned(); // Heap's algorithm needs to mutate the array heap_recurse(&mut arr, n, &mut collector); collector } fn heap_recurse<T: Clone + Debug>(arr: &mut [T], k: usize, collector: &mut Vec<Vec<T>>) { if k == 1 { // same base-case as in the naive version collector.push((*arr).to_owned()); return; } // Remember the naive recursion. We did the following: swap(i, last), recurse, swap back(i, last) // Heap's algorithm has a more clever way of permuting the elements so that we never need to swap back! for i in 0..k { // now deal with [a, b] let swap_idx = if k.is_multiple_of(2) { i } else { 0 }; arr.swap(swap_idx, k - 1); heap_recurse(arr, k - 1, collector); } } #[cfg(test)] mod tests { use quickcheck_macros::quickcheck; use crate::general::permutations::heap_permute; use crate::general::permutations::tests::{ assert_permutations, assert_valid_permutation, NotTooBigVec, }; #[test] fn test_3_different_values() { let original = vec![1, 2, 3]; let res = heap_permute(&original); assert_eq!(res.len(), 6); // 3! for permut in res { assert_valid_permutation(&original, &permut) } } #[test] fn test_3_times_the_same_value() { let original = vec![1, 1, 1]; let res = heap_permute(&original); assert_eq!(res.len(), 6); // 3! for permut in res { assert_valid_permutation(&original, &permut) } } #[quickcheck] fn test_some_elements(NotTooBigVec { inner: original }: NotTooBigVec) { let permutations = heap_permute(&original); assert_permutations(&original, &permutations) } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/navigation/rhumbline.rs
src/navigation/rhumbline.rs
use std::f64::consts::PI; const EARTH_RADIUS: f64 = 6371000.0; pub fn rhumb_dist(lat1: f64, long1: f64, lat2: f64, long2: f64) -> f64 { let phi1 = lat1 * PI / 180.00; let phi2 = lat2 * PI / 180.00; let del_phi = phi2 - phi1; let mut del_lambda = (long2 - long1) * PI / 180.00; if del_lambda > PI { del_lambda -= 2.00 * PI; } else if del_lambda < -PI { del_lambda += 2.00 * PI; } let del_psi = ((phi2 / 2.00 + PI / 4.00).tan() / (phi1 / 2.00 + PI / 4.00).tan()).ln(); let q = if del_psi.abs() > 1e-12 { del_phi / del_psi } else { phi1.cos() }; (del_phi.powf(2.00) + (q * del_lambda).powf(2.00)).sqrt() * EARTH_RADIUS } pub fn rhumb_bearing(lat1: f64, long1: f64, lat2: f64, long2: f64) -> f64 { let phi1 = lat1 * PI / 180.00; let phi2 = lat2 * PI / 180.00; let mut del_lambda = (long2 - long1) * PI / 180.00; if del_lambda > PI { del_lambda -= 2.0 * PI; } else if del_lambda < -PI { del_lambda += 2.0 * PI; } let del_psi = ((phi2 / 2.00 + PI / 4.00).tan() / (phi1 / 2.00 + PI / 4.00).tan()).ln(); let bearing = del_lambda.atan2(del_psi) * 180.0 / PI; (bearing + 360.00) % 360.00 } pub fn rhumb_destination(lat: f64, long: f64, distance: f64, bearing: f64) -> (f64, f64) { let del = distance / EARTH_RADIUS; let phi1 = lat * PI / 180.00; let lambda1 = long * PI / 180.00; let theta = bearing * PI / 180.00; let del_phi = del * theta.cos(); let phi2 = (phi1 + del_phi).clamp(-PI / 2.0, PI / 2.0); let del_psi = ((phi2 / 2.00 + PI / 4.00).tan() / (phi1 / 2.0 + PI / 4.0).tan()).ln(); let q = if del_psi.abs() > 1e-12 { del_phi / del_psi } else { phi1.cos() }; let del_lambda = del * theta.sin() / q; let lambda2 = lambda1 + del_lambda; (phi2 * 180.00 / PI, lambda2 * 180.00 / PI) } // TESTS #[cfg(test)] mod tests { use super::*; #[test] fn test_rhumb_distance() { let distance = rhumb_dist(28.5416, 77.2006, 28.5457, 77.1928); assert!(distance > 700.00 && distance < 1000.0); } #[test] fn test_rhumb_bearing() { let bearing = rhumb_bearing(28.5416, 77.2006, 28.5457, 77.1928); assert!((bearing - 300.0).abs() < 5.0); } #[test] fn test_rhumb_destination_point() { let (lat, lng) = rhumb_destination(28.5457, 77.1928, 1000.00, 305.0); assert!((lat - 28.550).abs() < 0.010); assert!((lng - 77.1851).abs() < 0.010); } // edge cases #[test] fn test_rhumb_distance_cross_antimeridian() { // Test when del_lambda > PI (line 12) let distance = rhumb_dist(0.0, 170.0, 0.0, -170.0); assert!(distance > 0.0); } #[test] fn test_rhumb_distance_cross_antimeridian_negative() { // Test when del_lambda < -PI (line 14) let distance = rhumb_dist(0.0, -170.0, 0.0, 170.0); assert!(distance > 0.0); } #[test] fn test_rhumb_distance_to_equator() { // Test when del_psi is near zero (line 21 - the else branch) let distance = rhumb_dist(0.0, 0.0, 0.0, 1.0); assert!(distance > 0.0); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/navigation/bearing.rs
src/navigation/bearing.rs
use std::f64::consts::PI; pub fn bearing(lat1: f64, lng1: f64, lat2: f64, lng2: f64) -> f64 { let lat1 = lat1 * PI / 180.0; let lng1 = lng1 * PI / 180.0; let lat2 = lat2 * PI / 180.0; let lng2 = lng2 * PI / 180.0; let delta_longitude = lng2 - lng1; let y = delta_longitude.sin() * lat2.cos(); let x = lat1.cos() * lat2.sin() - lat1.sin() * lat2.cos() * delta_longitude.cos(); let mut brng = y.atan2(x); brng = brng.to_degrees(); (brng + 360.0) % 360.0 } #[cfg(test)] mod tests { use super::*; #[test] fn testing() { assert_eq!( format!( "{:.0}º", bearing( -27.2020447088982, -49.631891179172555, -3.106362, -60.025826, ) ), "336º" ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/navigation/mod.rs
src/navigation/mod.rs
mod bearing; mod haversine; mod rhumbline; pub use self::bearing::bearing; pub use self::haversine::haversine; pub use self::rhumbline::rhumb_bearing; pub use self::rhumbline::rhumb_destination; pub use self::rhumbline::rhumb_dist;
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/navigation/haversine.rs
src/navigation/haversine.rs
use std::f64::consts::PI; const EARTH_RADIUS: f64 = 6371000.00; pub fn haversine(lat1: f64, lng1: f64, lat2: f64, lng2: f64) -> f64 { let delta_dist_lat = (lat2 - lat1) * PI / 180.0; let delta_dist_lng = (lng2 - lng1) * PI / 180.0; let cos1 = lat1 * PI / 180.0; let cos2 = lat2 * PI / 180.0; let delta_lat = (delta_dist_lat / 2.0).sin().powf(2.0); let delta_lng = (delta_dist_lng / 2.0).sin().powf(2.0); let a = delta_lat + delta_lng * cos1.cos() * cos2.cos(); let result = 2.0 * a.asin().sqrt(); result * EARTH_RADIUS } #[cfg(test)] mod tests { use super::*; #[test] fn testing() { assert_eq!( format!( "{:.2}km", haversine(52.375603, 4.903206, 52.366059, 4.926692) / 1000.0 ), "1.92km" ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/signal_analysis/mod.rs
src/signal_analysis/mod.rs
mod yin; pub use self::yin::{Yin, YinResult};
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/signal_analysis/yin.rs
src/signal_analysis/yin.rs
use std::f64; #[derive(Clone, Debug)] pub struct YinResult { sample_rate: f64, best_lag: usize, cmndf: Vec<f64>, } impl YinResult { pub fn get_frequency(&self) -> f64 { self.sample_rate / self.best_lag as f64 } pub fn get_frequency_with_interpolation(&self) -> f64 { let best_lag_with_interpolation = parabolic_interpolation(self.best_lag, &self.cmndf); self.sample_rate / best_lag_with_interpolation } } fn parabolic_interpolation(lag: usize, cmndf: &[f64]) -> f64 { let x0 = lag.saturating_sub(1); // max(0, lag-1) let x2 = usize::min(cmndf.len() - 1, lag + 1); let s0 = cmndf[x0]; let s1 = cmndf[lag]; let s2 = cmndf[x2]; let denom = s0 - 2.0 * s1 + s2; if denom == 0.0 { return lag as f64; } let delta = (s0 - s2) / (2.0 * denom); lag as f64 + delta } #[derive(Clone, Debug)] pub struct Yin { threshold: f64, min_lag: usize, max_lag: usize, sample_rate: f64, } impl Yin { pub fn init( threshold: f64, min_expected_frequency: f64, max_expected_frequency: f64, sample_rate: f64, ) -> Yin { let min_lag = (sample_rate / max_expected_frequency) as usize; let max_lag = (sample_rate / min_expected_frequency) as usize; Yin { threshold, min_lag, max_lag, sample_rate, } } pub fn yin(&self, frequencies: &[f64]) -> Result<YinResult, String> { let df = difference_function_values(frequencies, self.max_lag); let cmndf = cumulative_mean_normalized_difference_function(&df, self.max_lag); let best_lag = find_cmndf_argmin(&cmndf, self.min_lag, self.max_lag, self.threshold); match best_lag { _ if best_lag == 0 => Err(format!( "Could not find lag value which minimizes CMNDF below the given threshold {}", self.threshold )), _ => Ok(YinResult { sample_rate: self.sample_rate, best_lag, cmndf, }), } } } #[allow(clippy::needless_range_loop)] fn difference_function_values(frequencies: &[f64], max_lag: usize) -> Vec<f64> { let mut df_list = vec![0.0; max_lag + 1]; for lag in 1..=max_lag { df_list[lag] = difference_function(frequencies, lag); } df_list } fn difference_function(f: &[f64], lag: usize) -> f64 { let mut sum = 0.0; let n = f.len(); for i in 0..(n - lag) { let diff = f[i] - f[i + lag]; sum += diff * diff; } sum } const EPSILON: f64 = 1e-10; fn cumulative_mean_normalized_difference_function(df: &[f64], max_lag: usize) -> Vec<f64> { let mut cmndf = vec![0.0; max_lag + 1]; cmndf[0] = 1.0; let mut sum = 0.0; for lag in 1..=max_lag { sum += df[lag]; cmndf[lag] = lag as f64 * df[lag] / if sum == 0.0 { EPSILON } else { sum }; } cmndf } fn find_cmndf_argmin(cmndf: &[f64], min_lag: usize, max_lag: usize, threshold: f64) -> usize { let mut lag = min_lag; while lag <= max_lag { if cmndf[lag] < threshold { while lag < max_lag && cmndf[lag + 1] < cmndf[lag] { lag += 1; } return lag; } lag += 1; } 0 } #[cfg(test)] mod tests { use super::*; fn generate_sine_wave(frequency: f64, sample_rate: f64, duration_secs: f64) -> Vec<f64> { let total_samples = (sample_rate * duration_secs).round() as usize; let two_pi_f = 2.0 * std::f64::consts::PI * frequency; (0..total_samples) .map(|n| { let t = n as f64 / sample_rate; (two_pi_f * t).sin() }) .collect() } fn diff_from_actual_frequency_smaller_than_threshold( result_frequency: f64, actual_frequency: f64, threshold: f64, ) -> bool { let result_diff_from_actual_freq = (result_frequency - actual_frequency).abs(); result_diff_from_actual_freq < threshold } fn interpolation_better_than_raw_result(result: YinResult, frequency: f64) -> bool { let result_frequency = result.get_frequency(); let refined_frequency = result.get_frequency_with_interpolation(); let result_diff = (result_frequency - frequency).abs(); let refined_diff = (refined_frequency - frequency).abs(); refined_diff < result_diff } #[test] fn test_simple_sine() { let sample_rate = 1000.0; let frequency = 12.0; let seconds = 10.0; let signal = generate_sine_wave(frequency, sample_rate, seconds); let min_expected_frequency = 10.0; let max_expected_frequency = 100.0; let yin = Yin::init( 0.1, min_expected_frequency, max_expected_frequency, sample_rate, ); let result = yin.yin(signal.as_slice()); assert!(result.is_ok()); let yin_result = result.unwrap(); assert!(diff_from_actual_frequency_smaller_than_threshold( yin_result.get_frequency(), frequency, 1.0 )); assert!(diff_from_actual_frequency_smaller_than_threshold( yin_result.get_frequency_with_interpolation(), frequency, 1.0, )); assert!(interpolation_better_than_raw_result(yin_result, frequency)); } #[test] fn test_sine_frequency_range() { let sample_rate = 5000.0; for freq in 30..50 { let frequency = freq as f64; let seconds = 2.0; let signal = generate_sine_wave(frequency, sample_rate, seconds); let min_expected_frequency = 5.0; let max_expected_frequency = 100.0; let yin = Yin::init( 0.1, min_expected_frequency, max_expected_frequency, sample_rate, ); let result = yin.yin(signal.as_slice()); assert!(result.is_ok()); let yin_result = result.unwrap(); if (sample_rate as i32 % freq) == 0 { assert_eq!(yin_result.get_frequency(), frequency); } else { assert!(diff_from_actual_frequency_smaller_than_threshold( yin_result.get_frequency(), frequency, 1.0 )); assert!(diff_from_actual_frequency_smaller_than_threshold( yin_result.get_frequency_with_interpolation(), frequency, 1.0, )); assert!(interpolation_better_than_raw_result(yin_result, frequency)); } } } #[test] fn test_harmonic_sines() { let sample_rate = 44100.0; let seconds = 2.0; let frequency_1 = 50.0; // Minimal/Fundamental frequency - this is what YIN should find let signal_1 = generate_sine_wave(frequency_1, sample_rate, seconds); let frequency_2 = 150.0; let signal_2 = generate_sine_wave(frequency_2, sample_rate, seconds); let frequency_3 = 300.0; let signal_3 = generate_sine_wave(frequency_3, sample_rate, seconds); let min_expected_frequency = 10.0; let max_expected_frequency = 500.0; let yin = Yin::init( 0.1, min_expected_frequency, max_expected_frequency, sample_rate, ); let total_samples = (sample_rate * seconds).round() as usize; let combined_signal: Vec<f64> = (0..total_samples) .map(|n| signal_1[n] + signal_2[n] + signal_3[n]) .collect(); let result = yin.yin(&combined_signal); assert!(result.is_ok()); let yin_result = result.unwrap(); assert!(diff_from_actual_frequency_smaller_than_threshold( yin_result.get_frequency(), frequency_1, 1.0 )); } #[test] fn test_unharmonic_sines() { let sample_rate = 44100.0; let seconds = 2.0; let frequency_1 = 50.0; let signal_1 = generate_sine_wave(frequency_1, sample_rate, seconds); let frequency_2 = 66.0; let signal_2 = generate_sine_wave(frequency_2, sample_rate, seconds); let frequency_3 = 300.0; let signal_3 = generate_sine_wave(frequency_3, sample_rate, seconds); let min_expected_frequency = 10.0; let max_expected_frequency = 500.0; let yin = Yin::init( 0.1, min_expected_frequency, max_expected_frequency, sample_rate, ); let total_samples = (sample_rate * seconds).round() as usize; let combined_signal: Vec<f64> = (0..total_samples) .map(|n| signal_1[n] + signal_2[n] + signal_3[n]) .collect(); let result = yin.yin(&combined_signal); assert!(result.is_ok()); let yin_result = result.unwrap(); let expected_frequency = (frequency_1 - frequency_2).abs(); assert!(diff_from_actual_frequency_smaller_than_threshold( yin_result.get_frequency(), expected_frequency, 1.0 )); assert!(interpolation_better_than_raw_result( yin_result, expected_frequency )); } #[test] fn test_err() { let sample_rate = 2500.0; let seconds = 2.0; let frequency = 440.0; // Can't find frequency 440 between 500 and 700 let min_expected_frequency = 500.0; let max_expected_frequency = 700.0; let yin = Yin::init( 0.1, min_expected_frequency, max_expected_frequency, sample_rate, ); let signal = generate_sine_wave(frequency, sample_rate, seconds); let result = yin.yin(&signal); assert!(result.is_err()); let yin_with_suitable_frequency_range = Yin::init( 0.1, min_expected_frequency - 100.0, max_expected_frequency, sample_rate, ); let result = yin_with_suitable_frequency_range.yin(&signal); assert!(result.is_ok()); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/greedy/mod.rs
src/greedy/mod.rs
mod stable_matching; pub use self::stable_matching::stable_matching;
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/greedy/stable_matching.rs
src/greedy/stable_matching.rs
use std::collections::{HashMap, VecDeque}; fn initialize_men( men_preferences: &HashMap<String, Vec<String>>, ) -> (VecDeque<String>, HashMap<String, usize>) { let mut free_men = VecDeque::new(); let mut next_proposal = HashMap::new(); for man in men_preferences.keys() { free_men.push_back(man.clone()); next_proposal.insert(man.clone(), 0); } (free_men, next_proposal) } fn initialize_women( women_preferences: &HashMap<String, Vec<String>>, ) -> HashMap<String, Option<String>> { let mut current_partner = HashMap::new(); for woman in women_preferences.keys() { current_partner.insert(woman.clone(), None); } current_partner } fn precompute_woman_ranks( women_preferences: &HashMap<String, Vec<String>>, ) -> HashMap<String, HashMap<String, usize>> { let mut woman_ranks = HashMap::new(); for (woman, preferences) in women_preferences { let mut rank_map = HashMap::new(); for (rank, man) in preferences.iter().enumerate() { rank_map.insert(man.clone(), rank); } woman_ranks.insert(woman.clone(), rank_map); } woman_ranks } fn process_proposal( man: &str, free_men: &mut VecDeque<String>, current_partner: &mut HashMap<String, Option<String>>, man_engaged: &mut HashMap<String, Option<String>>, next_proposal: &mut HashMap<String, usize>, men_preferences: &HashMap<String, Vec<String>>, woman_ranks: &HashMap<String, HashMap<String, usize>>, ) { let man_pref_list = &men_preferences[man]; let next_woman_idx = next_proposal[man]; let woman = &man_pref_list[next_woman_idx]; // Update man's next proposal index next_proposal.insert(man.to_string(), next_woman_idx + 1); if let Some(current_man) = current_partner[woman].clone() { // Woman is currently engaged, check if she prefers the new man if woman_prefers_new_man(woman, man, &current_man, woman_ranks) { engage_man( man, woman, free_men, current_partner, man_engaged, Some(current_man), ); } else { // Woman rejects the proposal, so the man remains free free_men.push_back(man.to_string()); } } else { // Woman is not engaged, so engage her with this man engage_man(man, woman, free_men, current_partner, man_engaged, None); } } fn woman_prefers_new_man( woman: &str, man1: &str, man2: &str, woman_ranks: &HashMap<String, HashMap<String, usize>>, ) -> bool { let ranks = &woman_ranks[woman]; ranks[man1] < ranks[man2] } fn engage_man( man: &str, woman: &str, free_men: &mut VecDeque<String>, current_partner: &mut HashMap<String, Option<String>>, man_engaged: &mut HashMap<String, Option<String>>, current_man: Option<String>, ) { man_engaged.insert(man.to_string(), Some(woman.to_string())); current_partner.insert(woman.to_string(), Some(man.to_string())); if let Some(current_man) = current_man { // The current man is now free free_men.push_back(current_man); } } fn finalize_matches(man_engaged: HashMap<String, Option<String>>) -> HashMap<String, String> { let mut stable_matches = HashMap::new(); for (man, woman_option) in man_engaged { if let Some(woman) = woman_option { stable_matches.insert(man, woman); } } stable_matches } pub fn stable_matching( men_preferences: &HashMap<String, Vec<String>>, women_preferences: &HashMap<String, Vec<String>>, ) -> HashMap<String, String> { let (mut free_men, mut next_proposal) = initialize_men(men_preferences); let mut current_partner = initialize_women(women_preferences); let mut man_engaged = HashMap::new(); let woman_ranks = precompute_woman_ranks(women_preferences); while let Some(man) = free_men.pop_front() { process_proposal( &man, &mut free_men, &mut current_partner, &mut man_engaged, &mut next_proposal, men_preferences, &woman_ranks, ); } finalize_matches(man_engaged) } #[cfg(test)] mod tests { use super::*; use std::collections::HashMap; #[test] fn test_stable_matching_scenario_1() { let men_preferences = HashMap::from([ ( "A".to_string(), vec!["X".to_string(), "Y".to_string(), "Z".to_string()], ), ( "B".to_string(), vec!["Y".to_string(), "X".to_string(), "Z".to_string()], ), ( "C".to_string(), vec!["X".to_string(), "Y".to_string(), "Z".to_string()], ), ]); let women_preferences = HashMap::from([ ( "X".to_string(), vec!["B".to_string(), "A".to_string(), "C".to_string()], ), ( "Y".to_string(), vec!["A".to_string(), "B".to_string(), "C".to_string()], ), ( "Z".to_string(), vec!["A".to_string(), "B".to_string(), "C".to_string()], ), ]); let matches = stable_matching(&men_preferences, &women_preferences); let expected_matches1 = HashMap::from([ ("A".to_string(), "Y".to_string()), ("B".to_string(), "X".to_string()), ("C".to_string(), "Z".to_string()), ]); let expected_matches2 = HashMap::from([ ("A".to_string(), "X".to_string()), ("B".to_string(), "Y".to_string()), ("C".to_string(), "Z".to_string()), ]); assert!(matches == expected_matches1 || matches == expected_matches2); } #[test] fn test_stable_matching_empty() { let men_preferences = HashMap::new(); let women_preferences = HashMap::new(); let matches = stable_matching(&men_preferences, &women_preferences); assert!(matches.is_empty()); } #[test] fn test_stable_matching_duplicate_preferences() { let men_preferences = HashMap::from([ ("A".to_string(), vec!["X".to_string(), "X".to_string()]), // Man with duplicate preferences ("B".to_string(), vec!["Y".to_string()]), ]); let women_preferences = HashMap::from([ ("X".to_string(), vec!["A".to_string(), "B".to_string()]), ("Y".to_string(), vec!["B".to_string()]), ]); let matches = stable_matching(&men_preferences, &women_preferences); let expected_matches = HashMap::from([ ("A".to_string(), "X".to_string()), ("B".to_string(), "Y".to_string()), ]); assert_eq!(matches, expected_matches); } #[test] fn test_stable_matching_single_pair() { let men_preferences = HashMap::from([("A".to_string(), vec!["X".to_string()])]); let women_preferences = HashMap::from([("X".to_string(), vec!["A".to_string()])]); let matches = stable_matching(&men_preferences, &women_preferences); let expected_matches = HashMap::from([("A".to_string(), "X".to_string())]); assert_eq!(matches, expected_matches); } #[test] fn test_woman_prefers_new_man() { let men_preferences = HashMap::from([ ( "A".to_string(), vec!["X".to_string(), "Y".to_string(), "Z".to_string()], ), ( "B".to_string(), vec!["X".to_string(), "Y".to_string(), "Z".to_string()], ), ( "C".to_string(), vec!["X".to_string(), "Y".to_string(), "Z".to_string()], ), ]); let women_preferences = HashMap::from([ ( "X".to_string(), vec!["B".to_string(), "A".to_string(), "C".to_string()], ), ( "Y".to_string(), vec!["A".to_string(), "B".to_string(), "C".to_string()], ), ( "Z".to_string(), vec!["A".to_string(), "B".to_string(), "C".to_string()], ), ]); let matches = stable_matching(&men_preferences, &women_preferences); let expected_matches = HashMap::from([ ("A".to_string(), "Y".to_string()), ("B".to_string(), "X".to_string()), ("C".to_string(), "Z".to_string()), ]); assert_eq!(matches, expected_matches); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/compound_interest.rs
src/financial/compound_interest.rs
// compound interest is given by A = P(1+r/n)^nt // where: A = Final Amount, P = Principal Amount, r = rate of interest, // n = number of times interest is compounded per year and t = time (in years) pub fn compound_interest(principal: f64, rate: f64, comp_per_year: u32, years: f64) -> f64 { principal * (1.00 + rate / comp_per_year as f64).powf(comp_per_year as f64 * years) } #[cfg(test)] mod tests { use super::*; #[test] fn test_compound_interest() { let principal = 1000.0; let rate = 0.05; // 5% annual interest let times_per_year = 4; // interest compounded quarterly let years = 2.0; // 2 years tenure let result = compound_interest(principal, rate, times_per_year, years); assert!((result - 1104.486).abs() < 0.001); // expected value rounded to 3 decimal // places } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/present_value.rs
src/financial/present_value.rs
/// In economics and finance, present value (PV), also known as present discounted value, /// is the value of an expected income stream determined as of the date of valuation. /// /// -> Wikipedia reference: https://en.wikipedia.org/wiki/Present_value #[derive(PartialEq, Eq, Debug)] pub enum PresentValueError { NegetiveDiscount, EmptyCashFlow, } pub fn present_value(discount_rate: f64, cash_flows: Vec<f64>) -> Result<f64, PresentValueError> { if discount_rate < 0.0 { return Err(PresentValueError::NegetiveDiscount); } if cash_flows.is_empty() { return Err(PresentValueError::EmptyCashFlow); } let present_value = cash_flows .iter() .enumerate() .map(|(i, &cash_flow)| cash_flow / (1.0 + discount_rate).powi(i as i32)) .sum::<f64>(); Ok(round(present_value)) } fn round(value: f64) -> f64 { (value * 100.0).round() / 100.0 } #[cfg(test)] mod tests { use super::*; macro_rules! test_present_value { ($($name:ident: $inputs:expr,)*) => { $( #[test] fn $name() { let ((discount_rate,cash_flows), expected) = $inputs; assert_eq!(present_value(discount_rate,cash_flows).unwrap(), expected); } )* } } macro_rules! test_present_value_Err { ($($name:ident: $inputs:expr,)*) => { $( #[test] fn $name() { let ((discount_rate,cash_flows), expected) = $inputs; assert_eq!(present_value(discount_rate,cash_flows).unwrap_err(), expected); } )* } } macro_rules! test_round { ($($name:ident: $inputs:expr,)*) => { $( #[test] fn $name() { let (input, expected) = $inputs; assert_eq!(round(input), expected); } )* } } test_present_value! { general_inputs1:((0.13, vec![10.0, 20.70, -293.0, 297.0]),4.69), general_inputs2:((0.07, vec![-109129.39, 30923.23, 15098.93, 29734.0, 39.0]),-42739.63), general_inputs3:((0.07, vec![109129.39, 30923.23, 15098.93, 29734.0, 39.0]), 175519.15), zero_input:((0.0, vec![109129.39, 30923.23, 15098.93, 29734.0, 39.0]), 184924.55), } test_present_value_Err! { negative_discount_rate:((-1.0, vec![10.0, 20.70, -293.0, 297.0]), PresentValueError::NegetiveDiscount), empty_cash_flow:((1.0, vec![]), PresentValueError::EmptyCashFlow), } test_round! { test1:(0.55434, 0.55), test2:(10.453, 10.45), test3:(1111_f64, 1111_f64), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/treynor_ratio.rs
src/financial/treynor_ratio.rs
/// Calculates the Treynor Ratio for a portfolio. /// /// # Inputs /// - `portfolio_return`: Portfolio return /// - `risk_free_rate`: Risk-free rate /// - `beta`: Portfolio beta /// where Beta is a financial metric that measures the systematic risk of a security or portfolio compared to the overall market. /// /// # Output /// - Returns excess return per unit of market risk pub fn treynor_ratio(portfolio_return: f64, risk_free_rate: f64, beta: f64) -> f64 { if beta == 0.0 { f64::NAN } else { (portfolio_return - risk_free_rate) / beta } } #[cfg(test)] mod tests { use super::*; #[test] fn test_treynor_ratio() { // for portfolio_return = 0.10, risk_free_rate = 0.05, beta = 1.5 // expected result: (0.10 - 0.05) / 1.5 = 0.033333... assert!((treynor_ratio(0.10, 0.05, 1.50) - 0.03333).abs() < 0.01); } #[test] fn test_treynor_ratio_empty_beta() { // test for zero beta (undefined ratio) assert!(treynor_ratio(0.10, 0.05, 0.00).is_nan()); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/payback.rs
src/financial/payback.rs
/// Returns the payback period in years /// If investment is not paid back, returns None. pub fn payback(cash_flow: &[f64]) -> Option<usize> { let mut total = 0.00; for (year, &cf) in cash_flow.iter().enumerate() { total += cf; if total >= 0.00 { return Some(year); } } None } #[cfg(test)] mod tests { use super::*; #[test] fn test_payback() { let cash_flows = vec![-1000.0, 300.0, 400.0, 500.0]; assert_eq!(payback(&cash_flows), Some(3)); // paid back in year 3 } #[test] fn test_no_payback() { let cash_flows = vec![-1000.0, 100.0, 100.0, 100.0]; assert_eq!(payback(&cash_flows), None); // never paid back } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/mod.rs
src/financial/mod.rs
mod compound_interest; mod finance_ratios; mod npv; mod npv_sensitivity; mod payback; mod present_value; mod treynor_ratio; pub use compound_interest::compound_interest; pub use npv::npv; pub use npv_sensitivity::npv_sensitivity; pub use payback::payback; pub use present_value::present_value; pub use treynor_ratio::treynor_ratio; pub use finance_ratios::debt_to_equity; pub use finance_ratios::earnings_per_sale; pub use finance_ratios::gross_profit_margin; pub use finance_ratios::return_on_investment;
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/npv_sensitivity.rs
src/financial/npv_sensitivity.rs
/// Computes the Net Present Value (NPV) of a cash flow series /// at multiple discount rates to show sensitivity. /// /// # Inputs: /// - `cash_flows`: A slice of cash flows, where each entry is a period value /// e.g., year 0 is initial investment, year 1+ are returns or costs /// - `discount_rates`: A slice of discount rates, e.g. `[0.05, 0.10, 0.20]`, /// where each rate is evaluated independently. /// /// # Output: /// - Returns a vector of NPV values, each corresponding to a rate in `discount_rates`. /// For example, output is `[npv_rate1, npv_rate2, ...]`. pub fn npv_sensitivity(cash_flows: &[f64], discount_rates: &[f64]) -> Vec<f64> { discount_rates .iter() .cloned() .map(|rate| { cash_flows .iter() .enumerate() .map(|(t, &cf)| cf / (1.0 + rate).powi(t as i32)) .sum() }) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn test_npv_sensitivity() { let cashflows = [-1000.00, 400.00, 400.00, 400.00]; let rates = [0.05, 0.1, 0.2]; let expected = [89.30, -5.26, -157.41]; let out = npv_sensitivity(&cashflows, &rates); assert_eq!(out.len(), 3); // value check for (o, e) in out.iter().zip(expected.iter()) { assert!((o - e).abs() < 0.1); } } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/npv.rs
src/financial/npv.rs
/// Calculates Net Present Value given a vector of cash flows and a discount rate. /// cash_flows: Vector of f64 representing cash flows for each period. /// rate: Discount rate as an f64 (e.g., 0.05 for 5%) pub fn npv(cash_flows: &[f64], rate: f64) -> f64 { cash_flows .iter() .enumerate() .map(|(t, &cf)| cf / (1.00 + rate).powi(t as i32)) .sum() } // tests #[cfg(test)] mod tests { use super::*; #[test] fn test_npv_basic() { let cash_flows = vec![-1000.0, 300.0, 400.0, -50.0]; let rate = 0.10; let result = npv(&cash_flows, rate); // Calculated value ≈ -434.25 assert!((result - (-434.25)).abs() < 0.05); // Allow small margin of error } #[test] fn test_npv_zero_rate() { let cash_flows = vec![100.0, 200.0, -50.0]; let rate = 0.0; let result = npv(&cash_flows, rate); assert!((result - 250.0).abs() < 0.05); } #[test] fn test_npv_empty() { // For empty cash flows: NPV should be 0 let cash_flows: Vec<f64> = vec![]; let rate = 0.05; let result = npv(&cash_flows, rate); assert_eq!(result, 0.0); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/finance_ratios.rs
src/financial/finance_ratios.rs
// Calculating simple ratios like Return on Investment (ROI), Debt to Equity, Gross Profit Margin // and Earnings per Sale (EPS) pub fn return_on_investment(gain: f64, cost: f64) -> f64 { (gain - cost) / cost } pub fn debt_to_equity(debt: f64, equity: f64) -> f64 { debt / equity } pub fn gross_profit_margin(revenue: f64, cost: f64) -> f64 { (revenue - cost) / revenue } pub fn earnings_per_sale(net_income: f64, pref_dividend: f64, share_avg: f64) -> f64 { (net_income - pref_dividend) / share_avg } #[cfg(test)] mod tests { use super::*; #[test] fn test_return_on_investment() { // let gain = 1200, cost = 1000 thus, ROI = (1200 - 1000)/1000 = 0.2 let result = return_on_investment(1200.0, 1000.0); assert!((result - 0.2).abs() < 0.001); } #[test] fn test_debt_to_equity() { // let debt = 300, equity = 150 thus, debt to equity ratio = 300/150 = 2 let result = debt_to_equity(300.0, 150.0); assert!((result - 2.0).abs() < 0.001); } #[test] fn test_gross_profit_margin() { // let revenue = 1000, cost = 800 thus, gross profit margin = (1000-800)/1000 = 0.2 let result = gross_profit_margin(1000.0, 800.0); assert!((result - 0.2).abs() < 0.01); } #[test] fn test_earnings_per_sale() { // let net_income = 350, pref_dividend = 50, share_avg = 25 this EPS = (350-50)/25 = 12 let result = earnings_per_sale(350.0, 50.0, 25.0); assert!((result - 12.0).abs() < 0.001); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/quick_sort_3_ways.rs
src/sorting/quick_sort_3_ways.rs
use std::cmp::{Ord, Ordering}; use rand::Rng; fn _quick_sort_3_ways<T: Ord>(arr: &mut [T], lo: usize, hi: usize) { if lo >= hi { return; } let mut rng = rand::rng(); arr.swap(lo, rng.random_range(lo..=hi)); let mut lt = lo; // arr[lo+1, lt] < v let mut gt = hi + 1; // arr[gt, r] > v let mut i = lo + 1; // arr[lt + 1, i) == v while i < gt { match arr[i].cmp(&arr[lo]) { Ordering::Less => { arr.swap(i, lt + 1); i += 1; lt += 1; } Ordering::Greater => { arr.swap(i, gt - 1); gt -= 1; } Ordering::Equal => { i += 1; } } } arr.swap(lo, lt); if lt > 1 { _quick_sort_3_ways(arr, lo, lt - 1); } _quick_sort_3_ways(arr, gt, hi); } pub fn quick_sort_3_ways<T: Ord>(arr: &mut [T]) { let len = arr.len(); if len > 1 { _quick_sort_3_ways(arr, 0, len - 1); } } #[cfg(test)] mod tests { use super::*; use crate::sorting::have_same_elements; use crate::sorting::is_sorted; use crate::sorting::sort_utils; #[test] fn basic() { let mut res = vec![10, 8, 4, 3, 1, 9, 2, 7, 5, 6]; let cloned = res.clone(); sort_utils::log_timed("basic", || { quick_sort_3_ways(&mut res); }); assert!(is_sorted(&res) && have_same_elements(&res, &cloned)); } #[test] fn basic_string() { let mut res = vec!["a", "bb", "d", "cc"]; let cloned = res.clone(); sort_utils::log_timed("basic string", || { quick_sort_3_ways(&mut res); }); assert!(is_sorted(&res) && have_same_elements(&res, &cloned)); } #[test] fn empty() { let mut res = Vec::<u8>::new(); let cloned = res.clone(); sort_utils::log_timed("empty", || { quick_sort_3_ways(&mut res); }); assert!(is_sorted(&res) && have_same_elements(&res, &cloned)); } #[test] fn one_element() { let mut res = sort_utils::generate_random_vec(1, 0, 1); let cloned = res.clone(); sort_utils::log_timed("one element", || { quick_sort_3_ways(&mut res); }); assert!(is_sorted(&res) && have_same_elements(&res, &cloned)); } #[test] fn pre_sorted() { let mut res = sort_utils::generate_nearly_ordered_vec(300000, 0); let cloned = res.clone(); sort_utils::log_timed("pre sorted", || { quick_sort_3_ways(&mut res); }); assert!(is_sorted(&res) && have_same_elements(&res, &cloned)); } #[test] fn reverse_sorted() { let mut res = sort_utils::generate_reverse_ordered_vec(300000); let cloned = res.clone(); sort_utils::log_timed("reverse sorted", || { quick_sort_3_ways(&mut res); }); assert!(is_sorted(&res) && have_same_elements(&res, &cloned)); } #[test] fn large_elements() { let mut res = sort_utils::generate_random_vec(300000, 0, 1000000); let cloned = res.clone(); sort_utils::log_timed("large elements test", || { quick_sort_3_ways(&mut res); }); assert!(is_sorted(&res) && have_same_elements(&res, &cloned)); } #[test] fn nearly_ordered_elements() { let mut res = sort_utils::generate_nearly_ordered_vec(300000, 10); let cloned = res.clone(); sort_utils::log_timed("nearly ordered elements test", || { quick_sort_3_ways(&mut res); }); assert!(is_sorted(&res) && have_same_elements(&res, &cloned)); } #[test] fn repeated_elements() { let mut res = sort_utils::generate_repeated_elements_vec(1000000, 3); let cloned = res.clone(); sort_utils::log_timed("repeated elements test", || { quick_sort_3_ways(&mut res); }); assert!(is_sorted(&res) && have_same_elements(&res, &cloned)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/heap_sort.rs
src/sorting/heap_sort.rs
//! This module provides functions for heap sort algorithm. use std::cmp::Ordering; /// Builds a heap from the provided array. /// /// This function builds either a max heap or a min heap based on the `is_max_heap` parameter. /// /// # Arguments /// /// * `arr` - A mutable reference to the array to be sorted. /// * `is_max_heap` - A boolean indicating whether to build a max heap (`true`) or a min heap (`false`). fn build_heap<T: Ord>(arr: &mut [T], is_max_heap: bool) { let mut i = (arr.len() - 1) / 2; while i > 0 { heapify(arr, i, is_max_heap); i -= 1; } heapify(arr, 0, is_max_heap); } /// Fixes a heap violation starting at the given index. /// /// This function adjusts the heap rooted at index `i` to fix the heap property violation. /// It assumes that the subtrees rooted at left and right children of `i` are already heaps. /// /// # Arguments /// /// * `arr` - A mutable reference to the array representing the heap. /// * `i` - The index to start fixing the heap violation. /// * `is_max_heap` - A boolean indicating whether to maintain a max heap or a min heap. fn heapify<T: Ord>(arr: &mut [T], i: usize, is_max_heap: bool) { let comparator: fn(&T, &T) -> Ordering = if is_max_heap { |a, b| a.cmp(b) } else { |a, b| b.cmp(a) }; let mut idx = i; let l = 2 * i + 1; let r = 2 * i + 2; if l < arr.len() && comparator(&arr[l], &arr[idx]) == Ordering::Greater { idx = l; } if r < arr.len() && comparator(&arr[r], &arr[idx]) == Ordering::Greater { idx = r; } if idx != i { arr.swap(i, idx); heapify(arr, idx, is_max_heap); } } /// Sorts the given array using heap sort algorithm. /// /// This function sorts the array either in ascending or descending order based on the `ascending` parameter. /// /// # Arguments /// /// * `arr` - A mutable reference to the array to be sorted. /// * `ascending` - A boolean indicating whether to sort in ascending order (`true`) or descending order (`false`). pub fn heap_sort<T: Ord>(arr: &mut [T], ascending: bool) { if arr.len() <= 1 { return; } // Build heap based on the order build_heap(arr, ascending); let mut end = arr.len() - 1; while end > 0 { arr.swap(0, end); heapify(&mut arr[..end], 0, ascending); end -= 1; } } #[cfg(test)] mod tests { use crate::sorting::{have_same_elements, heap_sort, is_descending_sorted, is_sorted}; macro_rules! test_heap_sort { ($($name:ident: $input:expr,)*) => { $( #[test] fn $name() { let input_array = $input; let mut arr_asc = input_array.clone(); heap_sort(&mut arr_asc, true); assert!(is_sorted(&arr_asc) && have_same_elements(&arr_asc, &input_array)); let mut arr_dsc = input_array.clone(); heap_sort(&mut arr_dsc, false); assert!(is_descending_sorted(&arr_dsc) && have_same_elements(&arr_dsc, &input_array)); } )* } } test_heap_sort! { empty_array: Vec::<i32>::new(), single_element_array: vec![5], sorted: vec![1, 2, 3, 4, 5], sorted_desc: vec![5, 4, 3, 2, 1, 0], basic_0: vec![9, 8, 7, 6, 5], basic_1: vec![8, 3, 1, 5, 7], basic_2: vec![4, 5, 7, 1, 2, 3, 2, 8, 5, 4, 9, 9, 100, 1, 2, 3, 6, 4, 3], duplicated_elements: vec![5, 5, 5, 5, 5], strings: vec!["aa", "a", "ba", "ab"], } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/cocktail_shaker_sort.rs
src/sorting/cocktail_shaker_sort.rs
pub fn cocktail_shaker_sort<T: Ord>(arr: &mut [T]) { let len = arr.len(); if len == 0 { return; } loop { let mut swapped = false; for i in 0..(len - 1).clamp(0, len) { if arr[i] > arr[i + 1] { arr.swap(i, i + 1); swapped = true; } } if !swapped { break; } swapped = false; for i in (0..(len - 1).clamp(0, len)).rev() { if arr[i] > arr[i + 1] { arr.swap(i, i + 1); swapped = true; } } if !swapped { break; } } } #[cfg(test)] mod tests { use super::*; use crate::sorting::have_same_elements; use crate::sorting::is_sorted; #[test] fn basic() { let mut arr = vec![5, 2, 1, 3, 4, 6]; let cloned = arr.clone(); cocktail_shaker_sort(&mut arr); assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned)); } #[test] fn empty() { let mut arr = Vec::<i32>::new(); let cloned = arr.clone(); cocktail_shaker_sort(&mut arr); assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned)); } #[test] fn one_element() { let mut arr = vec![1]; let cloned = arr.clone(); cocktail_shaker_sort(&mut arr); assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned)); } #[test] fn pre_sorted() { let mut arr = vec![1, 2, 3, 4, 5, 6]; let cloned = arr.clone(); cocktail_shaker_sort(&mut arr); assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/wiggle_sort.rs
src/sorting/wiggle_sort.rs
//Wiggle Sort. //Given an unsorted array nums, reorder it such //that nums[0] < nums[1] > nums[2] < nums[3].... //For example: //if input numbers = [3, 5, 2, 1, 6, 4] //one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4]. pub fn wiggle_sort(nums: &mut Vec<i32>) -> &mut Vec<i32> { //Rust implementation of wiggle. // Example: // >>> wiggle_sort([0, 5, 3, 2, 2]) // [0, 5, 2, 3, 2] // >>> wiggle_sort([]) // [] // >>> wiggle_sort([-2, -5, -45]) // [-45, -2, -5] let len = nums.len(); for i in 1..len { let num_x = nums[i - 1]; let num_y = nums[i]; if (i % 2 == 1) == (num_x > num_y) { nums[i - 1] = num_y; nums[i] = num_x; } } nums } #[cfg(test)] mod tests { use super::*; use crate::sorting::have_same_elements; fn is_wiggle_sorted(nums: &[i32]) -> bool { if nums.is_empty() { return true; } let mut previous = nums[0]; let mut result = true; nums.iter().enumerate().skip(1).for_each(|(i, &item)| { if i != 0 { result = result && ((i % 2 == 1 && previous < item) || (i % 2 == 0 && previous > item)); } previous = item; }); result } #[test] fn wingle_elements() { let arr = vec![3, 5, 2, 1, 6, 4]; let mut cloned = arr.clone(); let res = wiggle_sort(&mut cloned); assert!(is_wiggle_sorted(res)); assert!(have_same_elements(res, &arr)); } #[test] fn odd_number_of_elements() { let arr = vec![4, 1, 3, 5, 2]; let mut cloned = arr.clone(); let res = wiggle_sort(&mut cloned); assert!(is_wiggle_sorted(res)); assert!(have_same_elements(res, &arr)); } #[test] fn repeated_elements() { let arr = vec![5, 5, 5, 5]; let mut cloned = arr.clone(); let res = wiggle_sort(&mut cloned); // Negative test, can't be wiggle sorted assert!(!is_wiggle_sorted(res)); assert!(have_same_elements(res, &arr)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false