Skip to content

Commit 0daa2ae

Browse files
committed
csv.lua: move find's offsetting into field_find
1 parent 6892667 commit 0daa2ae

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

lua/csv.lua

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -182,24 +182,19 @@ local function separated_values_iterator(file, parameters)
182182
local function find(pattern, init)
183183
local first, last, capture
184184
while true do
185-
first, last, capture = buffer:find(pattern, anchor_pos + init - 1)
185+
first, last, capture = buffer:find(pattern, init)
186186
-- if we found nothing, or the last character is at the end of the
187187
-- buffer (and the match could potentially be longer) then read some
188188
-- more.
189189
if not first or last == #buffer then
190190
local s = file:read(buffer_size)
191-
-- if we read nothing from the file...
192-
if not s then
193-
if first then
194-
-- ...and last == #buffer, then the capture we found above is good.
195-
return first - anchor_pos + 1, last - anchor_pos + 1, capture
196-
else
197-
return
198-
end
199-
end
191+
-- if we read nothing from the file:
192+
-- - and first is nil, then below we're returning nil
193+
-- - and last == #buffer, then the capture we found above is good.
194+
if not s then return first, last, capture end
200195
buffer = buffer..s
201196
else
202-
return first - anchor_pos + 1, last - anchor_pos + 1, capture
197+
return first, last, capture
203198
end
204199
end
205200
end
@@ -231,6 +226,13 @@ local function separated_values_iterator(file, parameters)
231226
end
232227

233228

229+
local function field_find(pattern, init)
230+
local f, l, c = find(pattern, init + anchor_pos - 1)
231+
if not f then return end
232+
return f - anchor_pos + 1, l - anchor_pos + 1, c
233+
end
234+
235+
234236
-- If the user hasn't specified a separator, try to work out what it is.
235237
local sep = parameters.separator
236238
if not sep then
@@ -255,21 +257,21 @@ local function separated_values_iterator(file, parameters)
255257
advance(1)
256258
local current_pos = 0
257259
repeat
258-
local a, b, c = find('"("?)', current_pos + 1)
260+
local a, b, c = field_find('"("?)', current_pos + 1)
259261
current_pos = b
260262
until c ~= '"'
261263
if not current_pos then
262264
error(("%s:%d:%d: unmatched quote"):
263265
format(filename, field_start_line, field_start_column))
264266
end
265267
tidy = fix_quotes
266-
field_end, sep_end, this_sep = find(" *([^ ])", current_pos+1)
268+
field_end, sep_end, this_sep = field_find(" *([^ ])", current_pos+1)
267269
if this_sep and not this_sep:match(sep) then
268270
error(("%s:%d:%d: unmatched quote"):
269271
format(filename, field_start_line, field_start_column))
270272
end
271273
else
272-
field_end, sep_end, this_sep = find(sep, 1)
274+
field_end, sep_end, this_sep = field_find(sep, 1)
273275
tidy = trim_space
274276
end
275277

0 commit comments

Comments
 (0)