Skip to content

Commit b6afbe1

Browse files
authored
improves the peformance of the byte patterns matcher (#1404)
By precomputing all positions and storing them in arrays.
1 parent cd5aeb4 commit b6afbe1

File tree

1 file changed

+17
-19
lines changed

1 file changed

+17
-19
lines changed

plugins/patterns/patterns_main.ml

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -658,17 +658,13 @@ end
658658

659659
module Pattern : sig
660660
type t
661-
type field
662661

663662
val create : string -> t
664663
val empty : t
665664
val equal : t -> t -> bool
666665
val concat : t -> t -> t
667666
val length : t -> int
668667
val weight : t -> int
669-
val nth : field -> t -> int -> int
670-
val bits : field
671-
val mask : field
672668
val matches : t -> pos:int -> int -> bool
673669
val pp : Format.formatter -> t -> unit
674670
end = struct
@@ -744,22 +740,30 @@ end = struct
744740

745741
type t = {
746742
repr : string;
747-
bits : Z.t;
748-
mask : Z.t;
743+
bits : int array;
744+
mask : int array;
749745
pops : int;
750746
size : int;
751747
} [@@deriving equal]
752748

753749
type field = t -> Z.t
754750

751+
let nth_byte size x n =
752+
let off = (size / 8 - n - 1) * 8 in
753+
Z.to_int @@
754+
Z.(x asr off land of_int 0xff)
755+
755756
let create repr =
756757
let {Parser.size; bits; mask} = Parser.run repr in
757-
{bits; mask; size; pops = Z.popcount mask; repr}
758+
let pops = Z.popcount mask in
759+
let bits = Array.init (size/8) ~f:(nth_byte size bits) in
760+
let mask = Array.init (size/8) ~f:(nth_byte size mask) in
761+
{bits; mask; size; pops; repr}
758762

759763
let empty = {
760764
repr = "";
761-
bits = Z.zero;
762-
mask = Z.zero;
765+
bits = [||];
766+
mask = [||];
763767
pops = 0;
764768
size = 0;
765769
}
@@ -772,21 +776,15 @@ end = struct
772776

773777
let concat x y = {
774778
repr = x.repr ^ y.repr;
775-
bits = Z.(x.bits lsl y.size lor y.bits);
776-
mask = Z.(x.mask lsl y.size lor y.mask);
779+
bits = Array.append x.bits y.bits;
780+
mask = Array.append x.mask y.mask;
777781
pops = x.pops + y.pops;
778782
size = x.size + y.size;
779783
}
780784

781-
let nth what x n =
782-
let off = (x.size / 8 - n - 1) * 8 in
783-
Z.to_int @@
784-
Z.(what x asr off land of_int 0xff)
785785

786-
let matches x ~pos:n data =
787-
let mask = nth mask x n
788-
and bits = nth bits x n in
789-
data land mask = bits
786+
let matches {mask; bits} ~pos:n data =
787+
data land mask.(n) = bits.(n)
790788

791789
let pp ppf {repr} =
792790
Format.fprintf ppf "%s" repr

0 commit comments

Comments
 (0)