firewood-ffi 0.3.1

C FFI bindings for Firewood, an embedded key-value store optimized for blockchain state.
Documentation
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
// Copyright (C) 2025, Ava Labs, Inc. All rights reserved.
// See the file LICENSE.md for licensing terms.

use firewood::api;
use firewood::merkle;
use firewood_storage::TrieHash;
use std::fmt;

use crate::revision::{GetRevisionResult, RevisionHandle};
use crate::{
    ChangeProofContext, CodeIteratorHandle, CreateIteratorResult, CreateProposalResult, HashKey,
    IteratorHandle, KeyRange, NextKeyRange, OwnedBytes, OwnedKeyValueBatch, OwnedKeyValuePair,
    ProposalHandle, ProposedChangeProofContext, RangeProofContext, ReconstructedHandle,
    VerifiedChangeProofContext,
};

/// The result type returned from an FFI function that returns no value but may
/// return an error.
#[derive(Debug)]
#[repr(C, usize)]
pub enum VoidResult {
    /// The caller provided a null pointer to the input handle.
    NullHandlePointer,

    /// The operation was successful and no error occurred.
    Ok,

    /// An error occurred and the message is returned as an [`OwnedBytes`]. Its
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

impl From<()> for VoidResult {
    fn from((): ()) -> Self {
        VoidResult::Ok
    }
}

impl<E: fmt::Display> From<Result<(), E>> for VoidResult {
    fn from(value: Result<(), E>) -> Self {
        match value {
            Ok(()) => VoidResult::Ok,
            Err(err) => VoidResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

/// The result type returned from the open or create database functions.
#[derive(Debug)]
#[repr(C, usize)]
pub enum HandleResult {
    /// The database was opened or created successfully and the handle is
    /// returned as an opaque pointer.
    ///
    /// The caller must ensure that [`fwd_close_db`] is called to free resources
    /// associated with this handle when it is no longer needed.
    ///
    /// [`fwd_close_db`]: crate::fwd_close_db
    Ok(Box<crate::DatabaseHandle>),

    /// An error occurred and the message is returned as an [`OwnedBytes`]. If
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

impl<E: fmt::Display> From<Result<crate::DatabaseHandle, E>> for HandleResult {
    fn from(value: Result<crate::DatabaseHandle, E>) -> Self {
        match value {
            Ok(handle) => HandleResult::Ok(Box::new(handle)),
            Err(err) => HandleResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

/// A result type returned from FFI functions that retrieve a single value.
#[derive(Debug)]
#[repr(C, usize)]
pub enum ValueResult {
    /// The caller provided a null pointer to a database handle.
    NullHandlePointer,
    /// The provided root was not found in the database.
    RevisionNotFound(HashKey),
    /// The provided key was not found in the database or proposal.
    None,
    /// A value was found and is returned.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this value.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Some(OwnedBytes),
    /// An error occurred and the message is returned as an [`OwnedBytes`]. If
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

impl<E: fmt::Display> From<Result<String, E>> for ValueResult {
    fn from(value: Result<String, E>) -> Self {
        match value {
            Ok(data) => ValueResult::Some(data.into_bytes().into()),
            Err(err) => ValueResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

impl From<Result<Option<Box<[u8]>>, api::Error>> for ValueResult {
    fn from(value: Result<Option<Box<[u8]>>, api::Error>) -> Self {
        match value {
            Ok(None) => ValueResult::None,
            Err(api::Error::RevisionNotFound { provided }) => ValueResult::RevisionNotFound(
                HashKey::from(provided.unwrap_or_else(api::HashKey::empty)),
            ),
            Ok(Some(data)) => ValueResult::Some(data.into()),
            Err(err) => ValueResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

impl From<Result<Option<Box<[u8]>>, firewood::db::DbError>> for ValueResult {
    fn from(value: Result<Option<Box<[u8]>>, firewood::db::DbError>) -> Self {
        value.map_err(api::Error::from).into()
    }
}

impl From<Vec<u8>> for ValueResult {
    fn from(value: Vec<u8>) -> Self {
        value.into_boxed_slice().into()
    }
}

impl From<Box<[u8]>> for ValueResult {
    fn from(value: Box<[u8]>) -> Self {
        ValueResult::Some(value.into())
    }
}

/// A result type returned from FFI functions return the database root hash. This
/// may or may not be after a mutation.
#[derive(Debug)]
#[repr(C, usize)]
pub enum HashResult {
    /// The caller provided a null pointer to a database handle.
    NullHandlePointer,
    /// The proposal resulted in an empty database or the database currently has
    /// no root hash.
    None,
    /// The mutation was successful and the root hash is returned, if this result
    /// was from a mutation. Otherwise, this is the current root hash of the
    /// database.
    Some(HashKey),
    /// An error occurred and the message is returned as an [`OwnedBytes`]. If
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

impl<E: fmt::Display> From<Result<Option<api::HashKey>, E>> for HashResult {
    fn from(value: Result<Option<api::HashKey>, E>) -> Self {
        match value {
            Ok(hash) => hash.into(),
            Err(err) => HashResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

impl From<Option<TrieHash>> for HashResult {
    fn from(value: Option<TrieHash>) -> Self {
        match value {
            Some(hash) => HashResult::Some(hash.into()),
            None => HashResult::None,
        }
    }
}

impl From<Option<Result<HashKey, api::Error>>> for HashResult {
    fn from(value: Option<Result<HashKey, api::Error>>) -> Self {
        match value {
            Some(value) => match value {
                Ok(hash) => HashResult::Some(hash),
                Err(err) => HashResult::Err(err.to_string().into_bytes().into()),
            },
            None => HashResult::None,
        }
    }
}

/// A result type returned from FFI functions that create or parse range proofs.
///
/// The caller must ensure that [`fwd_free_range_proof`] is called to
/// free the memory associated with the returned context when it is no longer
/// needed.
///
/// [`fwd_free_range_proof`]: crate::fwd_free_range_proof
#[derive(Debug)]
#[repr(C, usize)]
pub enum RangeProofResult<'db> {
    /// The caller provided a null pointer to the input handle.
    NullHandlePointer,
    /// The provided root was not found in the database.
    RevisionNotFound(HashKey),
    /// A range proof was requested on an empty trie.
    EmptyTrie,
    /// The proof was successfully created or parsed.
    ///
    /// If the value was parsed from a serialized proof, this does not imply that
    /// the proof is valid, only that it is well-formed. The verify method must
    /// be called to ensure the proof is cryptographically valid.
    Ok(Box<RangeProofContext<'db>>),
    /// An error occurred and the message is returned as an [`OwnedBytes`]. If
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

impl From<Result<api::FrozenRangeProof, api::Error>> for RangeProofResult<'_> {
    fn from(value: Result<api::FrozenRangeProof, api::Error>) -> Self {
        match value {
            Ok(proof) => RangeProofResult::Ok(Box::new(proof.into())),
            Err(api::Error::RevisionNotFound { provided }) => RangeProofResult::RevisionNotFound(
                HashKey::from(provided.unwrap_or_else(api::HashKey::empty)),
            ),
            Err(api::Error::RangeProofOnEmptyTrie) => RangeProofResult::EmptyTrie,
            Err(err) => RangeProofResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

/// A result type returned from FFI functions that create or parse change proofs.
///
/// The caller must ensure that [`fwd_free_change_proof`] is called to
/// free the memory associated with the returned context when it is no longer
/// needed.
///
/// [`fwd_free_change_proof`]: crate::fwd_free_change_proof
#[derive(Debug)]
#[repr(C, usize)]
pub enum ChangeProofResult {
    /// The caller provided a null pointer to the input handle.
    NullHandlePointer,
    /// The provided start root was not found in the database.
    StartRevisionNotFound(HashKey),
    /// The provided end root was not found in the database.
    EndRevisionNotFound(HashKey),
    /// The proof was successfully created or parsed.
    ///
    /// If the value was parsed from a serialized proof, this does not imply that
    /// the proof is valid, only that it is well-formed. The verify method must
    /// be called to ensure the proof is cryptographically valid.
    Ok(Box<ChangeProofContext>),
    /// An error occurred and the message is returned as an [`OwnedBytes`]. If
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

#[derive(Debug)]
#[repr(C, usize)]
pub enum VerifiedChangeProofResult {
    /// The caller provided a null pointer to the input handle.
    NullHandlePointer,
    // The proof was successfully verified.
    Ok(Box<VerifiedChangeProofContext>),
    /// An error occurred and the message is returned as an [`OwnedBytes`]. If
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

#[derive(Debug)]
#[repr(C, usize)]
pub enum ProposedChangeProofResult<'db> {
    /// The caller provided a null pointer to the input handle.
    NullHandlePointer,
    /// A proposal was successfully created for this proof.
    Ok(Box<ProposedChangeProofContext<'db>>),
    /// An error occurred and the message is returned as an [`OwnedBytes`]. If
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

#[derive(Debug)]
#[repr(C, usize)]
pub enum NextKeyRangeResult {
    /// The caller provided a null pointer to the input handle.
    NullHandlePointer,
    /// The proof has not prepared into a proposal nor committed to the database.
    NotPrepared,
    /// There are no more keys to fetch.
    None,
    /// The next key range to fetch is returned.
    Some(NextKeyRange),
    /// An error occurred and the message is returned as an [`OwnedBytes`]. If
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

impl From<Result<Option<KeyRange>, api::Error>> for NextKeyRangeResult {
    fn from(value: Result<Option<KeyRange>, api::Error>) -> Self {
        match value {
            Ok(None) => NextKeyRangeResult::None,
            Ok(Some((start_key, end_key))) => NextKeyRangeResult::Some(NextKeyRange {
                start_key: start_key.into(),
                end_key: end_key.map(Into::into).into(),
            }),
            Err(api::Error::ProofError(firewood::ProofError::Unverified)) => {
                NextKeyRangeResult::NotPrepared
            }
            Err(err) => NextKeyRangeResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

/// A result type returned from FFI functions that create an code hash iterator
#[derive(Debug)]
#[repr(C, usize)]
pub enum CodeIteratorResult<'p> {
    /// The caller provided a null pointer to a proof handle.
    NullHandlePointer,
    /// Building the iterator was successful and the iterator handle is returned
    Ok {
        /// An opaque pointer to the [`CodeIteratorHandle`].
        /// The value should be freed with [`fwd_code_hash_iter_free`]
        ///
        /// [`fwd_code_hash_iter_free`]: crate::fwd_code_hash_iter_free
        handle: Box<CodeIteratorHandle<'p>>,
    },
    /// An error occurred and the message is returned as an [`OwnedBytes`].
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

impl<'a> From<Result<CodeIteratorHandle<'a>, api::Error>> for CodeIteratorResult<'a> {
    fn from(value: Result<CodeIteratorHandle<'a>, api::Error>) -> Self {
        match value {
            Ok(res) => CodeIteratorResult::Ok {
                handle: Box::new(res),
            },
            Err(err) => CodeIteratorResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

/// A result type returned from FFI functions that create a proposal but do not
/// commit it to the database.
#[derive(Debug)]
#[repr(C, usize)]
pub enum ProposalResult<'db> {
    /// The caller provided a null pointer to a database handle.
    NullHandlePointer,
    /// Buulding the proposal was successful and the proposal ID and root hash
    /// are returned.
    Ok {
        /// An opaque pointer to the [`ProposalHandle`] that can be use to create
        /// an additional proposal or later commit. The caller must ensure that this
        /// pointer is freed with [`fwd_free_proposal`] if it is not committed.
        ///
        /// [`fwd_free_proposal`]: crate::fwd_free_proposal
        // note: opaque pointers mut be boxed because the FFI does not the structure definition.
        handle: Box<ProposalHandle<'db>>,
        /// The root hash of the proposal. Zeroed if the proposal resulted in an
        /// empty database.
        root_hash: HashKey,
    },
    /// An error occurred and the message is returned as an [`OwnedBytes`]. If
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

/// A result type returned from FFI functions that create an iterator
#[derive(Debug)]
#[repr(C, usize)]
pub enum IteratorResult<'db> {
    /// The caller provided a null pointer to a revision/proposal handle.
    NullHandlePointer,
    /// Building the iterator was successful and the iterator handle is returned
    Ok {
        /// An opaque pointer to the [`IteratorHandle`].
        /// The value should be freed with [`fwd_free_iterator`]
        ///
        /// [`fwd_free_iterator`]: crate::fwd_free_iterator
        handle: Box<IteratorHandle<'db>>,
    },
    /// An error occurred and the message is returned as an [`OwnedBytes`].
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

/// A result type returned from iterator FFI functions
#[derive(Debug)]
#[repr(C, usize)]
pub enum KeyValueResult {
    /// The caller provided a null pointer to an iterator handle.
    NullHandlePointer,
    /// The iterator is exhausted
    None,
    /// The next item is returned.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with the key and the value of this pair.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Some(OwnedKeyValuePair),
    /// An error occurred and the message is returned as an [`OwnedBytes`]. The
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

impl From<Option<Result<(merkle::Key, merkle::Value), api::Error>>> for KeyValueResult {
    fn from(value: Option<Result<(merkle::Key, merkle::Value), api::Error>>) -> Self {
        match value {
            Some(value) => match value {
                Ok(value) => KeyValueResult::Some(value.into()),
                Err(err) => KeyValueResult::Err(err.to_string().into_bytes().into()),
            },
            None => KeyValueResult::None,
        }
    }
}

/// A result type returned from iterator FFI functions
#[derive(Debug)]
#[repr(C, usize)]
pub enum KeyValueBatchResult {
    /// The caller provided a null pointer to an iterator handle.
    NullHandlePointer,
    /// The next batch of items on iterator are returned.
    Some(OwnedKeyValueBatch),
    /// An error occurred and the message is returned as an [`OwnedBytes`]. If
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

impl From<Result<Vec<(merkle::Key, merkle::Value)>, api::Error>> for KeyValueBatchResult {
    fn from(value: Result<Vec<(merkle::Key, merkle::Value)>, api::Error>) -> Self {
        match value {
            Ok(pairs) => {
                let values: Vec<_> = pairs.into_iter().map(Into::into).collect();
                KeyValueBatchResult::Some(values.into())
            }
            Err(err) => KeyValueBatchResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

impl<'db> From<CreateIteratorResult<'db>> for IteratorResult<'db> {
    fn from(value: CreateIteratorResult<'db>) -> Self {
        IteratorResult::Ok {
            handle: Box::new(value.0),
        }
    }
}

impl<'db, E: fmt::Display> From<Result<CreateIteratorResult<'db>, E>> for IteratorResult<'db> {
    fn from(value: Result<CreateIteratorResult<'db>, E>) -> Self {
        match value {
            Ok(res) => res.into(),
            Err(err) => IteratorResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

/// A result type returned from FFI functions that get a revision
#[derive(Debug)]
#[repr(C, usize)]
pub enum RevisionResult<'db> {
    /// The caller provided a null pointer to a database handle.
    NullHandlePointer,
    /// The provided root was not found in the database.
    RevisionNotFound(HashKey),
    /// Getting the revision was successful and the revision handle and root
    /// hash are returned.
    Ok {
        /// An opaque pointer to the [`RevisionHandle`].
        /// The value should be freed with [`fwd_free_revision`]
        ///
        /// [`fwd_free_revision`]: crate::fwd_free_revision
        handle: Box<RevisionHandle<'db>>,
        /// The root hash of the revision.
        root_hash: HashKey,
    },
    /// An error occurred and the message is returned as an [`OwnedBytes`]. The
    /// value is guaranteed to contain only valid UTF-8.
    ///
    /// The caller must call [`fwd_free_owned_bytes`] to free the memory
    /// associated with this error.
    ///
    /// [`fwd_free_owned_bytes`]: crate::fwd_free_owned_bytes
    Err(OwnedBytes),
}

/// A result type returned from FFI functions that create a reconstructed view.
#[derive(Debug)]
#[repr(C, usize)]
pub enum ReconstructedResult<'db> {
    /// The caller provided a null pointer to an input handle.
    NullHandlePointer,
    /// Building the reconstructed view was successful and the handle is returned.
    Ok {
        /// An opaque pointer to the [`ReconstructedHandle`].
        /// The value should be freed with [`fwd_free_reconstructed`].
        ///
        /// [`fwd_free_reconstructed`]: crate::fwd_free_reconstructed
        handle: Box<ReconstructedHandle<'db>>,
    },
    /// An error occurred and the message is returned as an [`OwnedBytes`].
    Err(OwnedBytes),
}

impl<'db> From<GetRevisionResult<'db>> for RevisionResult<'db> {
    fn from(value: GetRevisionResult<'db>) -> Self {
        RevisionResult::Ok {
            handle: Box::new(value.handle),
            root_hash: HashKey::from(value.root_hash),
        }
    }
}

impl<'db> From<Result<GetRevisionResult<'db>, api::Error>> for RevisionResult<'db> {
    fn from(value: Result<GetRevisionResult<'db>, api::Error>) -> Self {
        match value {
            Ok(res) => res.into(),
            Err(api::Error::RevisionNotFound { provided }) => RevisionResult::RevisionNotFound(
                HashKey::from(provided.unwrap_or_else(api::HashKey::empty)),
            ),
            Err(err) => RevisionResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

impl<'db, E: fmt::Display> From<Result<CreateProposalResult<'db>, E>> for ProposalResult<'db> {
    fn from(value: Result<CreateProposalResult<'db>, E>) -> Self {
        match value {
            Ok(CreateProposalResult { handle, .. }) => ProposalResult::Ok {
                root_hash: handle.hash_key().unwrap_or_default(),
                handle: Box::new(handle),
            },
            Err(err) => ProposalResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

impl<'db, E: fmt::Display> From<Result<ReconstructedHandle<'db>, E>> for ReconstructedResult<'db> {
    fn from(value: Result<ReconstructedHandle<'db>, E>) -> Self {
        match value {
            Ok(handle) => ReconstructedResult::Ok {
                handle: Box::new(handle),
            },
            Err(err) => ReconstructedResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

impl From<Result<api::FrozenChangeProof, api::Error>> for ChangeProofResult {
    fn from(value: Result<api::FrozenChangeProof, api::Error>) -> Self {
        match value {
            Ok(proof) => ChangeProofResult::Ok(Box::new(proof.into())),
            Err(api::Error::StartRevisionNotFound { provided }) => {
                ChangeProofResult::StartRevisionNotFound(HashKey::from(
                    provided.unwrap_or_else(api::HashKey::empty),
                ))
            }
            Err(api::Error::EndRevisionNotFound { provided }) => {
                ChangeProofResult::EndRevisionNotFound(HashKey::from(
                    provided.unwrap_or_else(api::HashKey::empty),
                ))
            }
            Err(err) => ChangeProofResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

impl From<Result<VerifiedChangeProofContext, api::Error>> for VerifiedChangeProofResult {
    fn from(value: Result<VerifiedChangeProofContext, api::Error>) -> Self {
        match value {
            Ok(context) => VerifiedChangeProofResult::Ok(Box::new(context)),
            Err(err) => VerifiedChangeProofResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

impl<'db> From<Result<ProposedChangeProofContext<'db>, api::Error>>
    for ProposedChangeProofResult<'db>
{
    fn from(value: Result<ProposedChangeProofContext<'db>, api::Error>) -> Self {
        match value {
            Ok(context) => ProposedChangeProofResult::Ok(Box::new(context)),
            Err(err) => ProposedChangeProofResult::Err(err.to_string().into_bytes().into()),
        }
    }
}

/// Helper trait to handle the different result types returned from FFI functions.
///
/// Once Try trait is stable, we can use that instead of this trait:
///
/// ```ignore
/// impl std::ops::FromResidual<Option<std::convert::Infallible>> for VoidResult {
///     #[inline]
///     fn from_residual(residual: Option<std::convert::Infallible>) -> Self {
///         match residual {
///             None => VoidResult::NullHandlePointer,
///             // no other branches are needed because `std::convert::Infallible` is uninhabited
///             // this compiles without error because the compiler knows that Some(_) is impossible
///             // see: https://github.com/rust-lang/rust/blob/3fb1b53a9dbfcdf37a4b67d35cde373316829930/library/core/src/option.rs#L2627-L2631
///             // and: https://doc.rust-lang.org/nomicon/exotic-sizes.html#empty-types
///         }
///     }
/// }
/// ```
pub(crate) trait NullHandleResult: CResult {
    fn null_handle_pointer_error() -> Self;
}

pub(crate) trait CResult: Sized {
    #[cfg(panic = "unwind")]
    fn from_err(err: impl ToString) -> Self;

    #[cfg(panic = "unwind")]
    fn from_panic(panic: Box<dyn std::any::Any + Send>) -> Self
    where
        Self: Sized,
    {
        Self::from_err(Panic::from(panic))
    }
}

macro_rules! impl_null_handle_result {
    ($($Enum:ty),* $(,)?) => {
        $(
            impl NullHandleResult for $Enum {
                fn null_handle_pointer_error() -> Self {
                    Self::NullHandlePointer
                }
            }
        )*
    };
}

macro_rules! impl_cresult {
    ($($Enum:ty),* $(,)?) => {
        $(
            impl CResult for $Enum {
                #[cfg(panic = "unwind")]
                fn from_err(err: impl ToString) -> Self {
                    Self::Err(err.to_string().into_bytes().into())
                }
            }
        )*
    };
}

impl_null_handle_result!(
    VoidResult,
    ValueResult,
    HashResult,
    RangeProofResult<'_>,
    ChangeProofResult,
    VerifiedChangeProofResult,
    ProposedChangeProofResult<'_>,
    NextKeyRangeResult,
    CodeIteratorResult<'_>,
    ProposalResult<'_>,
    ReconstructedResult<'_>,
    IteratorResult<'_>,
    RevisionResult<'_>,
    KeyValueBatchResult,
    KeyValueResult,
);

impl_cresult!(
    VoidResult,
    ValueResult,
    HashResult,
    HandleResult,
    RangeProofResult<'_>,
    ChangeProofResult,
    VerifiedChangeProofResult,
    ProposedChangeProofResult<'_>,
    NextKeyRangeResult,
    CodeIteratorResult<'_>,
    ProposalResult<'_>,
    ReconstructedResult<'_>,
    IteratorResult<'_>,
    RevisionResult<'_>,
    KeyValueBatchResult,
    KeyValueResult,
);

#[cfg(panic = "unwind")]
enum Panic {
    Static(&'static str),
    Formatted(String),
    SendSyncErr(Box<dyn std::error::Error + Send + Sync>),
    SendErr(Box<dyn std::error::Error + Send>),
    Unknown(#[expect(unused)] Box<dyn std::any::Any + Send>),
    // TODO: add variant to capture backtrace with panic hook
    // https://doc.rust-lang.org/stable/std/panic/fn.set_hook.html
}

#[cfg(panic = "unwind")]
impl From<Box<dyn std::any::Any + Send>> for Panic {
    fn from(panic: Box<dyn std::any::Any + Send>) -> Self {
        macro_rules! downcast {
            ($Variant:ident($panic:ident)) => {
                let $panic = match $panic.downcast() {
                    Ok(panic) => return Panic::$Variant(*panic),
                    Err(panic) => panic,
                };
            };
        }

        downcast!(Static(panic));
        downcast!(Formatted(panic));
        downcast!(SendSyncErr(panic));
        downcast!(SendErr(panic));

        Self::Unknown(panic)
    }
}

#[cfg(panic = "unwind")]
impl fmt::Display for Panic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Panic::Static(msg) => f.pad(msg),
            Panic::Formatted(msg) => f.pad(msg),
            Panic::SendSyncErr(err) => err.fmt(f),
            Panic::SendErr(err) => err.fmt(f),
            Panic::Unknown(_) => f.pad("unknown panic type recovered"),
        }
    }
}