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
use crate::{
    address::Address,
    error::{PRes, PersyError},
    persy::PersyImpl,
    transaction::Transaction,
};
use data_encoding::BASE32_DNSSEC;
pub use std::fs::OpenOptions;
use std::{fmt, io::Write, str};
use unsigned_varint::{
    decode::{u32 as u32_vdec, u64 as u64_vdec},
    encode::{u32 as u32_venc, u32_buffer, u64 as u64_venc, u64_buffer},
};

fn write_id(f: &mut fmt::Formatter, id: u32) -> fmt::Result {
    let mut buffer = Vec::new();
    buffer
        .write_all(u32_venc(id, &mut u32_buffer()))
        .expect("no failure expected only memory allocation");
    buffer.push(0b0101_0101);
    write!(f, "{}", BASE32_DNSSEC.encode(&buffer))
}

fn read_id(s: &str) -> PRes<u32> {
    let bytes = BASE32_DNSSEC.decode(s.as_bytes())?;
    Ok(u32_vdec(&bytes)?.0)
}

#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Debug)]
pub struct RecRef {
    pub page: u64,
    pub pos: u32,
}

impl RecRef {
    #[inline]
    pub fn new(page: u64, pos: u32) -> RecRef {
        RecRef { page, pos }
    }
}

impl fmt::Display for RecRef {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut buffer = Vec::new();
        buffer
            .write_all(u64_venc(self.page, &mut u64_buffer()))
            .expect("no failure expected only memory allocation");
        buffer.push(0b0101_0101);
        buffer
            .write_all(u32_venc(self.pos, &mut u32_buffer()))
            .expect("no failure expected only memory allocation");
        write!(f, "{}", BASE32_DNSSEC.encode(&buffer))
    }
}

impl std::str::FromStr for RecRef {
    type Err = PersyError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let bytes = BASE32_DNSSEC.decode(s.as_bytes())?;
        let (page, rest) = u64_vdec(&bytes)?;
        let (pos, _) = u32_vdec(&rest[1..])?;
        Ok(RecRef::new(page, pos))
    }
}

/// Identifier of a persistent record, can be used for read, update or delete the record
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Debug)]
pub struct PersyId(pub(crate) RecRef);

impl fmt::Display for PersyId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::str::FromStr for PersyId {
    type Err = PersyError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(PersyId(s.parse()?))
    }
}

/// Represents a looked-up segment
///
/// # Invalidation
/// It may be only valid inside a specific transaction if the segment is
/// created and destroyed inside it.
/// When a segment is deleted, the corresponding SegmentId becomes invalid.
///
/// # Serialization
/// This type supports serialization,
/// but it contains information about a possible current transaction,
/// which is NOT serialized.
/// It does NOT serialize to the segment name.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SegmentId {
    pub(crate) id: u32,
}

impl SegmentId {
    #[inline]
    pub(crate) fn new(id: u32) -> Self {
        SegmentId { id }
    }
}

pub trait ToSegmentId {
    fn to_segment_id(self, address: &Address) -> PRes<SegmentId>;
    fn to_segment_id_tx(self, persy: &PersyImpl, tx: &Transaction) -> PRes<(SegmentId, bool)>;
}

impl ToSegmentId for SegmentId {
    #[inline]
    fn to_segment_id(self, _address: &Address) -> PRes<SegmentId> {
        Ok(self)
    }
    #[inline]
    fn to_segment_id_tx(self, _persy: &PersyImpl, tx: &Transaction) -> PRes<(SegmentId, bool)> {
        // Is safe to check only if is created in tx, because a segment cannot be created and
        // dropped in the same tx
        let id = self.id;
        Ok((self, tx.segment_created_in_tx(id)))
    }
}

impl<T: AsRef<str>> ToSegmentId for T {
    #[inline]
    fn to_segment_id(self, address: &Address) -> PRes<SegmentId> {
        address
            .segment_id(self.as_ref())?
            .map_or(Err(PersyError::SegmentNotFound), |id| Ok(SegmentId { id }))
    }
    #[inline]
    fn to_segment_id_tx(self, persy: &PersyImpl, tx: &Transaction) -> PRes<(SegmentId, bool)> {
        persy
            .check_segment_tx(tx, self.as_ref())
            .map(|(cr_in_tx, id)| (SegmentId::new(id), cr_in_tx))
    }
}

impl fmt::Display for SegmentId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write_id(f, self.id)
    }
}

impl std::str::FromStr for SegmentId {
    type Err = PersyError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(SegmentId::new(read_id(s)?))
    }
}

/// Unique identifier of an index
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Debug)]
pub struct IndexId {
    id: u32,
}

impl IndexId {
    pub(crate) fn new(id: u32) -> IndexId {
        IndexId { id }
    }
}

impl fmt::Display for IndexId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write_id(f, self.id)
    }
}

impl std::str::FromStr for IndexId {
    type Err = PersyError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(IndexId::new(read_id(s)?))
    }
}

#[cfg(test)]
mod tests {
    use super::{IndexId, RecRef, SegmentId};

    #[test]
    fn test_persy_id_string() {
        let id = RecRef::new(20, 30);
        let s = format!("{}", id);
        assert_eq!(s.parse::<RecRef>().ok(), Some(id));
    }

    #[test]
    fn test_persy_id_parse_failure() {
        let s = "ACCC";
        assert!(s.parse::<RecRef>().is_err());
    }

    #[test]
    fn test_segmend_id_string() {
        let id = SegmentId::new(20);
        let s = format!("{}", id);
        assert_eq!(s.parse::<SegmentId>().ok(), Some(id));
    }

    #[test]
    fn test_segment_id_parse_failure() {
        let s = "ACCC";
        assert!(s.parse::<SegmentId>().is_err());
    }

    #[test]
    fn test_index_id_string() {
        let id = IndexId::new(20);
        let s = format!("{}", id);
        assert_eq!(s.parse::<IndexId>().ok(), Some(id));
    }

    #[test]
    fn test_index_id_parse_failure() {
        let s = "ACCC";
        assert!(s.parse::<IndexId>().is_err());
    }
}