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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
use crate::{Payer, TableCursor, TableIndex, TableIterator};
use core::{borrow::Borrow, ptr::null_mut};
use eosio::{
    AccountName, Checksum160, Checksum256, Read, ReadError, ScopeName,
    SecondaryTableIndex, SecondaryTableName, Table, WriteError,
};
use eosio_cdt_sys::*;

pub enum Either<A, B> {
    A(A),
    B(B),
}

pub type EndFn = unsafe extern "C" fn(code: u64, scope: u64, table: u64) -> i32;
pub type NextFn = unsafe extern "C" fn(itr: i32, primary: *mut u64) -> i32;
pub type PreviousFn = unsafe extern "C" fn(itr: i32, primary: *mut u64) -> i32;
pub type RemoveFn = unsafe extern "C" fn(itr: i32);

pub type StoreValueFn<T> = unsafe extern "C" fn(
    scope: u64,
    table: u64,
    payer: u64,
    id: u64,
    secondary: *const T,
) -> i32;

pub type StoreArrayFn<T> = unsafe extern "C" fn(
    scope: u64,
    table: u64,
    payer: u64,
    id: u64,
    data: *const T,
    data_len: u32,
) -> i32;

pub type StoreFn<T> = Either<StoreValueFn<T>, StoreArrayFn<T>>;

pub type UpdateValueFn<T> =
    unsafe extern "C" fn(itr: i32, payer: u64, secondary: *const T);

pub type UpdateArrayFn<T> =
    unsafe extern "C" fn(itr: i32, payer: u64, data: *const T, data_len: u32);

pub type UpdateFn<T> = Either<UpdateValueFn<T>, UpdateArrayFn<T>>;

pub type LowerboundValueFn<T> = unsafe extern "C" fn(
    code: u64,
    scope: u64,
    table: u64,
    secondary: *mut T,
    primary: *mut u64,
) -> i32;

pub type LowerboundArrayFn<T> = unsafe extern "C" fn(
    code: u64,
    scope: u64,
    table: u64,
    data: *mut T,
    data_len: u32,
    primary: *mut u64,
) -> i32;

pub type LowerboundFn<T> = Either<LowerboundValueFn<T>, LowerboundArrayFn<T>>;

pub type UpperboundValueFn<T> = unsafe extern "C" fn(
    code: u64,
    scope: u64,
    table: u64,
    secondary: *mut T,
    primary: *mut u64,
) -> i32;

pub type UpperboundArrayFn<T> = unsafe extern "C" fn(
    code: u64,
    scope: u64,
    table: u64,
    data: *mut T,
    data_len: u32,
    primary: *mut u64,
) -> i32;

pub type UpperboundFn<T> = Either<UpperboundValueFn<T>, UpperboundArrayFn<T>>;

pub type FindPrimaryValueFn<T> = unsafe extern "C" fn(
    code: u64,
    scope: u64,
    table: u64,
    secondary: *mut T,
    primary: u64,
) -> i32;

pub type FindPrimaryArrayFn<T> = unsafe extern "C" fn(
    code: u64,
    scope: u64,
    table: u64,
    data: *mut T,
    data_len: u32,
    primary: u64,
) -> i32;

pub type FindPrimaryFn<T> =
    Either<FindPrimaryValueFn<T>, FindPrimaryArrayFn<T>>;

pub type FindSecondaryValueFn<T> = unsafe extern "C" fn(
    code: u64,
    scope: u64,
    table: u64,
    secondary: *const T,
    primary: *mut u64,
) -> i32;

pub type FindSecondaryArrayFn<T> = unsafe extern "C" fn(
    code: u64,
    scope: u64,
    table: u64,
    data: *const T,
    data_len: u32,
    primary: *mut u64,
) -> i32;

pub type FindSecondaryFn<T> =
    Either<FindSecondaryValueFn<T>, FindSecondaryArrayFn<T>>;

/// Trait for types that are natively supported by EOSIO to be used as secondary
/// keys
pub trait NativeSecondaryKey: Default {
    type NativeType;
    /// Unsafe native `end` function
    const END: EndFn;
    /// Unsafe native `next` function
    const NEXT: NextFn;
    /// Unsafe native `previous` function
    const PREVIOUS: PreviousFn;
    /// Unsafe native `remove` function
    const REMOVE: RemoveFn;
    /// Unsafe native `store` function
    const STORE: StoreFn<Self::NativeType>;
    /// Unsafe native `update` function
    const UPDATE: UpdateFn<Self::NativeType>;
    /// Unsafe native `lowerbound` function
    const LOWERBOUND: LowerboundFn<Self::NativeType>;
    /// Unsafe native `upperbound` function
    const UPPERBOUND: UpperboundFn<Self::NativeType>;
    /// Unsafe native `find_primary` function
    const FIND_PRIMARY: FindPrimaryFn<Self::NativeType>;
    /// Unsafe native `find_secondary` function
    const FIND_SECONDARY: FindSecondaryFn<Self::NativeType>;
    fn as_ptr(&self) -> *const Self::NativeType;
    fn as_mut_ptr(&mut self) -> *mut Self::NativeType;
    const DATA_LEN: u32 = 0;
    /// Safe wrapper around unsafe native function
    #[must_use]
    #[inline]
    fn db_idx_end(
        code: AccountName,
        scope: ScopeName,
        table: SecondaryTableName,
    ) -> i32 {
        unsafe { Self::END(code.as_u64(), scope.as_u64(), table.as_u64()) }
    }
    /// Safe wrapper around unsafe native function
    #[must_use]
    #[inline]
    fn db_idx_next(iterator: i32) -> (i32, u64) {
        let mut pk = 0_u64;
        let ptr: *mut u64 = &mut pk;
        let itr = unsafe { Self::NEXT(iterator, ptr) };
        (itr, pk)
    }
    /// Safe wrapper around unsafe native function
    #[must_use]
    #[inline]
    fn db_idx_previous(iterator: i32) -> (i32, u64) {
        let mut pk = 0_u64;
        let ptr: *mut u64 = &mut pk;
        let itr = unsafe { Self::PREVIOUS(iterator, ptr) };
        (itr, pk)
    }
    /// Safe wrapper around unsafe native function
    #[inline]
    fn db_idx_remove(iterator: i32) {
        unsafe { Self::REMOVE(iterator) }
    }
    /// Safe wrapper around unsafe native function
    #[inline]
    fn db_idx_store(
        &self,
        scope: ScopeName,
        table: SecondaryTableName,
        payer: AccountName,
        id: u64,
    ) -> i32 {
        match Self::STORE {
            Either::A(func) => unsafe {
                func(
                    scope.as_u64(),
                    table.as_u64(),
                    payer.as_u64(),
                    id,
                    self.as_ptr(),
                )
            },
            Either::B(func) => unsafe {
                func(
                    scope.as_u64(),
                    table.as_u64(),
                    payer.as_u64(),
                    id,
                    self.as_ptr(),
                    Self::DATA_LEN,
                )
            },
        }
    }
    /// Safe wrapper around unsafe native function
    #[inline]
    fn db_idx_update(&self, iterator: i32, payer: AccountName) {
        match Self::UPDATE {
            Either::A(func) => unsafe {
                func(iterator, payer.as_u64(), self.as_ptr())
            },
            Either::B(func) => unsafe {
                func(iterator, payer.as_u64(), self.as_ptr(), Self::DATA_LEN)
            },
        }
    }
    /// Safe wrapper around unsafe native function
    #[inline]
    fn db_idx_lowerbound(
        &mut self,
        code: AccountName,
        scope: ScopeName,
        table: SecondaryTableName,
    ) -> (i32, u64) {
        let mut pk = 0_u64;
        let itr = match Self::LOWERBOUND {
            Either::A(func) => unsafe {
                func(
                    code.as_u64(),
                    scope.as_u64(),
                    table.as_u64(),
                    self.as_mut_ptr(),
                    &mut pk as *mut u64,
                )
            },
            Either::B(func) => unsafe {
                func(
                    code.as_u64(),
                    scope.as_u64(),
                    table.as_u64(),
                    self.as_mut_ptr(),
                    Self::DATA_LEN,
                    &mut pk as *mut u64,
                )
            },
        };
        (itr, pk)
    }
    /// Safe wrapper around unsafe native function
    #[inline]
    fn db_idx_upperbound(
        &mut self,
        code: AccountName,
        scope: ScopeName,
        table: SecondaryTableName,
    ) -> (i32, u64) {
        let mut pk = 0_u64;
        let itr = match Self::UPPERBOUND {
            Either::A(func) => unsafe {
                func(
                    code.as_u64(),
                    scope.as_u64(),
                    table.as_u64(),
                    self.as_mut_ptr(),
                    &mut pk as *mut u64,
                )
            },
            Either::B(func) => unsafe {
                func(
                    code.as_u64(),
                    scope.as_u64(),
                    table.as_u64(),
                    self.as_mut_ptr(),
                    Self::DATA_LEN,
                    &mut pk as *mut u64,
                )
            },
        };
        (itr, pk)
    }
    /// Safe wrapper around unsafe native function
    #[inline]
    fn db_idx_find_primary(
        &mut self,
        code: AccountName,
        scope: ScopeName,
        table: SecondaryTableName,
        primary: u64,
    ) -> i32 {
        match Self::FIND_PRIMARY {
            Either::A(func) => unsafe {
                func(
                    code.as_u64(),
                    scope.as_u64(),
                    table.as_u64(),
                    self.as_mut_ptr(),
                    primary,
                )
            },
            Either::B(func) => unsafe {
                func(
                    code.as_u64(),
                    scope.as_u64(),
                    table.as_u64(),
                    self.as_mut_ptr(),
                    Self::DATA_LEN,
                    primary,
                )
            },
        }
    }
    /// Safe wrapper around unsafe native function
    #[inline]
    fn db_idx_find_secondary(
        &self,
        code: AccountName,
        scope: ScopeName,
        table: SecondaryTableName,
    ) -> (i32, u64) {
        let mut pk = 0_u64;
        let itr = match Self::FIND_SECONDARY {
            Either::A(func) => unsafe {
                func(
                    code.as_u64(),
                    scope.as_u64(),
                    table.as_u64(),
                    self.as_ptr(),
                    &mut pk as *mut u64,
                )
            },
            Either::B(func) => unsafe {
                func(
                    code.as_u64(),
                    scope.as_u64(),
                    table.as_u64(),
                    self.as_ptr(),
                    Self::DATA_LEN,
                    &mut pk as *mut u64,
                )
            },
        };
        (itr, pk)
    }
    /// Safe wrapper around unsafe native function
    #[inline]
    fn db_idx_upsert(
        &mut self,
        code: AccountName,
        scope: ScopeName,
        table: SecondaryTableName,
        payer: AccountName,
        id: u64,
    ) {
        let end = Self::db_idx_end(code, scope, table);
        let itr = self.db_idx_find_primary(code, scope, table, id);
        if itr == end {
            self.db_idx_store(scope, table, payer, id);
        } else {
            self.db_idx_update(itr, payer);
        }
    }
}

impl NativeSecondaryKey for u64 {
    type NativeType = Self;

    const END: EndFn = db_idx64_end;
    const FIND_PRIMARY: FindPrimaryFn<Self::NativeType> =
        Either::A(db_idx64_find_primary);
    const FIND_SECONDARY: FindSecondaryFn<Self::NativeType> =
        Either::A(db_idx64_find_secondary);
    const LOWERBOUND: LowerboundFn<Self::NativeType> =
        Either::A(db_idx64_lowerbound);
    const NEXT: NextFn = db_idx64_next;
    const PREVIOUS: PreviousFn = db_idx64_previous;
    const REMOVE: RemoveFn = db_idx64_remove;
    const STORE: StoreFn<Self::NativeType> = Either::A(db_idx64_store);
    const UPDATE: UpdateFn<Self::NativeType> = Either::A(db_idx64_update);
    const UPPERBOUND: UpperboundFn<Self::NativeType> =
        Either::A(db_idx64_upperbound);

    #[inline]
    fn as_ptr(&self) -> *const Self::NativeType {
        self as *const Self::NativeType
    }

    #[inline]
    fn as_mut_ptr(&mut self) -> *mut Self::NativeType {
        self as *mut Self::NativeType
    }
}

impl NativeSecondaryKey for f64 {
    type NativeType = Self;

    const END: EndFn = db_idx_double_end;
    const FIND_PRIMARY: FindPrimaryFn<Self::NativeType> =
        Either::A(db_idx_double_find_primary);
    const FIND_SECONDARY: FindSecondaryFn<Self::NativeType> =
        Either::A(db_idx_double_find_secondary);
    const LOWERBOUND: LowerboundFn<Self::NativeType> =
        Either::A(db_idx_double_lowerbound);
    const NEXT: NextFn = db_idx_double_next;
    const PREVIOUS: PreviousFn = db_idx_double_previous;
    const REMOVE: RemoveFn = db_idx_double_remove;
    const STORE: StoreFn<Self::NativeType> = Either::A(db_idx_double_store);
    const UPDATE: UpdateFn<Self::NativeType> = Either::A(db_idx_double_update);
    const UPPERBOUND: UpperboundFn<Self::NativeType> =
        Either::A(db_idx_double_upperbound);

    #[inline]
    fn as_ptr(&self) -> *const Self::NativeType {
        self as *const Self::NativeType
    }

    #[inline]
    fn as_mut_ptr(&mut self) -> *mut Self::NativeType {
        self as *mut Self::NativeType
    }
}

impl NativeSecondaryKey for u128 {
    type NativeType = Self;

    const END: EndFn = db_idx128_end;
    const FIND_PRIMARY: FindPrimaryFn<Self::NativeType> =
        Either::A(db_idx128_find_primary);
    const FIND_SECONDARY: FindSecondaryFn<Self::NativeType> =
        Either::A(db_idx128_find_secondary);
    const LOWERBOUND: LowerboundFn<Self::NativeType> =
        Either::A(db_idx128_lowerbound);
    const NEXT: NextFn = db_idx128_next;
    const PREVIOUS: PreviousFn = db_idx128_previous;
    const REMOVE: RemoveFn = db_idx128_remove;
    const STORE: StoreFn<Self::NativeType> = Either::A(db_idx128_store);
    const UPDATE: UpdateFn<Self::NativeType> = Either::A(db_idx128_update);
    const UPPERBOUND: UpperboundFn<Self::NativeType> =
        Either::A(db_idx128_upperbound);

    #[inline]
    fn as_ptr(&self) -> *const Self::NativeType {
        self as *const Self::NativeType
    }

    #[inline]
    fn as_mut_ptr(&mut self) -> *mut Self::NativeType {
        self as *mut Self::NativeType
    }
}

impl NativeSecondaryKey for [u8; 32] {
    type NativeType = u128;

    const DATA_LEN: u32 = 8 * 32 / 128;
    const END: EndFn = db_idx256_end;
    const FIND_PRIMARY: FindPrimaryFn<Self::NativeType> =
        Either::B(db_idx256_find_primary);
    const FIND_SECONDARY: FindSecondaryFn<Self::NativeType> =
        Either::B(db_idx256_find_secondary);
    const LOWERBOUND: LowerboundFn<Self::NativeType> =
        Either::B(db_idx256_lowerbound);
    const NEXT: NextFn = db_idx256_next;
    const PREVIOUS: PreviousFn = db_idx256_previous;
    const REMOVE: RemoveFn = db_idx256_remove;
    const STORE: StoreFn<Self::NativeType> = Either::B(db_idx256_store);
    const UPDATE: UpdateFn<Self::NativeType> = Either::B(db_idx256_update);
    const UPPERBOUND: UpperboundFn<Self::NativeType> =
        Either::B(db_idx256_upperbound);

    // TODO: Don't allow this clippy lint. This should be fixed
    #[inline]
    #[allow(clippy::cast_ptr_alignment)]
    fn as_ptr(&self) -> *const Self::NativeType {
        self as *const _ as *const Self::NativeType
    }

    // TODO: Don't allow this clippy lint. This should be fixed
    #[inline]
    #[allow(clippy::cast_ptr_alignment)]
    fn as_mut_ptr(&mut self) -> *mut Self::NativeType {
        self as *mut _ as *mut Self::NativeType
    }
}

/// Trait for types that can be turned into types that are native secondary keys
pub trait IntoNativeSecondaryKey {
    /// The native secondary key type
    type Native: NativeSecondaryKey;
    /// Turn self into the native secondary key type
    fn into_native_secondary_key(self) -> Self::Native;
}

impl IntoNativeSecondaryKey for u64 {
    type Native = Self;

    #[must_use]
    #[inline]
    fn into_native_secondary_key(self) -> Self::Native {
        self
    }
}

impl IntoNativeSecondaryKey for f64 {
    type Native = Self;

    #[must_use]
    #[inline]
    fn into_native_secondary_key(self) -> Self::Native {
        self
    }
}

impl IntoNativeSecondaryKey for u128 {
    type Native = Self;

    #[must_use]
    #[inline]
    fn into_native_secondary_key(self) -> Self::Native {
        self
    }
}

impl IntoNativeSecondaryKey for Checksum256 {
    type Native = [u8; 32];

    #[must_use]
    #[inline]
    fn into_native_secondary_key(self) -> Self::Native {
        self.to_bytes()
    }
}

impl IntoNativeSecondaryKey for Checksum160 {
    type Native = [u8; 32];

    #[must_use]
    #[inline]
    fn into_native_secondary_key(self) -> Self::Native {
        let b = self.to_bytes();
        [
            b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10],
            b[11], b[12], b[13], b[14], b[15], b[16], b[17], b[18], b[19], 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        ]
    }
}

macro_rules! impl_into_type {
    ($($t:ty, $x:ty)*) => ($(
        impl IntoNativeSecondaryKey for $x {
            type Native = $t;
            #[must_use]
            #[inline]
            fn into_native_secondary_key(self) -> Self::Native {
                self.into()
            }
        }
    )*)
}

impl_into_type! {
    u64, u8
    u64, u16
    u64, u32
    u64, eosio::Name
    u64, eosio::AccountName
    u64, eosio::TableName
    u64, eosio::PermissionName
    u64, eosio::ScopeName
    u64, eosio::ActionName
    u64, eosio::Symbol
    u64, eosio::SymbolCode
}

/// Cursor for a `SecondaryTableIndex`
#[allow(clippy::missing_inline_in_public_items)]
#[derive(Debug, Copy, Clone)]
pub struct SecondaryTableCursor<'a, K, T>
where
    T: Table,
{
    value: i32,
    pk: u64,
    index: &'a SecondaryTableIndex<K, T>,
}

impl<'a, K, T> TableCursor<T> for SecondaryTableCursor<'a, K, T>
where
    K: IntoNativeSecondaryKey,
    T: Table,
{
    #[inline]
    fn get(&self) -> Result<T::Row, ReadError> {
        let pk_itr = unsafe {
            db_find_i64(
                self.index.code.as_u64(),
                self.index.scope.as_u64(),
                T::NAME.as_u64(),
                self.pk,
            )
        };
        let nullptr: *mut c_void = null_mut() as *mut _ as *mut c_void;
        let size = unsafe { db_get_i64(self.value, nullptr, 0) };
        let mut bytes = vec![
            0_u8;
            #[allow(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss
            )]
            {
                size as usize
            }
        ];
        let ptr: *mut c_void = &mut bytes[..] as *mut _ as *mut c_void;
        unsafe {
            db_get_i64(
                pk_itr,
                ptr,
                #[allow(clippy::cast_sign_loss)]
                {
                    size as u32
                },
            );
        }
        let mut pos = 0;
        T::Row::read(&bytes, &mut pos)
    }

    #[inline]
    fn erase(&self) -> Result<T::Row, ReadError> {
        let table = self.index.primary_index();
        match table.find(self.pk) {
            Some(cursor) => cursor.erase(),
            None => Err(ReadError::NotEnoughBytes), // TODO: better error
        }
    }

    #[inline]
    fn modify<I: Borrow<T::Row>>(
        &self,
        payer: Payer,
        item: I,
    ) -> Result<usize, WriteError> {
        let table = self.index.primary_index();
        match table.find(self.pk) {
            Some(cursor) => cursor.modify(payer, item),
            None => Err(WriteError::NotEnoughSpace), // TODO: better error
        }
    }
}

impl<'a, K, T> IntoIterator for SecondaryTableCursor<'a, K, T>
where
    K: IntoNativeSecondaryKey,
    T: Table,
{
    type IntoIter = SecondaryTableIterator<'a, K, T>;
    type Item = Self;

    #[must_use]
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        let secondary_end = K::Native::db_idx_end(
            self.index.code,
            self.index.scope,
            self.index.table,
        );
        let primary_end = unsafe {
            db_end_i64(
                self.index.code.as_u64(),
                self.index.scope.as_u64(),
                T::NAME.as_u64(),
            )
        };
        SecondaryTableIterator {
            value: self.value,
            pk: self.pk,
            pk_end: primary_end,
            sk_end: secondary_end,
            index: self.index,
        }
    }
}

/// Iterate over a secondary table index
#[allow(clippy::missing_inline_in_public_items)]
#[derive(Copy, Clone, Debug)]
pub struct SecondaryTableIterator<'a, K, T>
where
    T: Table,
{
    value: i32,
    pk: u64,
    pk_end: i32,
    sk_end: i32,
    index: &'a SecondaryTableIndex<K, T>,
}

impl<'a, K, T> Iterator for SecondaryTableIterator<'a, K, T>
where
    K: IntoNativeSecondaryKey,
    T: Table,
{
    type Item = SecondaryTableCursor<'a, K, T>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.value == self.sk_end {
            return None;
        }

        let cursor = SecondaryTableCursor {
            value: self.value,
            pk: self.pk,
            index: self.index,
        };
        let (itr, pk) = K::Native::db_idx_next(self.value);
        self.value = itr;
        self.pk = pk;

        Some(cursor)
    }
}

impl<'a, K, T> DoubleEndedIterator for SecondaryTableIterator<'a, K, T>
where
    K: IntoNativeSecondaryKey,
    T: Table,
{
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.value == -1 {
            return None;
        }

        let cursor = SecondaryTableCursor {
            value: self.value,
            pk: self.pk,
            index: self.index,
        };
        let (itr, pk) = K::Native::db_idx_previous(self.value);
        self.value = itr;
        self.pk = pk;

        Some(cursor)
    }
}

impl<'a, K, T> TableIterator for SecondaryTableIterator<'a, K, T>
where
    K: IntoNativeSecondaryKey,
    T: Table,
{
}

impl<'a, K, T> TableIndex<'a, K, T> for SecondaryTableIndex<K, T>
where
    K: IntoNativeSecondaryKey + 'a,
    T: Table + 'a,
{
    type Cursor = SecondaryTableCursor<'a, K, T>;

    #[must_use]
    #[inline]
    fn code(&'a self) -> AccountName {
        self.code
    }

    #[must_use]
    #[inline]
    fn scope(&'a self) -> ScopeName {
        self.scope
    }

    #[inline]
    fn lower_bound<N: Into<K>>(&'a self, key: N) -> Option<Self::Cursor> {
        let (value, pk) = key
            .into()
            .into_native_secondary_key()
            .db_idx_lowerbound(self.code, self.scope, self.table);
        let end = K::Native::db_idx_end(self.code, self.scope, self.table);
        if value == end {
            None
        } else {
            Some(SecondaryTableCursor {
                value,
                pk,
                index: self,
            })
        }
    }

    #[inline]
    fn upper_bound<N: Into<K>>(&'a self, key: N) -> Option<Self::Cursor> {
        let (value, pk) = key
            .into()
            .into_native_secondary_key()
            .db_idx_upperbound(self.code, self.scope, self.table);
        let end = K::Native::db_idx_end(self.code, self.scope, self.table);
        if value == end {
            None
        } else {
            Some(SecondaryTableCursor {
                value,
                pk,
                index: self,
            })
        }
    }

    #[inline]
    fn find<N: Into<K>>(&'a self, key: N) -> Option<Self::Cursor> {
        let (value, pk) = key
            .into()
            .into_native_secondary_key()
            .db_idx_find_secondary(self.code, self.scope, self.table);
        let end = K::Native::db_idx_end(self.code, self.scope, self.table);
        if value == end {
            None
        } else {
            Some(SecondaryTableCursor {
                value,
                pk,
                index: self,
            })
        }
    }

    #[inline]
    fn emplace<I: Borrow<T::Row>>(
        &self,
        payer: AccountName,
        item: I,
    ) -> Result<(), WriteError> {
        let table = self.primary_index();
        table.emplace(payer, item)
    }
}