fidius_core/wire.rs
1// Copyright 2026 Colliery, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Wire format serialization for Fidius plugin FFI boundary.
16//!
17//! In debug builds (`cfg(debug_assertions)`), data is serialized as JSON for
18//! human readability. In release builds, bincode is used for compact, fast
19//! serialization. The `WIRE_FORMAT` constant encodes which format is active
20//! so the host can reject mismatched plugins at load time.
21
22use serde::de::DeserializeOwned;
23use serde::Serialize;
24
25use crate::descriptor::WireFormat;
26
27/// The wire format active in this build.
28#[cfg(debug_assertions)]
29pub const WIRE_FORMAT: WireFormat = WireFormat::Json;
30
31/// The wire format active in this build.
32#[cfg(not(debug_assertions))]
33pub const WIRE_FORMAT: WireFormat = WireFormat::Bincode;
34
35/// Errors that can occur during wire serialization or deserialization.
36#[derive(Debug, thiserror::Error)]
37pub enum WireError {
38 /// JSON serialization/deserialization error.
39 #[error("json wire error: {0}")]
40 Json(#[from] serde_json::Error),
41
42 /// Bincode serialization/deserialization error.
43 #[error("bincode wire error: {0}")]
44 Bincode(#[from] bincode::Error),
45}
46
47/// Serialize a value using the active wire format.
48///
49/// Returns JSON bytes in debug builds, bincode bytes in release builds.
50#[cfg(debug_assertions)]
51pub fn serialize<T: Serialize>(val: &T) -> Result<Vec<u8>, WireError> {
52 serde_json::to_vec(val).map_err(WireError::Json)
53}
54
55/// Deserialize a value from the active wire format.
56///
57/// Expects JSON bytes in debug builds, bincode bytes in release builds.
58#[cfg(debug_assertions)]
59pub fn deserialize<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, WireError> {
60 serde_json::from_slice(bytes).map_err(WireError::Json)
61}
62
63/// Serialize a value using the active wire format.
64///
65/// Returns JSON bytes in debug builds, bincode bytes in release builds.
66#[cfg(not(debug_assertions))]
67pub fn serialize<T: Serialize>(val: &T) -> Result<Vec<u8>, WireError> {
68 bincode::serialize(val).map_err(WireError::Bincode)
69}
70
71/// Deserialize a value from the active wire format.
72///
73/// Expects JSON bytes in debug builds, bincode bytes in release builds.
74#[cfg(not(debug_assertions))]
75pub fn deserialize<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, WireError> {
76 bincode::deserialize(bytes).map_err(WireError::Bincode)
77}