bytepeel_core/lib.rs
1//! Zero-dependency recursive decoder for encoded and binary data.
2//!
3//! `bytepeel-core` takes opaque input (a hex dump, a base64 blob, a PEM block,
4//! raw bytes) and peels it layer by layer into a [`Node`] tree. Where the bytes
5//! are genuinely ambiguous (a protobuf length-delimited field could be a string,
6//! a submessage or packed varints) it keeps the top interpretations with scores
7//! instead of silently picking one.
8//!
9//! ```
10//! use bytepeel_core::{peel, Options, Detail};
11//!
12//! let node = peel(b"SGVsbG8gd29ybGQ=", &Options::default()).unwrap();
13//! assert_eq!(node.codec.name(), "base64");
14//! let Detail::Layer { child, .. } = &node.detail else { panic!() };
15//! assert!(matches!(&child.detail, Detail::Text { text, .. } if text == "Hello world"));
16//! ```
17#![forbid(unsafe_code)]
18
19/// The README's examples, run as doctests.
20#[doc = include_str!("../README.md")]
21#[cfg(doctest)]
22pub struct ReadmeDoctests;
23
24mod cbor;
25mod compress;
26mod der;
27mod detect;
28mod dump;
29mod edit;
30mod encode_value;
31mod error;
32mod get;
33mod json;
34mod jsonpath;
35mod jwt;
36mod limits;
37mod msgpack;
38mod node;
39mod path;
40mod protobuf;
41mod reencode;
42mod text;
43mod tree;
44mod value;
45pub mod varint;
46
47pub use edit::{NewValue, Op, edit, parse_value, set};
48pub use error::Diag;
49pub use get::{Pick, get};
50pub use node::{
51 Alphabet, Alt, AltKind, Asn1, Asn1Value, BYTES_HEAD, Codec, Detail, Field, FieldValue, Node,
52 TEXT_HEAD, TagClass,
53};
54pub use path::{JwtPick, is_der, is_jwt, is_values, select, select_der, select_jwt, select_value};
55pub use text::{B64, decode_b64, decode_hex};
56pub use value::{Value, ValueKind};
57
58/// How to read the top-level input.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum InputForm {
61 /// Detect hex / base64 / PEM text, otherwise treat as raw bytes.
62 Auto,
63 /// The input is hex text (whitespace, `:` and `0x` prefixes allowed).
64 Hex,
65 /// The input is base64 text (standard or URL-safe, padded or not).
66 Base64,
67 /// The input is raw bytes; no text encoding is detected at the top level.
68 Raw,
69}
70
71/// Force the interpretation of the first non-text-encoding layer.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Force {
74 Protobuf,
75 Der,
76 Cbor,
77 Msgpack,
78 Text,
79 Bytes,
80}
81
82/// Decoding options.
83#[derive(Debug, Clone)]
84pub struct Options {
85 /// Maximum nesting of layers and protobuf messages.
86 pub depth: usize,
87 /// Maximum interpretations kept per protobuf LEN field (at least 1).
88 pub alts: usize,
89 /// How to read the top-level input.
90 pub input: InputForm,
91 /// Force the interpretation of the first decoded byte layer.
92 pub force: Option<Force>,
93 /// Maximum protobuf fields, CBOR/MessagePack values and DER elements per
94 /// peel, in total (`TOO_MANY_ITEMS` beyond it). Each costs memory and
95 /// output far beyond the input bytes it can take up.
96 pub max_items: usize,
97}
98
99/// Default for [`Options::max_items`].
100pub const MAX_ITEMS: usize = 1_000_000;
101
102impl Default for Options {
103 fn default() -> Self {
104 Self {
105 depth: 16,
106 alts: 3,
107 input: InputForm::Auto,
108 force: None,
109 max_items: MAX_ITEMS,
110 }
111 }
112}
113
114/// Decode `input` into a tree of layers.
115///
116/// Auto-detection never fails: anything undecodable ends as a `bytes` leaf.
117/// Errors are only returned when the caller forced a form (`InputForm::Hex`,
118/// `InputForm::Base64`, or `Options::force`) and the data does not match it.
119pub fn peel(input: &[u8], opts: &Options) -> Result<Node, Diag> {
120 detect::peel(input, opts)
121}
122
123/// Serialize a node tree as compact JSON. See `docs/DESIGN.md` for the schema.
124pub fn to_json(node: &Node) -> String {
125 json::node_to_json(node)
126}
127
128/// Serialize a single protobuf field (e.g. the result of [`select`]) as JSON.
129pub fn field_to_json(field: &Field) -> String {
130 json::field_to_json(field)
131}
132
133/// Serialize a diagnostic as `{"error":{"code":..,"message":..,"offset":..}}`.
134pub fn diag_to_json(diag: &Diag) -> String {
135 json::diag_to_json(diag)
136}
137
138/// Render a node tree as an indented, human-readable outline.
139pub fn to_tree(node: &Node) -> String {
140 tree::node_to_tree(node)
141}
142
143/// Serialize a single CBOR value (e.g. the result of [`select_value`]) as JSON.
144pub fn value_to_json(v: &Value) -> String {
145 json::value_to_json(v)
146}
147
148/// Render a single CBOR value as an indented outline.
149pub fn value_to_tree(v: &Value) -> String {
150 tree::value_to_tree(v)
151}
152
153/// Serialize a single DER element (e.g. the result of [`select_der`]) as JSON.
154pub fn asn1_to_json(e: &Asn1) -> String {
155 json::asn1_to_json(e)
156}
157
158/// Render a single DER element as an indented outline.
159pub fn asn1_to_tree(e: &Asn1) -> String {
160 tree::asn1_to_tree(e)
161}
162
163/// Render a single protobuf field as an indented outline.
164pub fn field_to_tree(field: &Field) -> String {
165 tree::field_to_tree(field)
166}