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
use std::cmp::{max, min};
use std::fmt;
use std::ops::RangeFrom;

const INITIAL_NUM_BINS: i32 = 128;
const GROW_LEFT_BY: i32 = 128;

fn new_vec(size: usize) -> Vec<u64> {
    vec![0; size]
}

#[derive(Clone)]
pub struct Store {
    bins: Vec<u64>,
    count: u64,
    min_key: i32,
    max_key: i32,
    max_num_bins: i32,
}

impl Store {
    pub fn new(max_num_bins: i32) -> Self {
        Store {
            bins: new_vec(INITIAL_NUM_BINS as usize),
            count: 0,
            min_key: 0,
            max_key: 0,
            max_num_bins,
        }
    }

    pub fn length(&self) -> i32 {
        self.bins.len() as i32
    }

    pub fn add(&mut self, key: i32) {
        if self.count == 0 {
            self.max_key = key;
            self.min_key = key - (self.length() as i32) + 1;
        }
        if key < self.min_key {
            self.grow_left(key)
        } else if key > self.max_key {
            self.grow_right(key)
        }

        let idx = max(key - self.min_key, 0) as usize;

        self.bins[idx] += 1;
        self.count += 1;
    }

    pub fn key_at_rank(&self, rank: u64) -> i32 {
        let mut n = 0;
        for (i, bin) in self.bins.iter().enumerate() {
            n += *bin;
            if n >= rank {
                return i as i32 + self.min_key;
            }
        }

        self.max_key
    }

    fn grow_left(&mut self, key: i32) {
        if self.min_key < key || self.length() >= self.max_num_bins {
            return;
        }

        let mut min_key;
        if self.max_key - key >= self.max_num_bins as i32 {
            min_key = self.max_key - (self.max_num_bins as i32) + 1
        } else {
            min_key = self.min_key;

            // XXX: remove this loop
            while min_key > key {
                min_key -= GROW_LEFT_BY;
            }
        }

        let mut tmp_bins = new_vec((self.max_key - min_key + 1) as usize);
        let tmp_slice = &mut tmp_bins[self.convert_range((self.min_key - min_key)..)];
        tmp_slice.copy_from_slice(&self.bins);
        self.bins = tmp_bins;
        self.min_key = min_key;
    }

    fn grow_right(&mut self, key: i32) {
        if self.max_key > key {
            return;
        }

        if key - self.max_key >= self.max_num_bins {
            self.bins = new_vec(self.max_num_bins as usize);
            self.max_key = key;
            self.min_key = key - self.max_num_bins + 1;
            self.bins[0] = self.count
        } else if key - self.min_key >= self.max_num_bins {
            let min_key = key - self.max_num_bins + 1;

            let mut n = 0;
            for i in self.min_key..min(min_key, self.max_key + 1) {
                n += self.bins[(i - self.min_key) as usize];
            }

            if self.length() < self.max_num_bins {
                let mut tmp_bins = new_vec(self.max_num_bins as usize);
                let src_slice = &self.bins[self.convert_range((min_key - self.min_key)..)];
                let tmp_slice = &mut tmp_bins[..src_slice.len()];
                tmp_slice.copy_from_slice(src_slice);
                self.bins = tmp_bins;
            } else {
                self.bins.drain(0..((min_key - self.min_key) as usize));
                for _i in (self.max_key - min_key + 1)..self.max_num_bins {
                    self.bins.push(0);
                }
            }
            self.max_key = key;
            self.min_key = min_key;
            self.bins[0] += n;
        } else {
            let new_sz = (key - self.min_key + 1) as usize;
            let mut tmp_bins = new_vec(new_sz);
            let tmp_slice = &mut tmp_bins[0..self.bins.len()];
            tmp_slice.copy_from_slice(&self.bins);
            self.bins = tmp_bins;
            self.max_key = key;
        }
    }

    pub fn count(&self) -> u64 {
        self.count
    }

    pub fn merge(&mut self, o: &Store) {
        if o.count == 0 {
            return;
        }

        if self.count == 0 {
            self.copy(o);
            return;
        }

        if self.max_key > o.max_key {
            if o.min_key < self.min_key {
                self.grow_left(o.min_key)
            }
            for i in max(self.min_key, o.min_key)..(o.max_key + 1) {
                self.bins[(i - self.min_key) as usize] += o.bins[(i - o.min_key) as usize];
            }
            let mut n = 0;
            for i in o.min_key..self.min_key {
                n += o.bins[(i - o.min_key) as usize];
            }
            self.bins[0] += n;
        } else {
            if o.min_key < self.min_key {
                let mut tmp_bins = o.bins.clone();
                for i in self.min_key..(self.max_key + 1) {
                    tmp_bins[(i - o.min_key) as usize] += self.bins[(i - self.min_key) as usize];
                }
                self.bins = tmp_bins;
                self.max_key = o.max_key;
                self.min_key = o.min_key
            } else {
                self.grow_right(o.max_key);
                for i in o.min_key..(o.max_key + 1) {
                    self.bins[(i - self.min_key) as usize] += o.bins[(i - o.min_key) as usize];
                }
            }
        }
        self.count += o.count;
    }

    fn copy(&mut self, o: &Store) {
        self.bins = o.bins.clone();
        self.min_key = o.min_key;
        self.max_key = o.max_key;
        self.count = o.count;
    }

    fn convert_range(&self, range: RangeFrom<i32>) -> RangeFrom<usize> {
        assert!(range.start >= 0);
        RangeFrom {
            start: range.start as usize,
        }
    }
}

impl fmt::Debug for Store {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Store {{ bins: [ ")?;
        for i in 0..self.bins.len() {
            if self.bins[i] > 0 {
                write!(
                    f,
                    "[{}] {}: {}, ",
                    i,
                    (i as i32) + self.min_key,
                    self.bins[i]
                )?;
            }
        }
        writeln!(
            f,
            "] count: {}, min_key: {}, max_key: {} }}",
            self.count, self.min_key, self.max_key
        )
    }
}

#[cfg(test)]
mod tests {
    use crate::store::Store;

    #[test]
    fn test_simple_store() {
        let mut s = Store::new(2048);

        for i in 0..2048 {
            s.add(i);
        }
    }

    #[test]
    fn test_simple_store_rev() {
        let mut s = Store::new(2048);

        for i in 2048..0 {
            s.add(i);
        }
    }
}