Skip to main content

codec_multicodec/
lookup.rs

1// SPDX-FileCopyrightText: Copyright © 2026 ReallyMe LLC. All rights reserved
2//
3// SPDX-License-Identifier: Apache-2.0
4
5use crate::table::{CodecTag, KeyMaterialKind, MULTICODEC_TABLE};
6
7/// Codec metadata resolved from a multicodec prefix.
8#[derive(Debug, Clone)]
9pub struct CodecLookupResult {
10    /// Canonical multicodec name (e.g. `ed25519-pub`).
11    pub name: &'static str,
12    /// Multicodec table tag.
13    pub tag: CodecTag,
14    /// Key-material class for `key` codecs.
15    pub key_material: KeyMaterialKind,
16    /// Human-readable algorithm name (e.g. `Ed25519`).
17    pub alg: &'static str,
18    /// The multicodec varint prefix bytes.
19    pub codec: &'static [u8],
20    /// Expected raw public key length after the prefix.
21    pub key_length: usize,
22}
23
24/// Lookup multicodec prefix → codec metadata
25pub fn lookup_codec_prefix(bytes: &[u8]) -> Option<CodecLookupResult> {
26    for (name, spec) in MULTICODEC_TABLE {
27        let prefix = spec.codec;
28        if bytes.len() >= prefix.len() && bytes.starts_with(prefix) {
29            return Some(CodecLookupResult {
30                name,
31                tag: spec.tag,
32                key_material: spec.key_material,
33                alg: spec.alg,
34                codec: spec.codec,
35                key_length: spec.key_length,
36            });
37        }
38    }
39    None
40}
41
42/// Strip multicodec prefix → raw key bytes
43///
44/// If no known prefix is found, returns the input unchanged.
45pub fn strip_codec_prefix(bytes: &[u8]) -> &[u8] {
46    if let Some(found) = lookup_codec_prefix(bytes) {
47        &bytes[found.codec.len()..]
48    } else {
49        bytes
50    }
51}