Files
addr2line
adler
aead
aes
aes_gcm
aes_soft
ahash
aho_corasick
ansi_term
anyhow
approx
arrayref
arrayvec
asn1_der
asn1_der_derive
async_channel
async_executor
async_global_executor
async_io
async_lock
async_mutex
async_process
async_std
collections
fs
future
io
net
option
os
path
pin
result
rt
stream
string
sync
task
unit
vec
async_task
async_trait
asynchronous_codec
atomic
atomic_waker
atty
backtrace
base58
base64
base_x
bincode
bip39
bitflags
bitvec
blake2
blake2_rfc
blake2b_simd
blake2s_simd
blake3
block_buffer
block_cipher
block_padding
blocking
bs58
bstr
bumpalo
byte_slice_cast
byteorder
bytes
cache_padded
cfg_if
chacha20
chacha20poly1305
chrono
cid
cipher
clap
concurrent_queue
constant_time_eq
convert_case
cpp_demangle
cpuid_bool
cranelift_bforest
cranelift_codegen
cranelift_codegen_shared
cranelift_entity
cranelift_frontend
cranelift_native
cranelift_wasm
crc32fast
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_utils
crunchy
crypto_mac
ct_logs
ctor
cuckoofilter
curve25519_dalek
data_encoding
data_encoding_macro
data_encoding_macro_internal
derive_more
digest
directories
directories_next
dirs_sys
dirs_sys_next
dns_parser
dyn_clonable
dyn_clonable_impl
dyn_clone
ed25519
ed25519_dalek
either
env_logger
environmental
erased_serde
errno
event_listener
exit_future
failure
failure_derive
fallible_iterator
fastrand
fdlimit
file_per_thread_logger
finality_grandpa
fixed_hash
flate2
fnv
fork_tree
form_urlencoded
frame_benchmarking
frame_benchmarking_cli
frame_executive
frame_metadata
frame_support
frame_support_procedural
frame_support_procedural_tools
frame_support_procedural_tools_derive
frame_system
frame_system_rpc_runtime_api
fs2
fs_swap
funty
futures
futures_channel
futures_core
futures_diagnose
futures_executor
futures_io
futures_lite
futures_macro
futures_rustls
futures_sink
futures_task
futures_timer
futures_util
async_await
compat
future
io
lock
sink
stream
task
generic_array
getrandom
ghash
gimli
globset
governance_os_node
governance_os_pallet_bylaws
governance_os_pallet_coin_voting
governance_os_pallet_compat
governance_os_pallet_conviction_voting
governance_os_pallet_organizations
governance_os_pallet_plcr_voting
governance_os_pallet_tokens
governance_os_primitives
governance_os_runtime
governance_os_support
h2
handlebars
hash256_std_hasher
hash_db
hashbrown
heck
hex
hex_fmt
hmac
hmac_drbg
http
http_body
httparse
httpdate
humantime
hyper
hyper_rustls
idna
if_watch
impl_codec
impl_serde
impl_trait_for_tuples
indexmap
inflector
cases
camelcase
case
classcase
kebabcase
pascalcase
screamingsnakecase
sentencecase
snakecase
tablecase
titlecase
traincase
numbers
deordinalize
ordinalize
string
constants
deconstantize
demodulize
pluralize
singularize
suffix
foreignkey
instant
integer_sqrt
intervalier
iovec
ip_network
ipnet
itertools
itoa
js_sys
jsonrpc_client_transports
jsonrpc_core
jsonrpc_core_client
jsonrpc_derive
jsonrpc_http_server
jsonrpc_ipc_server
jsonrpc_pubsub
jsonrpc_server_utils
jsonrpc_ws_server
keccak
kv_log_macro
kvdb
kvdb_memorydb
kvdb_rocksdb
lazy_static
lazycell
leb128
libc
libm
libp2p
libp2p_core
libp2p_core_derive
libp2p_deflate
libp2p_dns
libp2p_floodsub
libp2p_gossipsub
libp2p_identify
libp2p_kad
libp2p_mdns
libp2p_mplex
libp2p_noise
libp2p_ping
libp2p_plaintext
libp2p_pnet
libp2p_request_response
libp2p_swarm
libp2p_tcp
libp2p_uds
libp2p_wasm_ext
libp2p_websocket
libp2p_yamux
librocksdb_sys
libz_sys
linked_hash_map
linked_hash_set
linregress
lock_api
log
lru
maplit
matchers
matches
matrixmultiply
memchr
memmap2
memoffset
memory_db
memory_units
merlin
minicbor
minicbor_derive
miniz_oxide
mio
mio_extras
mio_named_pipes
mio_uds
miow
more_asserts
multibase
multihash
multihash_derive
multistream_select
nalgebra
base
geometry
linalg
names
nb_connect
net2
nohash_hasher
num_bigint
num_complex
num_cpus
num_integer
num_rational
num_traits
object
once_cell
opaque_debug
openssl_probe
owning_ref
pallet_aura
pallet_authorship
pallet_grandpa
pallet_randomness_collective_flip
pallet_session
pallet_timestamp
pallet_transaction_payment
pallet_transaction_payment_rpc
pallet_transaction_payment_rpc_runtime_api
parity_db
parity_multiaddr
parity_scale_codec
parity_scale_codec_derive
parity_send_wrapper
parity_tokio_ipc
parity_util_mem
parity_util_mem_derive
parity_wasm
parity_ws
parking
parking_lot
parking_lot_core
paste
paste_impl
pbkdf2
pdqselect
percent_encoding
pest
pest_derive
pest_generator
pest_meta
pin_project
pin_project_lite
pin_utils
polling
poly1305
polyval
ppv_lite86
primitive_types
proc_macro2
proc_macro_crate
proc_macro_error
proc_macro_error_attr
proc_macro_hack
proc_macro_nested
prometheus
prost
prost_derive
psm
pwasm_utils
quick_error
quicksink
quote
radium
rand
rand_chacha
rand_core
rand_distr
raw_cpuid
rawpointer
rayon
rayon_core
ref_cast
ref_cast_impl
regalloc
regex
regex_automata
regex_syntax
region
remove_dir_all
retain_mut
ring
rocksdb
rpassword
rustc_demangle
rustc_hash
rustc_hex
rustls
rustls_native_certs
rw_stream_sink
ryu
safe_mix
salsa20
sc_basic_authorship
sc_block_builder
sc_chain_spec
sc_chain_spec_derive
sc_cli
sc_client_api
sc_client_db
sc_consensus
sc_consensus_aura
sc_consensus_babe
sc_consensus_epochs
sc_consensus_slots
sc_consensus_uncles
sc_executor
sc_executor_common
sc_executor_wasmi
sc_executor_wasmtime
sc_finality_grandpa
sc_informant
sc_keystore
sc_light
sc_network
sc_network_gossip
sc_offchain
sc_peerset
sc_proposer_metrics
sc_rpc
sc_rpc_api
sc_rpc_server
sc_service
sc_state_db
sc_telemetry
sc_tracing
sc_tracing_proc_macro
sc_transaction_graph
sc_transaction_pool
schnorrkel
scoped_tls
scopeguard
scroll
scroll_derive
sct
secp256k1
secrecy
serde
serde_derive
serde_json
sha1
sha2
sha3
sharded_slab
signal_hook
signal_hook_registry
signature
simba
slab
smallvec
snow
socket2
soketto
sp_allocator
sp_api
sp_api_proc_macro
sp_application_crypto
sp_arithmetic
sp_authorship
sp_block_builder
sp_blockchain
sp_chain_spec
sp_consensus
sp_consensus_aura
sp_consensus_babe
sp_consensus_slots
sp_consensus_vrf
sp_core
sp_database
sp_debug_derive
sp_externalities
sp_finality_grandpa
sp_inherents
sp_io
sp_keyring
sp_keystore
sp_offchain
sp_panic_handler
sp_rpc
sp_runtime
sp_runtime_interface
sp_runtime_interface_proc_macro
sp_serializer
sp_session
sp_staking
sp_state_machine
sp_std
sp_storage
sp_tasks
sp_timestamp
sp_tracing
sp_transaction_pool
sp_trie
sp_utils
sp_version
sp_wasm_interface
spin
stable_deref_trait
static_assertions
statrs
stream_cipher
strsim
structopt
structopt_derive
strum
strum_macros
substrate_bip39
substrate_frame_rpc_system
substrate_prometheus_endpoint
subtle
syn
synstructure
take_mut
tap
target_lexicon
tempfile
termcolor
textwrap
thiserror
thiserror_impl
thread_local
threadpool
time
tiny_keccak
tinyvec
tinyvec_macros
tokio
future
io
loom
macros
net
park
runtime
signal
stream
sync
task
time
util
tokio_codec
tokio_executor
tokio_io
tokio_named_pipes
tokio_reactor
tokio_rustls
tokio_service
tokio_sync
tokio_uds
tokio_util
toml
tower_service
tracing
tracing_attributes
tracing_core
tracing_futures
tracing_log
tracing_serde
tracing_subscriber
trie_db
trie_root
try_lock
twox_hash
typenum
ucd_trie
uint
unicase
unicode_bidi
unicode_normalization
unicode_segmentation
unicode_width
unicode_xid
universal_hash
unsigned_varint
untrusted
url
value_bag
vec_arena
vec_map
void
waker_fn
want
wasm_bindgen
wasm_bindgen_backend
wasm_bindgen_futures
wasm_bindgen_macro
wasm_bindgen_macro_support
wasm_bindgen_shared
wasm_timer
wasmi
wasmi_validation
wasmparser
wasmtime
wasmtime_cache
wasmtime_cranelift
wasmtime_debug
wasmtime_environ
wasmtime_jit
wasmtime_obj
wasmtime_profiling
wasmtime_runtime
wast
wat
webpki
webpki_roots
winapi
wyz
x25519_dalek
yamux
zeroize
zeroize_derive
zstd
zstd_safe
zstd_sys
  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
use core::cmp;

use cow::CowBytes;
use ext_slice::ByteSlice;
use search::prefilter::{Freqy, PrefilterState};

/// An implementation of the TwoWay substring search algorithm, with heuristics
/// for accelerating search based on frequency analysis.
///
/// This searcher supports forward and reverse search, although not
/// simultaneously. It runs in O(n + m) time and O(1) space, where
/// `n ~ len(needle)` and `m ~ len(haystack)`.
///
/// The implementation here roughly matches that which was developed by
/// Crochemore and Perrin in their 1991 paper "Two-way string-matching." The
/// only change in this implementation is the use of zero-based indices and
/// the addition of heuristics for a fast skip loop. That is, this will detect
/// bytes that are believed to be rare in the needle and use fast vectorized
/// instructions to find their occurrences quickly. The Two-Way algorithm is
/// then used to confirm whether a match at that location occurred.
///
/// The heuristic for fast skipping is automatically shut off if it's
/// detected to be ineffective at search time. Generally, this only occurs in
/// pathological cases. But this is generally necessary in order to preserve
/// a `O(n + m)` time bound.
///
/// The code below is fairly complex and not obviously correct at all. It's
/// likely necessary to read the Two-Way paper cited above in order to fully
/// grok this code.
#[derive(Clone, Debug)]
pub struct TwoWay<'b> {
    /// The needle that we're looking for.
    needle: CowBytes<'b>,
    /// An implementation of a fast skip loop based on hard-coded frequency
    /// data. This is only used when conditions are deemed favorable.
    freqy: Freqy,
    /// A critical position in needle. Specifically, this position corresponds
    /// to beginning of either the minimal or maximal suffix in needle. (N.B.
    /// See SuffixType below for why "minimal" isn't quite the correct word
    /// here.)
    ///
    /// This is the position at which every search begins. Namely, search
    /// starts by scanning text to the right of this position, and only if
    /// there's a match does the text to the left of this position get scanned.
    critical_pos: usize,
    /// The amount we shift by in the Two-Way search algorithm. This
    /// corresponds to the "small period" and "large period" cases.
    shift: Shift,
}

impl<'b> TwoWay<'b> {
    /// Create a searcher that uses the Two-Way algorithm by searching forwards
    /// through any haystack.
    pub fn forward(needle: &'b [u8]) -> TwoWay<'b> {
        let freqy = Freqy::forward(needle);
        if needle.is_empty() {
            return TwoWay {
                needle: CowBytes::new(needle),
                freqy,
                critical_pos: 0,
                shift: Shift::Large { shift: 0 },
            };
        }

        let min_suffix = Suffix::forward(needle, SuffixKind::Minimal);
        let max_suffix = Suffix::forward(needle, SuffixKind::Maximal);
        let (period_lower_bound, critical_pos) =
            if min_suffix.pos > max_suffix.pos {
                (min_suffix.period, min_suffix.pos)
            } else {
                (max_suffix.period, max_suffix.pos)
            };
        let shift = Shift::forward(needle, period_lower_bound, critical_pos);
        let needle = CowBytes::new(needle);
        TwoWay { needle, freqy, critical_pos, shift }
    }

    /// Create a searcher that uses the Two-Way algorithm by searching in
    /// reverse through any haystack.
    pub fn reverse(needle: &'b [u8]) -> TwoWay<'b> {
        let freqy = Freqy::reverse(needle);
        if needle.is_empty() {
            return TwoWay {
                needle: CowBytes::new(needle),
                freqy,
                critical_pos: 0,
                shift: Shift::Large { shift: 0 },
            };
        }

        let min_suffix = Suffix::reverse(needle, SuffixKind::Minimal);
        let max_suffix = Suffix::reverse(needle, SuffixKind::Maximal);
        let (period_lower_bound, critical_pos) =
            if min_suffix.pos < max_suffix.pos {
                (min_suffix.period, min_suffix.pos)
            } else {
                (max_suffix.period, max_suffix.pos)
            };
        let shift = Shift::reverse(needle, period_lower_bound, critical_pos);
        let needle = CowBytes::new(needle);
        TwoWay { needle, freqy, critical_pos, shift }
    }

    /// Return a fresh prefilter state that can be used with this searcher.
    /// A prefilter state is used to track the effectiveness of a searcher's
    /// prefilter for speeding up searches. Therefore, the prefilter state
    /// should generally be reused on subsequent searches (such as in an
    /// iterator). For searches on a different haystack, then a new prefilter
    /// state should be used.
    ///
    /// This always initializes a valid prefilter state even if this searcher
    /// does not have a prefilter enabled.
    pub fn prefilter_state(&self) -> PrefilterState {
        self.freqy.prefilter_state()
    }

    /// Return the needle used by this searcher.
    pub fn needle(&self) -> &[u8] {
        self.needle.as_slice()
    }

    /// Convert this searched into an owned version, where the needle is
    /// copied if it isn't already owned.
    #[cfg(feature = "std")]
    pub fn into_owned(self) -> TwoWay<'static> {
        TwoWay {
            needle: self.needle.into_owned(),
            freqy: self.freqy,
            critical_pos: self.critical_pos,
            shift: self.shift,
        }
    }

    /// Find the position of the first occurrence of this searcher's needle in
    /// the given haystack. If one does not exist, then return None.
    ///
    /// This will automatically initialize prefilter state. This should only
    /// be used for one-off searches.
    pub fn find(&self, haystack: &[u8]) -> Option<usize> {
        self.find_with(&mut self.prefilter_state(), haystack)
    }

    /// Find the position of the last occurrence of this searcher's needle
    /// in the given haystack. If one does not exist, then return None.
    ///
    /// This will automatically initialize prefilter state. This should only
    /// be used for one-off searches.
    pub fn rfind(&self, haystack: &[u8]) -> Option<usize> {
        self.rfind_with(&mut self.prefilter_state(), haystack)
    }

    /// Find the position of the first occurrence of this searcher's needle in
    /// the given haystack. If one does not exist, then return None.
    ///
    /// This accepts prefilter state that is useful when using the same
    /// searcher multiple times, such as in an iterator.
    pub fn find_with(
        &self,
        prestate: &mut PrefilterState,
        haystack: &[u8],
    ) -> Option<usize> {
        if self.needle.is_empty() {
            return Some(0);
        } else if haystack.len() < self.needle.len() {
            return None;
        } else if self.needle.len() == 1 {
            return haystack.find_byte(self.needle[0]);
        }
        match self.shift {
            Shift::Small { period } => {
                self.find_small(prestate, haystack, period)
            }
            Shift::Large { shift } => {
                self.find_large(prestate, haystack, shift)
            }
        }
    }

    /// Find the position of the last occurrence of this searcher's needle
    /// in the given haystack. If one does not exist, then return None.
    ///
    /// This accepts prefilter state that is useful when using the same
    /// searcher multiple times, such as in an iterator.
    pub fn rfind_with(
        &self,
        prestate: &mut PrefilterState,
        haystack: &[u8],
    ) -> Option<usize> {
        if self.needle.is_empty() {
            return Some(haystack.len());
        } else if haystack.len() < self.needle.len() {
            return None;
        } else if self.needle.len() == 1 {
            return haystack.rfind_byte(self.needle[0]);
        }
        match self.shift {
            Shift::Small { period } => {
                self.rfind_small(prestate, haystack, period)
            }
            Shift::Large { shift } => {
                self.rfind_large(prestate, haystack, shift)
            }
        }
    }

    // Below is the actual implementation of TwoWay searching, including both
    // forwards and backwards searching. Each forward and reverse search has
    // two fairly similar implementations, each handling the small and large
    // period cases, for a total 4 different search routines.
    //
    // On top of that, each search implementation can be accelerated by a
    // Freqy prefilter, but it is not always enabled. To avoid its overhead
    // when its disabled, we explicitly inline each search implementation based
    // on whether Freqy will be used or not. This brings us up to a total of
    // 8 monomorphized versions of the search code.

    #[inline(never)]
    fn find_small(
        &self,
        prestate: &mut PrefilterState,
        haystack: &[u8],
        period: usize,
    ) -> Option<usize> {
        if prestate.is_effective() {
            self.find_small_imp(prestate, true, haystack, period)
        } else {
            self.find_small_imp(prestate, false, haystack, period)
        }
    }

    #[inline(always)]
    fn find_small_imp(
        &self,
        prestate: &mut PrefilterState,
        prefilter: bool,
        haystack: &[u8],
        period: usize,
    ) -> Option<usize> {
        let needle = self.needle.as_slice();
        let mut pos = 0;
        let mut shift = 0;
        while pos + needle.len() <= haystack.len() {
            let mut i = cmp::max(self.critical_pos, shift);
            if prefilter && prestate.is_effective() {
                match self.freqy.find_candidate(prestate, &haystack[pos..]) {
                    None => return None,
                    Some(found) => {
                        shift = 0;
                        i = self.critical_pos;
                        pos += found;
                        if pos + needle.len() > haystack.len() {
                            return None;
                        }
                    }
                }
            }
            while i < needle.len() && needle[i] == haystack[pos + i] {
                i += 1;
            }
            if i < needle.len() {
                pos += i - self.critical_pos + 1;
                shift = 0;
            } else {
                let mut j = self.critical_pos;
                while j > shift && needle[j] == haystack[pos + j] {
                    j -= 1;
                }
                if j <= shift && needle[shift] == haystack[pos + shift] {
                    return Some(pos);
                }
                pos += period;
                shift = needle.len() - period;
            }
        }
        None
    }

    #[inline(never)]
    fn find_large(
        &self,
        prestate: &mut PrefilterState,
        haystack: &[u8],
        shift: usize,
    ) -> Option<usize> {
        if prestate.is_effective() {
            self.find_large_imp(prestate, true, haystack, shift)
        } else {
            self.find_large_imp(prestate, false, haystack, shift)
        }
    }

    #[inline(always)]
    fn find_large_imp(
        &self,
        prestate: &mut PrefilterState,
        prefilter: bool,
        haystack: &[u8],
        shift: usize,
    ) -> Option<usize> {
        let needle = self.needle.as_slice();
        let mut pos = 0;
        while pos + needle.len() <= haystack.len() {
            let mut i = self.critical_pos;
            if prefilter && prestate.is_effective() {
                match self.freqy.find_candidate(prestate, &haystack[pos..]) {
                    None => return None,
                    Some(found) => {
                        pos += found;
                        if pos + needle.len() > haystack.len() {
                            return None;
                        }
                    }
                }
            }
            while i < needle.len() && needle[i] == haystack[pos + i] {
                i += 1;
            }
            if i < needle.len() {
                pos += i - self.critical_pos + 1;
            } else {
                let mut j = self.critical_pos;
                while j > 0 && needle[j] == haystack[pos + j] {
                    j -= 1;
                }
                if j == 0 && needle[0] == haystack[pos] {
                    return Some(pos);
                }
                pos += shift;
            }
        }
        None
    }

    #[inline(never)]
    fn rfind_small(
        &self,
        prestate: &mut PrefilterState,
        haystack: &[u8],
        period: usize,
    ) -> Option<usize> {
        if prestate.is_effective() {
            self.rfind_small_imp(prestate, true, haystack, period)
        } else {
            self.rfind_small_imp(prestate, false, haystack, period)
        }
    }

    #[inline(always)]
    fn rfind_small_imp(
        &self,
        prestate: &mut PrefilterState,
        prefilter: bool,
        haystack: &[u8],
        period: usize,
    ) -> Option<usize> {
        let needle = &*self.needle;
        let nlen = needle.len();
        let mut pos = haystack.len();
        let mut shift = nlen;
        while pos >= nlen {
            let mut i = cmp::min(self.critical_pos, shift);
            if prefilter && prestate.is_effective() {
                match self.freqy.rfind_candidate(prestate, &haystack[..pos]) {
                    None => return None,
                    Some(found) => {
                        shift = nlen;
                        i = self.critical_pos;
                        pos = found;
                        if pos < nlen {
                            return None;
                        }
                    }
                }
            }
            while i > 0 && needle[i - 1] == haystack[pos - nlen + i - 1] {
                i -= 1;
            }
            if i > 0 || needle[0] != haystack[pos - nlen] {
                pos -= self.critical_pos - i + 1;
                shift = nlen;
            } else {
                let mut j = self.critical_pos;
                while j < shift && needle[j] == haystack[pos - nlen + j] {
                    j += 1;
                }
                if j == shift {
                    return Some(pos - nlen);
                }
                pos -= period;
                shift = period;
            }
        }
        None
    }

    #[inline(never)]
    fn rfind_large(
        &self,
        prestate: &mut PrefilterState,
        haystack: &[u8],
        shift: usize,
    ) -> Option<usize> {
        if prestate.is_effective() {
            self.rfind_large_imp(prestate, true, haystack, shift)
        } else {
            self.rfind_large_imp(prestate, false, haystack, shift)
        }
    }

    #[inline(always)]
    fn rfind_large_imp(
        &self,
        prestate: &mut PrefilterState,
        prefilter: bool,
        haystack: &[u8],
        shift: usize,
    ) -> Option<usize> {
        let needle = &*self.needle;
        let nlen = needle.len();
        let mut pos = haystack.len();
        while pos >= nlen {
            if prefilter && prestate.is_effective() {
                match self.freqy.rfind_candidate(prestate, &haystack[..pos]) {
                    None => return None,
                    Some(found) => {
                        pos = found;
                        if pos < nlen {
                            return None;
                        }
                    }
                }
            }

            let mut i = self.critical_pos;
            while i > 0 && needle[i - 1] == haystack[pos - nlen + i - 1] {
                i -= 1;
            }
            if i > 0 || needle[0] != haystack[pos - nlen] {
                pos -= self.critical_pos - i + 1;
            } else {
                let mut j = self.critical_pos;
                while j < nlen && needle[j] == haystack[pos - nlen + j] {
                    j += 1;
                }
                if j == nlen {
                    return Some(pos - nlen);
                }
                pos -= shift;
            }
        }
        None
    }
}

/// A representation of the amount we're allowed to shift by during Two-Way
/// search.
///
/// When computing a critical factorization of the needle, we find the position
/// of the critical factorization by finding the needle's maximal (or minimal)
/// suffix, along with the period of that suffix. It turns out that the period
/// of that suffix is a lower bound on the period of the needle itself.
///
/// This lower bound is equivalent to the actual period of the needle in
/// some cases. To describe that case, we denote the needle as `x` where
/// `x = uv` and `v` is the lexicographic maximal suffix of `v`. The lower
/// bound given here is always the period of `v`, which is `<= period(x)`. The
/// case where `period(v) == period(x)` occurs when `len(u) < (len(x) / 2)` and
/// where `u` is a suffix of `v[0..period(v)]`.
///
/// This case is important because the search algorithm for when the
/// periods are equivalent is slightly different than the search algorithm
/// for when the periods are not equivalent. In particular, when they aren't
/// equivalent, we know that the period of the needle is no less than half its
/// length. In this case, we shift by an amount less than or equal to the
/// period of the needle (determined by the maximum length of the components
/// of the critical factorization of `x`, i.e., `max(len(u), len(v))`)..
///
/// The above two cases are represented by the variants below. Each entails
/// a different instantiation of the Two-Way search algorithm.
///
/// N.B. If we could find a way to compute the exact period in all cases,
/// then we could collapse this case analysis and simplify the algorithm. The
/// Two-Way paper suggests this is possible, but more reading is required to
/// grok why the authors didn't pursue that path.
#[derive(Clone, Debug)]
enum Shift {
    Small { period: usize },
    Large { shift: usize },
}

impl Shift {
    /// Compute the shift for a given needle in the forward direction.
    ///
    /// This requires a lower bound on the period and a critical position.
    /// These can be computed by extracting both the minimal and maximal
    /// lexicographic suffixes, and choosing the right-most starting position.
    /// The lower bound on the period is then the period of the chosen suffix.
    fn forward(
        needle: &[u8],
        period_lower_bound: usize,
        critical_pos: usize,
    ) -> Shift {
        let large = cmp::max(critical_pos, needle.len() - critical_pos);
        if critical_pos * 2 >= needle.len() {
            return Shift::Large { shift: large };
        }

        let (u, v) = needle.split_at(critical_pos);
        if !v[..period_lower_bound].ends_with(u) {
            return Shift::Large { shift: large };
        }
        Shift::Small { period: period_lower_bound }
    }

    /// Compute the shift for a given needle in the reverse direction.
    ///
    /// This requires a lower bound on the period and a critical position.
    /// These can be computed by extracting both the minimal and maximal
    /// lexicographic suffixes, and choosing the left-most starting position.
    /// The lower bound on the period is then the period of the chosen suffix.
    fn reverse(
        needle: &[u8],
        period_lower_bound: usize,
        critical_pos: usize,
    ) -> Shift {
        let large = cmp::max(critical_pos, needle.len() - critical_pos);
        if (needle.len() - critical_pos) * 2 >= needle.len() {
            return Shift::Large { shift: large };
        }

        let (v, u) = needle.split_at(critical_pos);
        if !v[v.len() - period_lower_bound..].starts_with(u) {
            return Shift::Large { shift: large };
        }
        Shift::Small { period: period_lower_bound }
    }
}

/// A suffix extracted from a needle along with its period.
#[derive(Debug)]
struct Suffix {
    /// The starting position of this suffix.
    ///
    /// If this is a forward suffix, then `&bytes[pos..]` can be used. If this
    /// is a reverse suffix, then `&bytes[..pos]` can be used. That is, for
    /// forward suffixes, this is an inclusive starting position, where as for
    /// reverse suffixes, this is an exclusive ending position.
    pos: usize,
    /// The period of this suffix.
    ///
    /// Note that this is NOT necessarily the period of the string from which
    /// this suffix comes from. (It is always less than or equal to the period
    /// of the original string.)
    period: usize,
}

impl Suffix {
    fn forward(needle: &[u8], kind: SuffixKind) -> Suffix {
        debug_assert!(!needle.is_empty());

        // suffix represents our maximal (or minimal) suffix, along with
        // its period.
        let mut suffix = Suffix { pos: 0, period: 1 };
        // The start of a suffix in `needle` that we are considering as a
        // more maximal (or minimal) suffix than what's in `suffix`.
        let mut candidate_start = 1;
        // The current offset of our suffixes that we're comparing.
        //
        // When the characters at this offset are the same, then we mush on
        // to the next position since no decision is possible. When the
        // candidate's character is greater (or lesser) than the corresponding
        // character than our current maximal (or minimal) suffix, then the
        // current suffix is changed over to the candidate and we restart our
        // search. Otherwise, the candidate suffix is no good and we restart
        // our search on the next candidate.
        //
        // The three cases above correspond to the three cases in the loop
        // below.
        let mut offset = 0;

        while candidate_start + offset < needle.len() {
            let current = needle[suffix.pos + offset];
            let candidate = needle[candidate_start + offset];
            match kind.cmp(current, candidate) {
                SuffixOrdering::Accept => {
                    suffix = Suffix { pos: candidate_start, period: 1 };
                    candidate_start += 1;
                    offset = 0;
                }
                SuffixOrdering::Skip => {
                    candidate_start += offset + 1;
                    offset = 0;
                    suffix.period = candidate_start - suffix.pos;
                }
                SuffixOrdering::Push => {
                    if offset + 1 == suffix.period {
                        candidate_start += suffix.period;
                        offset = 0;
                    } else {
                        offset += 1;
                    }
                }
            }
        }
        suffix
    }

    fn reverse(needle: &[u8], kind: SuffixKind) -> Suffix {
        debug_assert!(!needle.is_empty());

        // See the comments in `forward` for how this works.
        let mut suffix = Suffix { pos: needle.len(), period: 1 };
        if needle.len() == 1 {
            return suffix;
        }
        let mut candidate_start = needle.len() - 1;
        let mut offset = 0;

        while offset < candidate_start {
            let current = needle[suffix.pos - offset - 1];
            let candidate = needle[candidate_start - offset - 1];
            match kind.cmp(current, candidate) {
                SuffixOrdering::Accept => {
                    suffix = Suffix { pos: candidate_start, period: 1 };
                    candidate_start -= 1;
                    offset = 0;
                }
                SuffixOrdering::Skip => {
                    candidate_start -= offset + 1;
                    offset = 0;
                    suffix.period = suffix.pos - candidate_start;
                }
                SuffixOrdering::Push => {
                    if offset + 1 == suffix.period {
                        candidate_start -= suffix.period;
                        offset = 0;
                    } else {
                        offset += 1;
                    }
                }
            }
        }
        suffix
    }
}

/// The kind of suffix to extract.
#[derive(Clone, Copy, Debug)]
enum SuffixKind {
    /// Extract the smallest lexicographic suffix from a string.
    ///
    /// Technically, this doesn't actually pick the smallest lexicographic
    /// suffix. e.g., Given the choice between `a` and `aa`, this will choose
    /// the latter over the former, even though `a < aa`. The reasoning for
    /// this isn't clear from the paper, but it still smells like a minimal
    /// suffix.
    Minimal,
    /// Extract the largest lexicographic suffix from a string.
    ///
    /// Unlike `Minimal`, this really does pick the maximum suffix. e.g., Given
    /// the choice between `z` and `zz`, this will choose the latter over the
    /// former.
    Maximal,
}

/// The result of comparing corresponding bytes between two suffixes.
#[derive(Clone, Copy, Debug)]
enum SuffixOrdering {
    /// This occurs when the given candidate byte indicates that the candidate
    /// suffix is better than the current maximal (or minimal) suffix. That is,
    /// the current candidate suffix should supplant the current maximal (or
    /// minimal) suffix.
    Accept,
    /// This occurs when the given candidate byte excludes the candidate suffix
    /// from being better than the current maximal (or minimal) suffix. That
    /// is, the current candidate suffix should be dropped and the next one
    /// should be considered.
    Skip,
    /// This occurs when no decision to accept or skip the candidate suffix
    /// can be made, e.g., when corresponding bytes are equivalent. In this
    /// case, the next corresponding bytes should be compared.
    Push,
}

impl SuffixKind {
    /// Returns true if and only if the given candidate byte indicates that
    /// it should replace the current suffix as the maximal (or minimal)
    /// suffix.
    fn cmp(self, current: u8, candidate: u8) -> SuffixOrdering {
        use self::SuffixOrdering::*;

        match self {
            SuffixKind::Minimal if candidate < current => Accept,
            SuffixKind::Minimal if candidate > current => Skip,
            SuffixKind::Minimal => Push,
            SuffixKind::Maximal if candidate > current => Accept,
            SuffixKind::Maximal if candidate < current => Skip,
            SuffixKind::Maximal => Push,
        }
    }
}

// N.B. There are more holistic tests in src/search/tests.rs.
#[cfg(test)]
mod tests {
    use super::*;
    use ext_slice::B;

    /// Convenience wrapper for computing the suffix as a byte string.
    fn get_suffix_forward(needle: &[u8], kind: SuffixKind) -> (&[u8], usize) {
        let s = Suffix::forward(needle, kind);
        (&needle[s.pos..], s.period)
    }

    /// Convenience wrapper for computing the reverse suffix as a byte string.
    fn get_suffix_reverse(needle: &[u8], kind: SuffixKind) -> (&[u8], usize) {
        let s = Suffix::reverse(needle, kind);
        (&needle[..s.pos], s.period)
    }

    /// Return all of the non-empty suffixes in the given byte string.
    fn suffixes(bytes: &[u8]) -> Vec<&[u8]> {
        (0..bytes.len()).map(|i| &bytes[i..]).collect()
    }

    /// Return the lexicographically maximal suffix of the given byte string.
    fn naive_maximal_suffix_forward(needle: &[u8]) -> &[u8] {
        let mut sufs = suffixes(needle);
        sufs.sort();
        sufs.pop().unwrap()
    }

    /// Return the lexicographically maximal suffix of the reverse of the given
    /// byte string.
    fn naive_maximal_suffix_reverse(needle: &[u8]) -> Vec<u8> {
        let mut reversed = needle.to_vec();
        reversed.reverse();
        let mut got = naive_maximal_suffix_forward(&reversed).to_vec();
        got.reverse();
        got
    }

    #[test]
    fn suffix_forward() {
        macro_rules! assert_suffix_min {
            ($given:expr, $expected:expr, $period:expr) => {
                let (got_suffix, got_period) =
                    get_suffix_forward($given.as_bytes(), SuffixKind::Minimal);
                assert_eq!((B($expected), $period), (got_suffix, got_period));
            };
        }

        macro_rules! assert_suffix_max {
            ($given:expr, $expected:expr, $period:expr) => {
                let (got_suffix, got_period) =
                    get_suffix_forward($given.as_bytes(), SuffixKind::Maximal);
                assert_eq!((B($expected), $period), (got_suffix, got_period));
            };
        }

        assert_suffix_min!("a", "a", 1);
        assert_suffix_max!("a", "a", 1);

        assert_suffix_min!("ab", "ab", 2);
        assert_suffix_max!("ab", "b", 1);

        assert_suffix_min!("ba", "a", 1);
        assert_suffix_max!("ba", "ba", 2);

        assert_suffix_min!("abc", "abc", 3);
        assert_suffix_max!("abc", "c", 1);

        assert_suffix_min!("acb", "acb", 3);
        assert_suffix_max!("acb", "cb", 2);

        assert_suffix_min!("cba", "a", 1);
        assert_suffix_max!("cba", "cba", 3);

        assert_suffix_min!("abcabc", "abcabc", 3);
        assert_suffix_max!("abcabc", "cabc", 3);

        assert_suffix_min!("abcabcabc", "abcabcabc", 3);
        assert_suffix_max!("abcabcabc", "cabcabc", 3);

        assert_suffix_min!("abczz", "abczz", 5);
        assert_suffix_max!("abczz", "zz", 1);

        assert_suffix_min!("zzabc", "abc", 3);
        assert_suffix_max!("zzabc", "zzabc", 5);

        assert_suffix_min!("aaa", "aaa", 1);
        assert_suffix_max!("aaa", "aaa", 1);

        assert_suffix_min!("foobar", "ar", 2);
        assert_suffix_max!("foobar", "r", 1);
    }

    #[test]
    fn suffix_reverse() {
        macro_rules! assert_suffix_min {
            ($given:expr, $expected:expr, $period:expr) => {
                let (got_suffix, got_period) =
                    get_suffix_reverse($given.as_bytes(), SuffixKind::Minimal);
                assert_eq!((B($expected), $period), (got_suffix, got_period));
            };
        }

        macro_rules! assert_suffix_max {
            ($given:expr, $expected:expr, $period:expr) => {
                let (got_suffix, got_period) =
                    get_suffix_reverse($given.as_bytes(), SuffixKind::Maximal);
                assert_eq!((B($expected), $period), (got_suffix, got_period));
            };
        }

        assert_suffix_min!("a", "a", 1);
        assert_suffix_max!("a", "a", 1);

        assert_suffix_min!("ab", "a", 1);
        assert_suffix_max!("ab", "ab", 2);

        assert_suffix_min!("ba", "ba", 2);
        assert_suffix_max!("ba", "b", 1);

        assert_suffix_min!("abc", "a", 1);
        assert_suffix_max!("abc", "abc", 3);

        assert_suffix_min!("acb", "a", 1);
        assert_suffix_max!("acb", "ac", 2);

        assert_suffix_min!("cba", "cba", 3);
        assert_suffix_max!("cba", "c", 1);

        assert_suffix_min!("abcabc", "abca", 3);
        assert_suffix_max!("abcabc", "abcabc", 3);

        assert_suffix_min!("abcabcabc", "abcabca", 3);
        assert_suffix_max!("abcabcabc", "abcabcabc", 3);

        assert_suffix_min!("abczz", "a", 1);
        assert_suffix_max!("abczz", "abczz", 5);

        assert_suffix_min!("zzabc", "zza", 3);
        assert_suffix_max!("zzabc", "zz", 1);

        assert_suffix_min!("aaa", "aaa", 1);
        assert_suffix_max!("aaa", "aaa", 1);
    }

    quickcheck! {
        fn qc_suffix_forward_maximal(bytes: Vec<u8>) -> bool {
            if bytes.is_empty() {
                return true;
            }

            let (got, _) = get_suffix_forward(&bytes, SuffixKind::Maximal);
            let expected = naive_maximal_suffix_forward(&bytes);
            got == expected
        }

        fn qc_suffix_reverse_maximal(bytes: Vec<u8>) -> bool {
            if bytes.is_empty() {
                return true;
            }

            let (got, _) = get_suffix_reverse(&bytes, SuffixKind::Maximal);
            let expected = naive_maximal_suffix_reverse(&bytes);
            expected == got
        }
    }
}