Files
leleka/control-plane/src/kar_stream_encode/layout.rs
T

77 lines
2.4 KiB
Rust

//! Calibration checks and byte layout of one streamed KAR-2 section.
use super::{kar_codec, round_up};
/// Offsets and sizes of the scale, codebook and plane regions of a section.
pub(super) struct Layout {
pub(super) words: u64,
pub(super) books_start: u64,
pub(super) planes_start: u64,
pub(super) plane_stride: u64,
pub(super) section_bytes: u64,
}
fn valid_book(index: usize, book: &[u16]) -> bool {
book.len() == 1usize << (index + 1) && book.iter().all(|bits| bits & 0x7c00 != 0x7c00)
}
fn valid_calibration(calibration: &kar_codec::Calibration) -> bool {
let levels = calibration.books.len();
(1..=8).contains(&levels)
&& calibration.boundaries.len() == (1usize << levels) - 1
&& calibration
.boundaries
.iter()
.all(|boundary| boundary.is_finite())
&& calibration
.boundaries
.windows(2)
.all(|pair| pair[0] < pair[1])
&& calibration
.books
.iter()
.enumerate()
.all(|(index, book)| valid_book(index, book))
}
pub(super) fn check_calibration(
calibration: &kar_codec::Calibration,
elements: u64,
) -> Result<(), String> {
if elements == 0 || !valid_calibration(calibration) {
return Err("invalid streamed KAR calibration".into());
}
Ok(())
}
fn aligned_end(
start: u64,
len: u64,
alignment: u64,
overflow: &'static str,
) -> Result<u64, String> {
round_up(start.checked_add(len).ok_or(overflow)?, alignment)
}
pub(super) fn section_layout(elements: u64, levels: usize) -> Result<Layout, String> {
let words = elements.div_ceil(32);
let books_start = round_up(words.checked_mul(2).ok_or("KAR scales overflow")?, 16)?;
let books_bytes = (1u64 << (levels + 2)) - 4;
let planes_start = aligned_end(books_start, books_bytes, 16, "KAR books overflow")?;
let plane_stride = round_up(words.checked_mul(4).ok_or("KAR planes overflow")?, 16)?;
if plane_stride > u32::MAX as u64 {
return Err("KAR plane stride exceeds format limit".into());
}
let planes_bytes = plane_stride
.checked_mul(levels as u64)
.ok_or("KAR planes overflow")?;
let section_bytes = aligned_end(planes_start, planes_bytes, 256, "KAR section overflow")?;
Ok(Layout {
words,
books_start,
planes_start,
plane_stride,
section_bytes,
})
}