-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathRedisValue.cs
More file actions
1220 lines (1108 loc) · 53 KB
/
RedisValue.cs
File metadata and controls
1220 lines (1108 loc) · 53 KB
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
using System;
using System.Buffers;
using System.Buffers.Text;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StackExchange.Redis
{
/// <summary>
/// Represents values that can be stored in redis.
/// </summary>
public readonly struct RedisValue : IEquatable<RedisValue>, IComparable<RedisValue>, IComparable, IConvertible
{
internal static readonly RedisValue[] EmptyArray = Array.Empty<RedisValue>();
private readonly object? _objectOrSentinel;
private readonly ReadOnlyMemory<byte> _memory;
private readonly long _overlappedBits64;
private RedisValue(long overlappedValue64, ReadOnlyMemory<byte> memory, object? objectOrSentinel)
{
_overlappedBits64 = overlappedValue64;
_memory = memory;
_objectOrSentinel = objectOrSentinel;
}
internal RedisValue(object obj, long overlappedBits)
{
// this creates a bodged RedisValue which should **never**
// be seen directly; the contents are ... unexpected
_overlappedBits64 = overlappedBits;
_objectOrSentinel = obj;
_memory = default;
}
/// <summary>
/// Creates a <see cref="RedisValue"/> from a string.
/// </summary>
public RedisValue(string value) : this(0, default, value) { }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Roslynator", "RCS1085:Use auto-implemented property.", Justification = "Intentional field ref")]
internal object? DirectObject => _objectOrSentinel;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Roslynator", "RCS1085:Use auto-implemented property.", Justification = "Intentional field ref")]
internal long DirectOverlappedBits64 => _overlappedBits64;
private static readonly object Sentinel_SignedInteger = new();
private static readonly object Sentinel_UnsignedInteger = new();
private static readonly object Sentinel_Raw = new();
private static readonly object Sentinel_Double = new();
/// <summary>
/// Obtain this value as an object - to be used alongside Unbox.
/// </summary>
public object? Box()
{
var obj = _objectOrSentinel;
if (obj is null || obj is string || obj is byte[]) return obj;
if (obj == Sentinel_SignedInteger)
{
var l = OverlappedValueInt64;
if (l >= -1 && l <= 20) return s_CommonInt32[((int)l) + 1];
return l;
}
if (obj == Sentinel_UnsignedInteger)
{
return OverlappedValueUInt64;
}
if (obj == Sentinel_Double)
{
var d = OverlappedValueDouble;
if (double.IsPositiveInfinity(d)) return s_DoublePosInf;
if (double.IsNegativeInfinity(d)) return s_DoubleNegInf;
if (double.IsNaN(d)) return s_DoubleNAN;
return d;
}
if (obj == Sentinel_Raw && _memory.IsEmpty) return s_EmptyString;
return this;
}
/// <summary>
/// Parse this object as a value - to be used alongside Box.
/// </summary>
/// <param name="value">The value to unbox.</param>
public static RedisValue Unbox(object? value)
{
var val = TryParse(value, out var valid);
if (!valid) throw new ArgumentException("Could not parse value", nameof(value));
return val;
}
/// <summary>
/// Represents the string <c>""</c>.
/// </summary>
public static RedisValue EmptyString { get; } = new RedisValue(0, default, Sentinel_Raw);
// note: it is *really important* that this s_EmptyString assignment happens *after* the EmptyString initializer above!
private static readonly object s_DoubleNAN = double.NaN, s_DoublePosInf = double.PositiveInfinity, s_DoubleNegInf = double.NegativeInfinity,
s_EmptyString = RedisValue.EmptyString;
private static readonly object[] s_CommonInt32 = Enumerable.Range(-1, 22).Select(i => (object)i).ToArray(); // [-1,20] = 22 values
/// <summary>
/// A null value.
/// </summary>
public static RedisValue Null { get; } = new RedisValue(0, default, null);
/// <summary>
/// Indicates whether the **underlying** value is a primitive integer (signed or unsigned); this is **not**
/// the same as whether the value can be *treated* as an integer - see <seealso cref="TryParse(out int)"/>
/// and <seealso cref="TryParse(out long)"/>, which is usually the more appropriate test.
/// </summary>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] // hide it, because this *probably* isn't what callers need
public bool IsInteger => _objectOrSentinel == Sentinel_SignedInteger || _objectOrSentinel == Sentinel_UnsignedInteger;
/// <summary>
/// Indicates whether the value should be considered a null value.
/// </summary>
public bool IsNull => _objectOrSentinel == null;
/// <summary>
/// Indicates whether the value is either null or a zero-length value.
/// </summary>
public bool IsNullOrEmpty
{
get
{
if (IsNull) return true;
if (_objectOrSentinel == Sentinel_Raw && _memory.IsEmpty) return true;
if (_objectOrSentinel is string s && s.Length == 0) return true;
if (_objectOrSentinel is byte[] arr && arr.Length == 0) return true;
return false;
}
}
/// <summary>
/// Indicates whether the value is greater than zero-length or has an integer value.
/// </summary>
public bool HasValue => !IsNullOrEmpty;
/// <summary>
/// Indicates whether two RedisValue values are equivalent.
/// </summary>
/// <param name="x">The first <see cref="RedisValue"/> to compare.</param>
/// <param name="y">The second <see cref="RedisValue"/> to compare.</param>
public static bool operator !=(RedisValue x, RedisValue y) => !(x == y);
internal double OverlappedValueDouble
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => BitConverter.Int64BitsToDouble(_overlappedBits64);
}
internal long OverlappedValueInt64
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _overlappedBits64;
}
internal ulong OverlappedValueUInt64
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => unchecked((ulong)_overlappedBits64);
}
/// <summary>
/// Indicates whether two RedisValue values are equivalent.
/// </summary>
/// <param name="x">The first <see cref="RedisValue"/> to compare.</param>
/// <param name="y">The second <see cref="RedisValue"/> to compare.</param>
public static bool operator ==(RedisValue x, RedisValue y)
{
x = x.Simplify();
y = y.Simplify();
StorageType xType = x.Type, yType = y.Type;
if (xType == StorageType.Null) return yType == StorageType.Null;
if (yType == StorageType.Null) return false;
if (xType == yType)
{
switch (xType)
{
case StorageType.Double: // make sure we use double equality rules
return x.OverlappedValueDouble == y.OverlappedValueDouble;
case StorageType.Int64:
case StorageType.UInt64: // as long as xType == yType, only need to check the bits
return x._overlappedBits64 == y._overlappedBits64;
case StorageType.String:
return (string?)x._objectOrSentinel == (string?)y._objectOrSentinel;
case StorageType.Raw:
return x._memory.Span.SequenceEqual(y._memory.Span);
}
}
// if either is a numeric type, and the other isn't the *same* type (above), then:
// it can't be equal
switch (xType)
{
case StorageType.UInt64:
case StorageType.Int64:
case StorageType.Double:
return false;
}
switch (yType)
{
case StorageType.UInt64:
case StorageType.Int64:
case StorageType.Double:
return false;
}
// otherwise, compare as strings
return (string?)x == (string?)y;
}
/// <summary>
/// See <see cref="object.Equals(object)"/>.
/// </summary>
/// <param name="obj">The other <see cref="RedisValue"/> to compare.</param>
public override bool Equals(object? obj)
{
if (obj == null) return IsNull;
if (obj is RedisValue typed) return Equals(typed);
var other = TryParse(obj, out var valid);
return valid && this == other; // can't be equal if parse fail
}
/// <summary>
/// Indicates whether two RedisValue values are equivalent.
/// </summary>
/// <param name="other">The <see cref="RedisValue"/> to compare to.</param>
public bool Equals(RedisValue other) => this == other;
/// <inheritdoc/>
public override int GetHashCode() => GetHashCode(this);
private static int GetHashCode(RedisValue x)
{
x = x.Simplify();
return x.Type switch
{
StorageType.Null => -1,
StorageType.Double => x.OverlappedValueDouble.GetHashCode(),
StorageType.Int64 or StorageType.UInt64 => x._overlappedBits64.GetHashCode(),
StorageType.Raw => ((string)x!).GetHashCode(), // to match equality
_ => x._objectOrSentinel!.GetHashCode(),
};
}
/// <summary>
/// Returns a string representation of the value.
/// </summary>
public override string ToString() => (string?)this ?? string.Empty;
internal static unsafe bool Equals(byte[]? x, byte[]? y)
{
if ((object?)x == (object?)y) return true; // ref equals
if (x == null || y == null) return false;
int len = x.Length;
if (len != y.Length) return false;
int octets = len / 8, spare = len % 8;
fixed (byte* x8 = x, y8 = y)
{
long* x64 = (long*)x8, y64 = (long*)y8;
for (int i = 0; i < octets; i++)
{
if (x64[i] != y64[i]) return false;
}
int offset = len - spare;
while (spare-- != 0)
{
if (x8[offset] != y8[offset++]) return false;
}
}
return true;
}
internal static unsafe int GetHashCode(ReadOnlySpan<byte> span)
{
unchecked
{
int len = span.Length;
if (len == 0) return 0;
int acc = 728271210;
var span64 = MemoryMarshal.Cast<byte, long>(span);
for (int i = 0; i < span64.Length; i++)
{
var val = span64[i];
int valHash = ((int)val) ^ ((int)(val >> 32));
acc = ((acc << 5) + acc) ^ valHash;
}
int spare = len % 8, offset = len - spare;
while (spare-- != 0)
{
acc = ((acc << 5) + acc) ^ span[offset++];
}
return acc;
}
}
internal void AssertNotNull()
{
if (IsNull) throw new ArgumentException("A null value is not valid in this context");
}
internal enum StorageType
{
Null,
Int64,
UInt64,
Double,
Raw,
String,
}
internal StorageType Type
{
get
{
var objectOrSentinel = _objectOrSentinel;
if (objectOrSentinel == null) return StorageType.Null;
if (objectOrSentinel == Sentinel_SignedInteger) return StorageType.Int64;
if (objectOrSentinel == Sentinel_Double) return StorageType.Double;
if (objectOrSentinel == Sentinel_Raw) return StorageType.Raw;
if (objectOrSentinel is string) return StorageType.String;
if (objectOrSentinel is byte[]) return StorageType.Raw; // doubled-up, but retaining the array
if (objectOrSentinel == Sentinel_UnsignedInteger) return StorageType.UInt64;
throw new InvalidOperationException("Unknown type");
}
}
/// <summary>
/// Get the size of this value in bytes.
/// </summary>
public long Length() => Type switch
{
StorageType.Null => 0,
StorageType.Raw => _memory.Length,
StorageType.String => Encoding.UTF8.GetByteCount((string)_objectOrSentinel!),
StorageType.Int64 => Format.MeasureInt64(OverlappedValueInt64),
StorageType.UInt64 => Format.MeasureUInt64(OverlappedValueUInt64),
StorageType.Double => Format.MeasureDouble(OverlappedValueDouble),
_ => throw new InvalidOperationException("Unable to compute length of type: " + Type),
};
/// <summary>
/// Compare against a RedisValue for relative order.
/// </summary>
/// <param name="other">The other <see cref="RedisValue"/> to compare.</param>
public int CompareTo(RedisValue other) => CompareTo(this, other);
private static int CompareTo(RedisValue x, RedisValue y)
{
try
{
x = x.Simplify();
y = y.Simplify();
StorageType xType = x.Type, yType = y.Type;
if (xType == StorageType.Null) return yType == StorageType.Null ? 0 : -1;
if (yType == StorageType.Null) return 1;
if (xType == yType)
{
switch (xType)
{
case StorageType.Double:
return x.OverlappedValueDouble.CompareTo(y.OverlappedValueDouble);
case StorageType.Int64:
return x.OverlappedValueInt64.CompareTo(y.OverlappedValueInt64);
case StorageType.UInt64:
return x.OverlappedValueUInt64.CompareTo(y.OverlappedValueUInt64);
case StorageType.String:
return string.CompareOrdinal((string)x._objectOrSentinel!, (string)y._objectOrSentinel!);
case StorageType.Raw:
return x._memory.Span.SequenceCompareTo(y._memory.Span);
}
}
switch (xType)
{ // numbers can be still be compared between types
case StorageType.Double:
if (yType == StorageType.Int64) return x.OverlappedValueDouble.CompareTo((double)y.OverlappedValueInt64);
if (yType == StorageType.UInt64) return x.OverlappedValueDouble.CompareTo((double)y.OverlappedValueUInt64);
break;
case StorageType.Int64:
if (yType == StorageType.Double) return ((double)x.OverlappedValueInt64).CompareTo(y.OverlappedValueDouble);
if (yType == StorageType.UInt64) return 1; // we only use unsigned if > int64, so: y is bigger
break;
case StorageType.UInt64:
if (yType == StorageType.Double) return ((double)x.OverlappedValueUInt64).CompareTo(y.OverlappedValueDouble);
if (yType == StorageType.Int64) return -1; // we only use unsigned if > int64, so: x is bigger
break;
}
// otherwise, compare as strings
return string.CompareOrdinal((string?)x, (string?)y);
}
catch (Exception ex)
{
ConnectionMultiplexer.TraceWithoutContext(ex.Message);
}
// if all else fails, consider equivalent
return 0;
}
int IComparable.CompareTo(object? obj)
{
if (obj == null) return CompareTo(Null);
var val = TryParse(obj, out var valid);
if (!valid) return -1; // parse fail
return CompareTo(val);
}
internal static RedisValue TryParse(object? obj, out bool valid)
{
valid = true;
switch (obj)
{
case null: return Null;
case string v: return v;
case int v: return v;
case uint v: return v;
case double v: return v;
case byte[] v: return v;
case bool v: return v;
case long v: return v;
case ulong v: return v;
case float v: return v;
case ReadOnlyMemory<byte> v: return v;
case Memory<byte> v: return v;
case RedisValue v: return v;
default:
valid = false;
return Null;
}
}
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="int"/>.
/// </summary>
/// <param name="value">The <see cref="int"/> to convert to a <see cref="RedisValue"/>.</param>
public static implicit operator RedisValue(int value) => new RedisValue(value, default, Sentinel_SignedInteger);
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="T:Nullable{int}"/>.
/// </summary>
/// <param name="value">The <see cref="T:Nullable{int}"/> to convert to a <see cref="RedisValue"/>.</param>
public static implicit operator RedisValue(int? value) => value == null ? Null : (RedisValue)value.GetValueOrDefault();
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="long"/>.
/// </summary>
/// <param name="value">The <see cref="long"/> to convert to a <see cref="RedisValue"/>.</param>
public static implicit operator RedisValue(long value) => new RedisValue(value, default, Sentinel_SignedInteger);
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="T:Nullable{long}"/>.
/// </summary>
/// <param name="value">The <see cref="T:Nullable{long}"/> to convert to a <see cref="RedisValue"/>.</param>
public static implicit operator RedisValue(long? value) => value == null ? Null : (RedisValue)value.GetValueOrDefault();
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="ulong"/>.
/// </summary>
/// <param name="value">The <see cref="ulong"/> to convert to a <see cref="RedisValue"/>.</param>
[CLSCompliant(false)]
public static implicit operator RedisValue(ulong value)
{
const ulong MSB = 1UL << 63;
return (value & MSB) == 0
? new RedisValue((long)value, default, Sentinel_SignedInteger) // prefer signed whenever we can
: new RedisValue(unchecked((long)value), default, Sentinel_UnsignedInteger); // with unsigned as the fallback
}
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="T:Nullable{ulong}"/>.
/// </summary>
/// <param name="value">The <see cref="T:Nullable{ulong}"/> to convert to a <see cref="RedisValue"/>.</param>
[CLSCompliant(false)]
public static implicit operator RedisValue(ulong? value) => value == null ? Null : (RedisValue)value.GetValueOrDefault();
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="uint"/>.
/// </summary>
/// <param name="value">The <see cref="uint"/> to convert to a <see cref="RedisValue"/>.</param>
[CLSCompliant(false)]
public static implicit operator RedisValue(uint value) => new RedisValue(value, default, Sentinel_SignedInteger); // 32-bits always fits as signed
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="T:Nullable{uint}"/>.
/// </summary>
/// <param name="value">The <see cref="T:Nullable{uint}"/> to convert to a <see cref="RedisValue"/>.</param>
[CLSCompliant(false)]
public static implicit operator RedisValue(uint? value) => value == null ? Null : (RedisValue)value.GetValueOrDefault();
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="double"/>.
/// </summary>
/// <param name="value">The <see cref="double"/> to convert to a <see cref="RedisValue"/>.</param>
public static implicit operator RedisValue(double value)
{
try
{
var i64 = (long)value;
// note: double doesn't offer integer accuracy at 64 bits, so we know it can't be unsigned (only use that for 64-bit)
if (value == i64) return new RedisValue(i64, default, Sentinel_SignedInteger);
}
catch { }
return new RedisValue(BitConverter.DoubleToInt64Bits(value), default, Sentinel_Double);
}
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="T:Nullable{double}"/>.
/// </summary>
/// <param name="value">The <see cref="T:Nullable{double}"/> to convert to a <see cref="RedisValue"/>.</param>
public static implicit operator RedisValue(double? value) => value == null ? Null : (RedisValue)value.GetValueOrDefault();
/// <summary>
/// Creates a new <see cref="RedisValue"/> from a <see cref="T:ReadOnlyMemory{byte}"/>.
/// </summary>
/// <param name="value">The <see cref="T:ReadOnlyMemory{byte}"/> to convert to a <see cref="RedisValue"/>.</param>
public static implicit operator RedisValue(ReadOnlyMemory<byte> value)
{
if (value.Length == 0) return EmptyString;
return new RedisValue(0, value, Sentinel_Raw);
}
/// <summary>
/// Creates a new <see cref="RedisValue"/> from a <see cref="T:Memory{byte}"/>.
/// </summary>
/// <param name="value">The <see cref="T:Memory{byte}"/> to convert to a <see cref="RedisValue"/>.</param>
public static implicit operator RedisValue(Memory<byte> value) => (ReadOnlyMemory<byte>)value;
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="string"/>.
/// </summary>
/// <param name="value">The <see cref="string"/> to convert to a <see cref="RedisValue"/>.</param>
public static implicit operator RedisValue(string? value)
{
if (value == null) return Null;
if (value.Length == 0) return EmptyString;
return new RedisValue(0, default, value);
}
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="T:byte[]"/>.
/// </summary>
/// <param name="value">The <see cref="T:byte[]"/> to convert to a <see cref="RedisValue"/>.</param>
public static implicit operator RedisValue(byte[]? value)
{
if (value == null) return Null;
if (value.Length == 0) return EmptyString;
return new RedisValue(0, new Memory<byte>(value), value);
}
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="bool"/>.
/// </summary>
/// <param name="value">The <see cref="bool"/> to convert to a <see cref="RedisValue"/>.</param>
public static implicit operator RedisValue(bool value) => new RedisValue(value ? 1 : 0, default, Sentinel_SignedInteger);
/// <summary>
/// Creates a new <see cref="RedisValue"/> from an <see cref="T:Nullable{bool}"/>.
/// </summary>
/// <param name="value">The <see cref="T:Nullable{bool}"/> to convert to a <see cref="RedisValue"/>.</param>
public static implicit operator RedisValue(bool? value) => value == null ? Null : (RedisValue)value.GetValueOrDefault();
/// <summary>
/// Converts a <see cref="RedisValue"/> to a <see cref="bool"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static explicit operator bool(RedisValue value) => (long)value switch
{
0 => false,
1 => true,
_ => throw new InvalidCastException(),
};
/// <summary>
/// Converts a <see cref="RedisValue"/> to a <see cref="int"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static explicit operator int(RedisValue value)
=> checked((int)(long)value);
/// <summary>
/// Converts a <see cref="RedisValue"/> to a <see cref="long"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static explicit operator long(RedisValue value)
{
value = value.Simplify();
return value.Type switch
{
StorageType.Null => 0, // in redis, an arithmetic zero is kinda the same thing as not-exists (think "incr")
StorageType.Int64 => value.OverlappedValueInt64,
StorageType.UInt64 => checked((long)value.OverlappedValueUInt64), // this will throw since unsigned is always 64-bit
_ => throw new InvalidCastException($"Unable to cast from {value.Type} to long: '{value}'"),
};
}
/// <summary>
/// Converts a <see cref="RedisValue"/> to a <see cref="uint"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
[CLSCompliant(false)]
public static explicit operator uint(RedisValue value)
{
value = value.Simplify();
return value.Type switch
{
StorageType.Null => 0, // in redis, an arithmetic zero is kinda the same thing as not-exists (think "incr")
StorageType.Int64 => checked((uint)value.OverlappedValueInt64),
StorageType.UInt64 => checked((uint)value.OverlappedValueUInt64),
_ => throw new InvalidCastException($"Unable to cast from {value.Type} to uint: '{value}'"),
};
}
/// <summary>
/// Converts a <see cref="RedisValue"/> to a <see cref="long"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
[CLSCompliant(false)]
public static explicit operator ulong(RedisValue value)
{
value = value.Simplify();
return value.Type switch
{
StorageType.Null => 0, // in redis, an arithmetic zero is kinda the same thing as not-exists (think "incr")
StorageType.Int64 => checked((ulong)value.OverlappedValueInt64), // throw if negative
StorageType.UInt64 => value.OverlappedValueUInt64,
_ => throw new InvalidCastException($"Unable to cast from {value.Type} to ulong: '{value}'"),
};
}
/// <summary>
/// Converts a <see cref="RedisValue"/> to a <see cref="double"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static explicit operator double(RedisValue value)
{
value = value.Simplify();
return value.Type switch
{
StorageType.Null => 0, // in redis, an arithmetic zero is kinda the same thing as not-exists (think "incr")
StorageType.Int64 => value.OverlappedValueInt64,
StorageType.UInt64 => value.OverlappedValueUInt64,
StorageType.Double => value.OverlappedValueDouble,
_ => throw new InvalidCastException($"Unable to cast from {value.Type} to double: '{value}'"),
};
}
/// <summary>
/// Converts a <see cref="RedisValue"/> to a <see cref="decimal"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static explicit operator decimal(RedisValue value)
{
value = value.Simplify();
return value.Type switch
{
StorageType.Null => 0, // in redis, an arithmetic zero is kinda the same thing as not-exists (think "incr")
StorageType.Int64 => value.OverlappedValueInt64,
StorageType.UInt64 => value.OverlappedValueUInt64,
StorageType.Double => (decimal)value.OverlappedValueDouble,
_ => throw new InvalidCastException($"Unable to cast from {value.Type} to decimal: '{value}'"),
};
}
/// <summary>
/// Converts a <see cref="RedisValue"/> to a <see cref="float"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static explicit operator float(RedisValue value)
{
value = value.Simplify();
return value.Type switch
{
StorageType.Null => 0, // in redis, an arithmetic zero is kinda the same thing as not-exists (think "incr")
StorageType.Int64 => value.OverlappedValueInt64,
StorageType.UInt64 => value.OverlappedValueUInt64,
StorageType.Double => (float)value.OverlappedValueDouble,
_ => throw new InvalidCastException($"Unable to cast from {value.Type} to double: '{value}'"),
};
}
private static bool TryParseDouble(ReadOnlySpan<byte> blob, out double value)
{
// simple integer?
if (Format.CouldBeInteger(blob) && Format.TryParseInt64(blob, out var i64))
{
value = i64;
return true;
}
return Format.TryParseDouble(blob, out value);
}
/// <summary>
/// Converts the <see cref="RedisValue"/> to a <see cref="T:Nullable{double}"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static explicit operator double?(RedisValue value)
=> value.IsNull ? (double?)null : (double)value;
/// <summary>
/// Converts the <see cref="RedisValue"/> to a <see cref="T:Nullable{float}"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static explicit operator float?(RedisValue value)
=> value.IsNull ? (float?)null : (float)value;
/// <summary>
/// Converts the <see cref="RedisValue"/> to a <see cref="T:Nullable{decimal}"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static explicit operator decimal?(RedisValue value)
=> value.IsNull ? (decimal?)null : (decimal)value;
/// <summary>
/// Converts the <see cref="RedisValue"/> to a <see cref="T:Nullable{long}"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static explicit operator long?(RedisValue value)
=> value.IsNull ? (long?)null : (long)value;
/// <summary>
/// Converts the <see cref="RedisValue"/> to a <see cref="T:Nullable{ulong}"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
[CLSCompliant(false)]
public static explicit operator ulong?(RedisValue value)
=> value.IsNull ? (ulong?)null : (ulong)value;
/// <summary>
/// Converts the <see cref="RedisValue"/> to a <see cref="T:Nullable{int}"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static explicit operator int?(RedisValue value)
=> value.IsNull ? (int?)null : (int)value;
/// <summary>
/// Converts the <see cref="RedisValue"/> to a <see cref="T:Nullable{uint}"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
[CLSCompliant(false)]
public static explicit operator uint?(RedisValue value)
=> value.IsNull ? (uint?)null : (uint)value;
/// <summary>
/// Converts the <see cref="RedisValue"/> to a <see cref="T:Nullable{bool}"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static explicit operator bool?(RedisValue value)
=> value.IsNull ? (bool?)null : (bool)value;
/// <summary>
/// Converts a <see cref="RedisValue"/> to a <see cref="string"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static implicit operator string?(RedisValue value)
{
switch (value.Type)
{
case StorageType.Null: return null;
case StorageType.Double: return Format.ToString(value.OverlappedValueDouble);
case StorageType.Int64: return Format.ToString(value.OverlappedValueInt64);
case StorageType.UInt64: return Format.ToString(value.OverlappedValueUInt64);
case StorageType.String: return (string)value._objectOrSentinel!;
case StorageType.Raw:
var span = value._memory.Span;
if (span.IsEmpty) return "";
if (span.Length == 2 && span[0] == (byte)'O' && span[1] == (byte)'K') return "OK"; // frequent special-case
try
{
return Format.GetString(span);
}
catch
{
return ToHex(span);
}
default:
throw new InvalidOperationException();
}
}
private static string ToHex(ReadOnlySpan<byte> src)
{
const string HexValues = "0123456789ABCDEF";
if (src.IsEmpty) return "";
var s = new string((char)0, (src.Length * 3) - 1);
var dst = MemoryMarshal.AsMemory(s.AsMemory()).Span;
int i = 0;
int j = 0;
byte b = src[i++];
dst[j++] = HexValues[b >> 4];
dst[j++] = HexValues[b & 0xF];
while (i < src.Length)
{
b = src[i++];
dst[j++] = '-';
dst[j++] = HexValues[b >> 4];
dst[j++] = HexValues[b & 0xF];
}
return s;
}
/// <summary>
/// Converts a <see cref="RedisValue"/> to a <see cref="T:byte[]"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static implicit operator byte[]?(RedisValue value)
{
switch (value.Type)
{
case StorageType.Null: return null;
case StorageType.Raw:
if (value._objectOrSentinel is byte[] arr) return arr;
if (MemoryMarshal.TryGetArray(value._memory, out var segment)
&& segment.Offset == 0
&& segment.Count == (segment.Array?.Length ?? -1))
{
return segment.Array; // the memory is backed by an array, and we're reading all of it
}
return value._memory.ToArray();
case StorageType.Int64:
Debug.Assert(Format.MaxInt64TextLen <= 24);
Span<byte> span = stackalloc byte[24];
int len = Format.FormatInt64(value.OverlappedValueInt64, span);
return span.Slice(0, len).ToArray();
case StorageType.UInt64:
Debug.Assert(Format.MaxInt64TextLen <= 24);
span = stackalloc byte[24];
len = Format.FormatUInt64(value.OverlappedValueUInt64, span);
return span.Slice(0, len).ToArray();
case StorageType.Double:
span = stackalloc byte[Format.MaxDoubleTextLen];
len = Format.FormatDouble(value.OverlappedValueDouble, span);
return span.Slice(0, len).ToArray();
case StorageType.String:
return Encoding.UTF8.GetBytes((string)value._objectOrSentinel!);
}
// fallback: stringify and encode
return Encoding.UTF8.GetBytes((string)value!);
}
/// <summary>
/// Gets the length of the value in bytes.
/// </summary>
public int GetByteCount()
{
switch (Type)
{
case StorageType.Null: return 0;
case StorageType.Raw: return _memory.Length;
case StorageType.String: return Encoding.UTF8.GetByteCount((string)_objectOrSentinel!);
case StorageType.Int64: return Format.MeasureInt64(OverlappedValueInt64);
case StorageType.UInt64: return Format.MeasureUInt64(OverlappedValueUInt64);
case StorageType.Double: return Format.MeasureDouble(OverlappedValueDouble);
default: return ThrowUnableToMeasure();
}
}
private int ThrowUnableToMeasure() => throw new InvalidOperationException("Unable to compute length of type: " + Type);
/// <summary>
/// Gets the length of the value in bytes.
/// </summary>
/* right now, we only support int lengths, but adding this now so that
there are no surprises if/when we add support for discontiguous buffers */
public long GetLongByteCount() => GetByteCount();
/// <summary>
/// Copy the value as bytes to the provided <paramref name="destination"/>.
/// </summary>
public int CopyTo(Span<byte> destination)
{
switch (Type)
{
case StorageType.Null:
return 0;
case StorageType.Raw:
var srcBytes = _memory.Span;
srcBytes.CopyTo(destination);
return srcBytes.Length;
case StorageType.String:
return Encoding.UTF8.GetBytes(((string)_objectOrSentinel!).AsSpan(), destination);
case StorageType.Int64:
return Format.FormatInt64(OverlappedValueInt64, destination);
case StorageType.UInt64:
return Format.FormatUInt64(OverlappedValueUInt64, destination);
case StorageType.Double:
return Format.FormatDouble(OverlappedValueDouble, destination);
default:
return ThrowUnableToMeasure();
}
}
/// <summary>
/// Converts a <see cref="RedisValue"/> to a <see cref="ReadOnlyMemory{T}"/>.
/// </summary>
/// <param name="value">The <see cref="RedisValue"/> to convert.</param>
public static implicit operator ReadOnlyMemory<byte>(RedisValue value)
=> value.Type == StorageType.Raw ? value._memory : (byte[]?)value;
TypeCode IConvertible.GetTypeCode() => TypeCode.Object;
bool IConvertible.ToBoolean(IFormatProvider? provider) => (bool)this;
byte IConvertible.ToByte(IFormatProvider? provider) => (byte)(uint)this;
char IConvertible.ToChar(IFormatProvider? provider) => (char)(uint)this;
DateTime IConvertible.ToDateTime(IFormatProvider? provider) => DateTime.Parse(((string?)this)!, provider);
decimal IConvertible.ToDecimal(IFormatProvider? provider) => (decimal)this;
double IConvertible.ToDouble(IFormatProvider? provider) => (double)this;
short IConvertible.ToInt16(IFormatProvider? provider) => (short)this;
int IConvertible.ToInt32(IFormatProvider? provider) => (int)this;
long IConvertible.ToInt64(IFormatProvider? provider) => (long)this;
sbyte IConvertible.ToSByte(IFormatProvider? provider) => (sbyte)this;
float IConvertible.ToSingle(IFormatProvider? provider) => (float)this;
string IConvertible.ToString(IFormatProvider? provider) => ((string?)this)!;
object IConvertible.ToType(Type conversionType, IFormatProvider? provider)
{
if (conversionType == null) throw new ArgumentNullException(nameof(conversionType));
if (conversionType == typeof(byte[])) return ((byte[]?)this)!;
if (conversionType == typeof(ReadOnlyMemory<byte>)) return (ReadOnlyMemory<byte>)this;
if (conversionType == typeof(RedisValue)) return this;
return System.Type.GetTypeCode(conversionType) switch
{
TypeCode.Boolean => (bool)this,
TypeCode.Byte => checked((byte)(uint)this),
TypeCode.Char => checked((char)(uint)this),
TypeCode.DateTime => DateTime.Parse(((string?)this)!, provider),
TypeCode.Decimal => (decimal)this,
TypeCode.Double => (double)this,
TypeCode.Int16 => (short)this,
TypeCode.Int32 => (int)this,
TypeCode.Int64 => (long)this,
TypeCode.SByte => (sbyte)this,
TypeCode.Single => (float)this,
TypeCode.String => ((string?)this)!,
TypeCode.UInt16 => checked((ushort)(uint)this),
TypeCode.UInt32 => (uint)this,
TypeCode.UInt64 => (ulong)this,
TypeCode.Object => this,
_ => throw new NotSupportedException(),
};
}
ushort IConvertible.ToUInt16(IFormatProvider? provider) => checked((ushort)(uint)this);
uint IConvertible.ToUInt32(IFormatProvider? provider) => (uint)this;
ulong IConvertible.ToUInt64(IFormatProvider? provider) => (ulong)this;
/// <summary>
/// Attempt to reduce to canonical terms ahead of time; parses integers, floats, etc
/// Note: we don't use this aggressively ahead of time, a: because of extra CPU,
/// but more importantly b: because it can change values - for example, if they start
/// with "123.000", it should **stay** as "123.000", not become 123L; this could be
/// a hash key or similar - we don't want to break it; RedisConnection uses
/// the storage type, not the "does it look like a long?" - for this reason.
/// </summary>
internal RedisValue Simplify()
{
long i64;
ulong u64;
switch (Type)
{
case StorageType.String:
string s = (string)_objectOrSentinel!;
if (Format.CouldBeInteger(s))
{
if (Format.TryParseInt64(s, out i64)) return i64;
if (Format.TryParseUInt64(s, out u64)) return u64;
}
// note: don't simplify inf/nan, as that causes equality semantic problems
if (Format.TryParseDouble(s, out var f64) && !IsSpecialDouble(f64)) return f64;
break;
case StorageType.Raw:
var b = _memory.Span;
if (Format.CouldBeInteger(b))
{
if (Format.TryParseInt64(b, out i64)) return i64;
if (Format.TryParseUInt64(b, out u64)) return u64;
}
// note: don't simplify inf/nan, as that causes equality semantic problems
if (TryParseDouble(b, out f64) && !IsSpecialDouble(f64)) return f64;