-
Notifications
You must be signed in to change notification settings - Fork 461
/
Copy pathsparse.rs
2643 lines (2465 loc) · 99.7 KB
/
sparse.rs
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
/*!
Types and routines specific to sparse DFAs.
This module is the home of [`sparse::DFA`](DFA).
Unlike the [`dense`] module, this module does not contain a builder or
configuration specific for sparse DFAs. Instead, the intended way to build a
sparse DFA is either by using a default configuration with its constructor
[`sparse::DFA::new`](DFA::new), or by first configuring the construction of a
dense DFA with [`dense::Builder`] and then calling [`dense::DFA::to_sparse`].
For example, this configures a sparse DFA to do an overlapping search:
```
use regex_automata::{
dfa::{Automaton, OverlappingState, dense},
HalfMatch, Input, MatchKind,
};
let dense_re = dense::Builder::new()
.configure(dense::Config::new().match_kind(MatchKind::All))
.build(r"Samwise|Sam")?;
let sparse_re = dense_re.to_sparse()?;
// Setup our haystack and initial start state.
let input = Input::new("Samwise");
let mut state = OverlappingState::start();
// First, 'Sam' will match.
sparse_re.try_search_overlapping_fwd(&input, &mut state)?;
assert_eq!(Some(HalfMatch::must(0, 3)), state.get_match());
// And now 'Samwise' will match.
sparse_re.try_search_overlapping_fwd(&input, &mut state)?;
assert_eq!(Some(HalfMatch::must(0, 7)), state.get_match());
# Ok::<(), Box<dyn std::error::Error>>(())
```
*/
#[cfg(feature = "dfa-build")]
use core::iter;
use core::{fmt, mem::size_of};
#[cfg(feature = "dfa-build")]
use alloc::{vec, vec::Vec};
#[cfg(feature = "dfa-build")]
use crate::dfa::dense::{self, BuildError};
use crate::{
dfa::{
automaton::{fmt_state_indicator, Automaton, StartError},
dense::Flags,
special::Special,
StartKind, DEAD,
},
util::{
alphabet::{ByteClasses, ByteSet},
escape::DebugByte,
int::{Pointer, Usize, U16, U32},
prefilter::Prefilter,
primitives::{PatternID, StateID},
search::Anchored,
start::{self, Start, StartByteMap},
wire::{self, DeserializeError, Endian, SerializeError},
},
};
const LABEL: &str = "rust-regex-automata-dfa-sparse";
const VERSION: u32 = 2;
/// A sparse deterministic finite automaton (DFA) with variable sized states.
///
/// In contrast to a [dense::DFA], a sparse DFA uses a more space efficient
/// representation for its transitions. Consequently, sparse DFAs may use much
/// less memory than dense DFAs, but this comes at a price. In particular,
/// reading the more space efficient transitions takes more work, and
/// consequently, searching using a sparse DFA is typically slower than a dense
/// DFA.
///
/// A sparse DFA can be built using the default configuration via the
/// [`DFA::new`] constructor. Otherwise, one can configure various aspects of a
/// dense DFA via [`dense::Builder`], and then convert a dense DFA to a sparse
/// DFA using [`dense::DFA::to_sparse`].
///
/// In general, a sparse DFA supports all the same search operations as a dense
/// DFA.
///
/// Making the choice between a dense and sparse DFA depends on your specific
/// work load. If you can sacrifice a bit of search time performance, then a
/// sparse DFA might be the best choice. In particular, while sparse DFAs are
/// probably always slower than dense DFAs, you may find that they are easily
/// fast enough for your purposes!
///
/// # Type parameters
///
/// A `DFA` has one type parameter, `T`, which is used to represent the parts
/// of a sparse DFA. `T` is typically a `Vec<u8>` or a `&[u8]`.
///
/// # The `Automaton` trait
///
/// This type implements the [`Automaton`] trait, which means it can be used
/// for searching. For example:
///
/// ```
/// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
///
/// let dfa = DFA::new("foo[0-9]+")?;
/// let expected = Some(HalfMatch::must(0, 8));
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone)]
pub struct DFA<T> {
// When compared to a dense DFA, a sparse DFA *looks* a lot simpler
// representation-wise. In reality, it is perhaps more complicated. Namely,
// in a dense DFA, all information needs to be very cheaply accessible
// using only state IDs. In a sparse DFA however, each state uses a
// variable amount of space because each state encodes more information
// than just its transitions. Each state also includes an accelerator if
// one exists, along with the matching pattern IDs if the state is a match
// state.
//
// That is, a lot of the complexity is pushed down into how each state
// itself is represented.
tt: Transitions<T>,
st: StartTable<T>,
special: Special,
pre: Option<Prefilter>,
quitset: ByteSet,
flags: Flags,
}
#[cfg(feature = "dfa-build")]
impl DFA<Vec<u8>> {
/// Parse the given regular expression using a default configuration and
/// return the corresponding sparse DFA.
///
/// If you want a non-default configuration, then use the
/// [`dense::Builder`] to set your own configuration, and then call
/// [`dense::DFA::to_sparse`] to create a sparse DFA.
///
/// # Example
///
/// ```
/// use regex_automata::{dfa::{Automaton, sparse}, HalfMatch, Input};
///
/// let dfa = sparse::DFA::new("foo[0-9]+bar")?;
///
/// let expected = Some(HalfMatch::must(0, 11));
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345bar"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "syntax")]
pub fn new(pattern: &str) -> Result<DFA<Vec<u8>>, BuildError> {
dense::Builder::new()
.build(pattern)
.and_then(|dense| dense.to_sparse())
}
/// Parse the given regular expressions using a default configuration and
/// return the corresponding multi-DFA.
///
/// If you want a non-default configuration, then use the
/// [`dense::Builder`] to set your own configuration, and then call
/// [`dense::DFA::to_sparse`] to create a sparse DFA.
///
/// # Example
///
/// ```
/// use regex_automata::{dfa::{Automaton, sparse}, HalfMatch, Input};
///
/// let dfa = sparse::DFA::new_many(&["[0-9]+", "[a-z]+"])?;
/// let expected = Some(HalfMatch::must(1, 3));
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345bar"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "syntax")]
pub fn new_many<P: AsRef<str>>(
patterns: &[P],
) -> Result<DFA<Vec<u8>>, BuildError> {
dense::Builder::new()
.build_many(patterns)
.and_then(|dense| dense.to_sparse())
}
}
#[cfg(feature = "dfa-build")]
impl DFA<Vec<u8>> {
/// Create a new DFA that matches every input.
///
/// # Example
///
/// ```
/// use regex_automata::{
/// dfa::{Automaton, sparse},
/// HalfMatch, Input,
/// };
///
/// let dfa = sparse::DFA::always_match()?;
///
/// let expected = Some(HalfMatch::must(0, 0));
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new(""))?);
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn always_match() -> Result<DFA<Vec<u8>>, BuildError> {
dense::DFA::always_match()?.to_sparse()
}
/// Create a new sparse DFA that never matches any input.
///
/// # Example
///
/// ```
/// use regex_automata::{dfa::{Automaton, sparse}, Input};
///
/// let dfa = sparse::DFA::never_match()?;
/// assert_eq!(None, dfa.try_search_fwd(&Input::new(""))?);
/// assert_eq!(None, dfa.try_search_fwd(&Input::new("foo"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn never_match() -> Result<DFA<Vec<u8>>, BuildError> {
dense::DFA::never_match()?.to_sparse()
}
/// The implementation for constructing a sparse DFA from a dense DFA.
pub(crate) fn from_dense<T: AsRef<[u32]>>(
dfa: &dense::DFA<T>,
) -> Result<DFA<Vec<u8>>, BuildError> {
// In order to build the transition table, we need to be able to write
// state identifiers for each of the "next" transitions in each state.
// Our state identifiers correspond to the byte offset in the
// transition table at which the state is encoded. Therefore, we do not
// actually know what the state identifiers are until we've allocated
// exactly as much space as we need for each state. Thus, construction
// of the transition table happens in two passes.
//
// In the first pass, we fill out the shell of each state, which
// includes the transition length, the input byte ranges and
// zero-filled space for the transitions and accelerators, if present.
// In this first pass, we also build up a map from the state identifier
// index of the dense DFA to the state identifier in this sparse DFA.
//
// In the second pass, we fill in the transitions based on the map
// built in the first pass.
// The capacity given here reflects a minimum. (Well, the true minimum
// is likely even bigger, but hopefully this saves a few reallocs.)
let mut sparse = Vec::with_capacity(StateID::SIZE * dfa.state_len());
// This maps state indices from the dense DFA to StateIDs in the sparse
// DFA. We build out this map on the first pass, and then use it in the
// second pass to back-fill our transitions.
let mut remap: Vec<StateID> = vec![DEAD; dfa.state_len()];
for state in dfa.states() {
let pos = sparse.len();
remap[dfa.to_index(state.id())] = StateID::new(pos)
.map_err(|_| BuildError::too_many_states())?;
// zero-filled space for the transition length
sparse.push(0);
sparse.push(0);
let mut transition_len = 0;
for (unit1, unit2, _) in state.sparse_transitions() {
match (unit1.as_u8(), unit2.as_u8()) {
(Some(b1), Some(b2)) => {
transition_len += 1;
sparse.push(b1);
sparse.push(b2);
}
(None, None) => {}
(Some(_), None) | (None, Some(_)) => {
// can never occur because sparse_transitions never
// groups EOI with any other transition.
unreachable!()
}
}
}
// Add dummy EOI transition. This is never actually read while
// searching, but having space equivalent to the total number
// of transitions is convenient. Otherwise, we'd need to track
// a different number of transitions for the byte ranges as for
// the 'next' states.
//
// N.B. The loop above is not guaranteed to yield the EOI
// transition, since it may point to a DEAD state. By putting
// it here, we always write the EOI transition, and thus
// guarantee that our transition length is >0. Why do we always
// need the EOI transition? Because in order to implement
// Automaton::next_eoi_state, this lets us just ask for the last
// transition. There are probably other/better ways to do this.
transition_len += 1;
sparse.push(0);
sparse.push(0);
// Check some assumptions about transition length.
assert_ne!(
transition_len, 0,
"transition length should be non-zero",
);
assert!(
transition_len <= 257,
"expected transition length {} to be <= 257",
transition_len,
);
// Fill in the transition length.
// Since transition length is always <= 257, we use the most
// significant bit to indicate whether this is a match state or
// not.
let ntrans = if dfa.is_match_state(state.id()) {
transition_len | (1 << 15)
} else {
transition_len
};
wire::NE::write_u16(ntrans, &mut sparse[pos..]);
// zero-fill the actual transitions.
// Unwraps are OK since transition_length <= 257 and our minimum
// support usize size is 16-bits.
let zeros = usize::try_from(transition_len)
.unwrap()
.checked_mul(StateID::SIZE)
.unwrap();
sparse.extend(iter::repeat(0).take(zeros));
// If this is a match state, write the pattern IDs matched by this
// state.
if dfa.is_match_state(state.id()) {
let plen = dfa.match_pattern_len(state.id());
// Write the actual pattern IDs with a u32 length prefix.
// First, zero-fill space.
let mut pos = sparse.len();
// Unwraps are OK since it's guaranteed that plen <=
// PatternID::LIMIT, which is in turn guaranteed to fit into a
// u32.
let zeros = size_of::<u32>()
.checked_mul(plen)
.unwrap()
.checked_add(size_of::<u32>())
.unwrap();
sparse.extend(iter::repeat(0).take(zeros));
// Now write the length prefix.
wire::NE::write_u32(
// Will never fail since u32::MAX is invalid pattern ID.
// Thus, the number of pattern IDs is representable by a
// u32.
plen.try_into().expect("pattern ID length fits in u32"),
&mut sparse[pos..],
);
pos += size_of::<u32>();
// Now write the pattern IDs.
for &pid in dfa.pattern_id_slice(state.id()) {
pos += wire::write_pattern_id::<wire::NE>(
pid,
&mut sparse[pos..],
);
}
}
// And now add the accelerator, if one exists. An accelerator is
// at most 4 bytes and at least 1 byte. The first byte is the
// length, N. N bytes follow the length. The set of bytes that
// follow correspond (exhaustively) to the bytes that must be seen
// to leave this state.
let accel = dfa.accelerator(state.id());
sparse.push(accel.len().try_into().unwrap());
sparse.extend_from_slice(accel);
}
let mut new = DFA {
tt: Transitions {
sparse,
classes: dfa.byte_classes().clone(),
state_len: dfa.state_len(),
pattern_len: dfa.pattern_len(),
},
st: StartTable::from_dense_dfa(dfa, &remap)?,
special: dfa.special().remap(|id| remap[dfa.to_index(id)]),
pre: dfa.get_prefilter().map(|p| p.clone()),
quitset: dfa.quitset().clone(),
flags: dfa.flags().clone(),
};
// And here's our second pass. Iterate over all of the dense states
// again, and update the transitions in each of the states in the
// sparse DFA.
for old_state in dfa.states() {
let new_id = remap[dfa.to_index(old_state.id())];
let mut new_state = new.tt.state_mut(new_id);
let sparse = old_state.sparse_transitions();
for (i, (_, _, next)) in sparse.enumerate() {
let next = remap[dfa.to_index(next)];
new_state.set_next_at(i, next);
}
}
debug!(
"created sparse DFA, memory usage: {} (dense memory usage: {})",
new.memory_usage(),
dfa.memory_usage(),
);
Ok(new)
}
}
impl<T: AsRef<[u8]>> DFA<T> {
/// Cheaply return a borrowed version of this sparse DFA. Specifically, the
/// DFA returned always uses `&[u8]` for its transitions.
pub fn as_ref<'a>(&'a self) -> DFA<&'a [u8]> {
DFA {
tt: self.tt.as_ref(),
st: self.st.as_ref(),
special: self.special,
pre: self.pre.clone(),
quitset: self.quitset,
flags: self.flags,
}
}
/// Return an owned version of this sparse DFA. Specifically, the DFA
/// returned always uses `Vec<u8>` for its transitions.
///
/// Effectively, this returns a sparse DFA whose transitions live on the
/// heap.
#[cfg(feature = "alloc")]
pub fn to_owned(&self) -> DFA<alloc::vec::Vec<u8>> {
DFA {
tt: self.tt.to_owned(),
st: self.st.to_owned(),
special: self.special,
pre: self.pre.clone(),
quitset: self.quitset,
flags: self.flags,
}
}
/// Returns the starting state configuration for this DFA.
///
/// The default is [`StartKind::Both`], which means the DFA supports both
/// unanchored and anchored searches. However, this can generally lead to
/// bigger DFAs. Therefore, a DFA might be compiled with support for just
/// unanchored or anchored searches. In that case, running a search with
/// an unsupported configuration will panic.
pub fn start_kind(&self) -> StartKind {
self.st.kind
}
/// Returns true only if this DFA has starting states for each pattern.
///
/// When a DFA has starting states for each pattern, then a search with the
/// DFA can be configured to only look for anchored matches of a specific
/// pattern. Specifically, APIs like [`Automaton::try_search_fwd`] can
/// accept a [`Anchored::Pattern`] if and only if this method returns true.
/// Otherwise, an error will be returned.
///
/// Note that if the DFA is empty, this always returns false.
pub fn starts_for_each_pattern(&self) -> bool {
self.st.pattern_len.is_some()
}
/// Returns the equivalence classes that make up the alphabet for this DFA.
///
/// Unless [`dense::Config::byte_classes`] was disabled, it is possible
/// that multiple distinct bytes are grouped into the same equivalence
/// class if it is impossible for them to discriminate between a match and
/// a non-match. This has the effect of reducing the overall alphabet size
/// and in turn potentially substantially reducing the size of the DFA's
/// transition table.
///
/// The downside of using equivalence classes like this is that every state
/// transition will automatically use this map to convert an arbitrary
/// byte to its corresponding equivalence class. In practice this has a
/// negligible impact on performance.
pub fn byte_classes(&self) -> &ByteClasses {
&self.tt.classes
}
/// Returns the memory usage, in bytes, of this DFA.
///
/// The memory usage is computed based on the number of bytes used to
/// represent this DFA.
///
/// This does **not** include the stack size used up by this DFA. To
/// compute that, use `std::mem::size_of::<sparse::DFA>()`.
pub fn memory_usage(&self) -> usize {
self.tt.memory_usage() + self.st.memory_usage()
}
}
/// Routines for converting a sparse DFA to other representations, such as raw
/// bytes suitable for persistent storage.
impl<T: AsRef<[u8]>> DFA<T> {
/// Serialize this DFA as raw bytes to a `Vec<u8>` in little endian
/// format.
///
/// The written bytes are guaranteed to be deserialized correctly and
/// without errors in a semver compatible release of this crate by a
/// `DFA`'s deserialization APIs (assuming all other criteria for the
/// deserialization APIs has been satisfied):
///
/// * [`DFA::from_bytes`]
/// * [`DFA::from_bytes_unchecked`]
///
/// Note that unlike a [`dense::DFA`]'s serialization methods, this does
/// not add any initial padding to the returned bytes. Padding isn't
/// required for sparse DFAs since they have no alignment requirements.
///
/// # Example
///
/// This example shows how to serialize and deserialize a DFA:
///
/// ```
/// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
///
/// // Compile our original DFA.
/// let original_dfa = DFA::new("foo[0-9]+")?;
///
/// // N.B. We use native endianness here to make the example work, but
/// // using to_bytes_little_endian would work on a little endian target.
/// let buf = original_dfa.to_bytes_native_endian();
/// // Even if buf has initial padding, DFA::from_bytes will automatically
/// // ignore it.
/// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf)?.0;
///
/// let expected = Some(HalfMatch::must(0, 8));
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "dfa-build")]
pub fn to_bytes_little_endian(&self) -> Vec<u8> {
self.to_bytes::<wire::LE>()
}
/// Serialize this DFA as raw bytes to a `Vec<u8>` in big endian
/// format.
///
/// The written bytes are guaranteed to be deserialized correctly and
/// without errors in a semver compatible release of this crate by a
/// `DFA`'s deserialization APIs (assuming all other criteria for the
/// deserialization APIs has been satisfied):
///
/// * [`DFA::from_bytes`]
/// * [`DFA::from_bytes_unchecked`]
///
/// Note that unlike a [`dense::DFA`]'s serialization methods, this does
/// not add any initial padding to the returned bytes. Padding isn't
/// required for sparse DFAs since they have no alignment requirements.
///
/// # Example
///
/// This example shows how to serialize and deserialize a DFA:
///
/// ```
/// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
///
/// // Compile our original DFA.
/// let original_dfa = DFA::new("foo[0-9]+")?;
///
/// // N.B. We use native endianness here to make the example work, but
/// // using to_bytes_big_endian would work on a big endian target.
/// let buf = original_dfa.to_bytes_native_endian();
/// // Even if buf has initial padding, DFA::from_bytes will automatically
/// // ignore it.
/// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf)?.0;
///
/// let expected = Some(HalfMatch::must(0, 8));
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "dfa-build")]
pub fn to_bytes_big_endian(&self) -> Vec<u8> {
self.to_bytes::<wire::BE>()
}
/// Serialize this DFA as raw bytes to a `Vec<u8>` in native endian
/// format.
///
/// The written bytes are guaranteed to be deserialized correctly and
/// without errors in a semver compatible release of this crate by a
/// `DFA`'s deserialization APIs (assuming all other criteria for the
/// deserialization APIs has been satisfied):
///
/// * [`DFA::from_bytes`]
/// * [`DFA::from_bytes_unchecked`]
///
/// Note that unlike a [`dense::DFA`]'s serialization methods, this does
/// not add any initial padding to the returned bytes. Padding isn't
/// required for sparse DFAs since they have no alignment requirements.
///
/// Generally speaking, native endian format should only be used when
/// you know that the target you're compiling the DFA for matches the
/// endianness of the target on which you're compiling DFA. For example,
/// if serialization and deserialization happen in the same process or on
/// the same machine. Otherwise, when serializing a DFA for use in a
/// portable environment, you'll almost certainly want to serialize _both_
/// a little endian and a big endian version and then load the correct one
/// based on the target's configuration.
///
/// # Example
///
/// This example shows how to serialize and deserialize a DFA:
///
/// ```
/// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
///
/// // Compile our original DFA.
/// let original_dfa = DFA::new("foo[0-9]+")?;
///
/// let buf = original_dfa.to_bytes_native_endian();
/// // Even if buf has initial padding, DFA::from_bytes will automatically
/// // ignore it.
/// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf)?.0;
///
/// let expected = Some(HalfMatch::must(0, 8));
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "dfa-build")]
pub fn to_bytes_native_endian(&self) -> Vec<u8> {
self.to_bytes::<wire::NE>()
}
/// The implementation of the public `to_bytes` serialization methods,
/// which is generic over endianness.
#[cfg(feature = "dfa-build")]
fn to_bytes<E: Endian>(&self) -> Vec<u8> {
let mut buf = vec![0; self.write_to_len()];
// This should always succeed since the only possible serialization
// error is providing a buffer that's too small, but we've ensured that
// `buf` is big enough here.
self.write_to::<E>(&mut buf).unwrap();
buf
}
/// Serialize this DFA as raw bytes to the given slice, in little endian
/// format. Upon success, the total number of bytes written to `dst` is
/// returned.
///
/// The written bytes are guaranteed to be deserialized correctly and
/// without errors in a semver compatible release of this crate by a
/// `DFA`'s deserialization APIs (assuming all other criteria for the
/// deserialization APIs has been satisfied):
///
/// * [`DFA::from_bytes`]
/// * [`DFA::from_bytes_unchecked`]
///
/// # Errors
///
/// This returns an error if the given destination slice is not big enough
/// to contain the full serialized DFA. If an error occurs, then nothing
/// is written to `dst`.
///
/// # Example
///
/// This example shows how to serialize and deserialize a DFA without
/// dynamic memory allocation.
///
/// ```
/// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
///
/// // Compile our original DFA.
/// let original_dfa = DFA::new("foo[0-9]+")?;
///
/// // Create a 4KB buffer on the stack to store our serialized DFA.
/// let mut buf = [0u8; 4 * (1<<10)];
/// // N.B. We use native endianness here to make the example work, but
/// // using write_to_little_endian would work on a little endian target.
/// let written = original_dfa.write_to_native_endian(&mut buf)?;
/// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf[..written])?.0;
///
/// let expected = Some(HalfMatch::must(0, 8));
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn write_to_little_endian(
&self,
dst: &mut [u8],
) -> Result<usize, SerializeError> {
self.write_to::<wire::LE>(dst)
}
/// Serialize this DFA as raw bytes to the given slice, in big endian
/// format. Upon success, the total number of bytes written to `dst` is
/// returned.
///
/// The written bytes are guaranteed to be deserialized correctly and
/// without errors in a semver compatible release of this crate by a
/// `DFA`'s deserialization APIs (assuming all other criteria for the
/// deserialization APIs has been satisfied):
///
/// * [`DFA::from_bytes`]
/// * [`DFA::from_bytes_unchecked`]
///
/// # Errors
///
/// This returns an error if the given destination slice is not big enough
/// to contain the full serialized DFA. If an error occurs, then nothing
/// is written to `dst`.
///
/// # Example
///
/// This example shows how to serialize and deserialize a DFA without
/// dynamic memory allocation.
///
/// ```
/// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
///
/// // Compile our original DFA.
/// let original_dfa = DFA::new("foo[0-9]+")?;
///
/// // Create a 4KB buffer on the stack to store our serialized DFA.
/// let mut buf = [0u8; 4 * (1<<10)];
/// // N.B. We use native endianness here to make the example work, but
/// // using write_to_big_endian would work on a big endian target.
/// let written = original_dfa.write_to_native_endian(&mut buf)?;
/// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf[..written])?.0;
///
/// let expected = Some(HalfMatch::must(0, 8));
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn write_to_big_endian(
&self,
dst: &mut [u8],
) -> Result<usize, SerializeError> {
self.write_to::<wire::BE>(dst)
}
/// Serialize this DFA as raw bytes to the given slice, in native endian
/// format. Upon success, the total number of bytes written to `dst` is
/// returned.
///
/// The written bytes are guaranteed to be deserialized correctly and
/// without errors in a semver compatible release of this crate by a
/// `DFA`'s deserialization APIs (assuming all other criteria for the
/// deserialization APIs has been satisfied):
///
/// * [`DFA::from_bytes`]
/// * [`DFA::from_bytes_unchecked`]
///
/// Generally speaking, native endian format should only be used when
/// you know that the target you're compiling the DFA for matches the
/// endianness of the target on which you're compiling DFA. For example,
/// if serialization and deserialization happen in the same process or on
/// the same machine. Otherwise, when serializing a DFA for use in a
/// portable environment, you'll almost certainly want to serialize _both_
/// a little endian and a big endian version and then load the correct one
/// based on the target's configuration.
///
/// # Errors
///
/// This returns an error if the given destination slice is not big enough
/// to contain the full serialized DFA. If an error occurs, then nothing
/// is written to `dst`.
///
/// # Example
///
/// This example shows how to serialize and deserialize a DFA without
/// dynamic memory allocation.
///
/// ```
/// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
///
/// // Compile our original DFA.
/// let original_dfa = DFA::new("foo[0-9]+")?;
///
/// // Create a 4KB buffer on the stack to store our serialized DFA.
/// let mut buf = [0u8; 4 * (1<<10)];
/// let written = original_dfa.write_to_native_endian(&mut buf)?;
/// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf[..written])?.0;
///
/// let expected = Some(HalfMatch::must(0, 8));
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn write_to_native_endian(
&self,
dst: &mut [u8],
) -> Result<usize, SerializeError> {
self.write_to::<wire::NE>(dst)
}
/// The implementation of the public `write_to` serialization methods,
/// which is generic over endianness.
fn write_to<E: Endian>(
&self,
dst: &mut [u8],
) -> Result<usize, SerializeError> {
let mut nw = 0;
nw += wire::write_label(LABEL, &mut dst[nw..])?;
nw += wire::write_endianness_check::<E>(&mut dst[nw..])?;
nw += wire::write_version::<E>(VERSION, &mut dst[nw..])?;
nw += {
// Currently unused, intended for future flexibility
E::write_u32(0, &mut dst[nw..]);
size_of::<u32>()
};
nw += self.flags.write_to::<E>(&mut dst[nw..])?;
nw += self.tt.write_to::<E>(&mut dst[nw..])?;
nw += self.st.write_to::<E>(&mut dst[nw..])?;
nw += self.special.write_to::<E>(&mut dst[nw..])?;
nw += self.quitset.write_to::<E>(&mut dst[nw..])?;
Ok(nw)
}
/// Return the total number of bytes required to serialize this DFA.
///
/// This is useful for determining the size of the buffer required to pass
/// to one of the serialization routines:
///
/// * [`DFA::write_to_little_endian`]
/// * [`DFA::write_to_big_endian`]
/// * [`DFA::write_to_native_endian`]
///
/// Passing a buffer smaller than the size returned by this method will
/// result in a serialization error.
///
/// # Example
///
/// This example shows how to dynamically allocate enough room to serialize
/// a sparse DFA.
///
/// ```
/// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
///
/// // Compile our original DFA.
/// let original_dfa = DFA::new("foo[0-9]+")?;
///
/// let mut buf = vec![0; original_dfa.write_to_len()];
/// let written = original_dfa.write_to_native_endian(&mut buf)?;
/// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf[..written])?.0;
///
/// let expected = Some(HalfMatch::must(0, 8));
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn write_to_len(&self) -> usize {
wire::write_label_len(LABEL)
+ wire::write_endianness_check_len()
+ wire::write_version_len()
+ size_of::<u32>() // unused, intended for future flexibility
+ self.flags.write_to_len()
+ self.tt.write_to_len()
+ self.st.write_to_len()
+ self.special.write_to_len()
+ self.quitset.write_to_len()
}
}
impl<'a> DFA<&'a [u8]> {
/// Safely deserialize a sparse DFA with a specific state identifier
/// representation. Upon success, this returns both the deserialized DFA
/// and the number of bytes read from the given slice. Namely, the contents
/// of the slice beyond the DFA are not read.
///
/// Deserializing a DFA using this routine will never allocate heap memory.
/// For safety purposes, the DFA's transitions will be verified such that
/// every transition points to a valid state. If this verification is too
/// costly, then a [`DFA::from_bytes_unchecked`] API is provided, which
/// will always execute in constant time.
///
/// The bytes given must be generated by one of the serialization APIs
/// of a `DFA` using a semver compatible release of this crate. Those
/// include:
///
/// * [`DFA::to_bytes_little_endian`]
/// * [`DFA::to_bytes_big_endian`]
/// * [`DFA::to_bytes_native_endian`]
/// * [`DFA::write_to_little_endian`]
/// * [`DFA::write_to_big_endian`]
/// * [`DFA::write_to_native_endian`]
///
/// The `to_bytes` methods allocate and return a `Vec<u8>` for you. The
/// `write_to` methods do not allocate and write to an existing slice
/// (which may be on the stack). Since deserialization always uses the
/// native endianness of the target platform, the serialization API you use
/// should match the endianness of the target platform. (It's often a good
/// idea to generate serialized DFAs for both forms of endianness and then
/// load the correct one based on endianness.)
///
/// # Errors
///
/// Generally speaking, it's easier to state the conditions in which an
/// error is _not_ returned. All of the following must be true:
///
/// * The bytes given must be produced by one of the serialization APIs
/// on this DFA, as mentioned above.
/// * The endianness of the target platform matches the endianness used to
/// serialized the provided DFA.
///
/// If any of the above are not true, then an error will be returned.
///
/// Note that unlike deserializing a [`dense::DFA`], deserializing a sparse
/// DFA has no alignment requirements. That is, an alignment of `1` is
/// valid.
///
/// # Panics
///
/// This routine will never panic for any input.
///
/// # Example
///
/// This example shows how to serialize a DFA to raw bytes, deserialize it
/// and then use it for searching.
///
/// ```
/// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
///
/// let initial = DFA::new("foo[0-9]+")?;
/// let bytes = initial.to_bytes_native_endian();
/// let dfa: DFA<&[u8]> = DFA::from_bytes(&bytes)?.0;
///
/// let expected = Some(HalfMatch::must(0, 8));
/// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: loading a DFA from static memory
///
/// One use case this library supports is the ability to serialize a
/// DFA to disk and then use `include_bytes!` to store it in a compiled
/// Rust program. Those bytes can then be cheaply deserialized into a
/// `DFA` structure at runtime and used for searching without having to
/// re-compile the DFA (which can be quite costly).
///
/// We can show this in two parts. The first part is serializing the DFA to
/// a file:
///
/// ```no_run
/// use regex_automata::dfa::sparse::DFA;
///
/// let dfa = DFA::new("foo[0-9]+")?;
///
/// // Write a big endian serialized version of this DFA to a file.
/// let bytes = dfa.to_bytes_big_endian();
/// std::fs::write("foo.bigendian.dfa", &bytes)?;
///
/// // Do it again, but this time for little endian.
/// let bytes = dfa.to_bytes_little_endian();
/// std::fs::write("foo.littleendian.dfa", &bytes)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// And now the second part is embedding the DFA into the compiled program
/// and deserializing it at runtime on first use. We use conditional
/// compilation to choose the correct endianness. We do not need to employ
/// any special tricks to ensure a proper alignment, since a sparse DFA has
/// no alignment requirements.
///
/// ```no_run
/// use regex_automata::{
/// dfa::{Automaton, sparse::DFA},
/// util::lazy::Lazy,
/// HalfMatch, Input,
/// };
///
/// // This crate provides its own "lazy" type, kind of like
/// // lazy_static! or once_cell::sync::Lazy. But it works in no-alloc
/// // no-std environments and let's us write this using completely
/// // safe code.
/// static RE: Lazy<DFA<&'static [u8]>> = Lazy::new(|| {
/// # const _: &str = stringify! {
/// #[cfg(target_endian = "big")]
/// static BYTES: &[u8] = include_bytes!("foo.bigendian.dfa");
/// #[cfg(target_endian = "little")]
/// static BYTES: &[u8] = include_bytes!("foo.littleendian.dfa");
/// # };
/// # static BYTES: &[u8] = b"";
///
/// let (dfa, _) = DFA::from_bytes(BYTES)
/// .expect("serialized DFA should be valid");
/// dfa
/// });
///
/// let expected = Ok(Some(HalfMatch::must(0, 8)));
/// assert_eq!(expected, RE.try_search_fwd(&Input::new("foo12345")));
/// ```
///
/// Alternatively, consider using
/// [`lazy_static`](https://crates.io/crates/lazy_static)
/// or
/// [`once_cell`](https://crates.io/crates/once_cell),
/// which will guarantee safety for you.
pub fn from_bytes(
slice: &'a [u8],
) -> Result<(DFA<&'a [u8]>, usize), DeserializeError> {
// SAFETY: This is safe because we validate both the sparse transitions
// (by trying to decode every state) and start state ID list below. If
// either validation fails, then we return an error.
let (dfa, nread) = unsafe { DFA::from_bytes_unchecked(slice)? };
let seen = dfa.tt.validate(&dfa.special)?;
dfa.st.validate(&dfa.special, &seen)?;
// N.B. dfa.special doesn't have a way to do unchecked deserialization,
// so it has already been validated.
Ok((dfa, nread))
}
/// Deserialize a DFA with a specific state identifier representation in
/// constant time by omitting the verification of the validity of the
/// sparse transitions.