Skip to main content

oa/crypto/
primitives.rs

1//! CPU cryptographic primitives and typed hash/Merkle values.
2//!
3//! This is a direct algorithmic port of OA's FIPS 202 Keccak/SHAKE and SP
4//! 800-185 KMAC implementation. Secret-key operations remain on the CPU; no
5//! secret material is placed in generic device storage.
6
7use crate::{Error, Result, core::memory::zero_secure};
8
9const SHAKE128_RATE: usize = 168;
10const SHAKE256_RATE: usize = 136;
11const SHAKE_DOMAIN: u8 = 0x1f;
12const CSHAKE_DOMAIN: u8 = 0x04;
13
14const ROUND_CONSTANTS: [u64; 24] = [
15	0x0000_0000_0000_0001,
16	0x0000_0000_0000_8082,
17	0x8000_0000_0000_808a,
18	0x8000_0000_8000_8000,
19	0x0000_0000_0000_808b,
20	0x0000_0000_8000_0001,
21	0x8000_0000_8000_8081,
22	0x8000_0000_0000_8009,
23	0x0000_0000_0000_008a,
24	0x0000_0000_0000_0088,
25	0x0000_0000_8000_8009,
26	0x0000_0000_8000_000a,
27	0x0000_0000_8000_808b,
28	0x8000_0000_0000_008b,
29	0x8000_0000_0000_8089,
30	0x8000_0000_0000_8003,
31	0x8000_0000_0000_8002,
32	0x8000_0000_0000_0080,
33	0x0000_0000_0000_800a,
34	0x8000_0000_8000_000a,
35	0x8000_0000_8000_8081,
36	0x8000_0000_0000_8080,
37	0x0000_0000_8000_0001,
38	0x8000_0000_8000_8008,
39];
40
41const ROTATION_OFFSETS: [u32; 25] = [
42	0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14,
43];
44
45/// A fixed 32-byte SHAKE-256 digest.
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
47pub struct Hash([u8; Self::SIZE]);
48
49impl Hash {
50	/// Hash storage size in bytes.
51	pub const SIZE: usize = 32;
52
53	/// Return the all-zero sentinel hash.
54	#[must_use]
55	pub const fn zero() -> Self {
56		Self([0; Self::SIZE])
57	}
58
59	/// Parse exactly 32 bytes.
60	///
61	/// # Errors
62	///
63	/// Returns an error when `bytes` is not exactly 32 bytes long.
64	pub fn new_from_bytes(bytes: &[u8]) -> Result<Self> {
65		let bytes = <[u8; Self::SIZE]>::try_from(bytes)
66			.map_err(|_| Error::invalid_argument("Hash requires exactly 32 bytes"))?;
67		Ok(Self(bytes))
68	}
69
70	/// Parse exactly 64 hexadecimal ASCII characters.
71	///
72	/// # Errors
73	///
74	/// Returns an error for the wrong length or a non-hexadecimal character.
75	pub fn new_from_hex(hex: &str) -> Result<Self> {
76		if hex.len() != Self::SIZE * 2 {
77			return Err(Error::invalid_argument(
78				"Hash hexadecimal text must contain exactly 64 characters",
79			));
80		}
81		let mut bytes = [0_u8; Self::SIZE];
82		let (pairs, remainder) = hex.as_bytes().as_chunks::<2>();
83		debug_assert!(remainder.is_empty());
84		for (index, pair) in pairs.iter().enumerate() {
85			let high = hex_nibble(pair[0]).ok_or_else(|| {
86				Error::invalid_argument("Hash hexadecimal text contains a non-hexadecimal character")
87			})?;
88			let low = hex_nibble(pair[1]).ok_or_else(|| {
89				Error::invalid_argument("Hash hexadecimal text contains a non-hexadecimal character")
90			})?;
91			bytes[index] = (high << 4) | low;
92		}
93		Ok(Self(bytes))
94	}
95
96	/// Return the digest bytes.
97	#[must_use]
98	pub const fn as_bytes(&self) -> &[u8; Self::SIZE] {
99		&self.0
100	}
101
102	/// Return whether this is the all-zero sentinel.
103	#[must_use]
104	pub fn is_zero(&self) -> bool {
105		self.0.iter().all(|byte| *byte == 0)
106	}
107
108	/// Format all 32 bytes as lowercase hexadecimal text.
109	#[must_use]
110	pub fn to_hex(self) -> String {
111		const HEX: &[u8; 16] = b"0123456789abcdef";
112		let mut output = String::with_capacity(Self::SIZE * 2);
113		for byte in self.0 {
114			output.push(char::from(HEX[usize::from(byte >> 4)]));
115			output.push(char::from(HEX[usize::from(byte & 0x0f)]));
116		}
117		output
118	}
119
120	/// Format the first eight bytes as lowercase hexadecimal text.
121	#[must_use]
122	pub fn to_short_hex(self) -> String {
123		self.to_hex()[..16].to_owned()
124	}
125}
126
127/// Apply the 24-round Keccak-f\[1600\] permutation in place.
128pub fn keccak_f1600(state: &mut [u64; 25]) {
129	for round_constant in ROUND_CONSTANTS {
130		let mut columns = [0_u64; 5];
131		for index in 0..5 {
132			columns[index] =
133				state[index] ^ state[5 + index] ^ state[10 + index] ^ state[15 + index] ^ state[20 + index];
134		}
135		let mut differences = [0_u64; 5];
136		for index in 0..5 {
137			differences[index] = columns[(index + 4) % 5] ^ columns[(index + 1) % 5].rotate_left(1);
138		}
139		for index in 0..25 {
140			state[index] ^= differences[index % 5];
141		}
142
143		let mut rotated = [0_u64; 25];
144		for index in 0..25 {
145			let x = index % 5;
146			let y = index / 5;
147			let next_x = y;
148			let next_y = (2 * x + 3 * y) % 5;
149			rotated[5 * next_y + next_x] = state[index].rotate_left(ROTATION_OFFSETS[index]);
150		}
151
152		for y in 0..5 {
153			let base = y * 5;
154			state[base] = rotated[base] ^ (!rotated[base + 1] & rotated[base + 2]);
155			state[base + 1] = rotated[base + 1] ^ (!rotated[base + 2] & rotated[base + 3]);
156			state[base + 2] = rotated[base + 2] ^ (!rotated[base + 3] & rotated[base + 4]);
157			state[base + 3] = rotated[base + 3] ^ (!rotated[base + 4] & rotated[base]);
158			state[base + 4] = rotated[base + 4] ^ (!rotated[base] & rotated[base + 1]);
159		}
160
161		state[0] ^= round_constant;
162	}
163}
164
165/// Produce SHAKE-128 output of exactly `output.len()` bytes.
166pub fn shake128(input: &[u8], output: &mut [u8]) {
167	let mut sponge = Sponge::new(SHAKE128_RATE, SHAKE_DOMAIN);
168	sponge.absorb(input);
169	sponge.squeeze(output);
170}
171
172/// Produce SHAKE-256 output of exactly `output.len()` bytes.
173pub fn shake256(input: &[u8], output: &mut [u8]) {
174	let mut sponge = Sponge::new(SHAKE256_RATE, SHAKE_DOMAIN);
175	sponge.absorb(input);
176	sponge.squeeze(output);
177}
178
179/// Compute the canonical 32-byte SHAKE-256 digest.
180#[must_use]
181pub fn hash(input: &[u8]) -> Hash {
182	let mut output = [0_u8; Hash::SIZE];
183	shake256(input, &mut output);
184	Hash(output)
185}
186
187/// Incremental SHAKE-128 context.
188pub struct Shake128(Sponge);
189
190impl Shake128 {
191	/// Create an empty SHAKE-128 context.
192	#[must_use]
193	pub fn new() -> Self {
194		Self(Sponge::new(SHAKE128_RATE, SHAKE_DOMAIN))
195	}
196
197	/// Absorb another input chunk.
198	///
199	/// # Errors
200	///
201	/// Returns an error after the first squeeze operation.
202	pub fn update(&mut self, input: &[u8]) -> Result<()> {
203		self.0.update(input)
204	}
205
206	/// Squeeze the next output bytes, finalizing on the first call.
207	pub fn squeeze(&mut self, output: &mut [u8]) {
208		self.0.squeeze(output);
209	}
210
211	/// Reset to a fresh empty context.
212	pub fn reset(&mut self) {
213		self.0.reset();
214	}
215}
216
217impl Default for Shake128 {
218	fn default() -> Self {
219		Self::new()
220	}
221}
222
223/// Incremental SHAKE-256 context.
224pub struct Shake256(Sponge);
225
226impl Shake256 {
227	/// Create an empty SHAKE-256 context.
228	#[must_use]
229	pub fn new() -> Self {
230		Self(Sponge::new(SHAKE256_RATE, SHAKE_DOMAIN))
231	}
232
233	/// Absorb another input chunk.
234	///
235	/// # Errors
236	///
237	/// Returns an error after the first squeeze operation.
238	pub fn update(&mut self, input: &[u8]) -> Result<()> {
239		self.0.update(input)
240	}
241
242	/// Squeeze the next output bytes, finalizing on the first call.
243	pub fn squeeze(&mut self, output: &mut [u8]) {
244		self.0.squeeze(output);
245	}
246
247	/// Reset to a fresh empty context.
248	pub fn reset(&mut self) {
249		self.0.reset();
250	}
251}
252
253impl Default for Shake256 {
254	fn default() -> Self {
255		Self::new()
256	}
257}
258
259/// Incremental canonical 32-byte SHAKE-256 hasher.
260#[derive(Default)]
261pub struct Hasher {
262	context: Shake256,
263	digest: Option<Hash>,
264}
265
266impl Hasher {
267	/// Create an empty hasher.
268	#[must_use]
269	pub fn new() -> Self {
270		Self::default()
271	}
272
273	/// Absorb another input chunk.
274	///
275	/// # Errors
276	///
277	/// Returns an error after [`Self::finalize`] until [`Self::reset`] is called.
278	pub fn update(&mut self, input: &[u8]) -> Result<()> {
279		if self.digest.is_some() {
280			return Err(Error::failed_precondition(
281				"Hasher cannot absorb after finalize; call reset first",
282			));
283		}
284		self.context.update(input)
285	}
286
287	/// Finalize and return the digest. Repeated calls return the same value.
288	pub fn finalize(&mut self) -> Hash {
289		if let Some(digest) = self.digest {
290			return digest;
291		}
292		let mut bytes = [0_u8; Hash::SIZE];
293		self.context.squeeze(&mut bytes);
294		let digest = Hash(bytes);
295		self.digest = Some(digest);
296		digest
297	}
298
299	/// Reset to the empty-message state.
300	pub fn reset(&mut self) {
301		self.context.reset();
302		self.digest = None;
303	}
304}
305
306/// Compute KMAC-256 according to NIST SP 800-185.
307///
308/// # Errors
309///
310/// Returns an error when a bit length, encoded length, or allocation size
311/// overflows the platform or SP 800-185 `u64` encoding.
312pub fn kmac256(
313	key: &[u8],
314	data: &[u8],
315	customization: &[u8],
316	output_len: usize,
317) -> Result<Vec<u8>> {
318	let key_bits = bit_length(key.len(), "KMAC key")?;
319	let custom_bits = bit_length(customization.len(), "KMAC customization")?;
320	let output_bits = bit_length(output_len, "KMAC output")?;
321
322	let mut prefix = SecureBytes::new(bytepad_len(
323		left_encode_len(SHAKE256_RATE as u64)
324			.checked_add(encoded_string_len(4)?)
325			.and_then(|length| length.checked_add(encoded_string_len(customization.len()).ok()?))
326			.ok_or_else(|| Error::out_of_range("KMAC customization encoding is too large"))?,
327		SHAKE256_RATE,
328	)?)?;
329	append_left_encode(&mut prefix.bytes, SHAKE256_RATE as u64);
330	append_encode_string(&mut prefix.bytes, b"KMAC", 32);
331	append_encode_string(&mut prefix.bytes, customization, custom_bits);
332	prefix.pad_to_capacity();
333
334	let mut key_block = SecureBytes::new(bytepad_len(
335		left_encode_len(SHAKE256_RATE as u64)
336			.checked_add(left_encode_len(key_bits))
337			.and_then(|length| length.checked_add(key.len()))
338			.ok_or_else(|| Error::out_of_range("KMAC key encoding is too large"))?,
339		SHAKE256_RATE,
340	)?)?;
341	append_left_encode(&mut key_block.bytes, SHAKE256_RATE as u64);
342	append_encode_string(&mut key_block.bytes, key, key_bits);
343	key_block.pad_to_capacity();
344
345	let mut right_encoded = [0_u8; 9];
346	let right_len = write_right_encode(output_bits, &mut right_encoded);
347	let mut sponge = Sponge::new(SHAKE256_RATE, CSHAKE_DOMAIN);
348	sponge.absorb(&prefix.bytes);
349	sponge.absorb(&key_block.bytes);
350	sponge.absorb(data);
351	sponge.absorb(&right_encoded[..right_len]);
352
353	let mut output = Vec::new();
354	output
355		.try_reserve_exact(output_len)
356		.map_err(|_| Error::resource_exhausted("KMAC output allocation failed"))?;
357	output.resize(output_len, 0);
358	sponge.squeeze(&mut output);
359	zero_secure(&mut right_encoded);
360	Ok(output)
361}
362
363/// Combine two Merkle nodes as SHAKE-256(`left || right`).
364#[must_use]
365pub fn hash_combine(left: &Hash, right: &Hash) -> Hash {
366	let mut pair = [0_u8; Hash::SIZE * 2];
367	pair[..Hash::SIZE].copy_from_slice(left.as_bytes());
368	pair[Hash::SIZE..].copy_from_slice(right.as_bytes());
369	hash(&pair)
370}
371
372/// Compute the Merkle root, duplicating the final node of each odd level.
373#[must_use]
374pub fn merkle_root(leaves: &[Hash]) -> Hash {
375	if leaves.is_empty() {
376		return Hash::zero();
377	}
378	let mut level = leaves.to_vec();
379	while level.len() > 1 {
380		let mut next = Vec::with_capacity(level.len().div_ceil(2));
381		for pair in level.chunks(2) {
382			let right = pair.get(1).unwrap_or(&pair[0]);
383			next.push(hash_combine(&pair[0], right));
384		}
385		level = next;
386	}
387	level[0]
388}
389
390/// Fully materialized CPU Merkle tree, with leaves at level zero.
391pub struct MerkleTree {
392	levels: Vec<Vec<Hash>>,
393	root: Hash,
394}
395
396impl MerkleTree {
397	/// Return all levels from leaves through the root.
398	#[must_use]
399	pub fn levels(&self) -> &[Vec<Hash>] {
400		&self.levels
401	}
402
403	/// Return the tree root.
404	#[must_use]
405	pub const fn root(&self) -> Hash {
406		self.root
407	}
408}
409
410/// Build a materialized Merkle tree.
411#[must_use]
412pub fn build_merkle_tree(leaves: &[Hash]) -> MerkleTree {
413	if leaves.is_empty() {
414		return MerkleTree {
415			levels: Vec::new(),
416			root: Hash::zero(),
417		};
418	}
419	let mut levels = vec![leaves.to_vec()];
420	while levels.last().is_some_and(|level| level.len() > 1) {
421		let previous = &levels[levels.len() - 1];
422		let mut next = Vec::with_capacity(previous.len().div_ceil(2));
423		for pair in previous.chunks(2) {
424			let right = pair.get(1).unwrap_or(&pair[0]);
425			next.push(hash_combine(&pair[0], right));
426		}
427		levels.push(next);
428	}
429	let root = levels[levels.len() - 1][0];
430	MerkleTree { levels, root }
431}
432
433/// Sibling nodes and directions for one Merkle inclusion proof.
434pub struct MerkleProof {
435	siblings: Vec<Hash>,
436	is_left: Vec<bool>,
437}
438
439impl MerkleProof {
440	/// Construct a checked proof representation.
441	///
442	/// # Errors
443	///
444	/// Returns an error unless each sibling has one matching direction flag.
445	pub fn new_from_parts(siblings: Vec<Hash>, is_left: Vec<bool>) -> Result<Self> {
446		if siblings.len() != is_left.len() {
447			return Err(Error::invalid_argument(
448				"Merkle proof sibling and direction counts differ",
449			));
450		}
451		Ok(Self { siblings, is_left })
452	}
453
454	/// Return sibling nodes from leaf level upward.
455	#[must_use]
456	pub fn siblings(&self) -> &[Hash] {
457		&self.siblings
458	}
459
460	/// Return whether each sibling appears to the left of the running hash.
461	#[must_use]
462	pub fn sibling_is_left(&self) -> &[bool] {
463		&self.is_left
464	}
465}
466
467/// Construct the inclusion proof for one leaf.
468///
469/// # Errors
470///
471/// Returns an error for an empty tree or an out-of-range leaf index.
472pub fn merkle_proof(tree: &MerkleTree, leaf_index: usize) -> Result<MerkleProof> {
473	let leaves = tree
474		.levels
475		.first()
476		.ok_or_else(|| Error::invalid_argument("cannot prove membership in an empty Merkle tree"))?;
477	if leaf_index >= leaves.len() {
478		return Err(Error::out_of_range("Merkle leaf index is out of range"));
479	}
480	let mut index = leaf_index;
481	let mut siblings = Vec::with_capacity(tree.levels.len().saturating_sub(1));
482	let mut is_left = Vec::with_capacity(tree.levels.len().saturating_sub(1));
483	for nodes in tree.levels.iter().take(tree.levels.len() - 1) {
484		let sibling_index = if index.is_multiple_of(2) {
485			index + 1
486		} else {
487			index - 1
488		};
489		siblings.push(*nodes.get(sibling_index).unwrap_or(&nodes[index]));
490		is_left.push(!index.is_multiple_of(2));
491		index /= 2;
492	}
493	MerkleProof::new_from_parts(siblings, is_left)
494}
495
496/// Verify one Merkle inclusion proof against `root`.
497#[must_use]
498pub fn verify_merkle_proof(leaf: &Hash, proof: &MerkleProof, root: &Hash) -> bool {
499	if proof.siblings.len() != proof.is_left.len() {
500		return false;
501	}
502	let mut current = *leaf;
503	for (sibling, is_left) in proof.siblings.iter().zip(&proof.is_left) {
504		current = if *is_left {
505			hash_combine(sibling, &current)
506		} else {
507			hash_combine(&current, sibling)
508		};
509	}
510	current == *root
511}
512
513struct Sponge {
514	state: [u64; 25],
515	buffer: [u8; SHAKE128_RATE],
516	buffer_len: usize,
517	rate: usize,
518	domain: u8,
519	squeezing: bool,
520	squeeze_offset: usize,
521}
522
523impl Sponge {
524	const fn new(rate: usize, domain: u8) -> Self {
525		Self {
526			state: [0; 25],
527			buffer: [0; SHAKE128_RATE],
528			buffer_len: 0,
529			rate,
530			domain,
531			squeezing: false,
532			squeeze_offset: 0,
533		}
534	}
535
536	fn update(&mut self, input: &[u8]) -> Result<()> {
537		if self.squeezing {
538			return Err(Error::failed_precondition(
539				"SHAKE cannot absorb after squeezing; reset the context first",
540			));
541		}
542		self.absorb(input);
543		Ok(())
544	}
545
546	fn absorb(&mut self, mut input: &[u8]) {
547		debug_assert!(!self.squeezing);
548		while !input.is_empty() {
549			let chunk = input.len().min(self.rate - self.buffer_len);
550			self.buffer[self.buffer_len..self.buffer_len + chunk].copy_from_slice(&input[..chunk]);
551			self.buffer_len += chunk;
552			input = &input[chunk..];
553			if self.buffer_len == self.rate {
554				xor_bytes_into_state(&mut self.state, &self.buffer[..self.rate]);
555				keccak_f1600(&mut self.state);
556				self.buffer[..self.rate].fill(0);
557				self.buffer_len = 0;
558			}
559		}
560	}
561
562	fn squeeze(&mut self, mut output: &mut [u8]) {
563		if !self.squeezing {
564			self.buffer[self.buffer_len] = self.domain;
565			self.buffer[self.buffer_len + 1..self.rate].fill(0);
566			self.buffer[self.rate - 1] |= 0x80;
567			xor_bytes_into_state(&mut self.state, &self.buffer[..self.rate]);
568			keccak_f1600(&mut self.state);
569			self.buffer[..self.rate].fill(0);
570			self.buffer_len = 0;
571			self.squeezing = true;
572			self.squeeze_offset = 0;
573		}
574
575		while !output.is_empty() {
576			if self.squeeze_offset == self.rate {
577				keccak_f1600(&mut self.state);
578				self.squeeze_offset = 0;
579			}
580			let chunk = output.len().min(self.rate - self.squeeze_offset);
581			extract_bytes(&self.state, self.squeeze_offset, &mut output[..chunk]);
582			self.squeeze_offset += chunk;
583			output = &mut output[chunk..];
584		}
585	}
586
587	fn reset(&mut self) {
588		zeroize_lanes(&mut self.state);
589		zero_secure(&mut self.buffer);
590		self.buffer_len = 0;
591		self.squeezing = false;
592		self.squeeze_offset = 0;
593	}
594}
595
596impl Drop for Sponge {
597	fn drop(&mut self) {
598		zeroize_lanes(&mut self.state);
599		zero_secure(&mut self.buffer);
600	}
601}
602
603struct SecureBytes {
604	bytes: Vec<u8>,
605	capacity: usize,
606}
607
608impl SecureBytes {
609	fn new(capacity: usize) -> Result<Self> {
610		let mut bytes = Vec::new();
611		bytes
612			.try_reserve_exact(capacity)
613			.map_err(|_| Error::resource_exhausted("KMAC temporary allocation failed"))?;
614		Ok(Self { bytes, capacity })
615	}
616
617	fn pad_to_capacity(&mut self) {
618		self.bytes.resize(self.capacity, 0);
619	}
620}
621
622impl Drop for SecureBytes {
623	fn drop(&mut self) {
624		zero_secure(&mut self.bytes);
625	}
626}
627
628fn xor_bytes_into_state(state: &mut [u64; 25], bytes: &[u8]) {
629	for (index, byte) in bytes.iter().copied().enumerate() {
630		state[index / 8] ^= u64::from(byte) << ((index % 8) * 8);
631	}
632}
633
634fn extract_bytes(state: &[u64; 25], offset: usize, output: &mut [u8]) {
635	for (output_index, byte) in output.iter_mut().enumerate() {
636		let state_index = offset + output_index;
637		*byte = (state[state_index / 8] >> ((state_index % 8) * 8)) as u8;
638	}
639}
640
641fn zeroize_lanes(state: &mut [u64; 25]) {
642	let byte_len = size_of_val(state);
643	// SAFETY: `state` is a live, exclusively borrowed contiguous array. A byte
644	// slice may view every initialized byte of any value, and its exact extent is
645	// `size_of_val(state)`. The slice does not outlive the borrow.
646	let bytes = unsafe { std::slice::from_raw_parts_mut(state.as_mut_ptr().cast(), byte_len) };
647	zero_secure(bytes);
648}
649
650fn bit_length(byte_length: usize, name: &'static str) -> Result<u64> {
651	let bytes = u64::try_from(byte_length)
652		.map_err(|_| Error::out_of_range(format!("{name} length exceeds u64")))?;
653	bytes
654		.checked_mul(8)
655		.ok_or_else(|| Error::out_of_range(format!("{name} bit length exceeds u64")))
656}
657
658fn left_encode_len(value: u64) -> usize {
659	if value == 0 {
660		2
661	} else {
662		1 + ((u64::BITS - value.leading_zeros()) as usize).div_ceil(8)
663	}
664}
665
666fn encoded_string_len(byte_length: usize) -> Result<usize> {
667	let bits = bit_length(byte_length, "encoded string")?;
668	left_encode_len(bits)
669		.checked_add(byte_length)
670		.ok_or_else(|| Error::out_of_range("encoded string length overflows usize"))
671}
672
673fn bytepad_len(raw_length: usize, rate: usize) -> Result<usize> {
674	raw_length
675		.checked_add(rate - 1)
676		.map(|length| length / rate * rate)
677		.ok_or_else(|| Error::out_of_range("KMAC bytepad length overflows usize"))
678}
679
680fn append_left_encode(output: &mut Vec<u8>, value: u64) {
681	let mut encoded = [0_u8; 9];
682	let length = write_left_encode(value, &mut encoded);
683	output.extend_from_slice(&encoded[..length]);
684}
685
686fn append_encode_string(output: &mut Vec<u8>, input: &[u8], bit_length: u64) {
687	append_left_encode(output, bit_length);
688	output.extend_from_slice(input);
689}
690
691fn write_left_encode(value: u64, output: &mut [u8; 9]) -> usize {
692	let bytes = if value == 0 {
693		1
694	} else {
695		((u64::BITS - value.leading_zeros()) as usize).div_ceil(8)
696	};
697	output[0] = bytes as u8;
698	for (index, byte) in output[1..=bytes].iter_mut().enumerate() {
699		*byte = (value >> (8 * (bytes - 1 - index))) as u8;
700	}
701	bytes + 1
702}
703
704fn write_right_encode(value: u64, output: &mut [u8; 9]) -> usize {
705	let bytes = if value == 0 {
706		1
707	} else {
708		((u64::BITS - value.leading_zeros()) as usize).div_ceil(8)
709	};
710	for (index, byte) in output[..bytes].iter_mut().enumerate() {
711		*byte = (value >> (8 * (bytes - 1 - index))) as u8;
712	}
713	output[bytes] = bytes as u8;
714	bytes + 1
715}
716
717const fn hex_nibble(byte: u8) -> Option<u8> {
718	match byte {
719		b'0'..=b'9' => Some(byte - b'0'),
720		b'a'..=b'f' => Some(byte - b'a' + 10),
721		b'A'..=b'F' => Some(byte - b'A' + 10),
722		_ => None,
723	}
724}