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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
use std::ops::Range;
#[cfg(feature = "pack")]
use std::{
    io::{Read, Result, Write},
    path::Path,
};

#[cfg(feature = "pack")]
use super::packed_sa::PackedSuffixArray;
use super::saca::saca;
use super::utils::*;

/// Suffix array for byte string.
#[derive(Clone)]
pub struct SuffixArray<'a> {
    s: &'a [u8],
    sa: Vec<u32>,
    bkt: Option<Vec<u32>>,
}

impl<'a> SuffixArray<'a> {
    // Construct new suffix array for given byte string.
    pub fn new(s: &'a [u8]) -> Self {
        let mut sa = vec![0; s.len() + 1];
        saca(s, &mut sa[..]);
        SuffixArray { s, sa, bkt: None }
    }

    // Construct suffix array in place.
    pub fn set(&mut self, s: &'a [u8]) {
        self.sa.resize(s.len() + 1, 0);
        saca(s, &mut self.sa[..]);
    }

    // Release the unused memory of suffix array.
    pub fn fit(&mut self) {
        self.sa.shrink_to_fit()
    }

    /// Length of the underlying byte string.
    pub fn len(&self) -> usize {
        self.s.len()
    }

    /// Test if the underlying byte string is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Take out the suffix array and its corresponding byte string.
    pub fn into_parts(self) -> (&'a [u8], Vec<u32>) {
        (self.s, self.sa)
    }

    /// Compose existed suffix array and its corresponding byte string
    /// together, and checks the integrity.
    pub fn from_parts(s: &'a [u8], sa: Vec<u32>) -> Option<Self> {
        let compose = SuffixArray { s, sa, bkt: None };
        if compose.check_integrity() {
            Some(compose)
        } else {
            None
        }
    }

    /// Compose existed suffix array and its corresponding byte string
    /// together without integrity check.
    pub unsafe fn unchecked_from_parts(s: &'a [u8], sa: Vec<u32>) -> Self {
        SuffixArray { s, sa, bkt: None }
    }

    fn check_integrity(&self) -> bool {
        if self.s.len() + 1 != self.sa.len() {
            return false;
        }
        for i in 1..self.sa.len() {
            let x = &self.s[self.sa[i - 1] as usize..];
            let y = &self.s[self.sa[i] as usize..];
            if x >= y {
                return false;
            }
        }
        true
    }

    /// Enable bucket pointers to speed up large amount of pattern searching.
    ///
    /// The overhead is about 257 KiB.
    pub fn enable_buckets(&mut self) {
        if self.bkt.is_some() {
            return;
        }

        // the layout is [$; (0, $), (0, 0), ..., (0, 255); ...; (255, $), (255, 0), ..., (255, 255)]
        let mut bkt = vec![0; 256 * 257 + 1];

        // count occurrences.
        bkt[0] = 1;
        if self.s.len() > 0 {
            for i in 0..self.s.len() - 1 {
                let c0 = unsafe { *self.s.get_unchecked(i) };
                let c1 = unsafe { *self.s.get_unchecked(i + 1) };
                let idx = (c0 as usize * 257) + (c1 as usize + 1) + 1;
                bkt[idx] += 1;
            }
            let c0 = unsafe { *self.s.get_unchecked(self.s.len() - 1) };
            let idx = (c0 as usize * 257) + 1;
            bkt[idx] += 1;
        }

        // store the right boundaries of each bucket.
        let mut sum = 0;
        for p in bkt.iter_mut() {
            sum += *p;
            *p = sum;
        }

        self.bkt = Some(bkt);
    }

    /// Get the bucket of pattern.
    #[inline]
    fn get_bucket(&self, pat: &[u8]) -> Range<usize> {
        if let Some(ref bkt) = self.bkt {
            if pat.len() > 1 {
                // sub-bucket (c0, c1).
                let c0 = pat[0];
                let c1 = pat[1];
                let idx = (c0 as usize * 257) + (c1 as usize + 1) + 1;
                bkt[idx - 1] as usize..bkt[idx] as usize
            } else if pat.len() == 1 {
                // top-level bucket (c0, $)..=(c0, 255).
                let c0 = pat[0];
                let start_idx = c0 as usize * 257;
                let end_idx = start_idx + 257;
                bkt[start_idx] as usize..bkt[end_idx] as usize
            } else {
                // the sentinel bucket.
                0..1
            }
        } else {
            0..self.sa.len()
        }
    }

    /// Get the top-level bucket.
    #[inline]
    fn get_top_bucket(&self, pat: &[u8]) -> Range<usize> {
        if let Some(ref bkt) = self.bkt {
            if pat.len() > 0 {
                let c0 = pat[0];
                let start_idx = c0 as usize * 257;
                let end_idx = start_idx + 257;
                bkt[start_idx] as usize..bkt[end_idx] as usize
            } else {
                0..1
            }
        } else {
            0..self.sa.len()
        }
    }

    /// Test if it contains the given pattern.
    pub fn contains(&self, pat: &[u8]) -> bool {
        let s = self.s;
        let sa = &self.sa[self.get_bucket(pat)];

        sa.binary_search_by_key(&pat, |&i| trunc(&s[i as usize..], pat.len()))
            .is_ok()
    }

    /// Search for all the unsorted occurrence of given pattern (can overlap).
    pub fn search_all(&self, pat: &[u8]) -> &[u32] {
        let s = self.s;
        let sa = if pat.len() > 0 {
            &self.sa[self.get_bucket(pat)]
        } else {
            &self.sa[..]
        };

        let mut i = 0;
        let mut k = sa.len();
        while i < k {
            let m = i + (k - i) / 2;
            if pat > &s[sa[m] as usize..] {
                i = m + 1;
            } else {
                k = m;
            }
        }

        let mut j = i;
        let mut k = sa.len();
        while j < k {
            let m = j + (k - j) / 2;
            if s[sa[m] as usize..].starts_with(pat) {
                j = m + 1;
            } else {
                k = m;
            }
        }

        &sa[i..j]
    }

    /// Search for a sub-string that has the longest common prefix of the given pattern.
    pub fn search_lcp(&self, pat: &[u8]) -> Range<usize> {
        let s = self.s;
        let sa = &self.sa[self.get_bucket(pat)];

        if sa.len() == 0 {
            // pat.len() > 0, for any i < s.len(): lcp(pat, s[i..]) <= 1.
            let sa = &self.sa[self.get_top_bucket(pat)];
            if sa.len() > 0 {
                // there exists i < s.len(): lcp(pat, s[i..]) == 1.
                let i = sa[0] as usize;
                return i..i + 1;
            } else {
                // for any i < s.len(): lcp(pat, s[i..]) == 0.
                return self.s.len()..self.s.len();
            }
        }

        match sa.binary_search_by(|&i| s[i as usize..].cmp(pat)) {
            Ok(i) => {
                // find a suffix equals to the pattern.
                let start = sa[i] as usize;
                start..s.len()
            }
            Err(i) => {
                // find a position to insert the pattern.
                if i > 0 && i < sa.len() {
                    let start_a = sa[i - 1] as usize;
                    let start_b = sa[i] as usize;
                    let len_a = lcp(pat, &s[start_a..]);
                    let len_b = lcp(pat, &s[start_b..]);
                    if len_a > len_b {
                        start_a..start_a + len_a
                    } else {
                        start_b..start_b + len_b
                    }
                } else if i == 0 {
                    let start = sa[i] as usize;
                    let len = lcp(pat, &s[start..]);
                    start..start + len
                } else {
                    let start = sa[i - 1] as usize;
                    let len = lcp(pat, &s[start..]);
                    start..start + len
                }
            }
        }
    }

    /// Dump the suffix array.
    #[cfg(feature = "pack")]
    pub fn dump<W: Write>(&self, file: W) -> Result<()> {
        let psa = PackedSuffixArray::from_sa(&self.sa[..]);
        psa.dump(file)
    }

    /// Create a file and write the suffix array.
    #[cfg(feature = "pack")]
    pub fn dump_file<P: AsRef<Path>>(&self, name: P) -> Result<()> {
        use std::fs::File;
        use std::io::BufWriter;

        let file = BufWriter::new(File::create(name)?);
        let psa = PackedSuffixArray::from_sa(&self.sa[..]);
        psa.dump(file)
    }

    /// Dump the suffix array as bytes.
    #[cfg(feature = "pack")]
    pub fn dump_bytes(&self) -> Result<Vec<u8>> {
        let psa = PackedSuffixArray::from_sa(&self.sa[..]);
        psa.dump_bytes()
    }

    /// Load suffix array from reader without integrity check.
    #[cfg(feature = "pack")]
    pub unsafe fn unchecked_load<R: Read>(
        s: &'a [u8],
        file: R,
    ) -> Result<Self> {
        let psa = PackedSuffixArray::load(file)?;
        let sa = psa.into_sa();
        Ok(Self::unchecked_from_parts(s, sa))
    }

    /// Load suffix array from reader.
    #[cfg(feature = "pack")]
    pub fn load<R: Read>(s: &'a [u8], file: R) -> Result<Self> {
        use std::io::{Error, ErrorKind};

        let sa = unsafe { Self::unchecked_load(s, file)? };
        if !sa.check_integrity() {
            Err(Error::new(
                ErrorKind::InvalidData,
                "inconsistent suffix array",
            ))
        } else {
            Ok(sa)
        }
    }

    /// Load suffix array from a file without integrity check.
    #[cfg(feature = "pack")]
    pub unsafe fn unchecked_load_file<P: AsRef<Path>>(
        s: &'a [u8],
        name: P,
    ) -> Result<Self> {
        use std::fs::File;
        use std::io::BufReader;

        let file = BufReader::new(File::open(name)?);
        Self::unchecked_load(s, file)
    }

    /// Load suffix array from a file.
    #[cfg(feature = "pack")]
    pub fn load_file<P: AsRef<Path>>(s: &'a [u8], name: P) -> Result<Self> {
        use std::io::{Error, ErrorKind};

        let sa = unsafe { Self::unchecked_load_file(s, name)? };
        if !sa.check_integrity() {
            Err(Error::new(
                ErrorKind::InvalidData,
                "inconsistent suffix array",
            ))
        } else {
            Ok(sa)
        }
    }

    /// Load suffix array from bytes without integrity check.
    #[cfg(feature = "pack")]
    pub unsafe fn unchecked_load_bytes(
        s: &'a [u8],
        bytes: &[u8],
    ) -> Result<Self> {
        let psa = PackedSuffixArray::load_bytes(bytes)?;
        let sa = psa.into_sa();
        Ok(Self::unchecked_from_parts(s, sa))
    }

    /// Load suffix array from bytes.
    #[cfg(feature = "pack")]
    pub fn load_bytes(s: &'a [u8], bytes: &[u8]) -> Result<Self> {
        use std::io::{Error, ErrorKind};

        let sa = unsafe { Self::unchecked_load_bytes(s, bytes)? };
        if !sa.check_integrity() {
            Err(Error::new(
                ErrorKind::InvalidData,
                "inconsistent suffix array",
            ))
        } else {
            Ok(sa)
        }
    }
}

impl<'a> From<SuffixArray<'a>> for Vec<u32> {
    fn from(sa: SuffixArray<'a>) -> Vec<u32> {
        sa.sa
    }
}

impl<'a> AsRef<[u8]> for SuffixArray<'a> {
    fn as_ref(&self) -> &[u8] {
        self.s
    }
}