use core::fmt::{Display, Formatter};
use core::str::FromStr;
use bytemuck::{Pod, Zeroable};
use num_enum::{IntoPrimitive, TryFromPrimitive};
#[cfg(feature = "wincode")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "wincode")]
use wincode_derive::{SchemaRead, SchemaWrite};
use crate::erasure::MAX_GROUP_SIZE;
pub const TAPENET_CLAY: ClayParams = ClayParams::new(20, 7, 16);
pub const TAPENET_PROFILE: ErasureCode = ErasureCode::Clay(TAPENET_CLAY);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ProfileError {
UnknownEncoding,
Width,
Recovery,
Helpers,
Syntax,
}
impl Display for ProfileError {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
Self::UnknownEncoding => write!(f, "unknown encoding type"),
Self::Width => write!(f, "n is outside 1..={MAX_GROUP_SIZE}"),
Self::Recovery => write!(f, "k is outside 1..n"),
Self::Helpers => write!(f, "d is outside k + 1..n"),
Self::Syntax => write!(f, "expected clay:n,k,d, rs:n,k or copies:n"),
}
}
}
impl std::error::Error for ProfileError {}
#[repr(u64)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
pub enum EncodingType {
#[default]
Unknown = 0,
ReedSolomon = 1,
Clay = 2,
Replication = 3,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Pod, Zeroable)]
#[cfg_attr(feature = "wincode", derive(Serialize, Deserialize, SchemaRead, SchemaWrite))]
pub struct EncodingProfile {
pub encoding: u64,
pub params: u64,
}
impl EncodingProfile {
#[inline]
pub fn encoding_type(&self) -> Option<EncodingType> {
EncodingType::try_from(self.encoding).ok()
}
#[inline]
pub const fn clay(params: ClayParams) -> Self {
Self {
encoding: EncodingType::Clay as u64,
params: params.as_u64(),
}
}
#[inline]
pub const fn reed_solomon(params: RSParams) -> Self {
Self {
encoding: EncodingType::ReedSolomon as u64,
params: params.as_u64(),
}
}
#[inline]
pub const fn replication(params: RepParams) -> Self {
Self {
encoding: EncodingType::Replication as u64,
params: params.as_u64(),
}
}
pub fn pack(&self) -> [u8; 16] {
let mut out = [0u8; 16];
out[..8].copy_from_slice(&self.encoding.to_le_bytes());
out[8..16].copy_from_slice(&self.params.to_le_bytes());
out
}
pub fn unpack(data: [u8; 16]) -> Self {
Self {
encoding: u64::from_le_bytes(data[..8].try_into().unwrap()),
params: u64::from_le_bytes(data[8..16].try_into().unwrap()),
}
}
#[inline]
pub const fn unknown() -> Self {
Self {
encoding: EncodingType::Unknown as u64,
params: 0,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ErasureCode {
Clay(ClayParams),
ReedSolomon(RSParams),
Replication(RepParams),
}
impl ErasureCode {
#[inline]
pub const fn n(&self) -> u8 {
match self {
Self::Clay(params) => params.n(),
Self::ReedSolomon(params) => params.n(),
Self::Replication(params) => params.n(),
}
}
#[inline]
pub const fn k(&self) -> u8 {
match self {
Self::Clay(params) => params.k(),
Self::ReedSolomon(params) => params.k(),
Self::Replication(params) => params.k(),
}
}
#[inline]
pub const fn m(&self) -> u8 {
match self {
Self::Clay(params) => params.m(),
Self::ReedSolomon(params) => params.m(),
Self::Replication(params) => params.m(),
}
}
#[inline]
pub const fn d(&self) -> Option<u8> {
match self {
Self::Clay(params) => Some(params.d()),
Self::ReedSolomon(_) | Self::Replication(_) => None,
}
}
pub const fn validate(&self) -> Result<(), ProfileError> {
match self {
Self::Clay(params) => params.validate(),
Self::ReedSolomon(params) => params.validate(),
Self::Replication(params) => params.validate(),
}
}
}
impl TryFrom<EncodingProfile> for ErasureCode {
type Error = ProfileError;
fn try_from(profile: EncodingProfile) -> Result<Self, ProfileError> {
let code = match profile.encoding_type() {
Some(EncodingType::Clay) => Self::Clay(ClayParams::from_u64(profile.params)),
Some(EncodingType::ReedSolomon) => Self::ReedSolomon(RSParams::from_u64(profile.params)),
Some(EncodingType::Replication) => Self::Replication(RepParams::from_u64(profile.params)),
Some(EncodingType::Unknown) | None => return Err(ProfileError::UnknownEncoding),
};
code.validate()?;
Ok(code)
}
}
impl From<ErasureCode> for EncodingProfile {
fn from(code: ErasureCode) -> Self {
match code {
ErasureCode::Clay(params) => Self::clay(params),
ErasureCode::ReedSolomon(params) => Self::reed_solomon(params),
ErasureCode::Replication(params) => Self::replication(params),
}
}
}
impl Display for ErasureCode {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
Self::Clay(params) => write!(f, "clay:{},{},{}", params.n(), params.k(), params.d()),
Self::ReedSolomon(params) => write!(f, "rs:{},{}", params.n(), params.k()),
Self::Replication(params) => write!(f, "copies:{}", params.n()),
}
}
}
impl FromStr for ErasureCode {
type Err = ProfileError;
fn from_str(text: &str) -> Result<Self, ProfileError> {
let (name, list) = text.split_once(':').ok_or(ProfileError::Syntax)?;
let mut numbers = [0u8; 3];
let mut count = 0;
for number in list.split(',') {
let slot = numbers.get_mut(count).ok_or(ProfileError::Syntax)?;
*slot = number.trim().parse().map_err(|_| ProfileError::Syntax)?;
count += 1;
}
let code = match (name.trim(), &numbers[..count]) {
("clay", [n, k, d]) => Self::Clay(ClayParams::new(*n, *k, *d)),
("rs", [n, k]) => Self::ReedSolomon(RSParams::new(*k, n.saturating_sub(*k))),
("copies", [n]) => Self::Replication(RepParams::new(*n)),
_ => return Err(ProfileError::Syntax),
};
code.validate()?;
Ok(code)
}
}
const fn is_width(n: u8) -> bool {
n >= 1 && n as usize <= MAX_GROUP_SIZE
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Pod, Zeroable)]
pub struct ClayParams {
packed: u64,
}
impl ClayParams {
#[inline]
pub const fn new(n: u8, k: u8, d: u8) -> Self {
Self {
packed: (n as u64) | ((k as u64) << 8) | ((d as u64) << 16),
}
}
#[inline]
pub const fn n(&self) -> u8 {
(self.packed & 0xFF) as u8
}
#[inline]
pub const fn k(&self) -> u8 {
((self.packed >> 8) & 0xFF) as u8
}
#[inline]
pub const fn d(&self) -> u8 {
((self.packed >> 16) & 0xFF) as u8
}
#[inline]
pub const fn m(&self) -> u8 {
self.n().saturating_sub(self.k())
}
#[inline]
pub const fn alpha(&self) -> u64 {
let q = self.d().saturating_sub(self.k()) as u64 + 1;
let n = self.n() as u64;
let t = (n + q - 1) / q;
let mut out = 1u64;
let mut i = 0;
while i < t {
out = out.saturating_mul(q);
i += 1;
}
out
}
#[inline]
pub const fn stripe_alignment(&self) -> u64 {
(self.k() as u64).saturating_mul(self.alpha()).saturating_mul(2)
}
pub const fn validate(&self) -> Result<(), ProfileError> {
let (n, k, d) = (self.n(), self.k(), self.d());
if !is_width(n) {
return Err(ProfileError::Width);
}
if k == 0 || k >= n {
return Err(ProfileError::Recovery);
}
if d <= k || d >= n {
return Err(ProfileError::Helpers);
}
Ok(())
}
#[inline]
pub const fn as_u64(&self) -> u64 {
self.packed
}
#[inline]
pub const fn from_u64(v: u64) -> Self {
Self { packed: v }
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Pod, Zeroable)]
pub struct RSParams {
packed: u64,
}
impl RSParams {
#[inline]
pub const fn new(k: u8, m: u8) -> Self {
let n = k.saturating_add(m);
Self {
packed: (n as u64) | ((k as u64) << 8),
}
}
#[inline]
pub const fn n(&self) -> u8 {
(self.packed & 0xFF) as u8
}
#[inline]
pub const fn k(&self) -> u8 {
((self.packed >> 8) & 0xFF) as u8
}
#[inline]
pub const fn m(&self) -> u8 {
self.n().saturating_sub(self.k())
}
pub const fn validate(&self) -> Result<(), ProfileError> {
let (n, k) = (self.n(), self.k());
if !is_width(n) {
return Err(ProfileError::Width);
}
if k == 0 || k >= n {
return Err(ProfileError::Recovery);
}
Ok(())
}
#[inline]
pub const fn as_u64(&self) -> u64 {
self.packed
}
#[inline]
pub const fn from_u64(v: u64) -> Self {
Self { packed: v }
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Pod, Zeroable)]
pub struct RepParams {
packed: u64,
}
impl RepParams {
#[inline]
pub const fn new(n: u8) -> Self {
Self { packed: n as u64 }
}
#[inline]
pub const fn n(&self) -> u8 {
(self.packed & 0xFF) as u8
}
#[inline]
pub const fn k(&self) -> u8 {
1
}
#[inline]
pub const fn m(&self) -> u8 {
self.n().saturating_sub(1)
}
pub const fn validate(&self) -> Result<(), ProfileError> {
if !is_width(self.n()) {
return Err(ProfileError::Width);
}
Ok(())
}
#[inline]
pub const fn as_u64(&self) -> u64 {
self.packed
}
#[inline]
pub const fn from_u64(v: u64) -> Self {
Self { packed: v }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_clay_params_new() {
let params = ClayParams::new(20, 10, 19);
assert_eq!(params.n(), 20);
assert_eq!(params.k(), 10);
assert_eq!(params.d(), 19);
assert_eq!(params.m(), 10);
}
#[test]
fn test_clay_params_roundtrip() {
let params = ClayParams::new(20, 10, 19);
let packed = params.as_u64();
let recovered = ClayParams::from_u64(packed);
assert_eq!(params, recovered);
}
#[test]
fn test_rs_params_new() {
let params = RSParams::new(10, 10);
assert_eq!(params.n(), 20);
assert_eq!(params.k(), 10);
assert_eq!(params.m(), 10);
}
#[test]
fn test_rs_params_roundtrip() {
let params = RSParams::new(8, 4);
let packed = params.as_u64();
let recovered = RSParams::from_u64(packed);
assert_eq!(params, recovered);
}
#[test]
fn test_rs_params_size() {
assert_eq!(std::mem::size_of::<RSParams>(), 8);
}
#[test]
fn test_encoding_profile_unknown() {
let profile = EncodingProfile::unknown();
assert_eq!(profile.encoding_type(), Some(EncodingType::Unknown));
}
#[test]
fn test_encoding_profile_zeroed() {
let profile = EncodingProfile::zeroed();
assert_eq!(profile.encoding_type(), Some(EncodingType::Unknown));
}
#[test]
fn test_encoding_profile_size() {
assert_eq!(std::mem::size_of::<EncodingProfile>(), 16);
}
#[test]
fn test_clay_params_size() {
assert_eq!(std::mem::size_of::<ClayParams>(), 8);
}
#[test]
fn test_encoding_type_values() {
assert_eq!(EncodingType::Unknown as u64, 0);
assert_eq!(EncodingType::ReedSolomon as u64, 1);
assert_eq!(EncodingType::Clay as u64, 2);
assert_eq!(EncodingType::Replication as u64, 3);
}
#[test]
fn test_different_clay_params() {
let params1 = ClayParams::new(20, 6, 19);
assert_eq!(params1.k(), 6);
assert_eq!(params1.m(), 14);
let params2 = ClayParams::new(20, 14, 19);
assert_eq!(params2.k(), 14);
assert_eq!(params2.m(), 6);
assert_ne!(params1, params2);
}
#[test]
fn tapenet() {
let code = ErasureCode::try_from(EncodingProfile::from(TAPENET_PROFILE)).expect("tapenet");
assert_eq!(code, TAPENET_PROFILE);
assert_eq!((code.n(), code.k(), code.m()), (20, 7, 13));
assert_eq!(TAPENET_CLAY.d(), 16);
assert_eq!(TAPENET_CLAY.alpha(), 100);
assert_eq!(TAPENET_CLAY.stripe_alignment(), 1_400);
}
#[test]
fn stored_form() {
let codes = [
ErasureCode::Clay(ClayParams::new(10, 7, 9)),
ErasureCode::ReedSolomon(RSParams::new(4, 2)),
ErasureCode::Replication(RepParams::new(2)),
];
for code in codes {
let profile = EncodingProfile::from(code);
let unpacked = EncodingProfile::unpack(profile.pack());
assert_eq!(ErasureCode::try_from(unpacked), Ok(code));
}
}
#[test]
fn counts() {
let reed_solomon = ErasureCode::ReedSolomon(RSParams::new(4, 2));
let copies = ErasureCode::Replication(RepParams::new(3));
assert_eq!((reed_solomon.n(), reed_solomon.k(), reed_solomon.m()), (6, 4, 2));
assert_eq!((copies.n(), copies.k(), copies.m()), (3, 1, 2));
}
#[test]
fn unknown_encoding() {
let unassigned = EncodingProfile { encoding: 9, params: TAPENET_CLAY.as_u64() };
assert_eq!(ErasureCode::try_from(EncodingProfile::unknown()), Err(ProfileError::UnknownEncoding));
assert_eq!(ErasureCode::try_from(EncodingProfile::zeroed()), Err(ProfileError::UnknownEncoding));
assert_eq!(ErasureCode::try_from(unassigned), Err(ProfileError::UnknownEncoding));
}
#[test]
fn clay_rules() {
assert_eq!(TAPENET_CLAY.validate(), Ok(()));
assert_eq!(ClayParams::new(4, 2, 3).validate(), Ok(()));
assert_eq!(ClayParams::new(20, 10, 12).validate(), Ok(()));
assert_eq!(ClayParams::new(0, 0, 0).validate(), Err(ProfileError::Width));
assert_eq!(ClayParams::new(21, 7, 16).validate(), Err(ProfileError::Width));
assert_eq!(ClayParams::new(20, 0, 16).validate(), Err(ProfileError::Recovery));
assert_eq!(ClayParams::new(20, 20, 16).validate(), Err(ProfileError::Recovery));
assert_eq!(ClayParams::new(20, 7, 7).validate(), Err(ProfileError::Helpers));
assert_eq!(ClayParams::new(20, 7, 20).validate(), Err(ProfileError::Helpers));
assert_eq!(ClayParams::new(4, 3, 3).validate(), Err(ProfileError::Helpers));
}
#[test]
fn reed_solomon_rules() {
assert_eq!(RSParams::new(3, 1).validate(), Ok(()));
assert_eq!(RSParams::new(4, 2).validate(), Ok(()));
assert_eq!(RSParams::new(1, 19).validate(), Ok(()));
assert_eq!(RSParams::new(0, 0).validate(), Err(ProfileError::Width));
assert_eq!(RSParams::new(10, 11).validate(), Err(ProfileError::Width));
assert_eq!(RSParams::new(0, 4).validate(), Err(ProfileError::Recovery));
assert_eq!(RSParams::new(4, 0).validate(), Err(ProfileError::Recovery));
}
#[test]
fn replication_rules() {
assert_eq!(RepParams::new(1).validate(), Ok(()));
assert_eq!(RepParams::new(20).validate(), Ok(()));
assert_eq!(RepParams::new(0).validate(), Err(ProfileError::Width));
assert_eq!(RepParams::new(21).validate(), Err(ProfileError::Width));
}
#[test]
fn parse_validates() {
let wide = EncodingProfile::replication(RepParams::new(255));
let no_parity = EncodingProfile::reed_solomon(RSParams::new(4, 0));
assert_eq!(ErasureCode::try_from(wide), Err(ProfileError::Width));
assert_eq!(ErasureCode::try_from(no_parity), Err(ProfileError::Recovery));
}
#[test]
fn text_form() {
let codes = [
(TAPENET_PROFILE, "clay:20,7,16"),
(ErasureCode::ReedSolomon(RSParams::new(3, 1)), "rs:4,3"),
(ErasureCode::Replication(RepParams::new(2)), "copies:2"),
];
for (code, text) in codes {
assert_eq!(code.to_string(), text);
assert_eq!(text.parse(), Ok(code));
}
}
#[test]
fn bad_text() {
for text in ["", "clay", "clay:20,7", "rs:4,3,2", "copies:two", "raid:4,3"] {
assert_eq!(text.parse::<ErasureCode>(), Err(ProfileError::Syntax), "{text}");
}
assert_eq!("rs:4,4".parse::<ErasureCode>(), Err(ProfileError::Recovery));
assert_eq!("copies:21".parse::<ErasureCode>(), Err(ProfileError::Width));
}
#[test]
fn alpha_total() {
for packed in [0u64, u64::MAX, ClayParams::new(255, 255, 0).as_u64(), ClayParams::new(255, 0, 1).as_u64()] {
let params = ClayParams::from_u64(packed);
let _ = params.alpha();
let _ = params.stripe_alignment();
}
assert_eq!(ClayParams::new(20, 10, 12).alpha(), 2_187);
}
}