-
Notifications
You must be signed in to change notification settings - Fork 2
/
SearchEngine.scala
39 lines (26 loc) · 1003 Bytes
/
SearchEngine.scala
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
package search.engine
object SearchEngine {
sealed trait MultiSearchResult
case class Found(foundAt: Int, foundNeedleId: Int) extends MultiSearchResult
case object NotFound extends MultiSearchResult
def indexOf(haystack: Array[Byte], processor: SearchProcessor, from: Int = 0): Int = {
val matchAt = indexOfImpl(haystack, processor, from)
if (matchAt < 0) -1
else matchAt - processor.needleLength + 1
}
def indexOfMultiple(haystack: Array[Byte], processor: MultiSearchProcessor, from: Int = 0): MultiSearchResult = {
val matchAt = indexOfImpl(haystack, processor, from)
if (matchAt < 0) NotFound
else Found(
foundAt = matchAt - processor.needleLength + 1,
foundNeedleId = processor.getFoundNeedleId)
}
private def indexOfImpl(haystack: Array[Byte], processor: SearchProcessor, from: Int): Int = {
var i = from max 0
while (i < haystack.length) {
if (!processor.process(haystack(i))) return i
i += 1
}
-1
}
}