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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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace UnityEngine.InputSystem.Utilities
{
    /// <summary>
    /// A JSON parser that instead of turning a string in JSON format into a
    /// C# object graph, allows navigating the source text directly.
    /// </summary>
    /// <remarks>
    /// This helper is most useful for avoiding a great many string and general object allocations
    /// that would happen when turning a JSON object into a C# object graph.
    /// </remarks>
    internal struct JsonParser
    {
        public JsonParser(string json)
            : this()
        {
            if (json == null)
                throw new ArgumentNullException(nameof(json));

            m_Text = json;
            m_Length = json.Length;
        }

        public void Reset()
        {
            m_Position = 0;
            m_MatchAnyElementInArray = false;
            m_DryRun = false;
        }

        public override string ToString()
        {
            if (m_Text != null)
                return $"{m_Position}: {m_Text.Substring(m_Position)}";
            return base.ToString();
        }

        /// <summary>
        /// Navigate to the given property.
        /// </summary>
        /// <param name="path"></param>
        /// <remarks>
        /// This navigates from the current property.
        /// </remarks>
        public bool NavigateToProperty(string path)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException(nameof(path));

            var pathLength = path.Length;
            var pathPosition = 0;

            m_DryRun = true;
            if (!ParseToken('{'))
                return false;

            while (m_Position < m_Length && pathPosition < pathLength)
            {
                // Find start of property name.
                SkipWhitespace();
                if (m_Position == m_Length)
                    return false;
                if (m_Text[m_Position] != '"')
                    return false;
                ++m_Position;

                // Try to match single path component.
                var pathStartPosition = pathPosition;
                while (pathPosition < pathLength)
                {
                    var ch = path[pathPosition];
                    if (ch == '/' || ch == '[')
                        break;

                    if (m_Text[m_Position] != ch)
                        break;

                    ++m_Position;
                    ++pathPosition;
                }

                // See if we have a match.
                if (m_Position < m_Length && m_Text[m_Position] == '"' && (pathPosition >= pathLength || path[pathPosition] == '/' || path[pathPosition] == '['))
                {
                    // Have matched a property name. Navigate to value.
                    ++m_Position;
                    if (!SkipToValue())
                        return false;

                    // Check if we have matched everything in the path.
                    if (pathPosition >= pathLength)
                        return true;
                    if (path[pathPosition] == '/')
                    {
                        ++pathPosition;
                        if (!ParseToken('{'))
                            return false;
                    }
                    else if (path[pathPosition] == '[')
                    {
                        ++pathPosition;
                        if (pathPosition == pathLength)
                            throw new ArgumentException("Malformed JSON property path: " + path, nameof(path));
                        if (path[pathPosition] == ']')
                        {
                            m_MatchAnyElementInArray = true;
                            ++pathPosition;
                            if (pathPosition == pathLength)
                                return true;
                        }
                        else
                            throw new NotImplementedException("Navigating to specific array element");
                    }
                }
                else
                {
                    // This property isn't it. Skip the property and its value and reset
                    // to where we started in this iteration in the property path.

                    pathPosition = pathStartPosition;
                    while (m_Position < m_Length && m_Text[m_Position] != '"')
                        ++m_Position;
                    if (m_Position == m_Length || m_Text[m_Position] != '"')
                        return false;
                    ++m_Position;
                    if (!SkipToValue() || !ParseValue())
                        return false;
                    SkipWhitespace();
                    if (m_Position == m_Length || m_Text[m_Position] == '}' || m_Text[m_Position] != ',')
                        return false;
                    ++m_Position;
                }
            }

            return false;
        }

        /// <summary>
        /// Return true if the current property has a value matching <paramref name="expectedValue"/>.
        /// </summary>
        /// <param name="expectedValue"></param>
        /// <returns></returns>
        public bool CurrentPropertyHasValueEqualTo(JsonValue expectedValue)
        {
            // Grab property value.
            var savedPosition = m_Position;
            m_DryRun = false;
            if (!ParseValue(out var propertyValue))
            {
                m_Position = savedPosition;
                return false;
            }
            m_Position = savedPosition;

            // Match given value.
            var isMatch = false;
            if (propertyValue.type == JsonValueType.Array && m_MatchAnyElementInArray)
            {
                var array = propertyValue.arrayValue;
                for (var i = 0; !isMatch && i < array.Count; ++i)
                    isMatch = array[i] == expectedValue;
            }
            else
            {
                isMatch = propertyValue == expectedValue;
            }

            return isMatch;
        }

        public bool ParseToken(char token)
        {
            SkipWhitespace();
            if (m_Position == m_Length)
                return false;

            if (m_Text[m_Position] != token)
                return false;

            ++m_Position;
            SkipWhitespace();

            return m_Position < m_Length;
        }

        public bool ParseValue()
        {
            return ParseValue(out var result);
        }

        public bool ParseValue(out JsonValue result)
        {
            result = default;

            SkipWhitespace();
            if (m_Position == m_Length)
                return false;

            var ch = m_Text[m_Position];
            switch (ch)
            {
                case '"':
                    if (ParseStringValue(out result))
                        return true;
                    break;
                case '[':
                    if (ParseArrayValue(out result))
                        return true;
                    break;
                case '{':
                    if (ParseObjectValue(out result))
                        return true;
                    break;
                case 't':
                case 'f':
                    if (ParseBooleanValue(out result))
                        return true;
                    break;
                case 'n':
                    if (ParseNullValue(out result))
                        return true;
                    break;
                default:
                    if (ParseNumber(out result))
                        return true;
                    break;
            }

            return false;
        }

        public bool ParseStringValue(out JsonValue result)
        {
            result = default;

            SkipWhitespace();
            if (m_Position == m_Length || m_Text[m_Position] != '"')
                return false;
            ++m_Position;

            var startIndex = m_Position;
            var hasEscapes = false;

            while (m_Position < m_Length)
            {
                var ch = m_Text[m_Position];
                if (ch == '\\')
                {
                    ++m_Position;
                    if (m_Position == m_Length)
                        break;
                    hasEscapes = true;
                }
                else if (ch == '"')
                {
                    ++m_Position;
                    result = new JsonString
                    {
                        text = new Substring(m_Text, startIndex, m_Position - startIndex - 1),
                        hasEscapes = hasEscapes
                    };
                    return true;
                }
                ++m_Position;
            }

            return false;
        }

        public bool ParseArrayValue(out JsonValue result)
        {
            result = default;

            SkipWhitespace();
            if (m_Position == m_Length || m_Text[m_Position] != '[')
                return false;
            ++m_Position;

            if (m_Position == m_Length)
                return false;
            if (m_Text[m_Position] == ']')
            {
                // Empty array.
                result = new JsonValue { type = JsonValueType.Array };
                ++m_Position;
                return true;
            }

            List<JsonValue> values = null;
            if (!m_DryRun)
                values = new List<JsonValue>();

            while (m_Position < m_Length)
            {
                if (!ParseValue(out var value))
                    return false;
                if (!m_DryRun)
                    values.Add(value);
                SkipWhitespace();
                if (m_Position == m_Length)
                    return false;
                var ch = m_Text[m_Position];
                if (ch == ']')
                {
                    ++m_Position;
                    if (!m_DryRun)
                        result = values;
                    return true;
                }
                if (ch == ',')
                    ++m_Position;
            }

            return false;
        }

        public bool ParseObjectValue(out JsonValue result)
        {
            result = default;

            if (!ParseToken('{'))
                return false;
            if (m_Position < m_Length && m_Text[m_Position] == '}')
            {
                result = new JsonValue { type = JsonValueType.Object };
                ++m_Position;
                return true;
            }

            while (m_Position < m_Length)
            {
                if (!ParseStringValue(out var propertyName))
                    return false;

                if (!SkipToValue())
                    return false;

                if (!ParseValue(out var propertyValue))
                    return false;

                if (!m_DryRun)
                    throw new NotImplementedException();

                SkipWhitespace();
                if (m_Position < m_Length && m_Text[m_Position] == '}')
                {
                    if (!m_DryRun)
                        throw new NotImplementedException();
                    ++m_Position;
                    return true;
                }
            }

            return false;
        }

        public bool ParseNumber(out JsonValue result)
        {
            result = default;

            SkipWhitespace();
            if (m_Position == m_Length)
                return false;

            var negative = false;
            var haveFractionalPart = false;
            var integralPart = 0L;
            var fractionalPart = 0.0;
            var fractionalDivisor = 10.0;
            var exponent = 0;

            // Parse sign.
            if (m_Text[m_Position] == '-')
            {
                negative = true;
                ++m_Position;
            }

            if (m_Position == m_Length || !char.IsDigit(m_Text[m_Position]))
                return false;

            // Parse integral part.
            while (m_Position < m_Length)
            {
                var ch = m_Text[m_Position];
                if (ch == '.')
                    break;
                if (ch < '0' || ch > '9')
                    break;
                integralPart = integralPart * 10 + ch - '0';
                ++m_Position;
            }

            // Parse fractional part.
            if (m_Position < m_Length && m_Text[m_Position] == '.')
            {
                haveFractionalPart = true;
                ++m_Position;
                if (m_Position == m_Length || !char.IsDigit(m_Text[m_Position]))
                    return false;
                while (m_Position < m_Length)
                {
                    var ch = m_Text[m_Position];
                    if (ch < '0' || ch > '9')
                        break;
                    fractionalPart = (ch - '0') / fractionalDivisor + fractionalPart;
                    fractionalDivisor *= 10;
                    ++m_Position;
                }
            }

            if (m_Position < m_Length && (m_Text[m_Position] == 'e' || m_Text[m_Position] == 'E'))
            {
                ++m_Position;
                var isNegative = false;
                if (m_Position < m_Length && m_Text[m_Position] == '-')
                {
                    isNegative = true;
                    ++m_Position;
                }
                else if (m_Position < m_Length && m_Text[m_Position] == '+')
                {
                    ++m_Position;
                }

                var multiplier = 1;
                while (m_Position < m_Length && char.IsDigit(m_Text[m_Position]))
                {
                    var digit = m_Text[m_Position] - '0';
                    exponent *= multiplier;
                    exponent += digit;
                    multiplier *= 10;
                    ++m_Position;
                }

                if (isNegative)
                    exponent *= -1;
            }

            if (!m_DryRun)
            {
                if (!haveFractionalPart && exponent == 0)
                {
                    if (negative)
                        result = -integralPart;
                    else
                        result = integralPart;
                }
                else
                {
                    float value;
                    if (negative)
                        value = (float)-(integralPart + fractionalPart);
                    else
                        value = (float)(integralPart + fractionalPart);
                    if (exponent != 0)
                        value *= Mathf.Pow(10, exponent);
                    result = value;
                }
            }

            return true;
        }

        public bool ParseBooleanValue(out JsonValue result)
        {
            SkipWhitespace();
            if (SkipString("true"))
            {
                result = true;
                return true;
            }

            if (SkipString("false"))
            {
                result = false;
                return true;
            }

            result = default;
            return false;
        }

        public bool ParseNullValue(out JsonValue result)
        {
            result = default;
            return SkipString("null");
        }

        public bool SkipToValue()
        {
            SkipWhitespace();
            if (m_Position == m_Length || m_Text[m_Position] != ':')
                return false;
            ++m_Position;
            SkipWhitespace();
            return true;
        }

        private bool SkipString(string text)
        {
            SkipWhitespace();
            var length = text.Length;
            if (m_Position + length >= m_Length)
                return false;
            for (var i = 0; i < length; ++i)
            {
                if (m_Text[m_Position + i] != text[i])
                    return false;
            }

            m_Position += length;
            return true;
        }

        private void SkipWhitespace()
        {
            while (m_Position < m_Length && char.IsWhiteSpace(m_Text[m_Position]))
                ++m_Position;
        }

        public bool isAtEnd => m_Position >= m_Length;

        private readonly string m_Text;
        private readonly int m_Length;
        private int m_Position;
        private bool m_MatchAnyElementInArray;
        private bool m_DryRun;

        public enum JsonValueType
        {
            None,
            Bool,
            Real,
            Integer,
            String,
            Array,
            Object,
            Any,
        }

        public struct JsonString : IEquatable<JsonString>
        {
            public Substring text;
            public bool hasEscapes;

            public override string ToString()
            {
                if (!hasEscapes)
                    return text.ToString();

                var builder = new StringBuilder();
                var length = text.length;
                for (var i = 0; i < length; ++i)
                {
                    var ch = text[i];
                    if (ch == '\\')
                    {
                        ++i;
                        if (i == length)
                            break;
                        ch = text[i];
                    }
                    builder.Append(ch);
                }
                return builder.ToString();
            }

            public bool Equals(JsonString other)
            {
                if (hasEscapes == other.hasEscapes)
                    return Substring.Compare(text, other.text, StringComparison.InvariantCultureIgnoreCase) == 0;

                var thisLength = text.length;
                var otherLength = other.text.length;

                int thisIndex = 0, otherIndex = 0;
                for (; thisIndex < thisLength && otherIndex < otherLength; ++thisIndex, ++otherIndex)
                {
                    var thisChar = text[thisIndex];
                    var otherChar = other.text[otherIndex];

                    if (thisChar == '\\')
                    {
                        ++thisIndex;
                        if (thisIndex == thisLength)
                            return false;
                        thisChar = text[thisIndex];
                    }

                    if (otherChar == '\\')
                    {
                        ++otherIndex;
                        if (otherIndex == otherLength)
                            return false;
                        otherChar = other.text[otherIndex];
                    }

                    if (char.ToUpperInvariant(thisChar) != char.ToUpperInvariant(otherChar))
                        return false;
                }

                return thisIndex == thisLength && otherIndex == otherLength;
            }

            public override bool Equals(object obj)
            {
                return obj is JsonString other && Equals(other);
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    return (text.GetHashCode() * 397) ^ hasEscapes.GetHashCode();
                }
            }

            public static bool operator==(JsonString left, JsonString right)
            {
                return left.Equals(right);
            }

            public static bool operator!=(JsonString left, JsonString right)
            {
                return !left.Equals(right);
            }

            public static implicit operator JsonString(string str)
            {
                return new JsonString { text = str };
            }
        }

        public struct JsonValue : IEquatable<JsonValue>
        {
            public JsonValueType type;
            public bool boolValue;
            public double realValue;
            public long integerValue;
            public JsonString stringValue;
            public List<JsonValue> arrayValue; // Allocates.
            public Dictionary<string, JsonValue> objectValue; // Allocates.
            public object anyValue;

            public bool ToBoolean()
            {
                switch (type)
                {
                    case JsonValueType.Bool: return boolValue;
                    case JsonValueType.Integer: return integerValue != 0;
                    case JsonValueType.Real: return NumberHelpers.Approximately(0, realValue);
                    case JsonValueType.String: return Convert.ToBoolean(ToString());
                }
                return default;
            }

            public long ToInteger()
            {
                switch (type)
                {
                    case JsonValueType.Bool: return boolValue ? 1 : 0;
                    case JsonValueType.Integer: return integerValue;
                    case JsonValueType.Real: return (long)realValue;
                    case JsonValueType.String: return Convert.ToInt64(ToString());
                }
                return default;
            }

            public double ToDouble()
            {
                switch (type)
                {
                    case JsonValueType.Bool: return boolValue ? 1 : 0;
                    case JsonValueType.Integer: return integerValue;
                    case JsonValueType.Real: return realValue;
                    case JsonValueType.String: return Convert.ToSingle(ToString());
                }
                return default;
            }

            public override string ToString()
            {
                switch (type)
                {
                    case JsonValueType.None: return "null";
                    case JsonValueType.Bool: return boolValue.ToString();
                    case JsonValueType.Integer: return integerValue.ToString(CultureInfo.InvariantCulture);
                    case JsonValueType.Real: return realValue.ToString(CultureInfo.InvariantCulture);
                    case JsonValueType.String: return stringValue.ToString();
                    case JsonValueType.Array:
                        if (arrayValue == null)
                            return "[]";
                        return $"[{string.Join(",", arrayValue.Select(x => x.ToString()))}]";
                    case JsonValueType.Object:
                        if (objectValue == null)
                            return "{}";
                        var elements = objectValue.Select(pair => $"\"{pair.Key}\" : \"{pair.Value}\"");
                        return $"{{{string.Join(",", elements)}}}";
                    case JsonValueType.Any: return anyValue.ToString();
                }
                return base.ToString();
            }

            public static implicit operator JsonValue(bool val)
            {
                return new JsonValue
                {
                    type = JsonValueType.Bool,
                    boolValue = val
                };
            }

            public static implicit operator JsonValue(long val)
            {
                return new JsonValue
                {
                    type = JsonValueType.Integer,
                    integerValue = val
                };
            }

            public static implicit operator JsonValue(double val)
            {
                return new JsonValue
                {
                    type = JsonValueType.Real,
                    realValue = val
                };
            }

            public static implicit operator JsonValue(string str)
            {
                return new JsonValue
                {
                    type = JsonValueType.String,
                    stringValue = new JsonString { text = str }
                };
            }

            public static implicit operator JsonValue(JsonString str)
            {
                return new JsonValue
                {
                    type = JsonValueType.String,
                    stringValue = str
                };
            }

            public static implicit operator JsonValue(List<JsonValue> array)
            {
                return new JsonValue
                {
                    type = JsonValueType.Array,
                    arrayValue = array
                };
            }

            public static implicit operator JsonValue(Dictionary<string, JsonValue> obj)
            {
                return new JsonValue
                {
                    type = JsonValueType.Object,
                    objectValue = obj
                };
            }

            public static implicit operator JsonValue(Enum val)
            {
                return new JsonValue
                {
                    type = JsonValueType.Any,
                    anyValue = val
                };
            }

            public bool Equals(JsonValue other)
            {
                // Default comparisons.
                if (type == other.type)
                {
                    switch (type)
                    {
                        case JsonValueType.None: return true;
                        case JsonValueType.Bool: return boolValue == other.boolValue;
                        case JsonValueType.Integer: return integerValue == other.integerValue;
                        case JsonValueType.Real: return NumberHelpers.Approximately(realValue, other.realValue);
                        case JsonValueType.String: return stringValue == other.stringValue;
                        case JsonValueType.Object: throw new NotImplementedException();
                        case JsonValueType.Array: throw new NotImplementedException();
                        case JsonValueType.Any: return anyValue.Equals(other.anyValue);
                    }
                    return false;
                }

                // anyValue-based comparisons.
                if (anyValue != null)
                    return Equals(anyValue, other);
                if (other.anyValue != null)
                    return Equals(other.anyValue, this);

                return false;
            }

            private static bool Equals(object obj, JsonValue value)
            {
                if (obj == null)
                    return false;

                if (obj is Regex regex)
                    return regex.IsMatch(value.ToString());
                if (obj is string str)
                {
                    switch (value.type)
                    {
                        case JsonValueType.String: return value.stringValue == str;
                        case JsonValueType.Integer: return long.TryParse(str, out var si) && si == value.integerValue;
                        case JsonValueType.Real:
                            return double.TryParse(str, out var sf) && NumberHelpers.Approximately(sf, value.realValue);
                        case JsonValueType.Bool:
                            if (value.boolValue)
                                return str == "True" || str == "true" || str == "1";
                            return str == "False" || str == "false" || str == "0";
                    }
                }
                if (obj is float f)
                {
                    if (value.type == JsonValueType.Real)
                        return NumberHelpers.Approximately(f, value.realValue);
                    if (value.type == JsonValueType.String)
                        return float.TryParse(value.ToString(), out var otherF) && Mathf.Approximately(f, otherF);
                }
                if (obj is double d)
                {
                    if (value.type == JsonValueType.Real)
                        return NumberHelpers.Approximately(d, value.realValue);
                    if (value.type == JsonValueType.String)
                        return double.TryParse(value.ToString(), out var otherD) &&
                            NumberHelpers.Approximately(d, otherD);
                }
                if (obj is int i)
                {
                    if (value.type == JsonValueType.Integer)
                        return i == value.integerValue;
                    if (value.type == JsonValueType.String)
                        return int.TryParse(value.ToString(), out var otherI) && i == otherI;
                }
                if (obj is long l)
                {
                    if (value.type == JsonValueType.Integer)
                        return l == value.integerValue;
                    if (value.type == JsonValueType.String)
                        return long.TryParse(value.ToString(), out var otherL) && l == otherL;
                }
                if (obj is bool b)
                {
                    if (value.type == JsonValueType.Bool)
                        return b == value.boolValue;
                    if (value.type == JsonValueType.String)
                    {
                        if (b)
                            return value.stringValue == "true" || value.stringValue == "True" ||
                                value.stringValue == "1";
                        return value.stringValue == "false" || value.stringValue == "False" ||
                            value.stringValue == "0";
                    }
                }
                // NOTE: The enum-based comparisons allocate both on the Convert.ToInt64() and Enum.GetName() path. I've found
                //       no way to do either comparison in a way that does not allocate.
                if (obj is Enum)
                {
                    if (value.type == JsonValueType.Integer)
                        return Convert.ToInt64(obj) == value.integerValue;
                    if (value.type == JsonValueType.String)
                        return value.stringValue == Enum.GetName(obj.GetType(), obj);
                }

                return false;
            }

            public override bool Equals(object obj)
            {
                return obj is JsonValue other && Equals(other);
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    var hashCode = (int)type;
                    hashCode = (hashCode * 397) ^ boolValue.GetHashCode();
                    hashCode = (hashCode * 397) ^ realValue.GetHashCode();
                    hashCode = (hashCode * 397) ^ integerValue.GetHashCode();
                    hashCode = (hashCode * 397) ^ stringValue.GetHashCode();
                    hashCode = (hashCode * 397) ^ (arrayValue != null ? arrayValue.GetHashCode() : 0);
                    hashCode = (hashCode * 397) ^ (objectValue != null ? objectValue.GetHashCode() : 0);
                    hashCode = (hashCode * 397) ^ (anyValue != null ? anyValue.GetHashCode() : 0);
                    return hashCode;
                }
            }

            public static bool operator==(JsonValue left, JsonValue right)
            {
                return left.Equals(right);
            }

            public static bool operator!=(JsonValue left, JsonValue right)
            {
                return !left.Equals(right);
            }
        }
    }
}