-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.go
More file actions
104 lines (85 loc) · 2.22 KB
/
generator.go
File metadata and controls
104 lines (85 loc) · 2.22 KB
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
package main
import (
"log"
"runtime"
"sync"
)
var (
Dictionary []string
Separator byte = ' '
MaxWorkers = runtime.NumCPU() * 2 // Dynamically adjusts based on CPU
)
type StackItem struct {
chainBuffer []byte
pos int
depth int
used []bool
}
// Generates chains efficiently (fast, low memory, proper spacing)
func generateChains(elemMin, elemMax int, out *outFile) {
if len(Dictionary) == 0 {
log.Fatal("Error: Wordlist is empty")
return
}
var wg sync.WaitGroup
writeMutex := &sync.Mutex{} // sync to control write buffer in parallel scope
workQueue := make(chan int, len(Dictionary))
// Worker function processing a subset of words
worker := func() {
for i := range workQueue {
chainBuilder(elemMin, elemMax, out, writeMutex, i)
wg.Done()
}
}
// Start workers
for i := 0; i < MaxWorkers; i++ {
go worker()
}
// Distribute work (each word starts a chain worker - i.e. goroutine)
for idx := range Dictionary {
wg.Add(1)
workQueue <- idx
}
close(workQueue)
wg.Wait()
}
func chainBuilder(elemMin, elemMax int, out *outFile, writeMutex *sync.Mutex, startIdx int) {
stack := make([]StackItem, 0, 100)
// Start from the assigned `startIdx`
word := Dictionary[startIdx]
chainBuffer := make([]byte, 512)
copy(chainBuffer, word)
used := make([]bool, len(Dictionary))
used[startIdx] = true
stack = append(stack, StackItem{chainBuffer, len(word), 1, used})
for len(stack) > 0 {
item := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if item.depth >= elemMin {
output := string(item.chainBuffer[:item.pos]) + "\n"
writeMutex.Lock()
out.buf.WriteString(output)
writeMutex.Unlock()
}
if item.depth >= elemMax {
continue
}
for i := 0; i < len(Dictionary); i++ {
if item.used[i] {
continue
}
newUsed := make([]bool, len(Dictionary))
copy(newUsed, item.used)
newUsed[i] = true
newBuffer := make([]byte, item.pos+len(Dictionary[i])+1)
copy(newBuffer, item.chainBuffer[:item.pos])
nextPos := item.pos
if item.pos > 0 {
newBuffer[nextPos] = Separator
nextPos++
}
copy(newBuffer[nextPos:], Dictionary[i])
stack = append(stack, StackItem{newBuffer, nextPos + len(Dictionary[i]), item.depth + 1, newUsed})
}
}
}