1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
//! Traits for encoding and decoding data types.
//!
//! This module provides the core trait abstractions for serializing Rust types
//! into a byte representation and deserializing byte data back into Rust types.
//!
//! # Traits
//!
//! - [`Encoder`]: Encodes items into byte sequences using serde serialization.
//! - [`Decoder`]: Decodes byte sequences back into items using serde deserialization.
//!
//! Both traits are object-safe, allowing for dynamic dispatch through trait objects.
//! They require associated types to implement `Send + Sync` for thread-safe usage.
use Bytes;
use ;
use automock;
use crate;
/// A trait for encoding items into byte sequences.
///
/// `Encoder` defines the interface for serializing Rust types into their byte representation.
/// The trait is object-safe, supporting dynamic dispatch through trait objects, which enables
/// runtime format selection—the core of the library's "any-format" design.
///
/// # Associated Types
///
/// * `Item` - The type being encoded. Must implement [`Serialize`] and be
/// `Send + Sync` for thread-safe usage.
/// * `Error` - The error type returned when encoding fails. Must implement
/// [`Error`](std::error::Error) and be `Send + Sync`. Each format can define its own error type
/// (e.g., `serde_json::Error`, `rmp_serde::Error`).
///
/// # Methods
///
/// * [`encode`](Self::encode) - Serializes an item into a byte sequence.
///
/// # Design Philosophy
///
/// Rather than restricting you to a fixed set of formats, this library lets you implement
/// `Encoder` for any serialization format. Built-in implementations (JSON, MessagePack) are
/// provided as examples, but you can add CBOR, Protocol Buffers, custom binary formats, or anything else.
///
/// # Examples
///
/// Implementing a custom plain-text encoder:
///
/// ```rust
/// use bytes::Bytes;
/// use serde::Serialize;
/// use object_transfer::encoders::Encoder;
///
/// #[derive(Serialize)]
/// struct MyType {
/// id: u32,
/// name: String,
/// }
///
/// struct PlainTextEncoder;
///
/// impl Encoder for PlainTextEncoder {
/// type Item = MyType;
/// type Error = std::fmt::Error;
///
/// fn encode(&self, item: &Self::Item) -> Result<Bytes, Self::Error> {
/// let text = format!("id={},name={}", item.id, item.name);
/// Ok(Bytes::from(text))
/// }
/// }
/// ```
///
/// Using your custom encoder with [`Pub`](crate::Pub):
///
/// ```rust,no_run
/// # use bytes::Bytes;
/// # use serde::Serialize;
/// # use object_transfer::encoders::Encoder;
/// # #[derive(Serialize)]
/// # struct MyType { id: u32, name: String }
/// # struct PlainTextEncoder;
/// # impl Encoder for PlainTextEncoder {
/// # type Item = MyType;
/// # type Error = serde_json::Error;
/// # fn encode(&self, item: &Self::Item) -> Result<Bytes, Self::Error> {
/// # serde_json::to_vec(item).map(|v| Bytes::from(v))
/// # }
/// # }
/// use std::sync::Arc;
/// use object_transfer::{Pub, traits::PubTrait};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = async_nats::connect("demo.nats.io").await?;
/// let js = Arc::new(async_nats::jetstream::new(client));
///
/// let publisher: Pub<MyType, _> = Pub::new(
/// js,
/// "events",
/// Arc::new(PlainTextEncoder),
/// );
///
/// publisher.publish(&MyType { id: 1, name: "test".to_string() }).await?;
/// Ok(())
/// }
/// ```
/// A trait for decoding byte sequences back into items.
///
/// `Decoder` defines the interface for deserializing byte data back into Rust types.
/// The trait is object-safe, supporting dynamic dispatch through trait objects, enabling
/// runtime format selection paired with [`Encoder`].
///
/// # Associated Types
///
/// * `Item` - The type being decoded. Must implement [`DeserializeOwned`] and be
/// `Send + Sync` for thread-safe usage.
/// * `Error` - The error type returned when decoding fails. Must implement
/// [`Error`](std::error::Error) and be `Send + Sync`. Each format can define its own error type
/// (e.g., `serde_json::Error`, custom parse errors).
///
/// # Methods
///
/// * [`decode`](Self::decode) - Deserializes a byte sequence into an item.
///
/// # Design Philosophy
///
/// Like [`Encoder`], this trait supports any deserialization format. Implement it alongside
/// [`Encoder`] to create custom serialization formats.
///
/// # Examples
///
/// Implementing a custom plain-text decoder:
///
/// ```rust
/// use bytes::Bytes;
/// use serde::Deserialize;
/// use object_transfer::encoders::Decoder;
/// use std::num::ParseIntError;
///
/// #[derive(Deserialize)]
/// struct MyType {
/// id: u32,
/// name: String,
/// }
///
/// #[derive(Debug)]
/// enum ParseError {
/// InvalidFormat,
/// ParseInt(ParseIntError),
/// }
///
/// impl std::fmt::Display for ParseError {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// match self {
/// ParseError::InvalidFormat => write!(f, "Invalid format"),
/// ParseError::ParseInt(e) => write!(f, "Parse error: {}", e),
/// }
/// }
/// }
///
/// impl std::error::Error for ParseError {}
///
/// impl serde::de::Error for ParseError {
/// fn custom<T: std::fmt::Display>(_msg: T) -> Self {
/// ParseError::InvalidFormat
/// }
/// }
///
/// struct PlainTextDecoder;
///
/// impl Decoder for PlainTextDecoder {
/// type Item = MyType;
/// type Error = ParseError;
///
/// fn decode(&self, data: Bytes) -> Result<Self::Item, Self::Error> {
/// let text = String::from_utf8(data.to_vec())
/// .map_err(|_| ParseError::InvalidFormat)?;
/// let parts: Vec<&str> = text.split(',').collect();
/// if parts.len() != 2 {
/// return Err(ParseError::InvalidFormat);
/// }
/// let id = parts[0]
/// .strip_prefix("id=")
/// .ok_or(ParseError::InvalidFormat)?
/// .parse::<u32>()
/// .map_err(ParseError::ParseInt)?;
/// let name = parts[1]
/// .strip_prefix("name=")
/// .ok_or(ParseError::InvalidFormat)?
/// .to_string();
/// Ok(MyType { id, name })
/// }
/// }
/// ```
///
/// Using your custom decoder with [`Sub`](crate::Sub):
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use futures::StreamExt;
/// use object_transfer::{Sub, SubOpt, traits::SubTrait};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = async_nats::connect("demo.nats.io").await?;
/// let js = Arc::new(async_nats::jetstream::new(client));
///
/// // Note: This example skips fetcher setup for brevity
/// // See the Sub documentation for a complete example
/// Ok(())
/// }
/// ```