Allow captures in gfind and gmatch to be used in-loop

This commit is contained in:
James Duran
2025-01-15 11:02:46 -08:00
parent e55b652916
commit a7971f9f6f
+10 -2
View File
@@ -682,11 +682,14 @@ find_aux :: proc(
// iterative matching which returns the 0th/1st match // iterative matching which returns the 0th/1st match
// rest has to be used from captures // rest has to be used from captures
// assumes captures is zeroed on first iteration
// resets captures to zero on last iteration
gmatch :: proc( gmatch :: proc(
haystack: ^string, haystack: ^string,
pattern: string, pattern: string,
captures: ^[MAX_CAPTURES]Match, captures: ^[MAX_CAPTURES]Match,
) -> (res: string, ok: bool) { ) -> (res: string, ok: bool) {
haystack^ = haystack[captures[0].byte_end:]
if len(haystack) > 0 { if len(haystack) > 0 {
length, err := find_aux(haystack^, pattern, 0, false, captures) length, err := find_aux(haystack^, pattern, 0, false, captures)
@@ -695,7 +698,8 @@ gmatch :: proc(
first := length > 1 ? 1 : 0 first := length > 1 ? 1 : 0
cap := captures[first] cap := captures[first]
res = haystack[cap.byte_start:cap.byte_end] res = haystack[cap.byte_start:cap.byte_end]
haystack^ = haystack[cap.byte_end:] } else {
captures^ = {}
} }
} }
@@ -794,11 +798,14 @@ gsub_with :: proc(
gsub :: proc { gsub_builder, gsub_allocator } gsub :: proc { gsub_builder, gsub_allocator }
// iterative find with zeroth capture only // iterative find with zeroth capture only
// assumes captures is zeroed on first iteration
// resets captures to zero on last iteration
gfind :: proc( gfind :: proc(
haystack: ^string, haystack: ^string,
pattern: string, pattern: string,
captures: ^[MAX_CAPTURES]Match, captures: ^[MAX_CAPTURES]Match,
) -> (res: string, ok: bool) { ) -> (res: string, ok: bool) {
haystack^ = haystack[captures[0].byte_end:]
if len(haystack) > 0 { if len(haystack) > 0 {
length, err := find_aux(haystack^, pattern, 0, true, captures) length, err := find_aux(haystack^, pattern, 0, true, captures)
@@ -806,7 +813,8 @@ gfind :: proc(
ok = true ok = true
cap := captures[0] cap := captures[0]
res = haystack[cap.byte_start:cap.byte_end] res = haystack[cap.byte_start:cap.byte_end]
haystack^ = haystack[cap.byte_end:] } else {
captures^ = {}
} }
} }