aerospike-core 2.1.0

Aerospike Client for Rust
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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
// Copyright 2015-2018 Aerospike, Inc.
//
// Portions may be licensed to Aerospike, Inc. under one or more contributor
// license agreements.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

use std::cmp::{Ordering, PartialOrd};
use std::collections::{BTreeMap, HashMap};
use std::convert::TryFrom;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::result::Result as StdResult;

use byteorder::{ByteOrder, NetworkEndian};

use ripemd::digest::Digest;
use ripemd::Ripemd160;

use std::vec::Vec;

use crate::commands::buffer::Buffer;
use crate::commands::ParticleType;
use crate::errors::{Error, Result};
use crate::msgpack::{decoder, encoder};

#[cfg(feature = "serialization")]
use serde::ser::{SerializeMap, SerializeSeq};
#[cfg(feature = "serialization")]
use serde::{Serialize, Serializer};

/// Container for floating point bin values stored in the Aerospike database.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FloatValue {
    /// Container for single precision float values.
    F32(u32),
    /// Container for double precision float values.
    F64(u64),
}

impl From<FloatValue> for f64 {
    fn from(val: FloatValue) -> f64 {
        match val {
            FloatValue::F32(_) => panic!(
                "This library does not automatically convert f32 -> f64 to be used in keys \
                 or bins."
            ),
            FloatValue::F64(val) => f64::from_bits(val),
        }
    }
}

impl From<&FloatValue> for f64 {
    fn from(val: &FloatValue) -> f64 {
        match *val {
            FloatValue::F32(_) => panic!(
                "This library does not automatically convert f32 -> f64 to be used in keys \
                 or bins."
            ),
            FloatValue::F64(val) => f64::from_bits(val),
        }
    }
}

impl From<f64> for FloatValue {
    fn from(val: f64) -> FloatValue {
        let mut val = val;
        if val.is_nan() {
            val = f64::NAN;
        } // make all NaNs have the same representation
        FloatValue::F64(val.to_bits())
    }
}

impl From<&f64> for FloatValue {
    fn from(val: &f64) -> FloatValue {
        let mut val = *val;
        if val.is_nan() {
            val = f64::NAN;
        } // make all NaNs have the same representation
        FloatValue::F64(val.to_bits())
    }
}

impl From<FloatValue> for f32 {
    fn from(val: FloatValue) -> f32 {
        match val {
            FloatValue::F32(val) => f32::from_bits(val),
            FloatValue::F64(val) => f32::from_bits(val as u32),
        }
    }
}

impl From<&FloatValue> for f32 {
    fn from(val: &FloatValue) -> f32 {
        match *val {
            FloatValue::F32(val) => f32::from_bits(val),
            FloatValue::F64(val) => f32::from_bits(val as u32),
        }
    }
}

impl From<f32> for FloatValue {
    fn from(val: f32) -> FloatValue {
        let mut val = val;
        if val.is_nan() {
            val = f32::NAN;
        } // make all NaNs have the same representation
        FloatValue::F32(val.to_bits())
    }
}

impl From<&f32> for FloatValue {
    fn from(val: &f32) -> FloatValue {
        let mut val = *val;
        if val.is_nan() {
            val = f32::NAN;
        } // make all NaNs have the same representation
        FloatValue::F32(val.to_bits())
    }
}

impl fmt::Display for FloatValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> StdResult<(), fmt::Error> {
        match *self {
            FloatValue::F32(val) => {
                let val: f32 = f32::from_bits(val);
                write!(f, "{val}")
            }
            FloatValue::F64(val) => {
                let val: f64 = f64::from_bits(val);
                write!(f, "{val}")
            }
        }
    }
}

/// Container for bin values stored in the Aerospike database.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Value {
    /// Empty value.
    Nil,

    /// Boolean value.
    Bool(bool),

    /// Integer value. All integers are represented as 64-bit numerics in Aerospike.
    Int(i64),

    /// Floating point value. All floating point values are stored in 64-bit IEEE-754 format in
    /// Aerospike. Aerospike server v3.6.0 and later support double data type.
    Float(FloatValue),

    /// String value.
    String(String),

    /// Byte array value.
    Blob(Vec<u8>),

    /// List data type is an ordered collection of values. Lists can contain values of any
    /// supported data type. List data order is maintained on writes and reads.
    List(Vec<Value>),

    /// Returned in cases where the server executes multiple operations for the same bin.
    /// This value is only sent from the server to the client, and can't be sent from the
    /// client to the server.
    MultiResult(Vec<Value>),

    /// Map data type is a collection of key-value pairs. Each key can only appear once in a
    /// collection and is associated with a value. Map values can be any supported data
    /// type.
    /// Map keys can only be of type String, Bytes, Integer, and that this will be enforced by the client and server.
    HashMap(HashMap<Value, Value>),

    /// `OrderedMap` data type where the map entries are sorted based key ordering (K-ordered maps).
    /// Each key can only appear once in a collection and is associated with a value.
    /// Map values can be any supported data type.
    /// Map keys can only be of type String, Bytes, Integer, and that this will be enforced by the client and server.
    OrderedMap(BTreeMap<Value, Value>),

    /// Result of any map operation in which the server returns a
    /// map requested with [`MapReturnType::KeyValue`].
    KeyValueList(Vec<(Value, Value)>),

    /// `GeoJSON` data type are JSON formatted strings to encode geo-spatial information.
    GeoJSON(String),

    /// HLL value
    HLL(Vec<u8>),

    /// Infinity Value
    Infinity,

    /// Infinity Value
    Wildcard,
}

#[allow(clippy::derived_hash_with_manual_eq)]
impl Hash for Value {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match *self {
            #[allow(clippy::collection_is_never_read)]
            Value::Nil => {
                let v: Option<u8> = None;
                v.hash(state);
            }
            Value::Bool(_) => panic!("Booleans cannot be used as map keys."),
            Value::Int(ref val) => val.hash(state),
            Value::Float(_) => panic!("Floats cannot be used as map keys."),
            Value::String(ref val) => val.hash(state),
            Value::GeoJSON(_) => panic!("GeoJson cannot be used as map keys."),
            Value::Blob(ref val) => val.hash(state),
            Value::HLL(_) => panic!("HLL cannot be used as map keys."),
            Value::MultiResult(_) => panic!("MultiValues cannot be used as map keys."),
            Value::List(_) => panic!("Lists cannot be used as map keys."),
            Value::HashMap(_) => panic!("HashMaps cannot be used as map keys."),
            Value::OrderedMap(_) | Value::KeyValueList(_) => {
                panic!("OrderedMaps cannot be used as map keys.")
            }
            Value::Infinity => panic!("Infinity cannot be used as map keys."),
            Value::Wildcard => panic!("Wildcard cannot be used as map keys."),
        }
    }
}

impl Value {
    /// Returns true if this value is the empty value (nil).
    pub const fn is_nil(&self) -> bool {
        matches!(*self, Value::Nil)
    }

    /// Return the particle type for the value used in the wire protocol.
    /// For internal use only.
    pub fn particle_type(&self) -> ParticleType {
        match *self {
            Value::Nil => ParticleType::NULL,
            Value::Int(_) => ParticleType::INTEGER,
            Value::Float(_) => ParticleType::FLOAT,
            Value::String(_) => ParticleType::STRING,
            Value::Blob(_) => ParticleType::BLOB,
            Value::Bool(_) => ParticleType::BOOL,
            Value::MultiResult(_) | Value::List(_) => ParticleType::LIST,
            Value::HashMap(_) | Value::OrderedMap(_) | Value::KeyValueList(_) => ParticleType::MAP,
            Value::GeoJSON(_) => ParticleType::GEOJSON,
            Value::HLL(_) => ParticleType::HLL,
            Value::Infinity | Value::Wildcard => unreachable!(),
        }
    }

    /// Returns a string representation of the value.
    pub fn as_string(&self) -> String {
        match *self {
            Value::Nil => "<null>".to_string(),
            Value::Int(ref val) => val.to_string(),
            Value::Bool(ref val) => val.to_string(),
            Value::Float(ref val) => val.to_string(),
            Value::String(ref val) | Value::GeoJSON(ref val) => val.clone(),
            Value::Blob(ref val) | Value::HLL(ref val) => format!("{val:?}"),
            Value::MultiResult(ref val) | Value::List(ref val) => format!("{val:?}"),
            Value::HashMap(ref val) => format!("{val:?}"),
            Value::OrderedMap(ref val) => format!("{val:?}"),
            Value::KeyValueList(ref val) => format!("{val:?}"),
            Value::Infinity => "INF".into(),
            Value::Wildcard => "*".into(),
        }
    }

    /// Calculate the size in bytes that the representation on wire for this value will require.
    /// For internal use only.
    pub(crate) fn estimate_size(&self) -> Result<usize> {
        let res = match *self {
            Value::Int(_) | Value::Float(_) => 8,
            Value::String(ref s) => s.len(),
            Value::Blob(ref b) => b.len(),
            Value::Bool(_) => 1,
            Value::MultiResult(_) => {
                return Err(Error::InvalidArgument("MultiValues are only returned as results from the server and never from the client.".into()));
            }
            Value::List(_) | Value::HashMap(_) | Value::OrderedMap(_) => {
                encoder::pack_value(&mut None, self)?
            }
            Value::KeyValueList(_) => {
                return Err(Error::InvalidArgument(
                    "The library never passes ordered maps to the server.".into(),
                ));
            }
            Value::GeoJSON(ref s) => 1 + 2 + s.len(), // flags + ncells + jsonstr
            Value::HLL(ref h) => h.len(),
            Value::Nil | Value::Infinity | Value::Wildcard => 0,
        };

        Ok(res)
    }

    /// Serialize the value into the given buffer.
    /// For internal use only.
    pub(crate) fn write_to(&self, buf: &mut Buffer) -> Result<usize> {
        let res = match *self {
            Value::Nil => 0,
            Value::Int(ref val) => buf.write_i64(*val),
            Value::Bool(ref val) => buf.write_bool(*val),
            Value::Float(ref val) => buf.write_f64(f64::from(val)),
            Value::String(ref val) => buf.write_str(val),
            Value::Blob(ref val) | Value::HLL(ref val) => buf.write_bytes(val),
            Value::MultiResult(_) => {
                return Err(Error::InvalidArgument("MultiValues are only returned as results from the server and never from the client.".into()));
            }
            Value::List(_) | Value::HashMap(_) | Value::OrderedMap(_) => {
                encoder::pack_value(&mut Some(buf), self)?
            }
            Value::KeyValueList(_) => {
                return Err(Error::InvalidArgument(
                    "The library never passes ordered maps to the server.".into(),
                ));
            }
            Value::GeoJSON(ref val) => buf.write_geo(val),
            Value::Infinity => encoder::pack_infinity(&mut Some(buf)),
            Value::Wildcard => encoder::pack_wildcard(&mut Some(buf)),
        };

        Ok(res)
    }

    /// Serialize the value as a record key.
    /// For internal use only.
    pub(crate) fn write_key_bytes(&self, h: &mut Ripemd160) -> Result<()> {
        match *self {
            Value::Int(ref val) => {
                let mut buf = [0; 8];
                NetworkEndian::write_i64(&mut buf, *val);
                h.update(buf);
                Ok(())
            }
            Value::String(ref val) => {
                h.update(val.as_bytes());
                Ok(())
            }
            Value::Blob(ref val) => {
                h.update(val);
                Ok(())
            }
            _ => Err(Error::InvalidArgument(
                "Data type is not supported as Key value.".into(),
            )),
        }
    }

    /// Order for Value types.
    pub(crate) const fn value_type_order(&self) -> u8 {
        match self {
            Value::Nil => 0,
            Value::Bool(_) => 1,
            Value::Int(_) => 2,
            Value::String(_) => 3,
            Value::List(_) => 4,
            Value::HashMap(_) => 5,
            Value::OrderedMap(_) => 6,
            Value::Blob(_) => 7,
            Value::HLL(_) => 8,
            Value::Float(_) => 9,
            Value::GeoJSON(_) => 10,
            // Just here for completion's sake
            Value::Infinity => 11,
            Value::Wildcard => 12,
            Value::MultiResult(_) => 13,
            Value::KeyValueList(_) => 14,
        }
    }
}

impl Ord for Value {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.value_type_order().cmp(&other.value_type_order()) {
            Ordering::Equal => {
                // Same type, compare by value
                match (self, other) {
                    (Value::Int(a_val), Value::Int(b_val)) => a_val.cmp(b_val),
                    (Value::String(a_val), Value::String(b_val))
                    | (Value::GeoJSON(a_val), Value::GeoJSON(b_val)) => a_val.cmp(b_val),
                    (Value::HLL(a_val), Value::HLL(b_val))
                    | (Value::Blob(a_val), Value::Blob(b_val)) => a_val.cmp(b_val),
                    (Value::Bool(a_val), Value::Bool(b_val)) => a_val.cmp(b_val),
                    (Value::HashMap(ref a_val), Value::HashMap(ref b_val)) => {
                        a_val.len().cmp(&b_val.len())
                    }
                    (Value::OrderedMap(ref a_val), Value::OrderedMap(ref b_val)) => {
                        a_val.len().cmp(&b_val.len())
                    }
                    (Value::KeyValueList(ref a_val), Value::KeyValueList(ref b_val)) => {
                        a_val.len().cmp(&b_val.len())
                    }
                    (Value::Float(a_val), Value::Float(b_val)) => {
                        // Compare float bits for deterministic ordering
                        let a_bits = match a_val {
                            FloatValue::F32(bits) => u64::from(*bits),
                            FloatValue::F64(bits) => *bits,
                        };

                        let b_bits = match b_val {
                            FloatValue::F32(bits) => u64::from(*bits),
                            FloatValue::F64(bits) => *bits,
                        };

                        a_bits.cmp(&b_bits)
                    }
                    _ => Ordering::Greater,
                }
            }

            ord => ord,
        }
    }
}

impl PartialOrd for Value {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter) -> StdResult<(), fmt::Error> {
        write!(f, "{}", self.as_string())
    }
}

impl From<String> for Value {
    fn from(val: String) -> Value {
        Value::String(val)
    }
}

impl From<Vec<u8>> for Value {
    fn from(val: Vec<u8>) -> Value {
        Value::Blob(val)
    }
}

impl From<Vec<Value>> for Value {
    fn from(val: Vec<Value>) -> Value {
        Value::List(val)
    }
}

impl From<HashMap<Value, Value>> for Value {
    fn from(val: HashMap<Value, Value>) -> Value {
        Value::HashMap(val)
    }
}

impl From<BTreeMap<Value, Value>> for Value {
    fn from(val: BTreeMap<Value, Value>) -> Value {
        Value::OrderedMap(val)
    }
}

impl From<f32> for Value {
    fn from(val: f32) -> Value {
        Value::Float(FloatValue::from(val))
    }
}

impl From<f64> for Value {
    fn from(val: f64) -> Value {
        Value::Float(FloatValue::from(val))
    }
}

impl<'a> From<&'a f32> for Value {
    fn from(val: &'a f32) -> Value {
        Value::Float(FloatValue::from(*val))
    }
}

impl<'a> From<&'a f64> for Value {
    fn from(val: &'a f64) -> Value {
        Value::Float(FloatValue::from(*val))
    }
}

impl<'a> From<&'a String> for Value {
    fn from(val: &'a String) -> Value {
        Value::String(val.clone())
    }
}

impl<'a> From<&'a str> for Value {
    fn from(val: &'a str) -> Value {
        Value::String(val.to_string())
    }
}

impl<'a> From<&'a Vec<u8>> for Value {
    fn from(val: &'a Vec<u8>) -> Value {
        Value::Blob(val.clone())
    }
}

impl<'a> From<&'a [u8]> for Value {
    fn from(val: &'a [u8]) -> Value {
        Value::Blob(val.to_vec())
    }
}

impl From<bool> for Value {
    fn from(val: bool) -> Value {
        Value::Bool(val)
    }
}

impl From<i8> for Value {
    fn from(val: i8) -> Value {
        Value::Int(i64::from(val))
    }
}

impl From<u8> for Value {
    fn from(val: u8) -> Value {
        Value::Int(i64::from(val))
    }
}

impl From<i16> for Value {
    fn from(val: i16) -> Value {
        Value::Int(i64::from(val))
    }
}

impl From<u16> for Value {
    fn from(val: u16) -> Value {
        Value::Int(i64::from(val))
    }
}

impl From<i32> for Value {
    fn from(val: i32) -> Value {
        Value::Int(i64::from(val))
    }
}

impl From<u32> for Value {
    fn from(val: u32) -> Value {
        Value::Int(i64::from(val))
    }
}

impl From<i64> for Value {
    fn from(val: i64) -> Value {
        Value::Int(val)
    }
}

impl From<u64> for Value {
    fn from(val: u64) -> Value {
        Value::Int(val as i64)
    }
}

impl From<isize> for Value {
    fn from(val: isize) -> Value {
        Value::Int(val as i64)
    }
}

impl From<usize> for Value {
    fn from(val: usize) -> Value {
        Value::Int(val as i64)
    }
}

impl<'a> From<&'a i8> for Value {
    fn from(val: &'a i8) -> Value {
        Value::Int(i64::from(*val))
    }
}

impl<'a> From<&'a u8> for Value {
    fn from(val: &'a u8) -> Value {
        Value::Int(i64::from(*val))
    }
}

impl<'a> From<&'a i16> for Value {
    fn from(val: &'a i16) -> Value {
        Value::Int(i64::from(*val))
    }
}

impl<'a> From<&'a u16> for Value {
    fn from(val: &'a u16) -> Value {
        Value::Int(i64::from(*val))
    }
}

impl<'a> From<&'a i32> for Value {
    fn from(val: &'a i32) -> Value {
        Value::Int(i64::from(*val))
    }
}

impl<'a> From<&'a u32> for Value {
    fn from(val: &'a u32) -> Value {
        Value::Int(i64::from(*val))
    }
}

impl<'a> From<&'a i64> for Value {
    fn from(val: &'a i64) -> Value {
        Value::Int(*val)
    }
}

impl<'a> From<&'a u64> for Value {
    fn from(val: &'a u64) -> Value {
        Value::Int(*val as i64)
    }
}

impl<'a> From<&'a isize> for Value {
    fn from(val: &'a isize) -> Value {
        Value::Int(*val as i64)
    }
}

impl<'a> From<&'a usize> for Value {
    fn from(val: &'a usize) -> Value {
        Value::Int(*val as i64)
    }
}

impl<'a> From<&'a bool> for Value {
    fn from(val: &'a bool) -> Value {
        Value::Bool(*val)
    }
}

impl From<Value> for i64 {
    fn from(val: Value) -> i64 {
        match val {
            Value::Int(val) => val,
            _ => panic!("Value is not an integer to convert."),
        }
    }
}

impl<'a> From<&'a Value> for i64 {
    fn from(val: &'a Value) -> i64 {
        match *val {
            Value::Int(val) => val,
            _ => panic!("Value is not an integer to convert."),
        }
    }
}

impl TryFrom<Value> for String {
    type Error = String;
    fn try_from(val: Value) -> std::result::Result<Self, Self::Error> {
        match val {
            Value::String(v) | Value::GeoJSON(v) => Ok(v),
            _ => Err(format!(
                "Invalid type conversion from Value::{} to {}",
                val.particle_type(),
                std::any::type_name::<Self>()
            )),
        }
    }
}

impl TryFrom<Value> for Vec<u8> {
    type Error = String;
    fn try_from(val: Value) -> std::result::Result<Self, Self::Error> {
        match val {
            Value::Blob(v) | Value::HLL(v) => Ok(v),
            _ => Err(format!(
                "Invalid type conversion from Value::{} to {}",
                val.particle_type(),
                std::any::type_name::<Self>()
            )),
        }
    }
}

impl TryFrom<Value> for Vec<Value> {
    type Error = String;
    fn try_from(val: Value) -> std::result::Result<Self, Self::Error> {
        match val {
            Value::List(v) | Value::MultiResult(v) => Ok(v),
            _ => Err(format!(
                "Invalid type conversion from Value::{} to {}",
                val.particle_type(),
                std::any::type_name::<Self>()
            )),
        }
    }
}

#[allow(clippy::implicit_hasher)]
impl TryFrom<Value> for HashMap<Value, Value> {
    type Error = String;
    fn try_from(val: Value) -> std::result::Result<Self, Self::Error> {
        match val {
            Value::HashMap(v) => Ok(v),
            _ => Err(format!(
                "Invalid type conversion from Value::{} to {}",
                val.particle_type(),
                std::any::type_name::<Self>()
            )),
        }
    }
}

impl TryFrom<Value> for BTreeMap<Value, Value> {
    type Error = String;
    fn try_from(val: Value) -> std::result::Result<Self, Self::Error> {
        match val {
            Value::OrderedMap(v) => Ok(v),
            _ => Err(format!(
                "Invalid type conversion from Value::{} to {}",
                val.particle_type(),
                std::any::type_name::<Self>()
            )),
        }
    }
}

impl TryFrom<Value> for Vec<(Value, Value)> {
    type Error = String;
    fn try_from(val: Value) -> std::result::Result<Self, Self::Error> {
        match val {
            Value::KeyValueList(v) => Ok(v),
            _ => Err(format!(
                "Invalid type conversion from Value::{} to {}",
                val.particle_type(),
                std::any::type_name::<Self>()
            )),
        }
    }
}

impl TryFrom<Value> for f64 {
    type Error = String;
    fn try_from(val: Value) -> std::result::Result<Self, Self::Error> {
        match val {
            Value::Float(v) => Ok(f64::from(v)),
            _ => Err(format!(
                "Invalid type conversion from Value::{} to {}",
                val.particle_type(),
                std::any::type_name::<Self>()
            )),
        }
    }
}

impl TryFrom<Value> for bool {
    type Error = String;
    fn try_from(val: Value) -> std::result::Result<Self, Self::Error> {
        match val {
            Value::Bool(v) => Ok(v),
            _ => Err("Invalid type bool".into()),
        }
    }
}

pub fn bytes_to_particle(ptype: u8, buf: &mut Buffer, len: usize) -> Result<Value> {
    match ParticleType::from(ptype) {
        ParticleType::NULL => Ok(Value::Nil),
        ParticleType::INTEGER => {
            let val = buf.read_i64(None);
            Ok(Value::Int(val))
        }
        ParticleType::FLOAT => {
            let val = buf.read_f64(None);
            Ok(Value::Float(FloatValue::from(val)))
        }
        ParticleType::STRING => {
            let val = buf.read_str(len)?;
            Ok(Value::String(val))
        }
        ParticleType::GEOJSON => {
            buf.skip(1);
            let ncells = buf.read_i16(None) as usize;
            let header_size: usize = ncells * 8;

            buf.skip(header_size);
            let val = buf.read_str(len - header_size - 3)?;
            Ok(Value::GeoJSON(val))
        }
        ParticleType::BLOB => Ok(Value::Blob(buf.read_blob(len))),
        ParticleType::LIST => {
            let val = decoder::unpack_value_list(buf)?;
            Ok(val)
        }
        ParticleType::MAP => {
            let val = decoder::unpack_value_map(buf)?;
            Ok(val)
        }
        ParticleType::DIGEST => Ok(Value::from("A DIGEST, NOT IMPLEMENTED YET!")),
        ParticleType::LDT => Ok(Value::from("A LDT, NOT IMPLEMENTED YET!")),
        ParticleType::HLL => Ok(Value::HLL(buf.read_blob(len))),
        ParticleType::BOOL => Ok(Value::Bool(buf.read_bool(len))),
    }
}

/// Constructs a new Value from one of the supported native data types.
#[macro_export]
macro_rules! as_val {
    ($val:expr) => {{
        $crate::Value::from($val)
    }};
}

/// Constructs a new `GeoJSON` Value from one of the supported native data types.
#[macro_export]
macro_rules! as_geo {
    ($val:expr) => {{
        $crate::Value::GeoJSON($val.to_owned())
    }};
}

/// Constructs a new Blob Value from one of the supported native data types.
#[macro_export]
macro_rules! as_blob {
    ($val:expr) => {{
        $crate::Value::Blob($val)
    }};
}

/// Constructs a new List Value from a list of one or more native data types.
///
/// # Examples
///
/// Write a list value to a record bin.
///
/// ```rust,edition2018
/// # use aerospike::*;
/// # use std::vec::Vec;
/// # #[tokio::main]
/// # async fn main() {
/// # let hosts = std::env::var("AEROSPIKE_HOSTS").unwrap_or_else(|_| "127.0.0.1:3000".to_string());
/// # let client = Client::new(&ClientPolicy::default(), &hosts).await.unwrap();
/// # let key = as_key!("test", "test", "mykey");
/// let list = as_list!("a", "b", "c");
/// let bin = as_bin!("list", list);
/// client.put(&WritePolicy::default(), &key, &vec![bin]).await.unwrap();
/// # }
/// ```
#[macro_export]
macro_rules! as_list {
    ( $( $v:expr),* ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push(as_val!($v));
            )*
            $crate::Value::List(temp_vec)
        }
    };
}

/// Constructs a vector of Values from a list of one or more native data types.
///
/// # Examples
///
/// Execute a user-defined function (UDF) with some arguments.
///
/// ```rust,should_panic,edition2018
/// # use aerospike::*;
/// # use std::vec::Vec;
///  # #[tokio::main]
/// # async fn main() {
/// # let hosts = std::env::var("AEROSPIKE_HOSTS").unwrap_or_else(|_| "127.0.0.1:3000".to_string());
/// # let client = Client::new(&ClientPolicy::default(), &hosts).await.unwrap();
/// # let key = as_key!("test", "test", "mykey");
/// let module = "myUDF";
/// let func = "myFunction";
/// let args = as_values!("a", "b", "c");
/// client.execute_udf(&WritePolicy::default(), &key,
///     &module, &func, Some(&args)).await.unwrap();
/// # }
/// ```
#[macro_export]
macro_rules! as_values {
    ( $( $v:expr),* ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push(as_val!($v));
            )*
            temp_vec
        }
    };
}

/// Constructs a Map Value from a list of key/value pairs.
///
/// # Examples
///
/// Write a map value to a record bin.
///
/// ```rust,edition2018
/// # use aerospike::*;
/// # #[tokio::main]
/// # async fn main() {
/// # let hosts = std::env::var("AEROSPIKE_HOSTS").unwrap_or_else(|_| "127.0.0.1:3000".to_string());
/// # let client = Client::new(&ClientPolicy::default(), &hosts).await.unwrap();
/// # let key = as_key!("test", "test", "mykey");
/// let map = as_map!("a" => 1, "b" => 2);
/// let bin = as_bin!("map", map);
/// client.put(&WritePolicy::default(), &key, &vec![bin]).await.unwrap();
/// # }
/// ```
#[macro_export]
macro_rules! as_map {
    ( $( $k:expr => $v:expr),* ) => {
        {
            let mut temp_map = std::collections::HashMap::new();
            $(
                temp_map.insert(as_val!($k), as_val!($v));
            )*
            $crate::Value::HashMap(temp_map)
        }
    };
}

/// Constructs an Ordered Map Value from a list of key/value pairs.
///
/// # Examples
///
/// Write a map value to a record bin.
///
/// ```rust,edition2018
/// # use aerospike::*;
/// # #[tokio::main]
/// # async fn main() {
/// # let hosts = std::env::var("AEROSPIKE_HOSTS").unwrap_or_else(|_| "127.0.0.1:3000".to_string());
/// # let client = Client::new(&ClientPolicy::default(), &hosts).await.unwrap();
/// # let key = as_key!("test", "test", "mykey");
/// let map = as_ord_map!("a" => 1, "b" => 2);
/// let bin = as_bin!("map", map);
/// client.put(&WritePolicy::default(), &key, &vec![bin]).await.unwrap();
/// # }
/// ```
#[macro_export]
macro_rules! as_ord_map {
    ( $( $k:expr => $v:expr),* ) => {
        {
            let mut temp_map = std::collections::BTreeMap::new();
            $(
                temp_map.insert(as_val!($k), as_val!($v));
            )*
            $crate::Value::OrderedMap(temp_map)
        }
    };
}

#[cfg(feature = "serialization")]
impl Serialize for Value {
    fn serialize<S>(
        &self,
        serializer: S,
    ) -> std::result::Result<<S as Serializer>::Ok, <S as Serializer>::Error>
    where
        S: Serializer,
    {
        match &self {
            Value::Nil => serializer.serialize_none(),
            Value::Bool(b) => serializer.serialize_bool(*b),
            Value::Int(i) => serializer.serialize_i64(*i),
            Value::Float(f) => match f {
                FloatValue::F32(u) => serializer.serialize_f32(f32::from_bits(*u)),
                FloatValue::F64(u) => serializer.serialize_f64(f64::from_bits(*u)),
            },
            Value::String(s) | Value::GeoJSON(s) => serializer.serialize_str(s),
            Value::Blob(b) | Value::HLL(b) => serializer.serialize_bytes(&b[..]),
            Value::List(l) => {
                let mut seq = serializer.serialize_seq(Some(l.len()))?;
                for elem in l {
                    seq.serialize_element(&elem)?;
                }
                seq.end()
            }
            Value::HashMap(m) => {
                let mut map = serializer.serialize_map(Some(m.len()))?;
                for (key, value) in m {
                    map.serialize_entry(&key, &value)?;
                }
                map.end()
            }
            Value::OrderedMap(m) => {
                let mut map = serializer.serialize_map(Some(m.len()))?;
                for (key, value) in m {
                    map.serialize_entry(&key, &value)?;
                }
                map.end()
            }
            Value::KeyValueList(m) => {
                let mut map = serializer.serialize_map(Some(m.len()))?;
                for (key, value) in m {
                    map.serialize_entry(&key, &value)?;
                }
                map.end()
            }
            Value::Infinity => panic!("Infinity cannot be serialized"),
            Value::Wildcard => panic!("Wildcard cannot be serialized"),
            Value::MultiResult(_) => panic!("MultiValue cannot be serialized"),
        }
    }
}

/// Allows either a `HashMap` or `BTreeMap` to be passed as arguments to certain methods.
#[allow(clippy::type_complexity)]
pub trait MapLike<K: Eq, V> {
    fn value(self) -> (Option<HashMap<K, V>>, Option<BTreeMap<K, V>>);
    fn value_as_ref(&self) -> (Option<&HashMap<K, V>>, Option<&BTreeMap<K, V>>);
}

impl<K: Eq + Ord, V> MapLike<K, V> for BTreeMap<K, V> {
    fn value(self) -> (Option<HashMap<K, V>>, Option<BTreeMap<K, V>>) {
        (None, Some(self))
    }

    fn value_as_ref(&self) -> (Option<&HashMap<K, V>>, Option<&BTreeMap<K, V>>) {
        (None, Some(self))
    }
}

impl<K: Eq + Hash, V> MapLike<K, V> for HashMap<K, V> {
    fn value(self) -> (Option<HashMap<K, V>>, Option<BTreeMap<K, V>>) {
        (Some(self), None)
    }

    fn value_as_ref(&self) -> (Option<&HashMap<K, V>>, Option<&BTreeMap<K, V>>) {
        (Some(self), None)
    }
}

#[cfg(test)]
mod tests {
    use super::Value;
    use std::collections::{BTreeMap, HashMap};
    use std::convert::TryInto;

    #[test]
    fn try_into() {
        let _: i64 = Value::Int(42).try_into().unwrap();
        let _: f64 = Value::from(42.1).try_into().unwrap();
        let _: String = Value::String("hello".into()).try_into().unwrap();
        let _: String = Value::GeoJSON(r#"{"type":"Point"}"#.into())
            .try_into()
            .unwrap();
        let _: Vec<u8> = Value::Blob("hello!".into()).try_into().unwrap();
        let _: Vec<u8> = Value::HLL("hello!".into()).try_into().unwrap();
        let _: bool = Value::Bool(false).try_into().unwrap();
        let _: HashMap<Value, Value> = Value::HashMap(HashMap::new()).try_into().unwrap();
        let _: BTreeMap<Value, Value> = Value::OrderedMap(BTreeMap::new()).try_into().unwrap();
        let _: Vec<(Value, Value)> = Value::KeyValueList(Vec::new()).try_into().unwrap();
    }

    #[test]
    fn as_string() {
        assert_eq!(Value::Nil.as_string(), String::from("<null>"));
        assert_eq!(Value::Int(42).as_string(), String::from("42"));
        assert_eq!(Value::Bool(true).as_string(), String::from("true"));
        assert_eq!(Value::from(4.1416).as_string(), String::from("4.1416"));
        assert_eq!(
            as_geo!(r#"{"type":"Point"}"#).as_string(),
            String::from(r#"{"type":"Point"}"#)
        );
    }

    #[test]
    fn as_geo() {
        let string = String::from(r#"{"type":"Point"}"#);
        let str = r#"{"type":"Point"}"#;
        assert_eq!(as_geo!(string), as_geo!(str));
    }

    #[test]
    #[cfg(feature = "serialization")]
    fn serializer() {
        let val: Value = as_list!(
            Value::Nil,
            "0",
            9,
            8,
            7,
            1,
            2.1f64,
            -1,
            as_list!(5, 6, 7, 8, "asd"),
            true,
            false
        );
        let json = serde_json::to_string(&val);
        assert_eq!(
            json.unwrap(),
            "[null,\"0\",9,8,7,1,4611911198408756429,-1,[5,6,7,8,\"asd\"],true,false]",
            "List Serialization failed"
        );

        let val: Value =
            as_map!("a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5, "f" => as_map!("test"=>123));
        let json = serde_json::to_string(&val);
        // We only check for the len of the String because HashMap serialization does not keep the key order. Comparing like the list above is not possible.
        assert_eq!(json.unwrap().len(), 48, "Map Serialization failed");
    }
}