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
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
#![deny(warnings)]
#![cfg_attr(feature = "hints", feature(core_intrinsics))]
#![cfg_attr(feature = "portable", feature(portable_simd))]
#![warn(unused_extern_crates)]
#![deny(
    clippy::all,
    clippy::unwrap_used,
    clippy::unnecessary_unwrap,
    clippy::pedantic,
    missing_docs
)]
#![allow(clippy::module_name_repetitions, renamed_and_removed_lints)]

//! simd-json is a rust port of the simdjson c++ library. It follows
//! most of the design closely with a few exceptions to make it better
//! fit into the rust ecosystem.
//!
//! Note: On `x86` it will select the best SIMD featureset
//! (`avx2`, or `sse4.2`) during runtime. If `simd-json` is compiled
//! with SIMD support, it will disable runtime detection.
//!
//! ## Goals
//!
//! the goal of the rust port of simdjson is not to create a one to
//! one copy, but to integrate the principles of the c++ library into
//! a rust library that plays well with the rust ecosystem. As such
//! we provide both compatibility with serde as well as parsing to a
//! dom to manipulate data.
//!
//! ## Performance
//!
//! As a rule of thumb this library tries to get as close as possible
//! to the performance of the c++ implementation, but some of the
//! design decisions - such as parsing to a dom or a tape, weigh
//! ergonomics over performance. In other places Rust makes it harder
//! to achieve the same level of performance.
//!
//! ## Safety
//!
//! this library uses unsafe all over the place, and while it leverages
//! quite a few test cases along with property based testing, please use
//! this library with caution.
//!
//!
//! ## Features
//!
//! simd-json.rs comes with a number of features that can be toggled,
//! the following features are intended for 'user' selection. Additional
//! features in the `Cargo.toml` exist to work around cargo limitations.
//!
//! ### `swar-number-parsing` (default)
//!
//! Enables a parsing method that will parse 8 digits at a time for
//! floats - this is a common pattern but comes as a slight perf hit
//! if all the floats have less then 8 digits.
//!
//! ### `serde_impl` (default)
//!
//! Compatibility with [serde](https://serde.rs/). This allows to use
//! [simd-json.rs](https://simd-json.rs) to deserialize serde objects
//! as well as serde compatibility of the different Value types.
//! This can be disabled if serde is not used alongside simd-json.
//!
//! ### `128bit`
//!
//! Support for signed and unsigned 128 bit integer. This feature
//! is disabled by default as 128 bit integers are rare in the wild
//! and parsing them comes as a performance penalty due to extra logic
//! and a changed memory layout.
//!
//! ### `known-key`
//!
//! The known-key feature changes hasher for the objects, from ahash
//! to fxhash, ahash is faster at hashing and provides protection
//! against DOS attacks by forcing multiple keys into a single hashing
//! bucket. fxhash on the other hand allows for repeatable hashing
//! results, that allows memorizing hashes for well know keys and saving
//! time on lookups. In workloads that are heavy at accessing some well
//! known keys this can be a performance advantage.
//!
//! ## Usage
//!
//! simd-json offers two main entry points for usage:
//!
//! ### Values API
//!
//! The values API is a set of optimized DOM objects that allow parsed
//! json to JSON data that has no known variable structure. simd-lite
//! has two versions of this:
//!
//! **Borrowed Values**
//!
//! ```
//! use simd_json;
//! let mut d = br#"{"some": ["key", "value", 2]}"#.to_vec();
//! let v: simd_json::BorrowedValue = simd_json::to_borrowed_value(&mut d).unwrap();
//! ```
//!
//! **Owned Values**
//!
//! ```
//! use simd_json;
//! let mut d = br#"{"some": ["key", "value", 2]}"#.to_vec();
//! let v: simd_json::OwnedValue = simd_json::to_owned_value(&mut d).unwrap();
//! ```
//!
//! ### Serde Compatible API
//!
//! ```ignore
//! use simd_json;
//! use serde_json::Value;
//!
//! let mut d = br#"{"some": ["key", "value", 2]}"#.to_vec();
//! let v: Value = simd_json::serde::from_slice(&mut d).unwrap();
//! ```

#[cfg(feature = "serde_impl")]
extern crate serde as serde_ext;

#[cfg(feature = "serde_impl")]
/// serde related helper functions
pub mod serde;

use crate::error::InternalError;
#[cfg(feature = "serde_impl")]
pub use crate::serde::{
    from_reader, from_slice, from_str, to_string, to_string_pretty, to_vec, to_vec_pretty,
    to_writer, to_writer_pretty,
};

/// Default trait imports;
pub mod prelude;

mod charutils;
#[macro_use]
mod macros;
mod error;
mod numberparse;
mod safer_unchecked;
mod stringparse;

use safer_unchecked::GetSaferUnchecked;
use stage2::StackState;

mod impls;

/// Reexport of Cow
pub mod cow;

/// The maximum padding size required by any SIMD implementation
pub const SIMDJSON_PADDING: usize = 32; // take upper limit mem::size_of::<__m256i>()
/// It's 64 for all (Is this correct?)
pub const SIMDINPUT_LENGTH: usize = 64;

mod stage2;
/// simd-json JSON-DOM value
pub mod value;

use std::{alloc::dealloc, mem};
pub use value_trait::StaticNode;

pub use crate::error::{Error, ErrorType};
pub use crate::value::*;
pub use value_trait::ValueType;

/// simd-json Result type
pub type Result<T> = std::result::Result<T, Error>;

#[cfg(feature = "known-key")]
mod known_key;
#[cfg(feature = "known-key")]
pub use known_key::{Error as KnownKeyError, KnownKey};

pub use crate::tape::{Node, Tape};
use std::alloc::{alloc, handle_alloc_error, Layout};
use std::ops::{Deref, DerefMut};
use std::ptr::NonNull;

use simdutf8::basic::imp::ChunkedUtf8Validator;

/// A struct to hold the buffers for the parser.
pub struct Buffers {
    string_buffer: Vec<u8>,
    structural_indexes: Vec<u32>,
    input_buffer: AlignedBuf,
    stage2_stack: Vec<StackState>,
}

impl Default for Buffers {
    #[cfg_attr(not(feature = "no-inline"), inline)]
    fn default() -> Self {
        Self::new(128)
    }
}

impl Buffers {
    /// Create new buffer for input length.
    /// If this is too small a new buffer will be allocated, if needed during parsing.
    #[cfg_attr(not(feature = "no-inline"), inline)]
    #[must_use]
    pub fn new(input_len: usize) -> Self {
        // this is a heuristic, it will likely be higher but it will avoid some reallocations hopefully
        let heuristic_index_cout = input_len / 128;
        Self {
            string_buffer: Vec::with_capacity(input_len + SIMDJSON_PADDING),
            structural_indexes: Vec::with_capacity(heuristic_index_cout),
            input_buffer: AlignedBuf::with_capacity(input_len + SIMDJSON_PADDING * 2),
            stage2_stack: Vec::with_capacity(heuristic_index_cout),
        }
    }
}

/// Creates a tape from the input for later consumption
/// # Errors
///
/// Will return `Err` if `s` is invalid JSON.
#[cfg_attr(not(feature = "no-inline"), inline)]
pub fn to_tape(s: &mut [u8]) -> Result<Tape> {
    Deserializer::from_slice(s).map(Deserializer::into_tape)
}

/// Creates a tape from the input for later consumption
/// # Errors
///
/// Will return `Err` if `s` is invalid JSON.
#[cfg_attr(not(feature = "no-inline"), inline)]
pub fn to_tape_with_buffers<'de>(s: &'de mut [u8], buffers: &mut Buffers) -> Result<Tape<'de>> {
    Deserializer::from_slice_with_buffers(s, buffers).map(Deserializer::into_tape)
}

/// Fills a already existing tape from the input for later consumption
/// # Errors
///
/// Will return `Err` if `s` is invalid JSON.
#[cfg_attr(not(feature = "no-inline"), inline)]
pub fn fill_tape<'de>(s: &'de mut [u8], buffers: &mut Buffers, tape: &mut Tape<'de>) -> Result<()> {
    tape.0.clear();
    Deserializer::fill_tape(s, buffers, &mut tape.0)
}

pub(crate) trait Stage1Parse {
    type Utf8Validator: ChunkedUtf8Validator;
    type SimdRepresentation;

    unsafe fn new(ptr: &[u8]) -> Self;

    unsafe fn compute_quote_mask(quote_bits: u64) -> u64;

    unsafe fn cmp_mask_against_input(&self, m: u8) -> u64;

    unsafe fn unsigned_lteq_against_input(&self, maxval: Self::SimdRepresentation) -> u64;

    unsafe fn find_whitespace_and_structurals(&self, whitespace: &mut u64, structurals: &mut u64);

    unsafe fn flatten_bits(base: &mut Vec<u32>, idx: u32, bits: u64);

    // return both the quote mask (which is a half-open mask that covers the first
    // quote in an unescaped quote pair and everything in the quote pair) and the
    // quote bits, which are the simple unescaped quoted bits.
    //
    // We also update the prev_iter_inside_quote value to tell the next iteration
    // whether we finished the final iteration inside a quote pair; if so, this
    // inverts our behavior of whether we're inside quotes for the next iteration.
    //
    // Note that we don't do any error checking to see if we have backslash
    // sequences outside quotes; these
    // backslash sequences (of any length) will be detected elsewhere.
    #[cfg_attr(not(feature = "no-inline"), inline)]
    fn find_quote_mask_and_bits(
        &self,
        odd_ends: u64,
        prev_iter_inside_quote: &mut u64,
        quote_bits: &mut u64,
        error_mask: &mut u64,
    ) -> u64 {
        unsafe {
            *quote_bits = self.cmp_mask_against_input(b'"');
            *quote_bits &= !odd_ends;
            // remove from the valid quoted region the unescaped characters.
            let mut quote_mask: u64 = Self::compute_quote_mask(*quote_bits);
            quote_mask ^= *prev_iter_inside_quote;
            // All Unicode characters may be placed within the
            // quotation marks, except for the characters that MUST be escaped:
            // quotation mark, reverse solidus, and the control characters (U+0000
            //through U+001F).
            // https://tools.ietf.org/html/rfc8259
            let unescaped: u64 = self.unsigned_lteq_against_input(Self::fill_s8(0x1F));
            *error_mask |= quote_mask & unescaped;
            // right shift of a signed value expected to be well-defined and standard
            // compliant as of C++20,
            // John Regher from Utah U. says this is fine code
            *prev_iter_inside_quote = static_cast_u64!(static_cast_i64!(quote_mask) >> 63);
            quote_mask
        }
    }

    // return a bitvector indicating where we have characters that end an odd-length
    // sequence of backslashes (and thus change the behavior of the next character
    // to follow). A even-length sequence of backslashes, and, for that matter, the
    // largest even-length prefix of our odd-length sequence of backslashes, simply
    // modify the behavior of the backslashes themselves.
    // We also update the prev_iter_ends_odd_backslash reference parameter to
    // indicate whether we end an iteration on an odd-length sequence of
    // backslashes, which modifies our subsequent search for odd-length
    // sequences of backslashes in an obvious way.
    #[cfg_attr(not(feature = "no-inline"), inline)]
    fn find_odd_backslash_sequences(&self, prev_iter_ends_odd_backslash: &mut u64) -> u64 {
        const EVEN_BITS: u64 = 0x5555_5555_5555_5555;
        const ODD_BITS: u64 = !EVEN_BITS;

        let bs_bits: u64 = unsafe { self.cmp_mask_against_input(b'\\') };
        let start_edges: u64 = bs_bits & !(bs_bits << 1);
        // flip lowest if we have an odd-length run at the end of the prior
        // iteration
        let even_start_mask: u64 = EVEN_BITS ^ *prev_iter_ends_odd_backslash;
        let even_starts: u64 = start_edges & even_start_mask;
        let odd_starts: u64 = start_edges & !even_start_mask;
        let even_carries: u64 = bs_bits.wrapping_add(even_starts);

        // must record the carry-out of our odd-carries out of bit 63; this
        // indicates whether the sense of any edge going to the next iteration
        // should be flipped
        let (mut odd_carries, iter_ends_odd_backslash) = bs_bits.overflowing_add(odd_starts);

        odd_carries |= *prev_iter_ends_odd_backslash;
        // push in bit zero as a potential end
        // if we had an odd-numbered run at the
        // end of the previous iteration
        *prev_iter_ends_odd_backslash = u64::from(iter_ends_odd_backslash);
        let even_carry_ends: u64 = even_carries & !bs_bits;
        let odd_carry_ends: u64 = odd_carries & !bs_bits;
        let even_start_odd_end: u64 = even_carry_ends & ODD_BITS;
        let odd_start_even_end: u64 = odd_carry_ends & EVEN_BITS;
        let odd_ends: u64 = even_start_odd_end | odd_start_even_end;
        odd_ends
    }

    // return a updated structural bit vector with quoted contents cleared out and
    // pseudo-structural characters added to the mask
    // updates prev_iter_ends_pseudo_pred which tells us whether the previous
    // iteration ended on a whitespace or a structural character (which means that
    // the next iteration
    // will have a pseudo-structural character at its start)
    #[cfg_attr(not(feature = "no-inline"), inline)]
    fn finalize_structurals(
        mut structurals: u64,
        whitespace: u64,
        quote_mask: u64,
        quote_bits: u64,
        prev_iter_ends_pseudo_pred: &mut u64,
    ) -> u64 {
        // mask off anything inside quotes
        structurals &= !quote_mask;
        // add the real quote bits back into our bitmask as well, so we can
        // quickly traverse the strings we've spent all this trouble gathering
        structurals |= quote_bits;
        // Now, establish "pseudo-structural characters". These are non-whitespace
        // characters that are (a) outside quotes and (b) have a predecessor that's
        // either whitespace or a structural character. This means that subsequent
        // passes will get a chance to encounter the first character of every string
        // of non-whitespace and, if we're parsing an atom like true/false/null or a
        // number we can stop at the first whitespace or structural character
        // following it.

        // a qualified predecessor is something that can happen 1 position before an
        // pseudo-structural character
        let pseudo_pred: u64 = structurals | whitespace;

        let shifted_pseudo_pred: u64 = (pseudo_pred << 1) | *prev_iter_ends_pseudo_pred;
        *prev_iter_ends_pseudo_pred = pseudo_pred >> 63;
        let pseudo_structurals: u64 = shifted_pseudo_pred & (!whitespace) & (!quote_mask);
        structurals |= pseudo_structurals;

        // now, we've used our close quotes all we need to. So let's switch them off
        // they will be off in the quote mask and on in quote bits.
        structurals &= !(quote_bits & !quote_mask);
        structurals
    }

    unsafe fn fill_s8(n: i8) -> Self::SimdRepresentation;
}

/// Deserializer struct to deserialize a JSON
pub struct Deserializer<'de> {
    // Note: we use the 2nd part as both index and length since only one is ever
    // used (array / object use len) everything else uses idx
    pub(crate) tape: Vec<Node<'de>>,
    idx: usize,
}

// architecture dependant parse_str

#[derive(Debug, Clone, Copy)]
pub(crate) struct SillyWrapper<'de> {
    input: *mut u8,
    _marker: std::marker::PhantomData<&'de ()>,
}

impl<'de> From<*mut u8> for SillyWrapper<'de> {
    #[cfg_attr(not(feature = "no-inline"), inline)]
    fn from(input: *mut u8) -> Self {
        Self {
            input,
            _marker: std::marker::PhantomData,
        }
    }
}

#[cfg(all(
    feature = "runtime-detection",
    any(target_arch = "x86_64", target_arch = "x86"),
))] // The runtime detection code is inspired from simdutf8's implementation
type FnRaw = *mut ();
#[cfg(all(
    feature = "runtime-detection",
    any(target_arch = "x86_64", target_arch = "x86"),
))]
type ParseStrFn = for<'invoke, 'de> unsafe fn(
    SillyWrapper<'de>,
    &'invoke [u8],
    &'invoke mut [u8],
    usize,
) -> std::result::Result<&'de str, error::Error>;
#[cfg(all(
    feature = "runtime-detection",
    any(target_arch = "x86_64", target_arch = "x86"),
))]
type FindStructuralBitsFn = unsafe fn(
    input: &[u8],
    structural_indexes: &mut Vec<u32>,
) -> std::result::Result<(), ErrorType>;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
/// Supported implementations
pub enum Implementation {
    /// Rust native implementation
    Native,
    /// Rust native implementation with using std::simd
    StdSimd,
    /// SSE4.2 implementation
    SSE42,
    /// AVX2 implementation
    AVX2,
    /// ARM NEON implementation
    NEON,
    /// WEBASM SIMD128 implementation
    SIMD128,
}

impl std::fmt::Display for Implementation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Implementation::Native => write!(f, "Rust Native"),
            Implementation::StdSimd => write!(f, "std::simd"),
            Implementation::SSE42 => write!(f, "SSE42"),
            Implementation::AVX2 => write!(f, "AVX2"),
            Implementation::NEON => write!(f, "NEON"),
            Implementation::SIMD128 => write!(f, "SIMD128"),
        }
    }
}

impl<'de> Deserializer<'de> {
    /// returns the algorithm / architecture used by the deserializer
    #[cfg(all(
        feature = "runtime-detection",
        any(target_arch = "x86_64", target_arch = "x86"),
    ))]
    #[must_use]
    pub fn algorithm() -> Implementation {
        if std::is_x86_feature_detected!("avx2") {
            Implementation::AVX2
        } else if std::is_x86_feature_detected!("sse4.2") {
            Implementation::SSE42
        } else {
            #[cfg(feature = "portable")]
            let r = Implementation::StdSimd;
            #[cfg(not(feature = "portable"))]
            let r = Implementation::Native;
            r
        }
    }
    #[cfg(not(any(
        all(
            feature = "runtime-detection",
            any(target_arch = "x86_64", target_arch = "x86")
        ),
        feature = "portable",
        target_feature = "avx2",
        target_feature = "sse4.2",
        target_feature = "simd128",
        target_arch = "aarch64",
    )))]
    /// returns the algorithm / architecture used by the deserializer
    #[must_use]
    pub fn algorithm() -> Implementation {
        Implementation::Native
    }
    #[cfg(all(feature = "portable", not(feature = "runtime-detection")))]
    /// returns the algorithm / architecture used by the deserializer
    #[must_use]
    pub fn algorithm() -> Implementation {
        Implementation::StdSimd
    }

    #[cfg(all(
        target_feature = "avx2",
        not(feature = "portable"),
        not(feature = "runtime-detection"),
    ))]
    /// returns the algorithm / architecture used by the deserializer
    #[must_use]
    pub fn algorithm() -> Implementation {
        Implementation::AVX2
    }

    #[cfg(all(
        target_feature = "sse4.2",
        not(target_feature = "avx2"),
        not(feature = "runtime-detection"),
        not(feature = "portable"),
    ))]
    /// returns the algorithm / architecture used by the deserializer
    #[must_use]
    pub fn algorithm() -> Implementation {
        Implementation::SSE42
    }

    #[cfg(all(target_arch = "aarch64", not(feature = "portable")))]
    /// returns the algorithm / architecture used by the deserializer
    #[must_use]
    pub fn algorithm() -> Implementation {
        Implementation::NEON
    }

    #[cfg(all(target_feature = "simd128", not(feature = "portable")))]
    /// returns the algorithm / architecture used by the deserializer
    #[must_use]
    pub fn algorithm() -> Implementation {
        Implementation::SIMD128
    }
}

impl<'de> Deserializer<'de> {
    #[cfg_attr(not(feature = "no-inline"), inline)]
    #[cfg(all(
        feature = "runtime-detection",
        any(target_arch = "x86_64", target_arch = "x86"),
    ))]
    pub(crate) unsafe fn parse_str_<'invoke>(
        input: *mut u8,
        data: &'invoke [u8],
        buffer: &'invoke mut [u8],
        idx: usize,
    ) -> Result<&'de str>
    where
        'de: 'invoke,
    {
        use std::sync::atomic::{AtomicPtr, Ordering};

        static FN: AtomicPtr<()> = AtomicPtr::new(get_fastest as FnRaw);

        #[cfg_attr(not(feature = "no-inline"), inline)]
        fn get_fastest_available_implementation() -> ParseStrFn {
            if std::is_x86_feature_detected!("avx2") {
                impls::avx2::parse_str
            } else if std::is_x86_feature_detected!("sse4.2") {
                impls::sse42::parse_str
            } else {
                #[cfg(feature = "portable")]
                let r = impls::portable::parse_str;
                #[cfg(not(feature = "portable"))]
                let r = impls::native::parse_str;
                r
            }
        }

        #[cfg_attr(not(feature = "no-inline"), inline)]
        unsafe fn get_fastest<'invoke, 'de>(
            input: SillyWrapper<'de>,
            data: &'invoke [u8],
            buffer: &'invoke mut [u8],
            idx: usize,
        ) -> core::result::Result<&'de str, error::Error>
        where
            'de: 'invoke,
        {
            let fun = get_fastest_available_implementation();
            FN.store(fun as FnRaw, Ordering::Relaxed);
            (fun)(input, data, buffer, idx)
        }

        let input: SillyWrapper<'de> = SillyWrapper::from(input);
        let fun = FN.load(Ordering::Relaxed);
        mem::transmute::<FnRaw, ParseStrFn>(fun)(input, data, buffer, idx)
    }
    #[cfg_attr(not(feature = "no-inline"), inline)]
    #[cfg(not(any(
        all(
            feature = "runtime-detection",
            any(target_arch = "x86_64", target_arch = "x86")
        ),
        feature = "portable",
        target_feature = "avx2",
        target_feature = "sse4.2",
        target_feature = "simd128",
        target_arch = "aarch64",
    )))]
    pub(crate) unsafe fn parse_str_<'invoke>(
        input: *mut u8,
        data: &'invoke [u8],
        buffer: &'invoke mut [u8],
        idx: usize,
    ) -> Result<&'de str>
    where
        'de: 'invoke,
    {
        let input: SillyWrapper<'de> = SillyWrapper::from(input);
        impls::native::parse_str(input, data, buffer, idx)
    }
    #[cfg_attr(not(feature = "no-inline"), inline)]
    #[cfg(all(feature = "portable", not(feature = "runtime-detection")))]
    pub(crate) unsafe fn parse_str_<'invoke>(
        input: *mut u8,
        data: &'invoke [u8],
        buffer: &'invoke mut [u8],
        idx: usize,
    ) -> Result<&'de str>
    where
        'de: 'invoke,
    {
        let input: SillyWrapper<'de> = SillyWrapper::from(input);
        impls::portable::parse_str(input, data, buffer, idx)
    }

    #[cfg_attr(not(feature = "no-inline"), inline)]
    #[cfg(all(
        target_feature = "avx2",
        not(feature = "portable"),
        not(feature = "runtime-detection"),
    ))]
    pub(crate) unsafe fn parse_str_<'invoke>(
        input: *mut u8,
        data: &'invoke [u8],
        buffer: &'invoke mut [u8],
        idx: usize,
    ) -> Result<&'de str> {
        let input: SillyWrapper<'de> = SillyWrapper::from(input);
        impls::avx2::parse_str(input, data, buffer, idx)
    }

    #[cfg_attr(not(feature = "no-inline"), inline)]
    #[cfg(all(
        target_feature = "sse4.2",
        not(target_feature = "avx2"),
        not(feature = "runtime-detection"),
        not(feature = "portable"),
    ))]
    pub(crate) unsafe fn parse_str_<'invoke>(
        input: *mut u8,
        data: &'invoke [u8],
        buffer: &'invoke mut [u8],
        idx: usize,
    ) -> Result<&'de str> {
        let input: SillyWrapper<'de> = SillyWrapper::from(input);
        impls::sse42::parse_str(input, data, buffer, idx)
    }

    #[cfg_attr(not(feature = "no-inline"), inline)]
    #[cfg(all(target_arch = "aarch64", not(feature = "portable")))]
    pub(crate) unsafe fn parse_str_<'invoke>(
        input: *mut u8,
        data: &'invoke [u8],
        buffer: &'invoke mut [u8],
        idx: usize,
    ) -> Result<&'de str> {
        let input: SillyWrapper<'de> = SillyWrapper::from(input);
        impls::neon::parse_str(input, data, buffer, idx)
    }
    #[cfg_attr(not(feature = "no-inline"), inline)]
    #[cfg(all(target_feature = "simd128", not(feature = "portable")))]
    pub(crate) unsafe fn parse_str_<'invoke>(
        input: *mut u8,
        data: &'invoke [u8],
        buffer: &'invoke mut [u8],
        idx: usize,
    ) -> Result<&'de str> {
        let input: SillyWrapper<'de> = SillyWrapper::from(input);
        impls::simd128::parse_str(input, data, buffer, idx)
    }
}

/// architecture dependant `find_structural_bits`
impl<'de> Deserializer<'de> {
    #[cfg_attr(not(feature = "no-inline"), inline)]
    #[cfg(all(
        feature = "runtime-detection",
        any(target_arch = "x86_64", target_arch = "x86"),
    ))]
    pub(crate) unsafe fn find_structural_bits(
        input: &[u8],
        structural_indexes: &mut Vec<u32>,
    ) -> std::result::Result<(), ErrorType> {
        use std::sync::atomic::{AtomicPtr, Ordering};

        static FN: AtomicPtr<()> = AtomicPtr::new(get_fastest as FnRaw);

        #[cfg_attr(not(feature = "no-inline"), inline)]
        fn get_fastest_available_implementation() -> FindStructuralBitsFn {
            if std::is_x86_feature_detected!("avx2") {
                Deserializer::_find_structural_bits::<impls::avx2::SimdInput>
            } else if std::is_x86_feature_detected!("sse4.2") {
                Deserializer::_find_structural_bits::<impls::sse42::SimdInput>
            } else {
                #[cfg(feature = "portable")]
                let r = Deserializer::_find_structural_bits::<impls::portable::SimdInput>;
                #[cfg(not(feature = "portable"))]
                let r = Deserializer::_find_structural_bits::<impls::native::SimdInput>;
                r
            }
        }

        #[cfg_attr(not(feature = "no-inline"), inline)]
        unsafe fn get_fastest(
            input: &[u8],
            structural_indexes: &mut Vec<u32>,
        ) -> core::result::Result<(), error::ErrorType> {
            let fun = get_fastest_available_implementation();
            FN.store(fun as FnRaw, Ordering::Relaxed);
            (fun)(input, structural_indexes)
        }

        let fun = FN.load(Ordering::Relaxed);
        mem::transmute::<FnRaw, FindStructuralBitsFn>(fun)(input, structural_indexes)
    }

    #[cfg(not(any(
        all(
            feature = "runtime-detection",
            any(target_arch = "x86_64", target_arch = "x86")
        ),
        feature = "portable",
        target_feature = "avx2",
        target_feature = "sse4.2",
        target_feature = "simd128",
        target_arch = "aarch64",
    )))]
    #[cfg_attr(not(feature = "no-inline"), inline)]
    pub(crate) unsafe fn find_structural_bits(
        input: &[u8],
        structural_indexes: &mut Vec<u32>,
    ) -> std::result::Result<(), ErrorType> {
        // This is a nasty hack, we don't have a chunked implementation for native rust
        // so we validate UTF8 ahead of time
        match core::str::from_utf8(input) {
            Ok(_) => (),
            Err(_) => return Err(ErrorType::InvalidUtf8),
        };
        #[cfg(not(feature = "portable"))]
        Self::_find_structural_bits::<impls::native::SimdInput>(input, structural_indexes)
    }

    #[cfg(all(feature = "portable", not(feature = "runtime-detection")))]
    #[cfg_attr(not(feature = "no-inline"), inline)]
    pub(crate) unsafe fn find_structural_bits(
        input: &[u8],
        structural_indexes: &mut Vec<u32>,
    ) -> std::result::Result<(), ErrorType> {
        Self::_find_structural_bits::<impls::portable::SimdInput>(input, structural_indexes)
    }

    #[cfg(all(
        target_feature = "avx2",
        not(feature = "portable"),
        not(feature = "runtime-detection"),
    ))]
    #[cfg_attr(not(feature = "no-inline"), inline)]
    pub(crate) unsafe fn find_structural_bits(
        input: &[u8],
        structural_indexes: &mut Vec<u32>,
    ) -> std::result::Result<(), ErrorType> {
        Self::_find_structural_bits::<impls::avx2::SimdInput>(input, structural_indexes)
    }

    #[cfg(all(
        target_feature = "sse4.2",
        not(target_feature = "avx2"),
        not(feature = "runtime-detection"),
        not(feature = "portable"),
    ))]
    #[cfg_attr(not(feature = "no-inline"), inline)]
    pub(crate) unsafe fn find_structural_bits(
        input: &[u8],
        structural_indexes: &mut Vec<u32>,
    ) -> std::result::Result<(), ErrorType> {
        Self::_find_structural_bits::<impls::sse42::SimdInput>(input, structural_indexes)
    }

    #[cfg(all(target_arch = "aarch64", not(feature = "portable")))]
    #[cfg_attr(not(feature = "no-inline"), inline)]
    pub(crate) unsafe fn find_structural_bits(
        input: &[u8],
        structural_indexes: &mut Vec<u32>,
    ) -> std::result::Result<(), ErrorType> {
        Self::_find_structural_bits::<impls::neon::SimdInput>(input, structural_indexes)
    }

    #[cfg(all(target_feature = "simd128", not(feature = "portable")))]
    #[cfg_attr(not(feature = "no-inline"), inline)]
    pub(crate) unsafe fn find_structural_bits(
        input: &[u8],
        structural_indexes: &mut Vec<u32>,
    ) -> std::result::Result<(), ErrorType> {
        Self::_find_structural_bits::<impls::simd128::SimdInput>(input, structural_indexes)
    }
}

impl<'de> Deserializer<'de> {
    /// Extracts the tape from the Deserializer
    #[must_use]
    pub fn into_tape(self) -> Tape<'de> {
        Tape(self.tape)
    }

    #[cfg_attr(not(feature = "no-inline"), inline)]
    fn error(error: ErrorType) -> Error {
        Error::new(0, None, error)
    }

    #[cfg_attr(not(feature = "no-inline"), inline)]
    fn error_c(idx: usize, c: char, error: ErrorType) -> Error {
        Error::new(idx, Some(c), error)
    }

    /// Creates a serializer from a mutable slice of bytes
    ///
    /// # Errors
    ///
    /// Will return `Err` if `s` is invalid JSON.
    pub fn from_slice(input: &'de mut [u8]) -> Result<Self> {
        let len = input.len();

        let mut buffer = Buffers::new(len);

        Self::from_slice_with_buffers(input, &mut buffer)
    }

    /// Fills the tape without creating a serializer, this function poses
    /// lifetime chalanges and can be frustrating, howver when it is
    /// usable it allows a allocation free (armotized) parsing of JSON
    ///
    /// # Errors
    ///
    /// Will return `Err` if `input` is invalid JSON.
    #[allow(clippy::uninit_vec)]
    #[cfg_attr(not(feature = "no-inline"), inline)]
    fn fill_tape(
        input: &'de mut [u8],
        buffer: &mut Buffers,
        tape: &mut Vec<Node<'de>>,
    ) -> Result<()> {
        const LOTS_OF_ZOERS: [u8; SIMDINPUT_LENGTH] = [0; SIMDINPUT_LENGTH];
        let len = input.len();
        let simd_safe_len = len + SIMDINPUT_LENGTH;

        if len > std::u32::MAX as usize {
            return Err(Self::error(ErrorType::InputTooLarge));
        }

        buffer.string_buffer.clear();
        buffer.string_buffer.reserve(len + SIMDJSON_PADDING);

        unsafe {
            buffer.string_buffer.set_len(len + SIMDJSON_PADDING);
        };

        let input_buffer = &mut buffer.input_buffer;
        if input_buffer.capacity() < simd_safe_len {
            *input_buffer = AlignedBuf::with_capacity(simd_safe_len);
        }

        unsafe {
            input_buffer
                .as_mut_ptr()
                .copy_from_nonoverlapping(input.as_ptr(), len);

            // initialize all remaining bytes
            // this also ensures we have a 0 to terminate the buffer
            input_buffer
                .as_mut_ptr()
                .add(len)
                .copy_from_nonoverlapping(LOTS_OF_ZOERS.as_ptr(), SIMDINPUT_LENGTH);

            // safety: all bytes are initialized
            input_buffer.set_len(simd_safe_len);

            Self::find_structural_bits(input, &mut buffer.structural_indexes)
                .map_err(Error::generic)?;
        };

        Self::build_tape(
            input,
            input_buffer,
            &mut buffer.string_buffer,
            &buffer.structural_indexes,
            &mut buffer.stage2_stack,
            tape,
        )
    }

    /// Creates a serializer from a mutable slice of bytes using a temporary
    /// buffer for strings for them to be copied in and out if needed
    ///
    /// # Errors
    ///
    /// Will return `Err` if `s` is invalid JSON.
    pub fn from_slice_with_buffers(input: &'de mut [u8], buffer: &mut Buffers) -> Result<Self> {
        let mut tape: Vec<Node<'de>> = Vec::with_capacity(buffer.structural_indexes.len());

        Self::fill_tape(input, buffer, &mut tape)?;

        Ok(Self { tape, idx: 0 })
    }

    #[cfg(feature = "serde_impl")]
    #[cfg_attr(not(feature = "no-inline"), inline)]
    fn skip(&mut self) {
        self.idx += 1;
    }

    /// Same as `next()` but we pull out the check so we don't need to
    /// stry every time. Use this only if you know the next element exists!
    ///
    /// # Safety
    ///
    /// This function is not safe to use, it is meant for internal use
    /// where it's know the tape isn't finished.
    #[cfg_attr(not(feature = "no-inline"), inline)]
    pub unsafe fn next_(&mut self) -> Node<'de> {
        let r = *self.tape.get_kinda_unchecked(self.idx);
        self.idx += 1;
        r
    }

    #[cfg_attr(not(feature = "no-inline"), inline)]
    #[allow(clippy::cast_possible_truncation)]
    pub(crate) unsafe fn _find_structural_bits<S: Stage1Parse>(
        input: &[u8],
        structural_indexes: &mut Vec<u32>,
    ) -> std::result::Result<(), ErrorType> {
        let len = input.len();
        // 8 is a heuristic number to estimate it turns out a rate of 1/8 structural characters
        // leads almost never to relocations.
        structural_indexes.clear();
        structural_indexes.reserve(len / 8);

        let mut utf8_validator = S::Utf8Validator::new();

        // we have padded the input out to 64 byte multiple with the remainder being
        // zeros

        // persistent state across loop
        // does the last iteration end with an odd-length sequence of backslashes?
        // either 0 or 1, but a 64-bit value
        let mut prev_iter_ends_odd_backslash: u64 = 0;
        // does the previous iteration end inside a double-quote pair?
        let mut prev_iter_inside_quote: u64 = 0;
        // either all zeros or all ones
        // does the previous iteration end on something that is a predecessor of a
        // pseudo-structural character - i.e. whitespace or a structural character
        // effectively the very first char is considered to follow "whitespace" for
        // the
        // purposes of pseudo-structural character detection so we initialize to 1
        let mut prev_iter_ends_pseudo_pred: u64 = 1;

        // structurals are persistent state across loop as we flatten them on the
        // subsequent iteration into our array pointed to be base_ptr.
        // This is harmless on the first iteration as structurals==0
        // and is done for performance reasons; we can hide some of the latency of the
        // expensive carryless multiply in the previous step with this work
        let mut structurals: u64 = 0;

        let lenminus64: usize = if len < 64 { 0 } else { len - 64 };
        let mut idx: usize = 0;
        let mut error_mask: u64 = 0; // for unescaped characters within strings (ASCII code points < 0x20)

        while idx < lenminus64 {
            /*
            #ifndef _MSC_VER
              __builtin_prefetch(buf + idx + 128);
            #endif
             */
            let chunk = input.get_kinda_unchecked(idx..idx + 64);
            utf8_validator.update_from_chunks(chunk);

            let input = S::new(chunk);
            // detect odd sequences of backslashes
            let odd_ends: u64 =
                input.find_odd_backslash_sequences(&mut prev_iter_ends_odd_backslash);

            // detect insides of quote pairs ("quote_mask") and also our quote_bits
            // themselves
            let mut quote_bits: u64 = 0;
            let quote_mask: u64 = input.find_quote_mask_and_bits(
                odd_ends,
                &mut prev_iter_inside_quote,
                &mut quote_bits,
                &mut error_mask,
            );

            // take the previous iterations structural bits, not our current iteration,
            // and flatten
            S::flatten_bits(structural_indexes, idx as u32, structurals);

            let mut whitespace: u64 = 0;
            input.find_whitespace_and_structurals(&mut whitespace, &mut structurals);

            // fixup structurals to reflect quotes and add pseudo-structural characters
            structurals = S::finalize_structurals(
                structurals,
                whitespace,
                quote_mask,
                quote_bits,
                &mut prev_iter_ends_pseudo_pred,
            );
            idx += SIMDINPUT_LENGTH;
        }

        // we use a giant copy-paste which is ugly.
        // but otherwise the string needs to be properly padded or else we
        // risk invalidating the UTF-8 checks.
        if idx < len {
            let mut tmpbuf: [u8; SIMDINPUT_LENGTH] = [0x20; SIMDINPUT_LENGTH];
            tmpbuf
                .as_mut_ptr()
                .copy_from(input.as_ptr().add(idx), len - idx);
            utf8_validator.update_from_chunks(&tmpbuf);

            let input = S::new(&tmpbuf);

            // detect odd sequences of backslashes
            let odd_ends: u64 =
                input.find_odd_backslash_sequences(&mut prev_iter_ends_odd_backslash);

            // detect insides of quote pairs ("quote_mask") and also our quote_bits
            // themselves
            let mut quote_bits: u64 = 0;
            let quote_mask: u64 = input.find_quote_mask_and_bits(
                odd_ends,
                &mut prev_iter_inside_quote,
                &mut quote_bits,
                &mut error_mask,
            );

            // take the previous iterations structural bits, not our current iteration,
            // and flatten
            S::flatten_bits(structural_indexes, idx as u32, structurals);

            let mut whitespace: u64 = 0;
            input.find_whitespace_and_structurals(&mut whitespace, &mut structurals);

            // fixup structurals to reflect quotes and add pseudo-structural characters
            structurals = S::finalize_structurals(
                structurals,
                whitespace,
                quote_mask,
                quote_bits,
                &mut prev_iter_ends_pseudo_pred,
            );
            idx += SIMDINPUT_LENGTH;
        }
        // This test isn't in upstream, for some reason the error mask is et for then.
        if prev_iter_inside_quote != 0 {
            return Err(ErrorType::Syntax);
        }
        // finally, flatten out the remaining structurals from the last iteration
        S::flatten_bits(structural_indexes, idx as u32, structurals);

        // a valid JSON file cannot have zero structural indexes - we should have
        // found something (note that we compare to 1 as we always add the root!)
        if structural_indexes.is_empty() {
            return Err(ErrorType::Eof);
        }

        if error_mask != 0 {
            return Err(ErrorType::Syntax);
        }

        if utf8_validator.finalize(None).is_err() {
            Err(ErrorType::InvalidUtf8)
        } else {
            Ok(())
        }
    }
}

/// SIMD aligned buffer
struct AlignedBuf {
    layout: Layout,
    capacity: usize,
    len: usize,
    inner: NonNull<u8>,
}
// We use allow Sync + Send here since we know u8 is sync and send
// we never reallocate or grow this buffer only allocate it in
// create then deallocate it in drop.
//
// An example of this can be found [in the official rust docs](https://doc.rust-lang.org/nomicon/vec/vec-raw.html).

unsafe impl Send for AlignedBuf {}
unsafe impl Sync for AlignedBuf {}
impl AlignedBuf {
    /// Creates a new buffer that is  aligned with the simd register size
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        let layout = match Layout::from_size_align(capacity, SIMDJSON_PADDING) {
            Ok(layout) => layout,
            Err(_) => Self::capacity_overflow(),
        };
        if mem::size_of::<usize>() < 8 && capacity > isize::MAX as usize {
            Self::capacity_overflow()
        }
        let inner = match unsafe { NonNull::new(alloc(layout)) } {
            Some(ptr) => ptr,
            None => handle_alloc_error(layout),
        };
        Self {
            layout,
            capacity,
            len: 0,
            inner,
        }
    }

    fn as_mut_ptr(&mut self) -> *mut u8 {
        self.inner.as_ptr()
    }

    fn capacity_overflow() -> ! {
        panic!("capacity overflow");
    }
    fn capacity(&self) -> usize {
        self.capacity
    }
    unsafe fn set_len(&mut self, n: usize) {
        assert!(
            n <= self.capacity,
            "New size ({}) can not be larger then capacity ({}).",
            n,
            self.capacity
        );
        self.len = n;
    }
}
impl Drop for AlignedBuf {
    fn drop(&mut self) {
        unsafe {
            dealloc(self.inner.as_ptr(), self.layout);
        }
    }
}

impl Deref for AlignedBuf {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        unsafe { std::slice::from_raw_parts(self.inner.as_ptr(), self.len) }
    }
}

impl DerefMut for AlignedBuf {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { std::slice::from_raw_parts_mut(self.inner.as_ptr(), self.len) }
    }
}

#[cfg(test)]
mod tests;