|
| 1 | +using System.Collections.Generic; |
| 2 | + |
| 3 | +namespace PatternScanBench.Implementations |
| 4 | +{ |
| 5 | + /// <summary> |
| 6 | + /// Pattern scan implementation 'ALittleBitNaiveFor' - by DI20ID |
| 7 | + /// https://github.com/DI20ID |
| 8 | + /// </summary> |
| 9 | + internal class PatternScanALittleBitNaiveFor : PatternScanAlgorithm |
| 10 | + { |
| 11 | + /// <summary> |
| 12 | + /// Authors name. |
| 13 | + /// </summary> |
| 14 | + internal override string Creator => "DI20ID"; |
| 15 | + internal PatternScanALittleBitNaiveFor() { } |
| 16 | + |
| 17 | + /// <summary> |
| 18 | + /// Initializes a new 'PatternScanTest'. |
| 19 | + /// </summary> |
| 20 | + /// <param name="cbMemory">The byte array to scan.</param> |
| 21 | + /// <returns>An optional string to display next to benchmark results.</returns> |
| 22 | + internal override string Init(in byte[] cbMemory) |
| 23 | + { |
| 24 | + return ""; |
| 25 | + } |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// Returns address of pattern using 'ALittleBitNaiveFor' implementation by DI20ID. Can match 0. |
| 29 | + /// </summary> |
| 30 | + /// <param name="cbMemory">The byte array to scan.</param> |
| 31 | + /// <param name="cbPattern">The byte pattern to look for, wildcard positions are replaced by 0.</param> |
| 32 | + /// <param name="szMask">A string that determines how pattern should be matched, 'x' is match, '?' acts as wildcard.</param> |
| 33 | + /// <returns>-1 if pattern is not found.</returns> |
| 34 | + internal override long FindPattern(in byte[] cbMemory, in byte[] cbPattern, string szMask) |
| 35 | + { |
| 36 | + long ix; |
| 37 | + int iy; |
| 38 | + |
| 39 | + List<byte> ls = new List<byte>(); |
| 40 | + List<int> ini = new List<int>(); |
| 41 | + |
| 42 | + int dataLength = cbMemory.Length - cbPattern.Length; |
| 43 | + |
| 44 | + for (iy = cbPattern.Length - 1; iy > -1; iy--) |
| 45 | + { |
| 46 | + if (szMask[iy] == 'x') |
| 47 | + { |
| 48 | + |
| 49 | + ls.Add(cbPattern[iy]); |
| 50 | + ini.Add(iy); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + byte[] arr = ls.ToArray(); |
| 55 | + byte[] arr1 = new byte[arr.Length]; |
| 56 | + |
| 57 | + for (ix = 0; ix < dataLength; ix++) |
| 58 | + { |
| 59 | + if (arr[arr.Length - 1] == cbMemory[ix]) |
| 60 | + { |
| 61 | + bool check = true; |
| 62 | + |
| 63 | + for (iy = arr.Length - 1; iy > -1; iy--) |
| 64 | + { |
| 65 | + if (arr[iy] == cbMemory[ix + ini[iy]]) |
| 66 | + continue; |
| 67 | + check = false; |
| 68 | + break; |
| 69 | + } |
| 70 | + |
| 71 | + if (check) |
| 72 | + { |
| 73 | + return ix; |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return -1; |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments