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
use super::{addresses::InliningAddresses, dectx::DeCtx, *};

/// Inlining ([Stream]ed) context.
pub trait InCtx<'a, Ctx: Context<'a>>: Stream {
    /// Read the next [Address].
    fn icnext_address<E>(self, err: impl FnOnce(&[u8]) -> E) -> Result<(Address, Self), E>;

    /// Read the next [Point].
    fn icnext_point<'b, A: MentionableBase<'a>, E>(
        self,
        factory: A::Fctr,
        err: impl FnOnce(&[u8]) -> E,
    ) -> Result<(Point<'a, Ctx, A>, Self), E> {
        let (point, inctx) = self.icnext_address(err)?;
        Ok((
            Point::from_address(point, factory, inctx.iresolver()),
            inctx,
        ))
    }

    /// Clone the reference to the current [Resolver].
    fn iresolver(&self) -> Arc<dyn Resolver<'a, Ctx>>;

    /// Return [Demoted] version of the context.
    fn demote<'d>(self) -> Demoted<'a, 'd, Ctx>
    where
        'a: 'd,
        Self: 'd;
}

impl<'a: 'c, 'c, Ctx: Context<'a>> Stream for &'c mut dyn DeCtx<'a, Ctx> {
    fn iread_n<A, E>(
        self,
        n: usize,
        ok: impl FnOnce(&[u8]) -> A,
        err: impl FnOnce(&[u8]) -> E,
    ) -> Result<(A, Self), E> {
        match self.deserializer().iread_n(n, ok, err) {
            Ok((a, _)) => Ok((a, self)),
            Err(e) => Err(e),
        }
    }

    fn iread_all<A>(self, ok: impl FnOnce(&[u8]) -> A) -> A {
        self.deserializer().iread_all(ok)
    }

    fn itell(&self) -> usize {
        self.tell()
    }
}

impl<'a: 'c, 'c, Ctx: Context<'a>> InCtx<'a, Ctx> for &'c mut dyn DeCtx<'a, Ctx> {
    fn icnext_address<E>(self, err: impl FnOnce(&[u8]) -> E) -> Result<(Address, Self), E> {
        let (addresses, deserialiser) = self.ad();
        match deserialiser.inext_address(addresses, err) {
            Ok((address, _)) => Ok((address, self)),
            Err(e) => Err(e),
        }
    }

    fn iresolver(&self) -> Arc<dyn Resolver<'a, Ctx>> {
        self.resolver()
    }

    fn demote<'d>(self) -> Demoted<'a, 'd, Ctx>
    where
        'a: 'd,
        Self: 'd,
    {
        Demoted(self)
    }
}