utf8_read/
stream_position.rs

1//a StreamPosition
2/// This representes the position of a character within a UTF8 stream
3#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
4pub struct StreamPosition {
5    /// Byte offset from start of file - starting at 0
6    byte     : usize,
7    /// Line number in the file - starting at 1
8    line_num : usize,
9    /// Character offset within the file - starting at 1
10    char_ofs : usize,
11}
12
13impl StreamPosition {
14    //fp new
15    /// Constructs a new [StreamPosition] for the default of byte 0,
16    /// first line, first character
17    pub fn new() -> Self {
18        Self { byte:0, line_num:1, char_ofs:1 }
19    }
20
21    //fp of_blc
22    /// Construct a new [StreamPosition] from byte, line and character offset
23    pub fn of_blc(byte:usize, line_num:usize, char_ofs:usize) -> Self {
24        Self { byte, line_num, char_ofs }
25    }
26
27    //mp move_on_bytes
28    /// Move the byte count on (to get past a bad UTF encoding, for example)
29    #[inline]
30    pub(crate) fn move_on_bytes(&mut self, n:usize) {
31        self.byte += n;
32    }
33
34    //mp move_by
35    /// Move the [StreamPosition] on by a number of bytes, and a
36    /// particular character
37    #[inline]
38    pub(crate) fn move_by(&mut self, n:usize, ch:char) {
39        self.byte += n;
40        match ch {
41            '\n' => {
42                self.line_num += 1;
43                self.char_ofs = 1;
44            }
45            _ => {
46                self.char_ofs += 1;
47            }
48        }
49    }
50
51    //mp byte
52    /// Find the byte that the [StreamPosition] holds
53    #[inline]
54    pub fn byte(&self) -> usize {
55        self.byte
56    }
57
58
59    //mp line_position
60    /// Get the line number and character within the line of the [StreamPosition]
61    #[inline]
62    pub fn line_position(&self) -> (usize, usize) {
63        (self.line_num, self.char_ofs)
64    }
65
66    //zz All done
67}
68
69
70//ip Display for StreamPosition
71impl std::fmt::Display for StreamPosition {
72    //mp fmt - format for humans
73    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
74        write!(f, "line {} char {}", self.line_num, self.char_ofs)
75    }
76}
77
78