libdd_trace_utils/msgpack_encoder/mod.rs
1// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4//! # Encoder layout & naming convention
5//!
6//! ```text
7//! msgpack_encoder/
8//! ├── v04/
9//! │ ├── mod.rs // public API + payload-level helpers
10//! │ ├── span_v04.rs // v0.4 in-memory Span → v0.4 wire (native)
11//! │ └── span_v1.rs // v1 in-memory Span → v0.4 wire (downgrade)
12//! └── v1/
13//! ├── mod.rs
14//! ├── span_v04.rs // v0.4 in-memory Span → V1 wire (upgrade)
15//! └── span_v1.rs // v1 in-memory Span → V1 wire (native)
16//! ```
17//!
18//! - **Module (`v04`/`v1`) = output wire format.**
19//! - **File suffix (`_v04`/`_v1`) = input span type.**
20//! - **Public functions carry a `_from_<input>` suffix**, so a caller reads the *output* from the
21//! module path and the *input* from the function name:
22//!
23//! | Module | Function | Input → Output |
24//! |--------|----------|----------------|
25//! | `v04::` | `to_vec_from_v04`, `write_to_slice_from_v04`, `to_encoded_byte_len_from_v04` | v04 → v0.4 (native) |
26//! | `v04::` | `to_vec_from_v1`, `write_to_slice_from_v1`, `to_encoded_byte_len_from_v1` | v1 → v0.4 (downgrade) |
27//! | `v1::` | `to_vec_from_v04`, `write_to_slice_from_v04`, `to_encoded_byte_len_from_v04` | v04 → V1 (upgrade) |
28//! | `v1::` | `to_vec_from_v1`, `write_to_slice_from_v1`, `to_encoded_byte_len_from_v1` | v1 → V1 (native) |
29
30pub mod v04;
31pub mod v1;
32
33use rmp::encode::ValueWriteError;
34use std::convert::Infallible;
35
36/// Flatten `ValueWriteError<Infallible>` (uninhabited because both variants wrap
37/// `Infallible`) into the bare `Infallible` so callers can use
38/// [`libdd_common::ResultInfallibleExt`].
39#[inline(always)]
40pub(crate) fn flatten_value_write_infallible(err: ValueWriteError<Infallible>) -> Infallible {
41 match err {
42 ValueWriteError::InvalidMarkerWrite(never) | ValueWriteError::InvalidDataWrite(never) => {
43 never
44 }
45 }
46}
47
48/// A writer that counts bytes without storing them, used to compute encoded payload size.
49pub(crate) struct CountLength(u32);
50
51impl std::io::Write for CountLength {
52 #[inline]
53 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
54 self.write_all(buf)?;
55 Ok(buf.len())
56 }
57
58 #[inline]
59 fn flush(&mut self) -> std::io::Result<()> {
60 Ok(())
61 }
62
63 #[inline]
64 fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
65 self.0 += buf.len() as u32;
66 Ok(())
67 }
68}