websocketz 0.2.0

A zerocopy websockets implementation for no_std environments.
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
//! HTTP request and response types.
//!
//! The [`Header`] type is re-exported from the [`httparse`] crate.

use framez::{decode::Decoder, encode::Encoder};
pub use httparse::Header;
use httparse::Status;

use crate::error::{HttpDecodeError, HttpEncodeError};

pub(crate) trait HeaderExt {
    fn header(&self, name: &str) -> Option<&Header<'_>>;

    fn header_value(&self, name: &str) -> Option<&'_ [u8]> {
        self.header(name).map(|h| h.value)
    }

    fn header_value_str(&self, name: &str) -> Option<&'_ str> {
        self.header_value(name)
            .and_then(|v| core::str::from_utf8(v).ok())
    }
}

impl HeaderExt for [Header<'_>] {
    fn header(&self, name: &str) -> Option<&Header<'_>> {
        self.iter().find(|h| h.name.eq_ignore_ascii_case(name))
    }
}

#[derive(Debug)]
pub(crate) struct OutResponse<'headers, 'buf> {
    code: &'buf str,
    status: &'buf str,
    headers: &'headers [Header<'buf>],
    additional_headers: &'headers [Header<'buf>],
}

impl<'headers, 'buf> OutResponse<'headers, 'buf> {
    const fn new(
        code: &'buf str,
        status: &'buf str,
        headers: &'headers [Header<'buf>],
        additional_headers: &'headers [Header<'buf>],
    ) -> Self {
        OutResponse {
            code,
            status,
            headers,
            additional_headers,
        }
    }

    pub const fn switching_protocols(
        headers: &'headers [Header<'buf>],
        additional_headers: &'headers [Header<'buf>],
    ) -> Self {
        Self::new("101", "Switching Protocols", headers, additional_headers)
    }
}

#[derive(Debug)]
pub(crate) struct OutResponseCodec {}

impl OutResponseCodec {
    pub const fn new() -> Self {
        OutResponseCodec {}
    }
}

impl Encoder<OutResponse<'_, '_>> for OutResponseCodec {
    type Error = HttpEncodeError;

    fn encode(&mut self, item: OutResponse<'_, '_>, dst: &mut [u8]) -> Result<usize, Self::Error> {
        let mut pos = 0;

        write(dst, &mut pos, b"HTTP/1.1 ")?;
        write(dst, &mut pos, item.code.as_bytes())?;
        write(dst, &mut pos, b" ")?;
        write(dst, &mut pos, item.status.as_bytes())?;
        write(dst, &mut pos, b"\r\n")?;

        for header in item.headers.iter() {
            write(dst, &mut pos, header.name.as_bytes())?;
            write(dst, &mut pos, b": ")?;
            write(dst, &mut pos, header.value)?;
            write(dst, &mut pos, b"\r\n")?;
        }

        for header in item.additional_headers.iter() {
            write(dst, &mut pos, header.name.as_bytes())?;
            write(dst, &mut pos, b": ")?;
            write(dst, &mut pos, header.value)?;
            write(dst, &mut pos, b"\r\n")?;
        }

        write(dst, &mut pos, b"\r\n")?;

        Ok(pos)
    }
}

/// An HTTP response.
#[derive(Debug)]
pub struct Response<'buf, const N: usize> {
    /// The response minor version, such as `1` for `HTTP/1.1`.
    pub version: u8,
    /// The response code, such as `200`.
    pub code: u16,
    /// The response reason-phrase, such as `OK`.
    ///
    /// Contains an empty string if the reason-phrase was missing or contained invalid characters.
    pub reason: &'buf str,
    /// The response headers.
    pub headers: [Header<'buf>; N],
}

impl<'buf, const N: usize> Response<'buf, N> {
    /// Creates a new [`Response`].
    pub const fn new(
        version: u8,
        code: u16,
        reason: &'buf str,
        headers: [Header<'buf>; N],
    ) -> Self {
        Response {
            version,
            code,
            reason,
            headers,
        }
    }

    /// Returns the HTTP version.
    pub const fn version(&self) -> u8 {
        self.version
    }

    /// Returns the response code.
    pub const fn code(&self) -> u16 {
        self.code
    }

    /// Returns the reason-phrase.
    pub const fn reason(&self) -> &'buf str {
        self.reason
    }

    /// Returns the headers.
    pub const fn headers(&self) -> &[Header<'buf>] {
        &self.headers
    }
}

#[derive(Debug)]
pub(crate) struct InResponseCodec<const N: usize> {}

impl<const N: usize> InResponseCodec<N> {
    pub const fn new() -> Self {
        InResponseCodec {}
    }
}

impl<const N: usize> framez::decode::DecodeError for InResponseCodec<N> {
    type Error = HttpDecodeError;
}

impl<'buf, const N: usize> Decoder<'buf> for InResponseCodec<N> {
    type Item = Response<'buf, N>;

    fn decode(&mut self, src: &'buf mut [u8]) -> Result<Option<(Self::Item, usize)>, Self::Error> {
        let mut headers = [httparse::EMPTY_HEADER; N];
        let mut response = httparse::Response::new(&mut headers);

        match response.parse(src)? {
            Status::Complete(len) => Ok(Some((
                Response::new(
                    response.version.expect("must be some"),
                    response.code.expect("must be some"),
                    response.reason.expect("must be some"),
                    headers,
                ),
                len,
            ))),
            Status::Partial => Ok(None),
        }
    }
}

#[derive(Debug)]
pub(crate) struct OutRequest<'headers, 'buf> {
    /// XXX: Must be valid
    method: &'buf str,
    /// XXX: Must be valid. Can not be empty
    path: &'buf str,
    headers: &'headers [Header<'buf>],
    additional_headers: &'headers [Header<'buf>],
}

impl<'headers, 'buf> OutRequest<'headers, 'buf> {
    /// See [`OutRequest`] docs.
    const fn new_unchecked(
        method: &'buf str,
        path: &'buf str,
        headers: &'headers [Header<'buf>],
        additional_headers: &'headers [Header<'buf>],
    ) -> Self {
        OutRequest {
            method,
            path,
            headers,
            additional_headers,
        }
    }

    /// See [`OutRequest`] docs.
    pub const fn get_unchecked(
        path: &'buf str,
        headers: &'headers [Header<'buf>],
        additional_headers: &'headers [Header<'buf>],
    ) -> Self {
        Self::new_unchecked("GET", path, headers, additional_headers)
    }
}

#[derive(Debug)]
pub(crate) struct OutRequestCodec {}

impl OutRequestCodec {
    pub const fn new() -> Self {
        OutRequestCodec {}
    }
}

impl Encoder<OutRequest<'_, '_>> for OutRequestCodec {
    type Error = HttpEncodeError;

    fn encode(&mut self, item: OutRequest<'_, '_>, dst: &mut [u8]) -> Result<usize, Self::Error> {
        let mut pos = 0;

        write(dst, &mut pos, item.method.as_bytes())?;
        write(dst, &mut pos, b" ")?;
        write(dst, &mut pos, item.path.as_bytes())?;
        write(dst, &mut pos, b" HTTP/1.1\r\n")?;

        for header in item.headers.iter() {
            write(dst, &mut pos, header.name.as_bytes())?;
            write(dst, &mut pos, b": ")?;
            write(dst, &mut pos, header.value)?;
            write(dst, &mut pos, b"\r\n")?;
        }

        for header in item.additional_headers.iter() {
            write(dst, &mut pos, header.name.as_bytes())?;
            write(dst, &mut pos, b": ")?;
            write(dst, &mut pos, header.value)?;
            write(dst, &mut pos, b"\r\n")?;
        }

        write(dst, &mut pos, b"\r\n")?;

        Ok(pos)
    }
}

/// An HTTP request.
#[derive(Debug)]
pub struct Request<'buf, const N: usize> {
    /// The request method, such as `GET`.
    pub method: &'buf str,
    /// The request path, such as `/about-us`.
    pub path: &'buf str,
    /// The request minor version, such as `1` for `HTTP/1.1`.
    pub version: u8,
    /// The request headers.
    pub headers: [Header<'buf>; N],
}

impl<'buf, const N: usize> Request<'buf, N> {
    /// Creates a new [`Request`].
    pub const fn new(
        method: &'buf str,
        path: &'buf str,
        version: u8,
        headers: [Header<'buf>; N],
    ) -> Self {
        Request {
            method,
            path,
            version,
            headers,
        }
    }

    /// Returns the request method.
    pub const fn method(&self) -> &'buf str {
        self.method
    }

    /// Returns the request path.
    pub const fn path(&self) -> &'buf str {
        self.path
    }

    /// Returns the HTTP version.
    pub const fn version(&self) -> u8 {
        self.version
    }

    /// Returns the headers.
    pub const fn headers(&self) -> &[Header<'buf>] {
        &self.headers
    }
}

#[derive(Debug)]
pub(crate) struct InRequestCodec<const N: usize> {}

impl<const N: usize> InRequestCodec<N> {
    pub const fn new() -> Self {
        InRequestCodec {}
    }
}

impl<const N: usize> framez::decode::DecodeError for InRequestCodec<N> {
    type Error = HttpDecodeError;
}

impl<'buf, const N: usize> Decoder<'buf> for InRequestCodec<N> {
    type Item = Request<'buf, N>;

    fn decode(&mut self, src: &'buf mut [u8]) -> Result<Option<(Self::Item, usize)>, Self::Error> {
        let mut headers = [httparse::EMPTY_HEADER; N];
        let mut request = httparse::Request::new(&mut headers);

        match request.parse(src)? {
            Status::Complete(len) => Ok(Some((
                Request::new(
                    request.method.expect("must be some"),
                    request.path.expect("must be some"),
                    request.version.expect("must be some"),
                    headers,
                ),
                len,
            ))),
            Status::Partial => Ok(None),
        }
    }
}

fn write(dst: &mut [u8], pos: &mut usize, data: &[u8]) -> Result<(), HttpEncodeError> {
    if *pos + data.len() > dst.len() {
        return Err(HttpEncodeError::BufferTooSmall);
    }

    dst[*pos..*pos + data.len()].copy_from_slice(data);

    *pos += data.len();

    Ok(())
}

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

    mod decode {
        use std::vec::Vec;

        use super::*;

        mod response {
            use super::*;

            const OK_RESPONSE: &[u8] =
            b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n\0\0\0\0\0\0";

            fn ok_response() -> Vec<u8> {
                OK_RESPONSE.to_vec()
            }

            fn partial_response() -> Vec<u8> {
                OK_RESPONSE[..16].to_vec()
            }

            #[test]
            fn ok() {
                let mut response = ok_response();
                let mut codec = InResponseCodec::<2>::new();

                let (response, len) = codec.decode(&mut response).unwrap().unwrap();

                assert_eq!(response.code(), 200);
                assert_eq!(
                    response.headers().header_value_str("content-type"),
                    Some("text/plain")
                );
                assert_eq!(
                    response.headers().header_value_str("Connection"),
                    Some("close")
                );
                assert_eq!(response.headers().len(), 2);

                assert_eq!(len, 64);
            }

            #[test]
            fn too_many_headers() {
                let mut response = ok_response();
                let mut codec = InResponseCodec::<1>::new();

                let error = codec.decode(&mut response).unwrap_err();

                assert!(matches!(
                    error,
                    HttpDecodeError::Parse(httparse::Error::TooManyHeaders)
                ));
            }

            #[test]
            fn partial() {
                let mut response = partial_response();
                let mut codec = InResponseCodec::<2>::new();

                let result = codec.decode(&mut response).unwrap();

                assert!(result.is_none());
            }
        }

        mod request {
            use super::*;

            const OK_REQUEST: &[u8] =
            b"GET /index.html HTTP/1.1\r\nHost: example.com\r\nUser-Agent: test-agent\r\nAccept: text/html\r\n\r\n\0\0\0\0\0\0";

            fn ok_request() -> Vec<u8> {
                OK_REQUEST.to_vec()
            }

            fn partial_request() -> Vec<u8> {
                OK_REQUEST[..16].to_vec()
            }

            #[test]
            fn ok() {
                let mut request = ok_request();
                let mut codec = InRequestCodec::<3>::new();

                let (request, len) = codec.decode(&mut request).unwrap().unwrap();

                assert_eq!(
                    request.headers().header_value_str("Host"),
                    Some("example.com")
                );
                assert_eq!(
                    request.headers().header_value_str("User-agent"),
                    Some("test-agent")
                );
                assert_eq!(
                    request.headers().header_value_str("accept"),
                    Some("text/html")
                );
                assert_eq!(len, 90);

                assert_eq!(request.headers().len(), 3);
            }

            #[test]
            fn too_many_headers() {
                let mut request = ok_request();
                let mut codec = InRequestCodec::<2>::new();

                let error = codec.decode(&mut request).unwrap_err();

                assert!(matches!(
                    error,
                    HttpDecodeError::Parse(httparse::Error::TooManyHeaders)
                ));
            }

            #[test]
            fn partial() {
                let mut request = partial_request();
                let mut codec = InRequestCodec::<3>::new();

                let result = codec.decode(&mut request).unwrap();

                assert!(result.is_none());
            }
        }
    }

    mod encode {
        use super::*;

        mod request {
            use super::*;

            const OK_REQUEST: &[u8] =
            b"GET /index.html HTTP/1.1\r\nHost: example.com\r\nUser-Agent: test-agent\r\nAccept: text/html\r\n\r\n";

            const HEADERS: &[Header] = &[
                Header {
                    name: "Host",
                    value: b"example.com",
                },
                Header {
                    name: "User-Agent",
                    value: b"test-agent",
                },
            ];

            const ADDITIONAL_HEADERS: &[Header] = &[Header {
                name: "Accept",
                value: b"text/html",
            }];

            #[test]
            fn ok() {
                let request = OutRequest::get_unchecked("/index.html", HEADERS, ADDITIONAL_HEADERS);

                let mut codec = OutRequestCodec::new();

                let mut buf = std::vec![0; 1024];

                let len = codec.encode(request, &mut buf).unwrap();

                assert!(len == OK_REQUEST.len());
                assert_eq!(&buf[..len], OK_REQUEST);
            }

            #[test]
            fn buffer_too_small() {
                let request = OutRequest::get_unchecked("/index.html", HEADERS, ADDITIONAL_HEADERS);

                let mut codec = OutRequestCodec::new();

                let mut buf = std::vec![0; 10];

                let error = codec.encode(request, &mut buf).unwrap_err();

                assert!(matches!(error, HttpEncodeError::BufferTooSmall));
            }
        }

        mod response {
            use super::*;

            const OK_RESPONSE: &[u8] =
                b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n";

            const SWITCHING_PROTOCOLS_RESPONSE: &[u8] =
                b"HTTP/1.1 101 Switching Protocols\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n";

            const HEADERS: &[Header] = &[Header {
                name: "Content-Type",
                value: b"text/plain",
            }];

            const ADDITIONAL_HEADERS: &[Header] = &[Header {
                name: "Connection",
                value: b"close",
            }];

            #[test]
            fn ok() {
                let response = OutResponse::new("200", "OK", HEADERS, ADDITIONAL_HEADERS);

                let mut codec = OutResponseCodec::new();

                let mut buf = std::vec![0; 1024];

                let len = codec.encode(response, &mut buf).unwrap();

                assert!(len == OK_RESPONSE.len());
                assert_eq!(&buf[..len], OK_RESPONSE);
            }

            #[test]
            fn ok_switching_protocols() {
                let response = OutResponse::switching_protocols(HEADERS, ADDITIONAL_HEADERS);

                let mut codec = OutResponseCodec::new();

                let mut buf = std::vec![0; 1024];

                let len = codec.encode(response, &mut buf).unwrap();

                assert!(len == SWITCHING_PROTOCOLS_RESPONSE.len());
                assert_eq!(&buf[..len], SWITCHING_PROTOCOLS_RESPONSE);
            }

            #[test]
            fn buffer_too_small() {
                let response = OutResponse::new("200", "OK", HEADERS, ADDITIONAL_HEADERS);

                let mut codec = OutResponseCodec::new();

                let mut buf = std::vec![0; 10];

                let error = codec.encode(response, &mut buf).unwrap_err();

                assert!(matches!(error, HttpEncodeError::BufferTooSmall));
            }
        }
    }
}