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
use crate::bucket::BucketIApi;
use crate::common::page::tree::leaf::BUCKET_LEAF_FLAG;
use crate::cursor::{CursorIApi, InnerCursor};
use crate::tx::TxIApi;
use crate::{BucketApi, BucketImpl, BucketRwImpl, TxImpl, TxRef, TxRwImpl, TxRwRef};
use std::marker::PhantomData;

struct KvIter<'tx: 'p, 'p> {
  c: InnerCursor<'tx>,
  started: bool,
  p: PhantomData<&'p u8>,
}

impl<'tx: 'p, 'p> KvIter<'tx, 'p> {
  pub(crate) fn new(c: InnerCursor<'tx>) -> KvIter<'tx, 'p> {
    KvIter {
      c,
      started: false,
      p: PhantomData,
    }
  }
}

impl<'tx: 'p, 'p> Iterator for KvIter<'tx, 'p> {
  type Item = (&'p [u8], &'p [u8], u32);

  fn next(&mut self) -> Option<Self::Item> {
    if !self.started {
      self.started = true;
      self.c.i_first()
    } else {
      self.c.i_next()
    }
  }
}

pub struct EntryIter<'tx: 'p, 'p> {
  i: KvIter<'tx, 'p>,
}

impl<'tx: 'p, 'p> EntryIter<'tx, 'p> {
  pub(crate) fn new(c: InnerCursor<'tx>) -> EntryIter<'tx, 'p> {
    EntryIter { i: KvIter::new(c) }
  }
}

impl<'tx: 'p, 'p> Iterator for EntryIter<'tx, 'p> {
  type Item = (&'p [u8], &'p [u8]);

  fn next(&mut self) -> Option<Self::Item> {
    for (k, v, flags) in self.i.by_ref() {
      if flags & BUCKET_LEAF_FLAG == 0 {
        return Some((k, v));
      }
    }
    None
  }
}

pub struct BucketIter<'tx: 'p, 'p> {
  i: KvIter<'tx, 'p>,
}

impl<'tx: 'p, 'p> BucketIter<'tx, 'p> {
  pub(crate) fn new(c: InnerCursor<'tx>) -> BucketIter<'tx, 'p> {
    BucketIter { i: KvIter::new(c) }
  }
}

impl<'tx: 'p, 'p> Iterator for BucketIter<'tx, 'p> {
  type Item = (&'p [u8], BucketImpl<'tx, 'p>);

  fn next(&mut self) -> Option<Self::Item> {
    for (k, _, flags) in self.i.by_ref() {
      if flags & BUCKET_LEAF_FLAG != 0 {
        let bucket = BucketImpl::from(self.i.c.bucket.api_bucket(k).unwrap());
        return Some((k, bucket));
      }
    }
    None
  }
}

impl<'tx: 'a, 'a> IntoIterator for &'a TxImpl<'tx> {
  type Item = (&'a [u8], BucketImpl<'tx, 'a>);
  type IntoIter = BucketIter<'tx, 'a>;

  fn into_iter(self) -> Self::IntoIter {
    BucketIter::new(self.tx.api_cursor())
  }
}

impl<'tx: 'a, 'a> IntoIterator for &'a TxRwImpl<'tx> {
  type Item = (&'a [u8], BucketImpl<'tx, 'a>);
  type IntoIter = BucketIter<'tx, 'a>;

  fn into_iter(self) -> Self::IntoIter {
    BucketIter::new(self.tx.api_cursor())
  }
}

impl<'tx: 'a, 'a> IntoIterator for &'a TxRef<'tx> {
  type Item = (&'a [u8], BucketImpl<'tx, 'a>);
  type IntoIter = BucketIter<'tx, 'a>;

  fn into_iter(self) -> Self::IntoIter {
    BucketIter::new(self.tx.api_cursor())
  }
}

impl<'tx: 'a, 'a> IntoIterator for &'a TxRwRef<'tx> {
  type Item = (&'a [u8], BucketImpl<'tx, 'a>);
  type IntoIter = BucketIter<'tx, 'a>;

  fn into_iter(self) -> Self::IntoIter {
    BucketIter::new(self.tx.api_cursor())
  }
}

pub struct BucketIterMut<'tx: 'p, 'p> {
  i: KvIter<'tx, 'p>,
}

impl<'tx: 'p, 'p> BucketIterMut<'tx, 'p> {
  pub(crate) fn new(c: InnerCursor<'tx>) -> BucketIterMut<'tx, 'p> {
    BucketIterMut { i: KvIter::new(c) }
  }
}

impl<'tx: 'p, 'p> Iterator for BucketIterMut<'tx, 'p> {
  type Item = (&'p [u8], BucketRwImpl<'tx, 'p>);

  fn next(&mut self) -> Option<Self::Item> {
    for (k, _, flags) in self.i.by_ref() {
      if flags & BUCKET_LEAF_FLAG != 0 {
        let bucket = BucketRwImpl::from(self.i.c.bucket.api_bucket(k).unwrap());
        return Some((k, bucket));
      }
    }
    None
  }
}

impl<'tx: 'a, 'a> IntoIterator for &'a mut TxRwImpl<'tx> {
  type Item = (&'a [u8], BucketRwImpl<'tx, 'a>);
  type IntoIter = BucketIterMut<'tx, 'a>;

  fn into_iter(self) -> Self::IntoIter {
    BucketIterMut::new(self.tx.api_cursor())
  }
}

impl<'tx: 'a, 'a> IntoIterator for &'a mut TxRwRef<'tx> {
  type Item = (&'a [u8], BucketRwImpl<'tx, 'a>);
  type IntoIter = BucketIterMut<'tx, 'a>;

  fn into_iter(self) -> Self::IntoIter {
    BucketIterMut::new(self.tx.api_cursor())
  }
}

pub enum ValueBucket<'tx: 'p, 'p> {
  Value(&'p [u8]),
  Bucket(BucketImpl<'tx, 'p>),
}

pub struct ValueBucketIter<'tx: 'p, 'p> {
  i: KvIter<'tx, 'p>,
}

impl<'tx: 'p, 'p> ValueBucketIter<'tx, 'p> {
  pub(crate) fn new(c: InnerCursor<'tx>) -> ValueBucketIter<'tx, 'p> {
    ValueBucketIter { i: KvIter::new(c) }
  }
}

impl<'tx: 'p, 'p> Iterator for ValueBucketIter<'tx, 'p> {
  type Item = (&'p [u8], ValueBucket<'tx, 'p>);

  fn next(&mut self) -> Option<Self::Item> {
    if let Some((k, v, flags)) = self.i.by_ref().next() {
      return if flags & BUCKET_LEAF_FLAG == 0 {
        Some((k, ValueBucket::Value(v)))
      } else {
        let bucket = BucketImpl::from(self.i.c.bucket.api_bucket(k).unwrap());
        Some((k, ValueBucket::Bucket(bucket)))
      };
    }
    None
  }
}

#[derive(Debug)]
pub enum ValueBucketSeq<'p> {
  Value(&'p [u8]),
  BucketSeq(u64),
}

impl<'p> ValueBucketSeq<'p> {
  pub fn len(&self) -> usize {
    match self {
      ValueBucketSeq::Value(v) => v.len(),
      ValueBucketSeq::BucketSeq(_) => 0,
    }
  }
}

pub struct DbWalker<'tx: 'p, 'p> {
  root_buckets: BucketIter<'tx, 'p>,
  path: Vec<&'p [u8]>,
  cursors: Vec<ValueBucketIter<'tx, 'p>>,
  bucket_seq: bool,
  p: PhantomData<&'p u8>,
}

impl<'tx: 'p, 'p> DbWalker<'tx, 'p> {
  pub(crate) fn new(root_cursor: InnerCursor<'tx>) -> DbWalker<'tx, 'p> {
    DbWalker {
      root_buckets: BucketIter::new(root_cursor),
      path: Vec::new(),
      cursors: Vec::new(),
      bucket_seq: false,
      p: PhantomData,
    }
  }

  pub fn path(&self) -> &[&'p [u8]] {
    if self.bucket_seq {
      self.path.split_last().unwrap().1
    } else {
      &self.path
    }
  }
}

impl<'tx: 'p, 'p> Iterator for DbWalker<'tx, 'p> {
  type Item = (&'p [u8], ValueBucketSeq<'p>);

  fn next(&mut self) -> Option<Self::Item> {
    self.bucket_seq = false;
    loop {
      if self.cursors.is_empty() {
        return if let Some((k, b)) = self.root_buckets.next() {
          let seq = b.sequence();
          self.bucket_seq = true;
          self.path.push(k);
          let i = ValueBucketIter::new(b.b.i_cursor());
          self.cursors.push(i);
          Some((k, ValueBucketSeq::BucketSeq(seq)))
        } else {
          None
        };
      }
      if let Some((k, vb)) = self.cursors.last_mut().and_then(|i| i.next()) {
        return match vb {
          ValueBucket::Value(v) => Some((k, ValueBucketSeq::Value(v))),
          ValueBucket::Bucket(b) => {
            let seq = b.sequence();
            self.bucket_seq = true;
            self.path.push(k);
            let i = ValueBucketIter::new(b.b.i_cursor());
            self.cursors.push(i);
            Some((k, ValueBucketSeq::BucketSeq(seq)))
          }
        };
      } else {
        self.path.pop();
        self.cursors.pop();
      }
    }
  }
}

#[cfg(test)]
mod test {
  use crate::iter::DbWalker;
  use crate::test_support::TestDb;
  use crate::tx::TxIApi;
  use crate::{BucketApi, BucketRwApi, DbRwAPI, TxRwRefApi};

  #[test]
  fn test_tx_for_each_no_error() -> crate::Result<()> {
    let mut db = TestDb::new()?;
    db.update(|mut tx| {
      let mut b = tx.create_bucket("widgets")?;
      b.put("foo", "bar")?;

      for (k, mut b) in tx.iter_mut_buckets() {
        let mut wb = b.create_bucket("woojits")?;
        wb.put("fooz", "ball")?;
        for (k, wb) in b.iter_buckets() {
          println!("{:?}", k);
          for (k, v) in wb.iter_entries() {
            println!("{:?}", k);
          }
        }
      }
      Ok(())
    })?;
    Ok(())
  }

  #[test]
  fn test_tx_walk_no_error() -> crate::Result<()> {
    let mut db = TestDb::new()?;
    db.update(|mut tx| {
      let mut b = tx.create_bucket("widgets")?;
      b.put("foo1", "bar")?;
      b.put("foo2", "bar")?;
      let mut wb = b.create_bucket("woojits")?;
      wb.set_sequence(1)?;
      wb.put("fooz1", "ball")?;
      wb.put("fooz2", "ball")?;
      let mut hb = wb.create_bucket("hoojits")?;
      hb.set_sequence(2)?;
      hb.put("fooz1", "bill")?;
      hb.put("fooz2", "bill")?;
      let mut wb = b.create_bucket("wajits")?;
      wb.set_sequence(3)?;
      wb.put("fooz1", "balls")?;
      wb.put("fooz2", "balls")?;
      let mut pb = tx.create_bucket_path(&["one", "two", "three", "four"])?;
      pb.set_sequence(4)?;
      pb.put("five", "six")?;
      Ok(())
    })?;
    let tx = db.begin_tx()?;
    let mut w = DbWalker::new(tx.tx.api_cursor());
    while let Some(i) = w.next() {
      let path = w.path();
      println!("{:?}: {:?}", path, i);
    }
    drop(w);
    let c = DbWalker::new(tx.tx.api_cursor()).count();
    println!("{:?}", c);
    Ok(())
  }
}