qualia_core_db/bundle/stream/protection/
ids.rs1use super::{publisher::PublisherError as E, PreparedSource};
3use crate::crypto::network::{digest::sha384, entropy::fill_os};
4use crate::net::qdnf::types::StrongDigest;
5#[derive(Clone, Copy)]
6pub struct Mapping {
7 pub(super) id: u32,
8 pub(super) source_slot: usize,
9 pub(super) digest: StrongDigest,
10}
11impl Mapping {
12 pub const EMPTY: Self = Self {
13 id: 0,
14 source_slot: 0,
15 digest: StrongDigest::ZERO,
16 };
17}
18pub(super) fn assign(source: &PreparedSource<'_, '_>, out: &mut [Mapping]) -> Result<(), E> {
19 assign_with(source, out, |b| fill_os(b).map_err(|_| E::Crypto))
20}
21fn assign_with(
22 source: &PreparedSource<'_, '_>,
23 out: &mut [Mapping],
24 mut random: impl FnMut(&mut [u8]) -> Result<(), E>,
25) -> Result<(), E> {
26 if out.len() != source.objects().len() {
27 return Err(E::Capacity);
28 }
29 for slot in 0..out.len() {
30 let mut chosen = None;
31 for _ in 0..16 {
32 let mut bytes = [0; 4];
33 random(&mut bytes)?;
34 let id = u32::from_be_bytes(bytes);
35 if id != 0 && !out[..slot].iter().any(|m| m.id == id) {
36 chosen = Some(id);
37 break;
38 }
39 }
40 out[slot] = Mapping {
41 id: chosen.ok_or(E::Entropy)?,
42 source_slot: slot,
43 digest: sha384(source.object_bytes(slot).map_err(|_| E::Source)?),
44 };
45 }
46 out.sort_unstable_by_key(|m| m.id);
47 Ok(())
48}
49#[cfg(test)]
50pub(super) fn assign_fixture(
51 source: &PreparedSource<'_, '_>,
52 out: &mut [Mapping],
53 random: impl FnMut(&mut [u8]) -> Result<(), E>,
54) -> Result<(), E> {
55 assign_with(source, out, random)
56}