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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use rkyv::{ser::Serializer, Fallible};

/// Marker type to be associated with write permissions to a backend
#[derive(Debug)]
pub enum Token {
    /// Token is active, being passed around or used to guard the write buffer
    Active,
    /// Token is somewhere else, no write permissions can be granted
    Vacant,
}

impl Token {
    /// Create a new token
    pub fn new() -> Self {
        Token::Active
    }

    /// Is the token being passed around?
    pub fn vacant(&self) -> bool {
        match self {
            Token::Active => false,
            Token::Vacant => true,
        }
    }

    /// Take the token from the slot, if any
    pub fn take(&mut self) -> Option<Token> {
        match self {
            Token::Active => {
                *self = Token::Vacant;
                Some(Token::Active)
            }
            Token::Vacant => None,
        }
    }

    /// Put the token back in its place
    pub fn return_token(&mut self, token: Token) {
        debug_assert!(self.vacant());
        debug_assert!(!token.vacant());
        *self = token;
    }
}

/// Writebuffer guarded by a `Token`
pub struct TokenBuffer {
    token: Token,
    buffer: *mut [u8],
    written: usize,
}

impl TokenBuffer {
    /// Construct a new `TokenBuffer` from a mutable slice of bytes and a token
    pub fn new(token: Token, buffer: &mut [u8]) -> Self {
        TokenBuffer {
            token,
            buffer,
            written: 0,
        }
    }

    pub(crate) fn placeholder() -> Self {
        TokenBuffer {
            token: Token::new(),
            buffer: &mut [],
            written: 0,
        }
    }

    /// Consume the buffer, returning the held token
    pub fn consume(self) -> Token {
        self.token
    }

    /// Return bytes that have been written into the tokenbuffer
    pub fn written_bytes(&self) -> &[u8] {
        let slice = unsafe { &*self.buffer };
        &slice[..self.written]
    }

    /// Return bytes that have not yet been written
    ///
    /// # Safety
    /// It is up to the caller to assure that Only one mutable reference may
    /// exist at a time
    pub unsafe fn unwritten_bytes(&mut self) -> &mut [u8] {
        let slice = &mut *self.buffer;
        &mut slice[self.written..]
    }

    /// Bump the buffer pointer forward, and reduce the internal count of
    /// written bytes.
    ///
    /// Returns the amount of bytes written into the lbuffer   
    pub fn advance(&mut self) -> usize {
        let written = self.written;
        self.buffer = &mut unsafe { &mut *self.buffer }[written..];
        self.written = 0;
        written
    }

    /// Remap TokenBuffer to the provided bytesg
    pub fn remap(&mut self, buffer: &mut [u8]) {
        self.buffer = buffer;
        self.written = 0;
    }
}

pub struct BufferOverflow;

impl Serializer for TokenBuffer {
    fn pos(&self) -> usize {
        self.written
    }

    fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
        let remaining_buffer = unsafe { self.unwritten_bytes() };
        let bytes_length = bytes.len();
        if remaining_buffer.len() >= bytes_length {
            remaining_buffer[..bytes_length].copy_from_slice(bytes);
            self.written += bytes_length;
            Ok(())
        } else {
            Err(BufferOverflow)
        }
    }
}

impl Fallible for TokenBuffer {
    type Error = BufferOverflow;
}

impl AsMut<[u8]> for TokenBuffer {
    fn as_mut(&mut self) -> &mut [u8] {
        unsafe { &mut *self.buffer }
    }
}