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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
use crate::cassandra::error::*;
use crate::cassandra::field::Field;
use crate::cassandra::schema::aggregate_meta::AggregateMeta;
use crate::cassandra::schema::column_meta::ColumnMeta;
use crate::cassandra::schema::function_meta::FunctionMeta;
use crate::cassandra::schema::keyspace_meta::KeyspaceMeta;
use crate::cassandra::schema::table_meta::TableMeta;
use crate::cassandra::util::{Protected, ProtectedInner};
use crate::cassandra::value::Value;

// use cassandra_sys::CassIteratorType as _CassIteratorType;
use crate::cassandra_sys::cass_false;
use crate::cassandra_sys::CassIterator as _CassIterator;
// use cassandra_sys::cass_iterator_type;
use crate::cassandra_sys::cass_iterator_free;
use crate::cassandra_sys::cass_iterator_get_aggregate_meta;
use crate::cassandra_sys::cass_iterator_get_column_meta;
use crate::cassandra_sys::cass_iterator_get_function_meta;
use crate::cassandra_sys::cass_iterator_get_keyspace_meta;
use crate::cassandra_sys::cass_iterator_get_map_key;
use crate::cassandra_sys::cass_iterator_get_map_value;
use crate::cassandra_sys::cass_iterator_get_meta_field_name;
use crate::cassandra_sys::cass_iterator_get_meta_field_value;
use crate::cassandra_sys::cass_iterator_get_table_meta;
use crate::cassandra_sys::cass_iterator_get_user_type_field_name;
use crate::cassandra_sys::cass_iterator_get_user_type_field_value;
use crate::cassandra_sys::cass_iterator_get_value;
use crate::cassandra_sys::cass_iterator_next;
use crate::cassandra_sys::cass_true;
use crate::cassandra_sys::CassKeyspaceMeta;
use crate::cassandra_sys::CassSchemaMeta;
use crate::cassandra_sys::CassTableMeta;
use crate::cassandra_sys::CassValue as _CassValue;

use std::marker::PhantomData;
use std::{slice, str};

/// Iterator that only allows access to a single item at a time. You must stop
/// using the returned item before getting the next.
///
/// Ultimately we will move to use a common crate for this, but to date
/// there is no good crate to follow.
/// https://blog.rust-lang.org/2022/11/03/Rust-1.65.0.html#generic-associated-types-gats
/// and https://github.com/Crazytieguy/gat-lending-iterator were references
/// for this code.
///
/// The idiomatic way to work with this trait is as follows:
///
/// ```
/// # use cassandra_cpp::*;
/// # struct MyLI;
/// # impl LendingIterator for MyLI {
/// #   type Item<'a> = ();
/// #   fn next<'a>(&'a mut self) -> Option<Self::Item<'a>> { None }
/// #   fn size_hint(&self) -> (usize, Option<usize>) { (0, Some(0)) }
/// # }
/// # let mut lending_iterator = MyLI;
/// while let Some(row) = lending_iterator.next() {
///   // ... do something with `row` ...
/// }
/// ```
pub trait LendingIterator {
    /// The type of each item.
    type Item<'a>
    where
        Self: 'a;

    /// Retrieve the next item from the iterator; it lives only as long as the
    /// mutable reference to the iterator.
    fn next(&mut self) -> Option<Self::Item<'_>>;

    /// Minimum and optional maximum expected length of the iterator.
    /// Default implementation returns `(0, None)`.
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }
}

/// Iterator over the aggregates in the keyspace.
///
/// A Cassandra iterator is a `LendingIterator` because it borrows from some
/// underlying value, but owns a single item. Each time `next()` is invoked it
/// decodes the current item into that item, thus invalidating its previous
/// value.
#[derive(Debug)]
pub struct AggregateIterator<'a>(*mut _CassIterator, PhantomData<&'a CassKeyspaceMeta>);

// The underlying C type has no thread-local state, and forbids only concurrent
// mutation/free: https://datastax.github.io/cpp-driver/topics/#thread-safety
unsafe impl Send for AggregateIterator<'_> {}
unsafe impl Sync for AggregateIterator<'_> {}

impl Drop for AggregateIterator<'_> {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl LendingIterator for AggregateIterator<'_> {
    type Item<'a> = AggregateMeta<'a> where Self: 'a;
    fn next(&mut self) -> Option<<Self as LendingIterator>::Item<'_>> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => {
                    let field_value = cass_iterator_get_aggregate_meta(self.0);
                    Some(AggregateMeta::build(field_value))
                }
            }
        }
    }
}

/// Iterator over the fields of a UDT
///
/// A Cassandra iterator is a `LendingIterator` because it borrows from some
/// underlying value, but owns a single item. Each time `next()` is invoked it
/// decodes the current item into that item, thus invalidating its previous
/// value.
#[derive(Debug)]
pub struct UserTypeIterator<'a>(*mut _CassIterator, PhantomData<&'a _CassValue>);

// The underlying C type has no thread-local state, and forbids only concurrent
// mutation/free: https://datastax.github.io/cpp-driver/topics/#thread-safety
unsafe impl Send for UserTypeIterator<'_> {}
unsafe impl Sync for UserTypeIterator<'_> {}

impl Drop for UserTypeIterator<'_> {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl LendingIterator for UserTypeIterator<'_> {
    type Item<'a> = (String, Value<'a>) where Self: 'a;
    fn next(&mut self) -> Option<<Self as LendingIterator>::Item<'_>> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some((self.get_field_name(), self.get_field_value())),
            }
        }
    }
}

impl UserTypeIterator<'_> {
    fn get_field_name(&self) -> String {
        unsafe {
            let mut name = std::ptr::null();
            let mut name_length = 0;
            cass_iterator_get_user_type_field_name(self.0, &mut name, &mut name_length)
                .to_result(())
                .and_then(|_| {
                    let slice = slice::from_raw_parts(name as *const u8, name_length);
                    let name = str::from_utf8(slice)?.to_owned();
                    Ok(name)
                })
                .expect("Cassandra error during iteration")
        }
    }

    fn get_field_value(&self) -> Value {
        unsafe { Value::build(cass_iterator_get_user_type_field_value(self.0)) }
    }
}

/// Iterator over the functions in a keyspace.
///
/// A Cassandra iterator is a `LendingIterator` because it borrows from some
/// underlying value, but owns a single item. Each time `next()` is invoked it
/// decodes the current item into that item, thus invalidating its previous
/// value.
#[derive(Debug)]
pub struct FunctionIterator<'a>(*mut _CassIterator, PhantomData<&'a CassKeyspaceMeta>);

// The underlying C type has no thread-local state, and forbids only concurrent
// mutation/free: https://datastax.github.io/cpp-driver/topics/#thread-safety
unsafe impl Send for FunctionIterator<'_> {}
unsafe impl Sync for FunctionIterator<'_> {}

impl LendingIterator for FunctionIterator<'_> {
    type Item<'a> = FunctionMeta<'a> where Self: 'a;
    fn next(&mut self) -> Option<<Self as LendingIterator>::Item<'_>> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(FunctionMeta::build(cass_iterator_get_function_meta(self.0))),
            }
        }
    }
}

/// Iterator over the tables in a keyspace.
///
/// A Cassandra iterator is a `LendingIterator` because it borrows from some
/// underlying value, but owns a single item. Each time `next()` is invoked it
/// decodes the current item into that item, thus invalidating its previous
/// value.
#[derive(Debug)]
pub struct TableIterator<'a>(*mut _CassIterator, PhantomData<&'a CassKeyspaceMeta>);

// The underlying C type has no thread-local state, and forbids only concurrent
// mutation/free: https://datastax.github.io/cpp-driver/topics/#thread-safety
unsafe impl Send for TableIterator<'_> {}
unsafe impl Sync for TableIterator<'_> {}

impl LendingIterator for TableIterator<'_> {
    type Item<'a> = TableMeta<'a> where Self: 'a;
    fn next(&mut self) -> Option<<Self as LendingIterator>::Item<'_>> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(TableMeta::build(cass_iterator_get_table_meta(self.0))),
            }
        }
    }
}

/// Iterator over the keyspaces in the schema.
///
/// A Cassandra iterator is a `LendingIterator` because it borrows from some
/// underlying value, but owns a single item. Each time `next()` is invoked it
/// decodes the current item into that item, thus invalidating its previous
/// value.
#[derive(Debug)]
pub struct KeyspaceIterator<'a>(*mut _CassIterator, PhantomData<&'a CassSchemaMeta>);

// The underlying C type has no thread-local state, and forbids only concurrent
// mutation/free: https://datastax.github.io/cpp-driver/topics/#thread-safety
unsafe impl Send for KeyspaceIterator<'_> {}
unsafe impl Sync for KeyspaceIterator<'_> {}

impl LendingIterator for KeyspaceIterator<'_> {
    type Item<'a> = KeyspaceMeta<'a> where Self: 'a;
    fn next(&mut self) -> Option<<Self as LendingIterator>::Item<'_>> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(KeyspaceMeta::build(cass_iterator_get_keyspace_meta(self.0))),
            }
        }
    }
}

/// Iterator over the columns in a table.
///
/// A Cassandra iterator is a `LendingIterator` because it borrows from some
/// underlying value, but owns a single item. Each time `next()` is invoked it
/// decodes the current item into that item, thus invalidating its previous
/// value.
#[derive(Debug)]
pub struct ColumnIterator<'a>(*mut _CassIterator, PhantomData<&'a CassTableMeta>);

// The underlying C type has no thread-local state, and forbids only concurrent
// mutation/free: https://datastax.github.io/cpp-driver/topics/#thread-safety
unsafe impl Send for ColumnIterator<'_> {}
unsafe impl Sync for ColumnIterator<'_> {}

impl LendingIterator for ColumnIterator<'_> {
    type Item<'a> = ColumnMeta<'a> where Self: 'a;
    fn next(&mut self) -> Option<<Self as LendingIterator>::Item<'_>> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(ColumnMeta::build(cass_iterator_get_column_meta(self.0))),
            }
        }
    }
}

/// Iterator over the fields in a metadata object.
///
/// A Cassandra iterator is a `LendingIterator` because it borrows from some
/// underlying value, but owns a single item. Each time `next()` is invoked it
/// decodes the current item into that item, thus invalidating its previous
/// value.
//
// Could be one of several underlying types; CassTableMeta is just a
// representative. Since it's a phantom, it doesn't matter which type we name.
#[derive(Debug)]
pub struct FieldIterator<'a>(*mut _CassIterator, PhantomData<&'a CassTableMeta>);

// The underlying C type has no thread-local state, and forbids only concurrent
// mutation/free: https://datastax.github.io/cpp-driver/topics/#thread-safety
unsafe impl Send for FieldIterator<'_> {}
unsafe impl Sync for FieldIterator<'_> {}

impl LendingIterator for FieldIterator<'_> {
    type Item<'a> = Field<'a> where Self: 'a;

    fn next(&mut self) -> Option<<Self as LendingIterator>::Item<'_>> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => {
                    let mut name = std::ptr::null();
                    let mut name_length = 0;
                    cass_iterator_get_meta_field_name(self.0, &mut name, &mut name_length)
                        .to_result(())
                        .and_then(|_| {
                            let slice = slice::from_raw_parts(name as *const u8, name_length);
                            let name = str::from_utf8(slice)?.to_owned();
                            let value = Value::build(cass_iterator_get_meta_field_value(self.0));
                            Ok(Some(Field { name, value }))
                        })
                }
                .expect("Cassandra error during iteration"),
            }
        }
    }
}

impl ProtectedInner<*mut _CassIterator> for UserTypeIterator<'_> {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
}

impl Protected<*mut _CassIterator> for UserTypeIterator<'_> {
    fn build(inner: *mut _CassIterator) -> Self {
        if inner.is_null() {
            panic!("Unexpected null pointer")
        };
        UserTypeIterator(inner, PhantomData)
    }
}

impl ProtectedInner<*mut _CassIterator> for AggregateIterator<'_> {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
}

impl Protected<*mut _CassIterator> for AggregateIterator<'_> {
    fn build(inner: *mut _CassIterator) -> Self {
        if inner.is_null() {
            panic!("Unexpected null pointer")
        };
        AggregateIterator(inner, PhantomData)
    }
}

impl ProtectedInner<*mut _CassIterator> for FunctionIterator<'_> {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
}

impl Protected<*mut _CassIterator> for FunctionIterator<'_> {
    fn build(inner: *mut _CassIterator) -> Self {
        if inner.is_null() {
            panic!("Unexpected null pointer")
        };
        FunctionIterator(inner, PhantomData)
    }
}

impl ProtectedInner<*mut _CassIterator> for KeyspaceIterator<'_> {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
}

impl Protected<*mut _CassIterator> for KeyspaceIterator<'_> {
    fn build(inner: *mut _CassIterator) -> Self {
        if inner.is_null() {
            panic!("Unexpected null pointer")
        };
        KeyspaceIterator(inner, PhantomData)
    }
}

impl ProtectedInner<*mut _CassIterator> for FieldIterator<'_> {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
}
impl Protected<*mut _CassIterator> for FieldIterator<'_> {
    fn build(inner: *mut _CassIterator) -> Self {
        if inner.is_null() {
            panic!("Unexpected null pointer")
        };
        FieldIterator(inner, PhantomData)
    }
}

impl ProtectedInner<*mut _CassIterator> for ColumnIterator<'_> {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
}

impl Protected<*mut _CassIterator> for ColumnIterator<'_> {
    fn build(inner: *mut _CassIterator) -> Self {
        if inner.is_null() {
            panic!("Unexpected null pointer")
        };
        ColumnIterator(inner, PhantomData)
    }
}

impl ProtectedInner<*mut _CassIterator> for TableIterator<'_> {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
}

impl Protected<*mut _CassIterator> for TableIterator<'_> {
    fn build(inner: *mut _CassIterator) -> Self {
        if inner.is_null() {
            panic!("Unexpected null pointer")
        };
        TableIterator(inner, PhantomData)
    }
}

impl ProtectedInner<*mut _CassIterator> for MapIterator<'_> {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
}

impl Protected<*mut _CassIterator> for MapIterator<'_> {
    fn build(inner: *mut _CassIterator) -> Self {
        if inner.is_null() {
            panic!("Unexpected null pointer")
        };
        MapIterator(inner, PhantomData)
    }
}

impl ProtectedInner<*mut _CassIterator> for SetIterator<'_> {
    fn inner(&self) -> *mut _CassIterator {
        self.0
    }
}

impl Protected<*mut _CassIterator> for SetIterator<'_> {
    fn build(inner: *mut _CassIterator) -> Self {
        if inner.is_null() {
            panic!("Unexpected null pointer")
        };
        SetIterator(inner, PhantomData)
    }
}

/// Iterator over the values in a set.
///
/// A Cassandra iterator is a `LendingIterator` because it borrows from some
/// underlying value, but owns a single item. Each time `next()` is invoked it
/// decodes the current item into that item, thus invalidating its previous
/// value.
#[derive(Debug)]
pub struct SetIterator<'a>(*mut _CassIterator, PhantomData<&'a _CassValue>);

// The underlying C type has no thread-local state, and forbids only concurrent
// mutation/free: https://datastax.github.io/cpp-driver/topics/#thread-safety
unsafe impl Send for SetIterator<'_> {}
unsafe impl Sync for SetIterator<'_> {}

impl Drop for SetIterator<'_> {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl LendingIterator for SetIterator<'_> {
    type Item<'a> = Value<'a> where Self: 'a;

    fn next(&mut self) -> Option<<Self as LendingIterator>::Item<'_>> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(self.get_value()),
            }
        }
    }
}

impl SetIterator<'_> {
    fn get_value(&self) -> Value {
        unsafe { Value::build(cass_iterator_get_value(self.0)) }
    }
}

/// An iterator over the k/v pairs in a map.
#[derive(Debug)]
///
/// A Cassandra iterator is a `LendingIterator` because it borrows from some
/// underlying value, but owns a single item. Each time `next()` is invoked it
/// decodes the current item into that item, thus invalidating its previous
/// value.
pub struct MapIterator<'a>(*mut _CassIterator, PhantomData<&'a _CassValue>);

// The underlying C type has no thread-local state, and forbids only concurrent
// mutation/free: https://datastax.github.io/cpp-driver/topics/#thread-safety
unsafe impl Send for MapIterator<'_> {}
unsafe impl Sync for MapIterator<'_> {}

impl MapIterator<'_> {
    fn get_key(&self) -> Value {
        unsafe { Value::build(cass_iterator_get_map_key(self.0)) }
    }
    fn get_value(&self) -> Value {
        unsafe { Value::build(cass_iterator_get_map_value(self.0)) }
    }

    /// Gets the next k/v pair in the map
    pub fn get_pair(&self) -> (Value, Value) {
        (self.get_key(), self.get_value())
    }
}

impl Drop for MapIterator<'_> {
    fn drop(&mut self) {
        unsafe { cass_iterator_free(self.0) }
    }
}

impl LendingIterator for MapIterator<'_> {
    type Item<'a> = (Value<'a>, Value<'a>) where Self: 'a;
    fn next(&mut self) -> Option<<Self as LendingIterator>::Item<'_>> {
        unsafe {
            match cass_iterator_next(self.0) {
                cass_false => None,
                cass_true => Some(self.get_pair()),
            }
        }
    }
}