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
//! # Input Manager
//!
//! Input manager is a ring-buffer based method of representing input
//! and output of a system.
//!
//! It intends to provide a similar function to a tty/terminal, but uses
//! a "chat bubble" metaphor to distinguish from "local input" and "remote
//! output".
//!
//! In a typical tty application, "Local" would correspond to stdin, and "Remote"
//! would correspond to "stdout".
//!
//! It uses a fixed-size array of lines for storage, where each line can hold
//! a dynamic number of characters. These lines can be cheaply reordered (using
//! a separate index for the ordering of lines).
//!
//! These lines are sorted into four distinct regions:
//!
//! 1. "Local Editing Region" - or lines that the user is currently typing in,
//!    but have not submitted. This is like the text box in a chat program - it
//!    is not "latched in" until you hit the send button (or in our case, you
//!    submit the lines.
//! 2. "Remote Editing Region" - or lines that the computer is currently typing in,
//!    but has not submitted. This would be like if you could preview the message
//!    being written by someone else in a chat program, before they hit send.
//! 3. "History region" - A listing of the most recent lines that have been
//!    submitted. This is like the history of a chat window. Each line is tagged
//!    with its source, either from the local or remote end.
//! 4. Empty lines, that have never been used for local or remote input. Initially
//!    all lines are empty lines, however eventually most lines will end up being
//!    editing or history lines, and there will be no empty lines
//!
//! When the local or remote end wants an additional line for editing, the history
//! lines (or empty lines, if available) will be recycled to become

#![cfg_attr(not(test), no_std)]

mod bricks;
mod lines;

use bricks::Bricks;
pub use bricks::{LineIter, LineIterMut};
pub use lines::Line;

/// # RingLine
///
/// The [RingLine] structure contains the textual history of a two entity conversation
///
/// It is generic over two numbers:
///
/// * `L` is the number of lines it can store
/// * `C` is the maximum number of ASCII characters per line
///
/// In general, `L` should be >= the number of lines you intend to display. If L is
/// larger than the number of lines you would like to display, it can also be used
/// as a "scrollback" buffer.
///
/// RingLine does NOT store lines in a "sparse" manner - if you have 16 lines and 80
/// characters per line, 1280 bytes will be used to store those characters, even if
/// all lines are blank.
#[derive(Debug)]
pub struct RingLine<const L: usize, const C: usize> {
    lines: [Line<C>; L],
    brick: Bricks<L>,
}

impl<const L: usize, const C: usize> RingLine<L, C> {
    const ONELINE: Line<C> = Line::<C>::new();
    const INIT: [Line<C>; L] = [Self::ONELINE; L];

    pub fn new() -> Self {
        Self {
            lines: Self::INIT,
            brick: Bricks::new(),
        }
    }

    /// Iterates all "historical" (e.g. not currently editing) lines, NEWEST to OLDEST
    ///
    /// Each line contans a status field that marks it as local or remote.
    ///
    /// The returned iterator implements [DoubleEndedIterator], and can be reversed with
    /// [Iterator::rev()] to obtain lines in OLDEST to NEWEST order.
    pub fn iter_history(&self) -> LineIter<'_, L, Line<C>> {
        let Self { lines, brick } = self;
        brick.iter_history(lines)
    }

    /// Iterates any lines that are currently being edited by the remote end, NEWEST to OLDEST
    ///
    /// The returned iterator implements [DoubleEndedIterator], and can be reversed with
    /// [Iterator::rev()] to obtain lines in OLDEST to NEWEST order.
    pub fn iter_remote_editing(&self) -> LineIter<'_, L, Line<C>> {
        let Self { lines, brick } = self;
        brick.iter_remote_editable(lines)
    }

    /// The number of ascii characters/bytes currently used by the local editing buffer
    pub fn local_editing_len(&self) -> usize {
        self.iter_local_editing().map(|l| l.len()).sum()
    }

    /// The number of ascii characters/bytes currently used by the remote editing buffer
    pub fn remote_editing_len(&self) -> usize {
        self.iter_remote_editing().map(|l| l.len()).sum()
    }

    /// Attempt to copy the entire current local editing buffer to a provided slice
    ///
    /// Useful for obtaining the full user input prior to submitting the line.
    ///
    /// Returns an error if the provided slice is not large enough to contain the entire
    /// local editing buffer contents. Otherwise, returns a subslice that contains the used
    /// contents of the provided slice. The length of this slice will be the same as the
    /// length returned by [RingLine::local_editing_len()].
    ///
    /// If you do not need the entire contents in a single slice, consider using
    /// [RingLine::iter_local_editing()] and calling `rev()` to get the contents oldest
    /// to newest.
    pub fn copy_local_editing_to<'a>(&self, buffer: &'a mut [u8]) -> Result<&'a mut [u8], LineError> {
        // We want to iterate oldest to newest, so reverse the editing iterator
        let lines = self.iter_local_editing().rev();
        let buf_len = buffer.len();

        // Take a sliding window of the "unused" portion of the provided buffer.
        let mut window = &mut buffer[..];
        for l in lines {
            let needed = l.len();
            if needed > window.len() {
                return Err(LineError::Full);
            }

            let (now, later) = window.split_at_mut(needed);
            window = later;
            now.copy_from_slice(l.as_str().as_bytes());
        }

        let taken = buf_len - window.len();
        Ok(&mut buffer[..taken])
    }

    /// Iterates any lines that are currently being edited by the local end, NEWEST to OLDEST
    ///
    /// The returned iterator implements [DoubleEndedIterator], and can be reversed with
    /// [Iterator::rev()] to obtain lines in OLDEST to NEWEST order.
    pub fn iter_local_editing(&self) -> LineIter<'_, L, Line<C>> {
        let Self { lines, brick } = self;
        brick.iter_local_editable(lines)
    }

    /// Iterates any lines that are currently being edited by the remote end, NEWEST to OLDEST
    ///
    /// The returned iterator implements [DoubleEndedIterator], and can be reversed with
    /// [Iterator::rev()] to obtain lines in OLDEST to NEWEST order.
    pub fn iter_remote_editing_mut(&mut self) -> LineIterMut<'_, '_, L, Line<C>> {
        let Self { lines, brick } = self;
        brick.iter_remote_editable_mut(lines)
    }

    /// Iterates any lines that are currently being edited by the local end, NEWEST to OLDEST
    ///
    /// The returned iterator implements [DoubleEndedIterator], and can be reversed with
    /// [Iterator::rev()] to obtain lines in OLDEST to NEWEST order.
    pub fn iter_local_editing_mut(&mut self) -> LineIterMut<'_, '_, L, Line<C>> {
        let Self { lines, brick } = self;
        brick.iter_local_editable_mut(lines)
    }

    /// Moves the local editing region into a user historical region
    pub fn submit_local_editing(&mut self) {
        self.brick.submit_local_editable();
    }

    /// Moves the remote editing region into a user historical region
    pub fn submit_remote_editing(&mut self) {
        self.brick.submit_remote_editable();
    }

    /// Attempts to append a character to the local editing region
    ///
    /// Does NOT accept control characters, such as `\n`.
    pub fn append_local_char(&mut self, c: u8) -> Result<(), RingLineError> {
        self.get_local_first_writeable()
            .ok_or(RingLineError::Line(LineError::Full))?
            .push(c)?;
        Ok(())
    }

    /// Attempts to append a character to the remote editing region
    ///
    /// Does NOT accept control characters, such as `\n`.
    pub fn append_remote_char(&mut self, c: u8) -> Result<(), RingLineError> {
        self.get_remote_first_writeable()
            .ok_or(RingLineError::Line(LineError::Full))?
            .push(c)?;
        Ok(())
    }

    /// Attempts to remove a character from the local editing region
    pub fn pop_local_char(&mut self) {
        let Self { lines, brick } = self;
        if let Some(cur) = brick.iter_local_editable_mut(lines).next() {
            if cur.is_empty() {
                brick.pop_local_editable_front();
            } else {
                cur.pop();
            }
        }
    }

    /// Attempts to remove a character from the local editing region
    pub fn pop_remote_char(&mut self) {
        let Self { lines, brick } = self;
        if let Some(cur) = brick.iter_remote_editable_mut(lines).next() {
            if cur.is_empty() {
                brick.pop_remote_editable_front();
            } else {
                cur.pop();
            }
        }
    }

    fn get_local_first_writeable(&mut self) -> Option<&mut Line<C>> {
        let Self { lines, brick } = self;
        // If empty, make a new one and return
        // If not empty, is the head writable and !full? => return
        // else, if not full make a new one and return
        // else, remove oldest, make a new one and return
        let mut new = false;
        let wr = if let Some(wr) = brick.local_editable_front() {
            let cur = &lines[wr];
            if cur.is_full() {
                new = true;
                self.brick.insert_local_editable_front().ok()?
            } else {
                wr
            }
        } else {
            new = true;
            self.brick.insert_local_editable_front().ok()?
        };
        let cur = &mut lines[wr];
        if new {
            cur.clear();
            cur.set_status(Source::Local);
        }

        Some(cur)
    }

    fn get_remote_first_writeable(&mut self) -> Option<&mut Line<C>> {
        let Self { lines, brick } = self;
        // If empty, make a new one and return
        // If not empty, is the head writable and !full? => return
        // else, if not full make a new one and return
        // else, remove oldest, make a new one and return
        let mut new = false;
        let wr = if let Some(wr) = brick.remote_editable_front() {
            let cur = &lines[wr];
            if cur.is_full() {
                new = true;
                self.brick.insert_remote_editable_front().ok()?
            } else {
                wr
            }
        } else {
            new = true;
            self.brick.insert_remote_editable_front().ok()?
        };
        let cur = &mut lines[wr];
        if new {
            cur.clear();
            cur.set_status(Source::Remote);
        }

        Some(cur)
    }
}

#[derive(Debug, PartialEq)]
pub enum RingLineError {
    Line(LineError),
}

impl From<LineError> for RingLineError {
    fn from(le: LineError) -> Self {
        RingLineError::Line(le)
    }
}

#[derive(Debug, PartialEq)]
pub enum LineError {
    Full,
    InvalidChar,
    ReadOnly,
    WriteGap,
}

#[derive(Debug, PartialEq, Copy, Clone)]
#[repr(u8)]
pub enum Source {
    Local,
    Remote,
}

#[inline]
pub(crate) fn rot_right<T: Sized>(sli: &mut [T]) {
    let len = sli.len();
    if len <= 1 {
        // Look, it's rotated!
        return;
    }
    unsafe {
        let ptr = sli.as_mut_ptr();
        let last_val = ptr.add(len - 1).read();
        core::ptr::copy(ptr, ptr.add(1), len - 1);
        ptr.write(last_val);
    }
}

#[inline]
pub(crate) fn rot_left<T: Sized>(sli: &mut [T]) {
    let len = sli.len();
    if len <= 1 {
        // Look, it's rotated!
        return;
    }
    unsafe {
        let ptr = sli.as_mut_ptr();
        let first_val = ptr.read();
        core::ptr::copy(ptr.add(1), ptr, len - 1);
        ptr.add(len - 1).write(first_val);
    }
}