rocketmq-model 1.0.0

Runtime-neutral RocketMQ domain models
Documentation
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// Copyright 2023 The RocketMQ Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// SIMD-accelerated JSON utility for high-performance serialization and deserialization.
///
/// This utility leverages SIMD instructions for faster JSON processing compared to standard
/// serde_json. It's particularly beneficial for:
/// - High-throughput message processing
/// - Large JSON payloads
/// - Performance-critical paths
///
/// # Performance Characteristics
///
/// Based on benchmarks:
/// - Encoding: ~5% faster than serde_json
/// - Decoding: ~10% faster than serde_json
/// - Roundtrip: ~23% faster than serde_json
/// - Throughput: ~30% higher than serde_json
///
/// # Feature Flag
///
/// This module requires the `simd` feature flag to be enabled.
///
/// # Example
///
/// ```ignore
/// use rocketmq_model::utils::simd_json_utils::SimdJsonUtils;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize)]
/// struct Message {
///     topic: String,
///     body: Vec<u8>,
/// }
///
/// let msg = Message {
///     topic: "test".to_string(),
///     body: vec![1, 2, 3],
/// };
///
/// // Serialize
/// let json_string = SimdJsonUtils::serialize_json(&msg)?;
/// let json_bytes = SimdJsonUtils::serialize_json_vec(&msg)?;
///
/// // Deserialize
/// let msg_from_str: Message = SimdJsonUtils::from_json_str(&json_string)?;
/// let msg_from_bytes: Message = SimdJsonUtils::from_json_slice(&json_bytes)?;
/// ```
#[cfg(feature = "simd")]
pub struct SimdJsonUtils;

#[cfg(feature = "simd")]
impl SimdJsonUtils {
    /// Deserialize JSON from bytes into a Rust type using SIMD acceleration.
    ///
    /// This method requires a mutable byte slice as simd-json modifies the input
    /// buffer in-place for performance. If you need to preserve the original data,
    /// clone it first.
    ///
    /// # Arguments
    ///
    /// * `bytes` - A mutable byte slice containing JSON data
    ///
    /// # Returns
    ///
    /// Returns the deserialized value or an error if parsing fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let mut json_data = br#"{"key":"value"}"#.to_vec();
    /// let result: HashMap<String, String> = SimdJsonUtils::from_json_bytes(&mut json_data)?;
    /// ```
    #[inline]
    pub fn from_json_bytes<T>(bytes: &mut [u8]) -> rocketmq_error::Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        simd_json::from_slice(bytes).map_err(|source| crate::error::serialization_source("decode", "SIMD-JSON", source))
    }

    /// Deserialize JSON from a mutable byte slice into a Rust type.
    ///
    /// This is an alias for `from_json_bytes` for consistency with the SerdeJsonUtils API.
    #[inline]
    pub fn from_json_slice<T>(bytes: &mut [u8]) -> rocketmq_error::Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        Self::from_json_bytes(bytes)
    }

    /// Deserialize JSON from a string into a Rust type using SIMD acceleration.
    ///
    /// This method creates a mutable copy of the input string for simd-json processing.
    ///
    /// # Arguments
    ///
    /// * `json` - A string slice containing JSON data
    ///
    /// # Returns
    ///
    /// Returns the deserialized value or an error if parsing fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let json_str = r#"{"key":"value"}"#;
    /// let result: HashMap<String, String> = SimdJsonUtils::from_json_str(json_str)?;
    /// ```
    #[inline]
    pub fn from_json_str<T>(json: &str) -> rocketmq_error::Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let mut bytes = json.as_bytes().to_vec();
        simd_json::from_slice(&mut bytes)
            .map_err(|source| crate::error::serialization_source("decode", "SIMD-JSON", source))
    }

    /// Serialize a Rust type into a JSON string (compact format) using SIMD acceleration.
    ///
    /// # Arguments
    ///
    /// * `value` - A reference to the value to serialize
    ///
    /// # Returns
    ///
    /// Returns a JSON string or an error if serialization fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let data = vec!["hello", "world"];
    /// let json_string = SimdJsonUtils::serialize_json(&data)?;
    /// ```
    #[inline]
    pub fn serialize_json<T>(value: &T) -> rocketmq_error::Result<String>
    where
        T: serde::Serialize,
    {
        simd_json::to_string(value).map_err(|source| crate::error::serialization_source("encode", "SIMD-JSON", source))
    }

    /// Serialize a Rust type into a JSON string (pretty-printed format).
    ///
    /// Note: simd-json doesn't have native pretty-print support, so this falls back
    /// to serde_json for pretty printing.
    ///
    /// # Arguments
    ///
    /// * `value` - A reference to the value to serialize
    ///
    /// # Returns
    ///
    /// Returns a pretty-printed JSON string or an error if serialization fails.
    #[inline]
    pub fn serialize_json_pretty<T>(value: &T) -> rocketmq_error::Result<String>
    where
        T: serde::Serialize,
    {
        // simd-json doesn't support pretty printing, fall back to serde_json
        serde_json::to_string_pretty(value)
            .map_err(|error| crate::error::serialization_source("serialize", "JSON", error))
    }

    /// Serialize a Rust type into a JSON byte vector (compact format) using SIMD acceleration.
    ///
    /// # Arguments
    ///
    /// * `value` - A reference to the value to serialize
    ///
    /// # Returns
    ///
    /// Returns a JSON byte vector or an error if serialization fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let data = vec!["hello", "world"];
    /// let json_bytes = SimdJsonUtils::serialize_json_vec(&data)?;
    /// ```
    #[inline]
    pub fn serialize_json_vec<T>(value: &T) -> rocketmq_error::Result<Vec<u8>>
    where
        T: serde::Serialize,
    {
        simd_json::to_vec(value).map_err(|source| crate::error::serialization_source("encode", "SIMD-JSON", source))
    }

    /// Serialize a Rust type into a JSON byte vector (pretty-printed format).
    ///
    /// Note: simd-json doesn't have native pretty-print support, so this falls back
    /// to serde_json for pretty printing.
    ///
    /// # Arguments
    ///
    /// * `value` - A reference to the value to serialize
    ///
    /// # Returns
    ///
    /// Returns a pretty-printed JSON byte vector or an error if serialization fails.
    #[inline]
    pub fn serialize_json_vec_pretty<T>(value: &T) -> rocketmq_error::Result<Vec<u8>>
    where
        T: serde::Serialize,
    {
        // simd-json doesn't support pretty printing, fall back to serde_json
        serde_json::to_vec_pretty(value).map_err(|error| crate::error::serialization_source("serialize", "JSON", error))
    }

    /// Serialize a Rust type into a JSON byte vector using a preallocated writer.
    ///
    /// This is more efficient when you already have a buffer to write into.
    ///
    /// # Arguments
    ///
    /// * `writer` - A mutable reference to a `Vec<u8>` to write JSON into
    /// * `value` - A reference to the value to serialize
    ///
    /// # Returns
    ///
    /// Returns Ok(()) on success or an error if serialization fails.
    #[inline]
    pub fn serialize_json_to_writer<T>(writer: &mut Vec<u8>, value: &T) -> rocketmq_error::Result<()>
    where
        T: serde::Serialize,
    {
        simd_json::to_writer(writer, value)
            .map_err(|source| crate::error::serialization_source("encode", "SIMD-JSON", source))
    }
}

#[cfg(all(test, feature = "simd"))]
mod tests {
    use serde::Deserialize;
    use serde::Serialize;
    use serde_json::json;
    use serde_json::Value;

    use super::*;

    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct TestStruct {
        name: String,
        age: u8,
    }

    #[test]
    fn test_from_json_str_success() {
        let json_str = r#"{"name":"Alice","age":30}"#;
        let expected = TestStruct {
            name: "Alice".to_string(),
            age: 30,
        };
        let result: TestStruct = SimdJsonUtils::from_json_str(json_str).unwrap();
        assert_eq!(result, expected);
    }

    #[test]
    fn test_from_json_str_error() {
        let json_str = r#"{"name":"Alice","age":"thirty"}"#;
        let result: rocketmq_error::Result<TestStruct> = SimdJsonUtils::from_json_str(json_str);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_json_bytes_success() {
        let mut json_data = br#"{"name":"Bob","age":25}"#.to_vec();
        let expected = TestStruct {
            name: "Bob".to_string(),
            age: 25,
        };
        let result: TestStruct = SimdJsonUtils::from_json_bytes(&mut json_data).unwrap();
        assert_eq!(result, expected);
    }

    #[test]
    fn test_from_json_bytes_error() {
        let mut json_data = br#"{"name":"Bob","age":"twenty-five"}"#.to_vec();
        let result: rocketmq_error::Result<TestStruct> = SimdJsonUtils::from_json_bytes(&mut json_data);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_json_slice_success() {
        let mut json_slice = br#"{"name":"Charlie","age":35}"#.to_vec();
        let expected = TestStruct {
            name: "Charlie".to_string(),
            age: 35,
        };
        let result: TestStruct = SimdJsonUtils::from_json_slice(&mut json_slice).unwrap();
        assert_eq!(result, expected);
    }

    #[test]
    fn test_serialize_json_success() {
        let value = TestStruct {
            name: "David".to_string(),
            age: 40,
        };
        let result: String = SimdJsonUtils::serialize_json(&value).unwrap();
        // simd-json may produce slightly different formatting
        assert!(result.contains("David"));
        assert!(result.contains("40"));
    }

    #[test]
    fn test_serialize_json_vec_success() {
        let value = TestStruct {
            name: "Eve".to_string(),
            age: 28,
        };
        let result: Vec<u8> = SimdJsonUtils::serialize_json_vec(&value).unwrap();
        let result_str = String::from_utf8(result).unwrap();
        assert!(result_str.contains("Eve"));
        assert!(result_str.contains("28"));
    }

    #[test]
    fn test_serialize_json_pretty_success() {
        let value = TestStruct {
            name: "Frank".to_string(),
            age: 45,
        };
        let result: String = SimdJsonUtils::serialize_json_pretty(&value).unwrap();
        // Pretty print should have newlines
        assert!(result.contains('\n'));
        assert!(result.contains("Frank"));
    }

    #[test]
    fn test_serialize_json_vec_pretty_success() {
        let value = TestStruct {
            name: "Grace".to_string(),
            age: 32,
        };
        let result: Vec<u8> = SimdJsonUtils::serialize_json_vec_pretty(&value).unwrap();
        let result_str = String::from_utf8(result).unwrap();
        assert!(result_str.contains('\n'));
        assert!(result_str.contains("Grace"));
    }

    #[test]
    fn test_serialize_json_to_writer_success() {
        let value = TestStruct {
            name: "Henry".to_string(),
            age: 50,
        };
        let mut writer = Vec::new();
        let result = SimdJsonUtils::serialize_json_to_writer(&mut writer, &value);
        assert!(result.is_ok());
        let result_str = String::from_utf8(writer).unwrap();
        assert!(result_str.contains("Henry"));
        assert!(result_str.contains("50"));
    }

    #[test]
    fn test_roundtrip() {
        let original = TestStruct {
            name: "Isabella".to_string(),
            age: 27,
        };

        // Serialize
        let json_str = SimdJsonUtils::serialize_json(&original).unwrap();

        // Deserialize
        let deserialized: TestStruct = SimdJsonUtils::from_json_str(&json_str).unwrap();

        assert_eq!(original, deserialized);
    }

    #[test]
    fn test_complex_types() {
        let value = json!({
            "string": "test",
            "number": 42,
            "boolean": true,
            "null": null,
            "array": [1, 2, 3],
            "object": {"nested": "value"}
        });

        let json_str = SimdJsonUtils::serialize_json(&value).unwrap();
        let deserialized: Value = SimdJsonUtils::from_json_str(&json_str).unwrap();

        assert_eq!(value["string"], deserialized["string"]);
        assert_eq!(value["number"], deserialized["number"]);
        assert_eq!(value["boolean"], deserialized["boolean"]);
    }

    #[test]
    fn test_large_payload() {
        let large_struct = TestStruct {
            name: "X".repeat(1000),
            age: 99,
        };

        let json_vec = SimdJsonUtils::serialize_json_vec(&large_struct).unwrap();
        let mut json_vec_mut = json_vec.clone();
        let deserialized: TestStruct = SimdJsonUtils::from_json_bytes(&mut json_vec_mut).unwrap();

        assert_eq!(large_struct, deserialized);
    }

    #[test]
    fn test_empty_struct() {
        #[derive(Serialize, Deserialize, Debug, PartialEq)]
        struct EmptyStruct {}

        let empty = EmptyStruct {};
        let json_str = SimdJsonUtils::serialize_json(&empty).unwrap();
        let deserialized: EmptyStruct = SimdJsonUtils::from_json_str(&json_str).unwrap();

        assert_eq!(empty, deserialized);
    }

    #[test]
    fn test_vector_serialization() {
        let vec_data = vec![1, 2, 3, 4, 5];
        let json_str = SimdJsonUtils::serialize_json(&vec_data).unwrap();
        let deserialized: Vec<i32> = SimdJsonUtils::from_json_str(&json_str).unwrap();

        assert_eq!(vec_data, deserialized);
    }
}