rama-core 0.3.0

rama service core code, used by rama and service authors
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
use pin_project_lite::pin_project;
use std::{
    io::{Cursor, Read},
    pin::Pin,
    task::{Context, Poll, ready},
};
use tokio::io::{self, AsyncBufRead, AsyncRead, ReadBuf};

use crate::bytes::{Buf, Bytes};

/// Read and discard exactly `n` bytes from `reader`.
///
/// Equivalent to `reader.read_exact(&mut vec![0u8; n])` but does not allocate
/// a buffer sized to `n`; it pipes the bytes through [`tokio::io::sink`] via
/// a `take` adaptor, reusing a small internal scratch buffer instead.
///
/// Returns an `UnexpectedEof` error if the reader yields fewer than `n` bytes
/// before EOF.
pub async fn discard<R>(reader: &mut R, n: u64) -> io::Result<()>
where
    R: AsyncRead + Unpin,
{
    if n == 0 {
        return Ok(());
    }
    let mut limited = tokio::io::AsyncReadExt::take(reader, n);
    let copied = tokio::io::copy(&mut limited, &mut tokio::io::sink()).await?;
    if copied < n {
        return Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "io::discard: reader EOF before requested byte count was consumed",
        ));
    }
    Ok(())
}

pin_project! {
    /// Reader for reading from a heap-allocated bytes buffer.
    #[derive(Debug, Clone)]
    pub struct HeapReader {
        #[pin]
        inner: Cursor<Vec<u8>>,
    }
}

impl HeapReader {
    /// Creates a new `HeapReader` with the specified bytes data.
    #[must_use]
    pub const fn new(data: Vec<u8>) -> Self {
        Self {
            inner: Cursor::new(data),
        }
    }

    /// How many bytes are there remaining
    #[must_use]
    pub fn remaining(&self) -> usize {
        self.inner.remaining()
    }

    /// Returns true if there are any more bytes to consume
    #[must_use]
    pub fn has_remaining(&self) -> bool {
        self.inner.has_remaining()
    }
}

impl From<Vec<u8>> for HeapReader {
    fn from(data: Vec<u8>) -> Self {
        Self::new(data)
    }
}

impl From<&[u8]> for HeapReader {
    fn from(data: &[u8]) -> Self {
        Self::new(data.to_vec())
    }
}

impl From<&str> for HeapReader {
    fn from(data: &str) -> Self {
        Self::new(data.as_bytes().to_vec())
    }
}

impl Default for HeapReader {
    fn default() -> Self {
        Self::new(Vec::new())
    }
}

impl From<Bytes> for HeapReader {
    fn from(data: Bytes) -> Self {
        Self::new(data.to_vec())
    }
}

#[warn(clippy::missing_trait_methods)]
impl AsyncRead for HeapReader {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        self.project().inner.poll_read(cx, buf)
    }
}

#[warn(clippy::missing_trait_methods)]
impl AsyncBufRead for HeapReader {
    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
        self.project().inner.poll_fill_buf(cx)
    }

    fn consume(self: Pin<&mut Self>, amt: usize) {
        self.project().inner.consume(amt);
    }
}

impl Read for HeapReader {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.inner.read(buf)
    }

    #[inline]
    fn read_exact(&mut self, buf: &mut [u8]) -> std::io::Result<()> {
        self.inner.read_exact(buf)
    }

    #[inline]
    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> std::io::Result<usize> {
        self.inner.read_to_end(buf)
    }

    #[inline]
    fn read_to_string(&mut self, buf: &mut String) -> std::io::Result<usize> {
        self.inner.read_to_string(buf)
    }

    #[inline]
    fn read_vectored(&mut self, bufs: &mut [std::io::IoSliceMut<'_>]) -> std::io::Result<usize> {
        self.inner.read_vectored(bufs)
    }
}

/// Reader for reading from a stack buffer
#[derive(Debug, Clone)]
pub struct StackReader<const N: usize> {
    data: [u8; N],
    offset: usize,
}

impl<const N: usize> StackReader<N> {
    /// Creates a new `StackReader` with the specified bytes data.
    #[must_use]
    pub const fn new(data: [u8; N]) -> Self {
        Self { data, offset: 0 }
    }

    /// Skip up to n bytes, less if n < m
    pub fn skip(&mut self, n: usize) {
        self.offset = (self.offset + n).min(N);
    }

    /// How many bytes are there remaining
    #[must_use]
    pub fn remaining(&self) -> usize {
        N - self.offset
    }

    /// Returns true if there are any more bytes to consume
    #[must_use]
    pub fn has_remaining(&self) -> bool {
        self.remaining() > 0
    }
}

impl<const N: usize> From<[u8; N]> for StackReader<N> {
    #[inline]
    fn from(data: [u8; N]) -> Self {
        Self::new(data)
    }
}

impl<const N: usize> AsyncRead for StackReader<N> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        if self.offset < N {
            let remaining = &self.data[self.offset..];
            let to_copy = remaining.len().min(buf.remaining());

            if to_copy > 0 {
                buf.put_slice(&remaining[..to_copy]);
                self.offset += to_copy;
            }
        }

        // done
        Poll::Ready(Ok(()))
    }
}

impl<const N: usize> AsyncBufRead for StackReader<N> {
    fn poll_fill_buf(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
        let me = self.get_mut();
        Poll::Ready(Ok(if me.offset < N {
            &me.data[me.offset..]
        } else {
            &[]
        }))
    }

    fn consume(self: Pin<&mut Self>, amt: usize) {
        self.get_mut().skip(amt)
    }
}

impl<const N: usize> Read for StackReader<N> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.offset < N {
            let remaining = &self.data[self.offset..];
            let to_copy = remaining.len().min(buf.len());

            if to_copy > 0 {
                buf[..to_copy].copy_from_slice(&remaining[..to_copy]);
                self.offset += to_copy;
                return Ok(to_copy);
            }
        }

        // done
        Ok(0)
    }
}

pin_project! {
    /// Reader that can be used to chain two readers together.
    #[must_use = "streams do nothing unless polled"]
    #[derive(Debug, Clone)]
    pub struct ChainReader<T, U> {
        #[pin]
        first: T,
        #[pin]
        second: U,
        done_first: bool,
    }
}

impl<T, U> ChainReader<T, U>
where
    T: AsyncRead,
    U: AsyncRead,
{
    /// Creates a new `ChainReader` with the specified readers.
    pub const fn new(first: T, second: U) -> Self {
        Self {
            first,
            second,
            done_first: false,
        }
    }

    /// Gets references to the underlying readers in this `ChainReader`.
    pub fn get_ref(&self) -> (&T, &U) {
        (&self.first, &self.second)
    }

    /// Gets mutable references to the underlying readers in this `ChainReader`.
    ///
    /// Care should be taken to avoid modifying the internal I/O state of the
    /// underlying readers as doing so may corrupt the internal state of this
    /// `ChainReader`.
    pub fn get_mut(&mut self) -> (&mut T, &mut U) {
        (&mut self.first, &mut self.second)
    }

    /// Gets pinned mutable references to the underlying readers in this `ChainReader`.
    ///
    /// Care should be taken to avoid modifying the internal I/O state of the
    /// underlying readers as doing so may corrupt the internal state of this
    /// `ChainReader`.
    #[must_use]
    pub fn get_pin_mut(self: Pin<&mut Self>) -> (Pin<&mut T>, Pin<&mut U>) {
        let me = self.project();
        (me.first, me.second)
    }

    /// Consumes the `ChainReader`, returning the wrapped readers.
    pub fn into_inner(self) -> (T, U) {
        (self.first, self.second)
    }
}

impl<T, U> AsyncRead for ChainReader<T, U>
where
    T: AsyncRead,
    U: AsyncRead,
{
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let me = self.project();

        if !*me.done_first {
            let rem = buf.remaining();
            ready!(me.first.poll_read(cx, buf))?;
            if buf.remaining() == rem {
                *me.done_first = true;
            } else {
                return Poll::Ready(Ok(()));
            }
        }
        me.second.poll_read(cx, buf)
    }
}

impl<T, U> Read for ChainReader<T, U>
where
    T: Read,
    U: Read,
{
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if !self.done_first {
            let n = self.first.read(buf)?;
            if n == 0 {
                self.done_first = true;
            } else {
                return Ok(n);
            }
        }
        self.second.read(buf)
    }
}

impl<T, U> AsyncBufRead for ChainReader<T, U>
where
    T: AsyncBufRead,
    U: AsyncBufRead,
{
    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
        let me = self.project();

        if !*me.done_first {
            match ready!(me.first.poll_fill_buf(cx)?) {
                [] => {
                    *me.done_first = true;
                }
                buf => return Poll::Ready(Ok(buf)),
            }
        }
        me.second.poll_fill_buf(cx)
    }

    fn consume(self: Pin<&mut Self>, amt: usize) {
        let me = self.project();
        if !*me.done_first {
            me.first.consume(amt)
        } else {
            me.second.consume(amt)
        }
    }
}

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

    use tokio::io::AsyncReadExt;

    #[tokio::test]
    async fn test_discard_consumes_exact_bytes() {
        let mut reader = Cursor::new(b"abcdefghij".to_vec());
        discard(&mut reader, 4).await.unwrap();
        let mut rest = Vec::new();
        tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut rest)
            .await
            .unwrap();
        assert_eq!(rest, b"efghij");
    }

    #[tokio::test]
    async fn test_discard_zero_is_noop() {
        let mut reader = Cursor::new(b"abc".to_vec());
        discard(&mut reader, 0).await.unwrap();
        let mut rest = Vec::new();
        tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut rest)
            .await
            .unwrap();
        assert_eq!(rest, b"abc");
    }

    #[tokio::test]
    async fn test_discard_eof_before_n_errors() {
        let mut reader = Cursor::new(b"abc".to_vec());
        let err = discard(&mut reader, 10).await.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
    }

    async fn test_multi_read_async<const N: usize>(
        mut stream: impl AsyncRead + Unpin,
        cases: &[&str],
    ) {
        let mut buf = [0u8; N];

        for (i, case) in cases.iter().enumerate() {
            let n = stream.read(&mut buf).await.unwrap();
            assert_eq!(
                n,
                case.len(),
                "[{N}][async] step #{} for cases: {:?}",
                i + 1,
                cases
            );
            assert_eq!(
                &buf[..n],
                case.as_bytes(),
                "[{N}][async] step #{} for cases: {:?}",
                i + 1,
                cases
            );
        }
    }

    fn test_multi_read_sync<const N: usize>(mut stream: impl Read, cases: &[&str]) {
        let mut buf = [0u8; N];

        for (i, case) in cases.iter().enumerate() {
            let n = stream.read(&mut buf).unwrap();
            assert_eq!(
                n,
                case.len(),
                "[{N}][sync] step #{} for cases: {:?}",
                i + 1,
                cases
            );
            assert_eq!(
                &buf[..n],
                case.as_bytes(),
                "[{N}][sync] step #{} for cases: {:?}",
                i + 1,
                cases
            );
        }
    }

    #[derive(Debug)]
    struct TestCase<const N: usize, R> {
        reader: R,
        expected_reads: &'static [&'static str],
    }

    impl<const N: usize, R: AsyncRead + Clone + Unpin + Read> TestCase<N, R> {
        async fn test_sync_and_async(&self) {
            let new_stream = || self.reader.clone();

            test_multi_read_async::<N>(&mut new_stream(), self.expected_reads).await;
            test_multi_read_sync::<N>(&mut new_stream(), self.expected_reads);
        }
    }

    #[tokio::test]
    async fn test_heap_reader() {
        TestCase::<5, _> {
            reader: HeapReader::from(""),
            expected_reads: &[""],
        }
        .test_sync_and_async()
        .await;

        TestCase::<5, _> {
            reader: HeapReader::from("hello world"),
            expected_reads: &["hello", " worl", "d", ""],
        }
        .test_sync_and_async()
        .await;

        TestCase::<10, _> {
            reader: HeapReader::from("hello world"),
            expected_reads: &["hello worl", "d", ""],
        }
        .test_sync_and_async()
        .await;
    }

    #[tokio::test]
    async fn test_stack_reader() {
        TestCase::<5, _> {
            reader: StackReader::new(*b""),
            expected_reads: &[""],
        }
        .test_sync_and_async()
        .await;

        TestCase::<5, _> {
            reader: StackReader::new(*b"hello world"),
            expected_reads: &["hello", " worl", "d", ""],
        }
        .test_sync_and_async()
        .await;

        TestCase::<10, _> {
            reader: StackReader::from(*b"hello world"),
            expected_reads: &["hello worl", "d", ""],
        }
        .test_sync_and_async()
        .await;
    }

    #[tokio::test]
    async fn test_chain_reader() {
        TestCase::<5, _> {
            reader: ChainReader::new(Cursor::new(""), Cursor::new("")),
            expected_reads: &[""],
        }
        .test_sync_and_async()
        .await;

        TestCase::<5, _> {
            reader: ChainReader::new(Cursor::new("hello world"), Cursor::new("")),
            expected_reads: &["hello", " worl", "d", ""],
        }
        .test_sync_and_async()
        .await;

        TestCase::<5, _> {
            reader: ChainReader::new(Cursor::new("hello "), Cursor::new("world")),
            expected_reads: &["hello", " ", "world", ""],
        }
        .test_sync_and_async()
        .await;

        TestCase::<5, _> {
            reader: ChainReader::new(Cursor::new(""), Cursor::new("hello world")),
            expected_reads: &["hello", " worl", "d", ""],
        }
        .test_sync_and_async()
        .await;
    }
}