Skip to content

Instantly share code, notes, and snippets.

@mattmoss
Last active March 29, 2021 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmoss/18bf78dfafe3469ab1127c9fde58f92e to your computer and use it in GitHub Desktop.
Save mattmoss/18bf78dfafe3469ab1127c9fde58f92e to your computer and use it in GitHub Desktop.
Basic implementation of globgrep (https://zserge.com/posts/better-c-benchmark/) using V (vlang.io)
module main
import os
fn glob(pattern string, text string) bool {
plen := pattern.len
tlen := text.len
mut p := 0
mut t := 0
mut np := 0
mut nt := 0
for p < plen || t < tlen {
if p < plen {
c := pattern[p]
match pattern[p] {
`*` {
np = p
nt = t + 1
p++
continue
}
`?` {
if nt < tlen {
p++
t++
continue
}
}
else {
if t < tlen {
if c == text[t] {
p++
t++
continue
}
}
}
}
}
if nt > 0 && nt <= tlen {
p = np
t = nt
continue
}
return false
}
return true
}
fn visitor(path string) {
pattern := os.args[1]
if os.is_file(path) && os.is_readable(path) {
lines := os.read_lines(path) or { return }
for index, line in lines {
if glob(pattern, line) {
lineno := index + 1
println("${path}:${lineno}\t${line}")
}
}
}
}
fn main() {
if os.args.len != 2 {
panic('USAGE: ${os.args[0]} <pattern>')
}
os.walk('.', visitor)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment