armature-core 0.8.2

High-performance async HTTP framework core - routing, handlers, middleware
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! Zero-Copy HTTP Body Handling
//!
//! This module provides efficient body types that use `bytes::Bytes` internally
//! for zero-copy operations. By avoiding `Vec<u8>` conversions, request and
//! response bodies can be passed through without copying.
//!
//! ## Performance
//!
//! - **Request body**: Hyper's body is collected to `Bytes` once, no further copies
//! - **Response body**: `Bytes` is passed directly to Hyper, no conversion needed
//! - **Cloning**: `Bytes::clone()` is O(1) - just increments reference count
//!
//! ## Usage
//!
//! ```rust,ignore
//! use armature_core::body::{RequestBody, ResponseBody};
//!
//! // Request body - zero-copy from Hyper
//! let body = RequestBody::from_hyper(hyper_body).await?;
//! let json: MyType = body.json()?;
//!
//! // Response body - zero-copy to Hyper
//! let response = ResponseBody::from_json(&data)?;
//! let hyper_body = response.into_hyper(); // No copy!
//! ```

use bytes::Bytes;
use http_body_util::Full;
use serde::{Serialize, de::DeserializeOwned};
use std::ops::Deref;

// Re-export Bytes for convenience
pub use bytes;

/// A request body backed by `Bytes` for zero-copy handling.
///
/// This wraps `bytes::Bytes` to provide efficient body handling
/// without copying data from Hyper's incoming body.
///
/// # Example
///
/// ```rust,ignore
/// // From Hyper body (zero-copy after initial collect)
/// let body = RequestBody::from_bytes(hyper_bytes);
///
/// // Access as slice (zero-copy)
/// let slice: &[u8] = body.as_ref();
///
/// // Parse as JSON (zero-copy read)
/// let data: MyType = body.json()?;
/// ```
#[derive(Clone, Default)]
pub struct RequestBody {
    inner: Bytes,
}

impl RequestBody {
    /// Create an empty request body.
    #[inline]
    pub const fn empty() -> Self {
        Self {
            inner: Bytes::new(),
        }
    }

    /// Create from `Bytes` (zero-copy).
    #[inline]
    pub fn from_bytes(bytes: Bytes) -> Self {
        Self { inner: bytes }
    }

    /// Create from a byte slice (copies data).
    ///
    /// Use `from_bytes` when possible to avoid copying.
    #[inline]
    pub fn from_slice(slice: &[u8]) -> Self {
        Self {
            inner: Bytes::copy_from_slice(slice),
        }
    }

    /// Create from a `Vec<u8>` (zero-copy conversion).
    #[inline]
    pub fn from_vec(vec: Vec<u8>) -> Self {
        Self {
            inner: Bytes::from(vec),
        }
    }

    /// Create from a static byte array (zero-copy).
    #[inline]
    pub fn from_static(bytes: &'static [u8]) -> Self {
        Self {
            inner: Bytes::from_static(bytes),
        }
    }

    /// Get the body length.
    #[inline]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Check if the body is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Get the underlying `Bytes`.
    #[inline]
    pub fn as_bytes(&self) -> &Bytes {
        &self.inner
    }

    /// Convert to `Bytes` (zero-copy).
    #[inline]
    pub fn into_bytes(self) -> Bytes {
        self.inner
    }

    /// Convert to `Vec<u8>` (may copy if shared).
    ///
    /// If this is the only reference to the data, this is O(1).
    /// If the data is shared, this will copy.
    #[inline]
    pub fn to_vec(&self) -> Vec<u8> {
        self.inner.to_vec()
    }

    /// Parse body as JSON.
    ///
    /// Uses SIMD-accelerated parsing when the `simd-json` feature is enabled.
    #[inline]
    pub fn json<T: DeserializeOwned>(&self) -> Result<T, crate::Error> {
        crate::json::from_slice(&self.inner)
            .map_err(|e| crate::Error::Deserialization(e.to_string()))
    }

    /// Parse body as URL-encoded form data.
    #[inline]
    pub fn form<T: DeserializeOwned>(&self) -> Result<T, crate::Error> {
        crate::form::parse_form(&self.inner)
    }

    /// Get body as UTF-8 string (zero-copy if valid UTF-8).
    #[inline]
    pub fn as_str(&self) -> Result<&str, std::str::Utf8Error> {
        std::str::from_utf8(&self.inner)
    }

    /// Get body as UTF-8 string, replacing invalid sequences.
    #[inline]
    pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
        String::from_utf8_lossy(&self.inner)
    }
}

impl Deref for RequestBody {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl AsRef<[u8]> for RequestBody {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        &self.inner
    }
}

impl From<Bytes> for RequestBody {
    #[inline]
    fn from(bytes: Bytes) -> Self {
        Self::from_bytes(bytes)
    }
}

impl From<Vec<u8>> for RequestBody {
    #[inline]
    fn from(vec: Vec<u8>) -> Self {
        Self::from_vec(vec)
    }
}

impl From<&'static [u8]> for RequestBody {
    #[inline]
    fn from(slice: &'static [u8]) -> Self {
        Self::from_static(slice)
    }
}

impl From<String> for RequestBody {
    #[inline]
    fn from(s: String) -> Self {
        Self::from_vec(s.into_bytes())
    }
}

impl From<&'static str> for RequestBody {
    #[inline]
    fn from(s: &'static str) -> Self {
        Self::from_static(s.as_bytes())
    }
}

impl std::fmt::Debug for RequestBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RequestBody")
            .field("len", &self.inner.len())
            .finish()
    }
}

// ============================================================================
// Response Body
// ============================================================================

/// A response body backed by `Bytes` for zero-copy handling.
///
/// This wraps `bytes::Bytes` to provide efficient body handling
/// that can be passed directly to Hyper without copying.
///
/// # Example
///
/// ```rust,ignore
/// // Create from JSON (serializes once)
/// let body = ResponseBody::from_json(&data)?;
///
/// // Convert to Hyper body (zero-copy)
/// let hyper_body: Full<Bytes> = body.into_hyper();
/// ```
#[derive(Clone, Default)]
pub struct ResponseBody {
    inner: Bytes,
}

impl ResponseBody {
    /// Create an empty response body.
    #[inline]
    pub const fn empty() -> Self {
        Self {
            inner: Bytes::new(),
        }
    }

    /// Create from `Bytes` (zero-copy).
    #[inline]
    pub fn from_bytes(bytes: Bytes) -> Self {
        Self { inner: bytes }
    }

    /// Create from a byte slice (copies data).
    #[inline]
    pub fn from_slice(slice: &[u8]) -> Self {
        Self {
            inner: Bytes::copy_from_slice(slice),
        }
    }

    /// Create from a `Vec<u8>` (zero-copy conversion).
    #[inline]
    pub fn from_vec(vec: Vec<u8>) -> Self {
        Self {
            inner: Bytes::from(vec),
        }
    }

    /// Create from a static byte array (zero-copy).
    #[inline]
    pub fn from_static(bytes: &'static [u8]) -> Self {
        Self {
            inner: Bytes::from_static(bytes),
        }
    }

    /// Create from JSON serialization.
    ///
    /// Uses SIMD-accelerated serialization when the `simd-json` feature is enabled.
    #[inline]
    pub fn from_json<T: Serialize>(value: &T) -> Result<Self, crate::Error> {
        let vec =
            crate::json::to_vec(value).map_err(|e| crate::Error::Serialization(e.to_string()))?;
        Ok(Self::from_vec(vec))
    }

    /// Create from JSON with pre-allocated capacity.
    ///
    /// Use this when you have a reasonable estimate of the output size.
    #[inline]
    pub fn from_json_with_capacity<T: Serialize>(
        value: &T,
        capacity: usize,
    ) -> Result<Self, crate::Error> {
        let vec = crate::json::to_vec_with_capacity(value, capacity)
            .map_err(|e| crate::Error::Serialization(e.to_string()))?;
        Ok(Self::from_vec(vec))
    }

    /// Get the body length.
    #[inline]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Check if the body is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Get the underlying `Bytes`.
    #[inline]
    pub fn as_bytes(&self) -> &Bytes {
        &self.inner
    }

    /// Convert to `Bytes` (zero-copy).
    #[inline]
    pub fn into_bytes(self) -> Bytes {
        self.inner
    }

    /// Convert to Hyper's body type (zero-copy).
    ///
    /// This is the key optimization - no copying needed!
    #[inline]
    pub fn into_hyper(self) -> Full<Bytes> {
        Full::new(self.inner)
    }

    /// Convert to `Vec<u8>` (may copy if shared).
    #[inline]
    pub fn to_vec(&self) -> Vec<u8> {
        self.inner.to_vec()
    }
}

impl Deref for ResponseBody {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl AsRef<[u8]> for ResponseBody {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        &self.inner
    }
}

impl From<Bytes> for ResponseBody {
    #[inline]
    fn from(bytes: Bytes) -> Self {
        Self::from_bytes(bytes)
    }
}

impl From<Vec<u8>> for ResponseBody {
    #[inline]
    fn from(vec: Vec<u8>) -> Self {
        Self::from_vec(vec)
    }
}

impl From<&'static [u8]> for ResponseBody {
    #[inline]
    fn from(slice: &'static [u8]) -> Self {
        Self::from_static(slice)
    }
}

impl From<String> for ResponseBody {
    #[inline]
    fn from(s: String) -> Self {
        Self::from_vec(s.into_bytes())
    }
}

impl From<&'static str> for ResponseBody {
    #[inline]
    fn from(s: &'static str) -> Self {
        Self::from_static(s.as_bytes())
    }
}

impl std::fmt::Debug for ResponseBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ResponseBody")
            .field("len", &self.inner.len())
            .finish()
    }
}

// ============================================================================
// Conversion to/from legacy types
// ============================================================================

impl From<RequestBody> for Vec<u8> {
    #[inline]
    fn from(body: RequestBody) -> Self {
        body.to_vec()
    }
}

impl From<ResponseBody> for Vec<u8> {
    #[inline]
    fn from(body: ResponseBody) -> Self {
        body.to_vec()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_request_body_from_bytes() {
        let bytes = Bytes::from_static(b"hello world");
        let body = RequestBody::from_bytes(bytes);
        assert_eq!(body.len(), 11);
        assert_eq!(&*body, b"hello world");
    }

    #[test]
    fn test_request_body_from_vec() {
        let vec = vec![1, 2, 3, 4, 5];
        let body = RequestBody::from_vec(vec);
        assert_eq!(body.len(), 5);
        assert_eq!(&*body, &[1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_request_body_json() {
        let json = br#"{"name":"John","age":30}"#;
        let body = RequestBody::from_slice(json);

        #[derive(serde::Deserialize, PartialEq, Debug)]
        struct Person {
            name: String,
            age: u32,
        }

        let person: Person = body.json().unwrap();
        assert_eq!(person.name, "John");
        assert_eq!(person.age, 30);
    }

    #[test]
    fn test_request_body_clone_is_cheap() {
        let body = RequestBody::from_static(b"large data here that would be expensive to copy");
        let _clone1 = body.clone(); // Should be O(1) - just ref count increment
        let _clone2 = body.clone();
        assert_eq!(body.len(), 47);
    }

    #[test]
    fn test_response_body_from_json() {
        #[derive(serde::Serialize)]
        struct Response {
            status: &'static str,
            code: u32,
        }

        let data = Response {
            status: "ok",
            code: 200,
        };

        let body = ResponseBody::from_json(&data).unwrap();
        assert!(!body.is_empty());
        assert!(String::from_utf8_lossy(&body).contains("ok"));
    }

    #[test]
    fn test_response_body_into_hyper() {
        let body = ResponseBody::from_static(b"response content");
        let hyper_body = body.into_hyper();
        // Full<Bytes> is the type Hyper expects - zero copy!
        let _ = hyper_body;
    }

    #[test]
    fn test_response_body_from_string() {
        let body = ResponseBody::from("hello world".to_string());
        assert_eq!(&*body, b"hello world");
    }

    #[test]
    fn test_request_body_as_str() {
        let body = RequestBody::from_static(b"valid utf-8");
        assert_eq!(body.as_str().unwrap(), "valid utf-8");

        let invalid = RequestBody::from_slice(&[0xff, 0xfe]);
        assert!(invalid.as_str().is_err());
    }

    #[test]
    fn test_empty_bodies() {
        let req = RequestBody::empty();
        assert!(req.is_empty());
        assert_eq!(req.len(), 0);

        let resp = ResponseBody::empty();
        assert!(resp.is_empty());
        assert_eq!(resp.len(), 0);
    }
}