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
use arc_bytes::serde::Bytes;
use serde::{Deserialize, Serialize};

mod timestamp;

pub use self::timestamp::Timestamp;
use crate::Error;

mod implementation {
    use arc_bytes::serde::Bytes;
    use async_trait::async_trait;
    use futures::future::BoxFuture;
    use serde::Serialize;

    use crate::keyvalue::{Command, KeyCheck, KeyOperation, KeyStatus, Output, Timestamp};
    use crate::Error;

    /// Types for executing get operations.
    pub mod get;
    /// Types for executing increment/decrement operations.
    pub mod increment;
    /// Types for handling key namespaces.
    pub mod namespaced;
    /// Types for executing set operations.
    pub mod set;

    use namespaced::Namespaced;

    use super::{IncompatibleTypeError, Numeric, Value};
    /// Key-Value store methods. The Key-Value store is designed to be a
    /// high-performance, lightweight storage mechanism.
    ///
    /// When compared to Collections, the Key-Value store does not offer
    /// ACID-compliant transactions. Instead, the Key-Value store is made more
    /// efficient by periodically flushing the store to disk rather than during
    /// each operation. As such, the Key-Value store is intended to be used as a
    /// lightweight caching layer. However, because each of the operations it
    /// supports are executed atomically, the Key-Value store can also be
    /// utilized for synchronized locking.
    ///
    /// ## Floating Point Operations
    ///
    /// When using [`KeyValue::set_numeric_key()`] or any numeric operations, if
    /// a [Not a Number (NaN) value][nan] is encountered, [`Error::NotANumber`]
    /// will be returned without allowing the operation to succeed.
    ///
    /// Positive and negative infinity values are allowed, as they do not break
    /// comparison operations.
    ///
    /// [nan]: https://en.wikipedia.org/wiki/NaN
    pub trait KeyValue: Sized + Send + Sync {
        /// Executes a single [`KeyOperation`].
        fn execute_key_operation(&self, op: KeyOperation) -> Result<Output, Error>;

        /// Sets `key` to `value`. This function returns a builder that is also a
        /// Future. Awaiting the builder will execute [`Command::Set`] with the options
        /// given.
        fn set_key<'a, S: Into<String>, V: Serialize + Send + Sync>(
            &'a self,
            key: S,
            value: &'a V,
        ) -> set::Builder<'a, Self, V> {
            set::Builder::new(
                self,
                self.key_namespace().map(Into::into),
                key.into(),
                PendingValue::Serializeable(value),
            )
        }

        /// Sets `key` to `bytes`. This function returns a builder that is also
        /// a Future. Awaiting the builder will execute [`Command::Set`] with
        /// the options given.
        fn set_binary_key<'a, S: Into<String>>(
            &'a self,
            key: S,
            bytes: &'a [u8],
        ) -> set::Builder<'a, Self, ()> {
            set::Builder::new(
                self,
                self.key_namespace().map(Into::into),
                key.into(),
                PendingValue::Bytes(bytes),
            )
        }

        /// Sets `key` to `value`. This stores the value as a `Numeric`,
        /// enabling atomic math operations to be performed on this key. This
        /// function returns a builder that is also a Future. Awaiting the
        /// builder will execute [`Command::Set`] with the options given.
        fn set_numeric_key<S: Into<String>, V: Into<Numeric>>(
            &self,
            key: S,
            value: V,
        ) -> set::Builder<'_, Self, ()> {
            set::Builder::new(
                self,
                self.key_namespace().map(Into::into),
                key.into(),
                PendingValue::Numeric(value.into()),
            )
        }

        /// Increments `key` by `value`. The value stored must be a `Numeric`,
        /// otherwise an error will be returned. The result of the increment
        /// will be the `value`'s type. For example, if the stored value is
        /// currently a `u64`, but `value` is a `f64`, the current value will be
        /// converted to an `f64`, and the stored value will be an `f64`.
        fn increment_key_by<
            S: Into<String> + Send + Sync,
            V: Into<Numeric> + TryFrom<Numeric, Error = IncompatibleTypeError> + Send + Sync,
        >(
            &self,
            key: S,
            value: V,
        ) -> increment::Builder<'_, Self, V> {
            increment::Builder::new(
                self,
                self.key_namespace().map(Into::into),
                true,
                key.into(),
                value.into(),
            )
        }

        /// Decrements `key` by `value`. The value stored must be a `Numeric`,
        /// otherwise an error will be returned. The result of the decrement
        /// will be the `value`'s type. For example, if the stored value is
        /// currently a `u64`, but `value` is a `f64`, the current value will be
        /// converted to an `f64`, and the stored value will be an `f64`.
        fn decrement_key_by<
            S: Into<String> + Send + Sync,
            V: Into<Numeric> + TryFrom<Numeric, Error = IncompatibleTypeError> + Send + Sync,
        >(
            &self,
            key: S,
            value: V,
        ) -> increment::Builder<'_, Self, V> {
            increment::Builder::new(
                self,
                self.key_namespace().map(Into::into),
                false,
                key.into(),
                value.into(),
            )
        }

        /// Gets the value stored at `key`. This function returns a builder that is also a
        /// Future. Awaiting the builder will execute [`Command::Get`] with the options
        /// given.
        fn get_key<S: Into<String>>(&'_ self, key: S) -> get::Builder<'_, Self> {
            get::Builder::new(self, self.key_namespace().map(Into::into), key.into())
        }

        /// Deletes the value stored at `key`.
        fn delete_key<S: Into<String> + Send>(&'_ self, key: S) -> Result<KeyStatus, Error> {
            match self.execute_key_operation(KeyOperation {
                namespace: self.key_namespace().map(ToOwned::to_owned),
                key: key.into(),
                command: Command::Delete,
            })? {
                Output::Status(status) => Ok(status),
                Output::Value(_) => unreachable!("invalid output from delete operation"),
            }
        }

        /// The current namespace.
        fn key_namespace(&self) -> Option<&'_ str> {
            None
        }

        /// Access this Key-Value store within a namespace. When using the returned
        /// [`Namespaced`] instance, all keys specified will be separated into their
        /// own storage designated by `namespace`.
        fn with_key_namespace(&'_ self, namespace: &str) -> Namespaced<'_, Self> {
            Namespaced::new(namespace.to_string(), self)
        }
    }

    /// Key-Value store methods. The Key-Value store is designed to be a
    /// high-performance, lightweight storage mechanism.
    ///
    /// When compared to Collections, the Key-Value store does not offer
    /// ACID-compliant transactions. Instead, the Key-Value store is made more
    /// efficient by periodically flushing the store to disk rather than during
    /// each operation. As such, the Key-Value store is intended to be used as a
    /// lightweight caching layer. However, because each of the operations it
    /// supports are executed atomically, the Key-Value store can also be
    /// utilized for synchronized locking.
    ///
    /// ## Floating Point Operations
    ///
    /// When using [`KeyValue::set_numeric_key()`] or any numeric operations, if
    /// a [Not a Number (NaN) value][nan] is encountered, [`Error::NotANumber`]
    /// will be returned without allowing the operation to succeed.
    ///
    /// Positive and negative infinity values are allowed, as they do not break
    /// comparison operations.
    ///
    /// [nan]: https://en.wikipedia.org/wiki/NaN
    #[async_trait]
    pub trait AsyncKeyValue: Sized + Send + Sync {
        /// Executes a single [`KeyOperation`].
        async fn execute_key_operation(&self, op: KeyOperation) -> Result<Output, Error>;

        /// Sets `key` to `value`. This function returns a builder that is also a
        /// Future. Awaiting the builder will execute [`Command::Set`] with the options
        /// given.
        fn set_key<'a, S: Into<String>, V: Serialize + Send + Sync>(
            &'a self,
            key: S,
            value: &'a V,
        ) -> set::AsyncBuilder<'a, Self, V> {
            set::AsyncBuilder::new(
                self,
                self.key_namespace().map(Into::into),
                key.into(),
                PendingValue::Serializeable(value),
            )
        }

        /// Sets `key` to `bytes`. This function returns a builder that is also
        /// a Future. Awaiting the builder will execute [`Command::Set`] with
        /// the options given.
        fn set_binary_key<'a, S: Into<String>>(
            &'a self,
            key: S,
            bytes: &'a [u8],
        ) -> set::AsyncBuilder<'a, Self, ()> {
            set::AsyncBuilder::new(
                self,
                self.key_namespace().map(Into::into),
                key.into(),
                PendingValue::Bytes(bytes),
            )
        }

        /// Sets `key` to `value`. This stores the value as a `Numeric`,
        /// enabling atomic math operations to be performed on this key. This
        /// function returns a builder that is also a Future. Awaiting the
        /// builder will execute [`Command::Set`] with the options given.
        fn set_numeric_key<S: Into<String>, V: Into<Numeric>>(
            &self,
            key: S,
            value: V,
        ) -> set::AsyncBuilder<'_, Self, ()> {
            set::AsyncBuilder::new(
                self,
                self.key_namespace().map(Into::into),
                key.into(),
                PendingValue::Numeric(value.into()),
            )
        }

        /// Increments `key` by `value`. The value stored must be a `Numeric`,
        /// otherwise an error will be returned. The result of the increment
        /// will be the `value`'s type. For example, if the stored value is
        /// currently a `u64`, but `value` is a `f64`, the current value will be
        /// converted to an `f64`, and the stored value will be an `f64`.
        fn increment_key_by<
            S: Into<String> + Send + Sync,
            V: Into<Numeric> + TryFrom<Numeric, Error = IncompatibleTypeError> + Send + Sync,
        >(
            &self,
            key: S,
            value: V,
        ) -> increment::AsyncBuilder<'_, Self, V> {
            increment::AsyncBuilder::new(
                self,
                self.key_namespace().map(Into::into),
                true,
                key.into(),
                value.into(),
            )
        }

        /// Decrements `key` by `value`. The value stored must be a `Numeric`,
        /// otherwise an error will be returned. The result of the decrement
        /// will be the `value`'s type. For example, if the stored value is
        /// currently a `u64`, but `value` is a `f64`, the current value will be
        /// converted to an `f64`, and the stored value will be an `f64`.
        fn decrement_key_by<
            S: Into<String> + Send + Sync,
            V: Into<Numeric> + TryFrom<Numeric, Error = IncompatibleTypeError> + Send + Sync,
        >(
            &self,
            key: S,
            value: V,
        ) -> increment::AsyncBuilder<'_, Self, V> {
            increment::AsyncBuilder::new(
                self,
                self.key_namespace().map(Into::into),
                false,
                key.into(),
                value.into(),
            )
        }

        /// Gets the value stored at `key`. This function returns a builder that is also a
        /// Future. Awaiting the builder will execute [`Command::Get`] with the options
        /// given.
        fn get_key<S: Into<String>>(&'_ self, key: S) -> get::AsyncBuilder<'_, Self> {
            get::AsyncBuilder::new(self, self.key_namespace().map(Into::into), key.into())
        }

        /// Deletes the value stored at `key`.
        async fn delete_key<S: Into<String> + Send>(&'_ self, key: S) -> Result<KeyStatus, Error> {
            match self
                .execute_key_operation(KeyOperation {
                    namespace: self.key_namespace().map(ToOwned::to_owned),
                    key: key.into(),
                    command: Command::Delete,
                })
                .await?
            {
                Output::Status(status) => Ok(status),
                Output::Value(_) => unreachable!("invalid output from delete operation"),
            }
        }

        /// The current namespace.
        fn key_namespace(&self) -> Option<&'_ str> {
            None
        }

        /// Access this Key-Value store within a namespace. When using the returned
        /// [`Namespaced`] instance, all keys specified will be separated into their
        /// own storage designated by `namespace`.
        fn with_key_namespace(&'_ self, namespace: &str) -> Namespaced<'_, Self> {
            Namespaced::new(namespace.to_string(), self)
        }
    }

    enum BuilderState<'a, T, V> {
        Pending(Option<T>),
        Executing(BoxFuture<'a, V>),
    }

    #[allow(clippy::redundant_pub_crate)]
    pub(crate) enum PendingValue<'a, V> {
        Bytes(&'a [u8]),
        Serializeable(&'a V),
        Numeric(Numeric),
    }

    impl<'a, V> PendingValue<'a, V>
    where
        V: Serialize,
    {
        fn prepare(self) -> Result<Value, Error> {
            match self {
                Self::Bytes(bytes) => Ok(Value::Bytes(Bytes::from(bytes))),
                Self::Serializeable(value) => Ok(Value::Bytes(Bytes::from(pot::to_vec(value)?))),
                Self::Numeric(numeric) => Ok(Value::Numeric(numeric)),
            }
        }
    }
}

pub use implementation::*;

/// Checks for existing keys.
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
pub enum KeyCheck {
    /// Only allow the operation if an existing key is present.
    OnlyIfPresent,
    /// Only allow the opeartion if the key isn't present.
    OnlyIfVacant,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
/// An operation performed on a key.
pub struct KeyOperation {
    /// The namespace for the key.
    pub namespace: Option<String>,
    /// The key to operate on.
    pub key: String,
    /// The command to execute.
    pub command: Command,
}

/// Commands for a key-value store.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum Command {
    /// Set a key/value pair.
    Set(SetCommand),
    /// Get the value from a key.
    Get {
        /// Remove the key after retrieving the value.
        delete: bool,
    },
    /// Increment a numeric key. Returns an error if the key cannot be
    /// deserialized to the same numeric type as `amount`. If `saturating` is
    /// true, overflows will be prevented and the value will remain within the
    /// numeric bounds.
    Increment {
        /// The amount to increment by.
        amount: Numeric,
        /// If true, the result will be constrained to the numerical bounds of
        /// the type of `amount`.
        saturating: bool,
    },
    /// Decrement a numeric key. Returns an error if the key cannot be
    /// deserialized to the same numeric type as `amount`. If `saturating` is
    /// true, overflows will be prevented and the value will remain within the
    /// numeric bounds.
    Decrement {
        /// The amount to increment by.
        amount: Numeric,
        /// If true, the result will be constrained to the numerical bounds of
        /// the type of `amount`.
        saturating: bool,
    },
    /// Delete a key.
    Delete,
}

/// Set a key/value pair.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct SetCommand {
    /// The value.
    pub value: Value,
    /// If set, the key will be set to expire automatically.
    pub expiration: Option<Timestamp>,
    /// If true and the key already exists, the expiration will not be
    /// updated. If false and an expiration is provided, the expiration will
    /// be set.
    pub keep_existing_expiration: bool,
    /// Conditional checks for whether the key is already present or not.
    pub check: Option<KeyCheck>,
    /// If true and the key already exists, the existing key will be returned if overwritten.
    pub return_previous_value: bool,
}

/// A value stored in a key.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum Value {
    /// A value stored as a byte array.
    Bytes(Bytes),
    /// A numeric value.
    Numeric(Numeric),
}

impl Value {
    /// Validates this value to ensure it is safe to store.
    pub fn validate(self) -> Result<Self, Error> {
        match self {
            Self::Numeric(numeric) => numeric.validate().map(Self::Numeric),
            Self::Bytes(vec) => Ok(Self::Bytes(vec)),
        }
    }

    /// Deserializes the bytes contained inside of this value. Returns an error
    /// if this value doesn't contain bytes.
    pub fn deserialize<V: for<'de> Deserialize<'de>>(&self) -> Result<V, Error> {
        match self {
            Self::Bytes(bytes) => Ok(pot::from_slice(bytes)?),
            Self::Numeric(_) => Err(Error::other(
                "key-value",
                "key contains numeric value, not serialized data",
            )),
        }
    }

    /// Returns this value as an `i64`, allowing for precision to be lost if the type was not an `i64` originally. If saturating is true, the conversion will not allow overflows. Returns None if the value is bytes.
    #[must_use]
    pub fn as_i64_lossy(&self, saturating: bool) -> Option<i64> {
        match self {
            Self::Bytes(_) => None,
            Self::Numeric(value) => Some(value.as_i64_lossy(saturating)),
        }
    }

    /// Returns this value as an `u64`, allowing for precision to be lost if the type was not an `u64` originally. If saturating is true, the conversion will not allow overflows. Returns None if the value is bytes.
    #[must_use]
    pub fn as_u64_lossy(&self, saturating: bool) -> Option<u64> {
        match self {
            Self::Bytes(_) => None,
            Self::Numeric(value) => Some(value.as_u64_lossy(saturating)),
        }
    }

    /// Returns this value as an `f64`, allowing for precision to be lost if the type was not an `f64` originally. Returns None if the value is bytes.
    #[must_use]
    pub const fn as_f64_lossy(&self) -> Option<f64> {
        match self {
            Self::Bytes(_) => None,
            Self::Numeric(value) => Some(value.as_f64_lossy()),
        }
    }

    /// Returns this numeric as an `i64`, allowing for precision to be lost if the type was not an `i64` originally. Returns None if the value is bytes.
    #[must_use]
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Self::Bytes(_) => None,
            Self::Numeric(value) => value.as_i64(),
        }
    }

    /// Returns this numeric as an `u64`, allowing for precision to be lost if the type was not an `u64` originally. Returns None if the value is bytes.
    #[must_use]
    pub fn as_u64(&self) -> Option<u64> {
        match self {
            Self::Bytes(_) => None,
            Self::Numeric(value) => value.as_u64(),
        }
    }

    /// Returns this numeric as an `f64`, allowing for precision to be lost if the type was not an `f64` originally. Returns None if the value is bytes.
    #[must_use]
    pub const fn as_f64(&self) -> Option<f64> {
        match self {
            Self::Bytes(_) => None,
            Self::Numeric(value) => value.as_f64(),
        }
    }
}

/// A numerical value.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum Numeric {
    /// A 64-bit signed integer.
    Integer(i64),
    /// A 64-bit unsigned integer.
    UnsignedInteger(u64),
    /// A 64-bit floating point number.
    Float(f64),
}

impl Numeric {
    /// Ensures this value contains a valid value.
    ///
    /// # Errors
    ///
    /// [`Error::NotANumber`] is returned if this contains a NaN floating point
    /// value.
    pub fn validate(self) -> Result<Self, Error> {
        if let Self::Float(float) = self {
            if float.is_nan() {
                return Err(Error::NotANumber);
            }
        }

        Ok(self)
    }

    /// Returns this numeric as an `i64`. If this conversion cannot be done
    /// without losing precision or overflowing, None will be returned.
    #[must_use]
    #[allow(clippy::cast_possible_truncation)]
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Self::Integer(value) => Some(*value),
            Self::UnsignedInteger(value) => (*value).try_into().ok(),
            Self::Float(value) => {
                if value.fract().abs() > 0. {
                    None
                } else {
                    Some(*value as i64)
                }
            }
        }
    }

    /// Returns this numeric as an `i64`, allowing for precision to be lost if
    /// the type was not an `i64` originally. If saturating is true, the
    /// conversion will not allow overflows.
    #[must_use]
    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    pub fn as_i64_lossy(&self, saturating: bool) -> i64 {
        match self {
            Self::Integer(value) => *value,
            Self::UnsignedInteger(value) => {
                if saturating {
                    (*value).try_into().unwrap_or(i64::MAX)
                } else {
                    *value as i64
                }
            }
            Self::Float(value) => *value as i64,
        }
    }

    /// Returns this numeric as an `u64`. If this conversion cannot be done
    /// without losing precision or overflowing, None will be returned.
    #[must_use]
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
    pub fn as_u64(&self) -> Option<u64> {
        match self {
            Self::UnsignedInteger(value) => Some(*value),
            Self::Integer(value) => (*value).try_into().ok(),
            Self::Float(value) => {
                if value.fract() < f64::EPSILON && value.is_sign_positive() {
                    Some(*value as u64)
                } else {
                    None
                }
            }
        }
    }

    /// Returns this numeric as an `u64`, allowing for precision to be lost if
    /// the type was not an `i64` originally. If saturating is true, the
    /// conversion will not allow overflows.
    #[must_use]
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
    pub fn as_u64_lossy(&self, saturating: bool) -> u64 {
        match self {
            Self::UnsignedInteger(value) => *value,
            Self::Integer(value) => {
                if saturating {
                    (*value).try_into().unwrap_or(0)
                } else {
                    *value as u64
                }
            }
            Self::Float(value) => *value as u64,
        }
    }

    /// Returns this numeric as an `f64`. If this conversion cannot be done
    /// without losing precision, None will be returned.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub const fn as_f64(&self) -> Option<f64> {
        match self {
            Self::UnsignedInteger(value) => {
                if *value > 2_u64.pow(f64::MANTISSA_DIGITS) {
                    None
                } else {
                    Some(*value as f64)
                }
            }
            Self::Integer(value) => {
                if *value > 2_i64.pow(f64::MANTISSA_DIGITS)
                    || *value < -(2_i64.pow(f64::MANTISSA_DIGITS))
                {
                    None
                } else {
                    Some(*value as f64)
                }
            }
            Self::Float(value) => Some(*value),
        }
    }

    /// Returns this numeric as an `f64`, allowing for precision to be lost if
    /// the type was not an `f64` originally.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub const fn as_f64_lossy(&self) -> f64 {
        match self {
            Self::UnsignedInteger(value) => *value as f64,
            Self::Integer(value) => *value as f64,
            Self::Float(value) => *value,
        }
    }
}

/// A conversion between numeric types wasn't supported.
#[derive(thiserror::Error, Debug)]
#[error("incompatible numeric type")]
pub struct IncompatibleTypeError;

impl From<f64> for Numeric {
    fn from(value: f64) -> Self {
        Self::Float(value)
    }
}

impl From<i64> for Numeric {
    fn from(value: i64) -> Self {
        Self::Integer(value)
    }
}

impl From<u64> for Numeric {
    fn from(value: u64) -> Self {
        Self::UnsignedInteger(value)
    }
}

#[allow(clippy::fallible_impl_from)]
impl TryFrom<Numeric> for f64 {
    type Error = IncompatibleTypeError;

    fn try_from(value: Numeric) -> Result<Self, IncompatibleTypeError> {
        if let Numeric::Float(value) = value {
            Ok(value)
        } else {
            Err(IncompatibleTypeError)
        }
    }
}

#[allow(clippy::fallible_impl_from)]
impl TryFrom<Numeric> for u64 {
    type Error = IncompatibleTypeError;

    fn try_from(value: Numeric) -> Result<Self, IncompatibleTypeError> {
        if let Numeric::UnsignedInteger(value) = value {
            Ok(value)
        } else {
            Err(IncompatibleTypeError)
        }
    }
}

#[allow(clippy::fallible_impl_from)]
impl TryFrom<Numeric> for i64 {
    type Error = IncompatibleTypeError;

    fn try_from(value: Numeric) -> Result<Self, IncompatibleTypeError> {
        if let Numeric::Integer(value) = value {
            Ok(value)
        } else {
            Err(IncompatibleTypeError)
        }
    }
}

/// The result of a [`KeyOperation`].
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum Output {
    /// A status was returned.
    Status(KeyStatus),
    /// A value was returned.
    Value(Option<Value>),
}
/// The status of an operation on a Key.
#[derive(Copy, Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
pub enum KeyStatus {
    /// A new key was inserted.
    Inserted,
    /// An existing key was updated with a new value.
    Updated,
    /// A key was deleted.
    Deleted,
    /// No changes were made.
    NotChanged,
}