code wiki / (root) / nx_grep.nx

nx_grep.nx source

↩ module page · 39 lines · 2135 B

1// nx_grep.nx -- SOVEREIGN grep in NishiLang (operator: "we want nishi lang only not .sh... same with 2// grep and other things you like to cheat with -- the nishi team should be all sovereign"). Replaces the 3// shell `grep`: read a file, scan it line by line, print + count lines matching a pattern -- all bits-up 4// over sys_read_file + substring search, no 3rd-party tool. This is the team owning text search over 5// files, not shelling out. license_tier: ORIGINAL Reuses re_find (nx_research_extract). 6 7import "nx_research_extract.nx" // re_find / re_strlen 8import "nx_syscalls.nx" 9 10func _gp_puts(s: *u8) -> i64 { var n: i64 = 0; while s[n] != (0 as u8) { n = n + 1 } sys_write(1, s, n); return 0 } 11 12// does line[0..len) contain `needle`? (substring, the grep match) 13func grep_line_matches(line: *u8, len: i64, needle: *u8) -> i64 { if re_find(line, len, needle) >= 0 { return 1 } return 0 } 14 15// grep `needle` in the file at `path`: print each matching line, return the match count (-1 if no file). 16func grep_file(path: *u8, needle: *u8, print_matches: i64) -> i64 { 17 let lenbox: *i64 = sys_mmap(16) as *i64 18 let buf: *u8 = sys_read_file(path, lenbox) 19 if (buf as i64) == 0 { return 0 - 1 } 20 let n: i64 = lenbox[0] 21 var count: i64 = 0 22 var start: i64 = 0; var i: i64 = 0 23 while i <= n { 24 if i == n { if i > start { if grep_line_matches(buf + start, i - start, needle) == 1 { count = count + 1; if print_matches == 1 { sys_write(1, buf + start, i - start); sys_write(1, "\n" as *u8, 1) } } } i = i + 1 } 25 else { 26 if buf[i] == 10 as u8 { 27 if grep_line_matches(buf + start, i - start, needle) == 1 { count = count + 1; if print_matches == 1 { sys_write(1, buf + start, i - start); sys_write(1, "\n" as *u8, 1) } } 28 start = i + 1 29 } 30 i = i + 1 31 } 32 } 33 return count 34} 35 36// grep -c : just the count. 37func grep_count(path: *u8, needle: *u8) -> i64 { return grep_file(path, needle, 0) } 38// grep -q : does it match at all? 39func grep_has(path: *u8, needle: *u8) -> i64 { if grep_file(path, needle, 0) > 0 { return 1 } return 0 }