robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
33.6 KiB1342 linesraw
1--- @brief
2---
3--- [vim.iter()]() is an interface for [iterable]s: it wraps a table or function argument into an
4--- [Iter]() object with methods (such as [Iter:filter()] and [Iter:map()]) that transform the
5--- underlying source data. These methods can be chained to create iterator "pipelines": the output
6--- of each pipeline stage is input to the next stage. The first stage depends on the type passed to
7--- `vim.iter()`:
8---
9--- - Lists or arrays (|lua-list|) yield only the value of each element.
10---   - Holes (nil values) are allowed (but discarded).
11---   - Use pairs() to treat array/list tables as dicts (preserve holes and non-contiguous integer
12---     keys): `vim.iter(pairs(…))`.
13---   - Use |Iter:enumerate()| to also pass the index to the next stage.
14---     - Or initialize with ipairs(): `vim.iter(ipairs(…))`.
15--- - Non-list tables (|lua-dict|) yield both the key and value of each element.
16--- - Function |iterator|s yield all values returned by the underlying function.
17--- - Tables with a |__call()| metamethod are treated as function iterators.
18---
19--- The iterator pipeline terminates when the underlying |iterable| is exhausted (for function
20--- iterators this means it returned nil).
21---
22--- Note: `vim.iter()` scans table input to decide if it is a list or a dict; to avoid this cost you
23--- can wrap the table with an iterator e.g. `vim.iter(ipairs({…}))`, but that precludes the use of
24--- |list-iterator| operations such as |IterArray:rev()|).
25---
26--- Examples:
27---
28--- ```lua
29--- local it = vim.iter({ 1, 2, 3, 4, 5 })
30--- it:map(function(v)
31---   return v * 3
32--- end)
33--- it:rev()
34--- it:skip(2)
35--- it:totable()
36--- -- { 9, 6, 3 }
37---
38--- -- ipairs() is a function iterator which returns both the index (i) and the value (v)
39--- vim.iter(ipairs({ 1, 2, 3, 4, 5 })):map(function(i, v)
40---   if i > 2 then return v end
41--- end):totable()
42--- -- { 3, 4, 5 }
43---
44--- local it = vim.iter(vim.gsplit('1,2,3,4,5', ','))
45--- it:map(function(s) return tonumber(s) end)
46--- for i, d in it:enumerate() do
47---   print(string.format("Column %d is %d", i, d))
48--- end
49--- -- Column 1 is 1
50--- -- Column 2 is 2
51--- -- Column 3 is 3
52--- -- Column 4 is 4
53--- -- Column 5 is 5
54---
55--- vim.iter({ a = 1, b = 2, c = 3, z = 26 }):any(function(k, v)
56---   return k == 'z'
57--- end)
58--- -- true
59---
60--- local rb = vim.ringbuf(3)
61--- rb:push("a")
62--- rb:push("b")
63--- vim.iter(rb):totable()
64--- -- { "a", "b" }
65--- ```
66
67-- `never` represents an empty tail for single-value iterators.
68--- @nodoc
69--- @class vim.IterModule
70--- @operator call: vim.Iter<any, any...>
71--- @overload fun<T>(src: T[]): vim.IterArray<T, never>
72--- @overload fun<K, V>(src: table<K, V>): vim.Iter<K, V>
73--- @overload fun(src: table, ...): vim.Iter<any, any...>
74--- @overload fun<S, C, R1, R...>(src: (fun(state: S, control: C): R1, R...), state?: S, control?: C): vim.Iter<R1, R...>
75local M = {}
76
77--- @nodoc
78--- @class vim.Iter<V1, V...>
79--- @field private _peeked V1|[V1, V...]? Cached peek value, if any. Nil if no value is peeked.
80--- @field private _next fun(): V1, V... The underlying function that returns the next packed value from the source.
81--- @overload fun(self: vim.Iter<V1, V...>): V1?, V...
82local Iter = {}
83Iter.__index = Iter
84
85function Iter:__call()
86  return self:next()
87end
88
89-- Special case implementations for iterators on list tables.
90--- @nodoc
91--- @class vim.IterArray<V1, V...> : vim.Iter<V1, V...>
92--- @field private _table (V1|[V1, V...])[] Underlying table data. Items may be packed tuples after transforms.
93--- @field private _head integer Index to the front of a table iterator
94--- @field private _tail integer Index to the end of a table iterator (exclusive)
95local IterArray = setmetatable({}, Iter)
96IterArray.__index = IterArray
97IterArray.__call = Iter.__call
98
99--- Packed tables use this as their metatable
100local packedmt = {}
101
102--- @generic V1, V...
103--- @param t V1|([V1, V...] & { n: integer })
104--- @return V1?, V...
105local function unpack(t)
106  if type(t) == 'table' and getmetatable(t) == packedmt then
107    return _G.unpack(t, 1, t.n)
108  end
109  return t
110end
111
112--- @generic T...
113--- @param ... T... Values to pack
114--- @return T|[T...]
115local function pack(...)
116  local n = select('#', ...)
117  if n > 1 then
118    return setmetatable({ n = n, ... }, packedmt)
119  end
120  return ...
121end
122
123--- @generic T
124--- @param t T
125local function sanitize(t)
126  if type(t) == 'table' and getmetatable(t) == packedmt then
127    --- @cast t table
128    -- Remove length tag and metatable
129    t.n = nil
130    setmetatable(t, nil)
131  end
132  return t
133end
134
135--- Flattens a single array-like table. Errors if it attempts to flatten a
136--- dict-like table
137--- @param t any value which should be flattened
138--- @param max_depth integer depth to which the table should be flattened
139--- @param depth integer current iteration depth
140--- @param result table output table that contains flattened result
141--- @return table? flattened table if it can be flattened, otherwise nil
142local function flatten(t, max_depth, depth, result)
143  if depth < max_depth and type(t) == 'table' then
144    for k, v in pairs(t) do
145      if type(k) ~= 'number' or k <= 0 or math.floor(k) ~= k then
146        -- short-circuit: this is not a list like table
147        return nil
148      end
149
150      if flatten(v, max_depth, depth + 1, result) == nil then
151        return nil
152      end
153    end
154  elseif t ~= nil then
155    result[#result + 1] = t
156  end
157
158  return result
159end
160
161--- Determine if the current iterator stage should continue.
162---
163--- If any arguments are passed to this function, then return those arguments
164--- and stop the current iterator stage. Otherwise, return true to signal that
165--- the current stage should continue.
166---
167--- @param ... any Function arguments.
168--- @return boolean True if the iterator stage should continue, false otherwise
169--- @return any Function arguments.
170local function continue(...)
171  if select(1, ...) ~= nil then
172    return false, ...
173  end
174  return true
175end
176
177--- If no input arguments are given return false, indicating the current
178--- iterator stage should stop. Otherwise, apply the arguments to the function
179--- f. If that function returns no values, the current iterator stage continues.
180--- Otherwise, those values are returned.
181---
182--- @generic T, R
183--- @param f fun(...:T...): R... Function to call with the given arguments
184--- @param ... T... Arguments to apply to f
185--- @return boolean : True if the iterator pipeline should continue, false otherwise
186--- @return R... : Return values of f
187local function apply(f, ...)
188  if select(1, ...) ~= nil then
189    return continue(f(...))
190  end
191  return false
192end
193
194--- Filters an iterator pipeline.
195---
196--- Example:
197---
198--- ```lua
199--- local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded)
200--- ```
201---
202--- @param f fun(v: V1, ...: V...): boolean Takes all values returned from the previous stage
203---                       in the pipeline and returns false or nil if the
204---                       current iterator element should be removed.
205--- @return vim.Iter<V1, V...>
206--- @overload fun<V1, V...>(self: vim.IterArray<V1, V...>, f: fun(v: V1, ...: V...): boolean): vim.IterArray<V1, V...>
207function Iter:filter(f)
208  return self:map(function(...)
209    if f(...) then
210      return ...
211    end
212  end)
213end
214
215--- @nodoc
216--- @param f fun(v: V1, ...: V...): boolean
217--- @return vim.IterArray<V1, V...>
218function IterArray:filter(f)
219  local inc = self._head < self._tail and 1 or -1
220  local n = self._head
221  for i = self._head, self._tail - inc, inc do
222    local v = self._table[i]
223    if f(unpack(v)) then
224      self._table[n] = v
225      n = n + inc
226    end
227  end
228  self._tail = n
229  return self
230end
231
232--- Removes duplicate values from an iterator pipeline.
233---
234--- Only the first occurrence of each value is kept.
235---
236--- Accepts an optional `key` argument, which if provided is called for each
237--- value in the iterator to compute a hash key for uniqueness comparison. This is
238--- useful for deduplicating table values or complex objects.
239--- If `key` returns `nil` for a value, that value will be considered unique,
240--- even if multiple values return `nil`.
241---
242--- If a function-based iterator returns multiple arguments, uniqueness is
243--- checked based on the first return value. To change this behavior, specify
244--- `key`.
245---
246--- Examples:
247---
248--- ```lua
249--- vim.iter({ 1, 2, 2, 3, 2 }):unique():totable()
250--- -- { 1, 2, 3 }
251---
252--- vim.iter({ {id=1}, {id=2}, {id=1} })
253---   :unique(function(x)
254---     return x.id
255---   end)
256---   :totable()
257--- -- { {id=1}, {id=2} }
258--- ```
259---
260--- @since 14
261--- @param key? fun(v: V1, ...: V...): any Optional hash function to determine uniqueness of values.
262--- @return vim.Iter<V1, V...>
263--- @overload fun<V1, V...>(self: vim.IterArray<V1, V...>, key: fun(v: V1, ...: V...): any?): vim.IterArray<V1, V...>
264--- @see |vim.list.unique()|
265function Iter:unique(key)
266  local seen = {} --- @type table<any,boolean>
267
268  key = key or function(a)
269    return a
270  end
271
272  return self:filter(function(...)
273    local hash = key(...)
274    if hash == nil then
275      return true
276    elseif not seen[hash] then
277      seen[hash] = true
278      return true
279    else
280      return false
281    end
282  end)
283end
284
285--- @nodoc
286--- @diagnostic disable-next-line:unused
287--- @param depth? integer
288function Iter:flatten(depth)
289  error('flatten() requires an array-like table')
290end
291
292--- Flattens a |list-iterator|, un-nesting nested values up to the given {depth}.
293--- Errors if it attempts to flatten a dict-like value.
294---
295--- Examples:
296---
297--- ```lua
298--- vim.iter({ 1, { 2 }, { { 3 } } }):flatten():totable()
299--- -- { 1, 2, { 3 } }
300---
301--- vim.iter({1, { { a = 2 } }, { 3 } }):flatten():totable()
302--- -- { 1, { a = 2 }, 3 }
303---
304--- vim.iter({ 1, { { a = 2 } }, { 3 } }):flatten(math.huge):totable()
305--- -- error: attempt to flatten a dict-like table
306--- ```
307---
308--- @since 12
309--- @param depth? integer Depth to which |list-iterator| should be flattened
310---                        (defaults to 1)
311--- @return vim.IterArray<V1, V...>
312function IterArray:flatten(depth)
313  depth = depth or 1
314  local inc = self._head < self._tail and 1 or -1
315  local target = {}
316
317  for i = self._head, self._tail - inc, inc do
318    local flattened = flatten(self._table[i], depth, 0, {})
319
320    -- exit early if we try to flatten a dict-like table
321    if flattened == nil then
322      error('flatten() requires an array-like table')
323    end
324
325    for _, v in pairs(flattened) do
326      target[#target + 1] = v
327    end
328  end
329
330  self._head = 1
331  self._tail = #target + 1
332  self._table = target
333  return self
334end
335
336--- Maps the items of an iterator pipeline to the values returned by `f`.
337---
338--- If the map function returns nil, the value is filtered from the iterator.
339---
340--- Example:
341---
342--- ```lua
343--- local it = vim.iter({ 1, 2, 3, 4 }):map(function(v)
344---   if v % 2 == 0 then
345---     return v * 3
346---   end
347--- end)
348--- it:totable()
349--- -- { 6, 12 }
350--- ```
351---
352--- @since 12
353--- @generic K2, V2...
354--- @param f fun(v: V1, ...: V...): K2, V2... Mapping function. Takes all values returned from
355---                      the previous stage in the pipeline as arguments
356---                      and returns one or more new values, which are used
357---                      in the next pipeline stage. Nil return values
358---                      are filtered from the output.
359--- @return vim.Iter<K2, V2...>
360--- @overload fun<V1, V..., K1, K...>(self: vim.IterArray<V1, V...>, f: fun(v: V1, ...: V...): K1, K...): vim.IterArray<K1, K...>
361function Iter:map(f)
362  -- Implementation note: the reader may be forgiven for observing that this
363  -- function appears excessively convoluted. The problem to solve is that each
364  -- stage of the iterator pipeline can return any number of values, and the
365  -- number of values could even change per iteration. And the return values
366  -- must be checked to determine if the pipeline has ended, so we cannot
367  -- naively forward them along to the next stage.
368  --
369  -- A simple approach is to pack all of the return values into a table, check
370  -- for nil, then unpack the table for the next stage. However, packing and
371  -- unpacking tables is quite slow. There is no other way in Lua to handle an
372  -- unknown number of function return values than to simply forward those
373  -- values along to another function. Hence the intricate function passing you
374  -- see here.
375
376  local next = self.next
377
378  --- Drain values from the upstream iterator source until a value can be
379  --- returned.
380  ---
381  --- This is a recursive function. The base case is when the first argument is
382  --- false, which indicates that the rest of the arguments should be returned
383  --- as the values for the current iteration stage.
384  ---
385  --- @param cont boolean If true, the current iterator stage should continue to
386  ---                    pull values from its upstream pipeline stage.
387  ---                    Otherwise, this stage is complete and returns the
388  ---                    values passed.
389  --- @param ... any Values to return if cont is false.
390  --- @return any
391  local function fn(cont, ...)
392    if cont then
393      return fn(apply(f, next(self)))
394    end
395    return ...
396  end
397
398  --- @diagnostic disable-next-line: duplicate-set-field
399  self.next = function()
400    return fn(apply(f, next(self)))
401  end
402  return self
403end
404
405--- @nodoc
406--- @generic K1, K...
407--- @param f fun(v: V1, ...: V...): K1, K...
408--- @return vim.IterArray<K1, K...>
409function IterArray:map(f)
410  local inc = self._head < self._tail and 1 or -1
411  local n = self._head
412  for i = self._head, self._tail - inc, inc do
413    local v = pack(f(unpack(self._table[i])))
414    if v ~= nil then
415      self._table[n] = v
416      n = n + inc
417    end
418  end
419  self._tail = n
420  return self
421end
422
423--- Calls a function once for each item in the pipeline, draining the iterator.
424---
425--- For functions with side effects. To modify the values in the iterator, use |Iter:map()|.
426---
427--- @since 12
428--- @param f fun(v: V1, ...: V...) Function to execute for each item in the pipeline.
429---                  Takes all of the values returned by the previous stage
430---                  in the pipeline as arguments.
431function Iter:each(f)
432  --- @param ... any
433  local function fn(...)
434    if select(1, ...) ~= nil then
435      f(...)
436      return true
437    end
438  end
439  while fn(self:next()) do
440  end
441end
442
443--- @nodoc
444--- @param f fun(v: V1, ...: V...)
445function IterArray:each(f)
446  local inc = self._head < self._tail and 1 or -1
447  for i = self._head, self._tail - inc, inc do
448    f(unpack(self._table[i]))
449  end
450  self._head = self._tail
451end
452
453--- Collect the iterator into a table.
454---
455--- The resulting table depends on the initial source in the iterator pipeline.
456--- Array-like tables and function iterators will be collected into an array-like
457--- table. If multiple values are returned from the final stage in the iterator
458--- pipeline, each value will be included in a table.
459---
460--- Examples:
461---
462--- ```lua
463--- vim.iter(string.gmatch('100 20 50', '%d+')):map(tonumber):totable()
464--- -- { 100, 20, 50 }
465---
466--- vim.iter({ 1, 2, 3 }):map(function(v) return v, 2 * v end):totable()
467--- -- { { 1, 2 }, { 2, 4 }, { 3, 6 } }
468---
469--- vim.iter({ a = 1, b = 2, c = 3 }):filter(function(k, v) return v % 2 ~= 0 end):totable()
470--- -- { { 'a', 1 }, { 'c', 3 } }
471--- ```
472---
473--- The generated table is an array-like table with consecutive, numeric indices.
474--- To create a map-like table with arbitrary keys, use |Iter:fold()|.
475---
476---
477--- @since 12
478--- @return any[]
479function Iter:totable()
480  local t = {}
481
482  while true do
483    local args = pack(self:next())
484    if args == nil then
485      break
486    end
487
488    t[#t + 1] = sanitize(args)
489  end
490  return t
491end
492
493--- @nodoc
494--- @return any[]
495function IterArray:totable()
496  if self.next ~= IterArray.next or self._head >= self._tail then
497    return Iter.totable(self)
498  end
499
500  local needs_sanitize = getmetatable(self._table[self._head]) == packedmt
501
502  -- Reindex and sanitize.
503  local len = self._tail - self._head
504
505  if needs_sanitize then
506    for i = 1, len do
507      self._table[i] = sanitize(self._table[self._head - 1 + i])
508    end
509  else
510    for i = 1, len do
511      self._table[i] = self._table[self._head - 1 + i]
512    end
513  end
514
515  for i = len + 1, table.maxn(self._table) do
516    self._table[i] = nil
517  end
518
519  self._head = 1
520  self._tail = len + 1
521
522  return self._table
523end
524
525--- Collect the iterator into a delimited string.
526---
527--- Each element in the iterator is joined into a string separated by {delim}.
528---
529--- Consumes the iterator.
530---
531--- @since 12
532--- @param delim string Delimiter
533--- @return string
534function Iter:join(delim)
535  return table.concat(self:totable(), delim)
536end
537
538--- Folds ("reduces") an iterator into a single value. [Iter:reduce()]()
539---
540--- Examples:
541---
542--- ```lua
543--- -- Create a new table with only even values
544--- vim.iter({ a = 1, b = 2, c = 3, d = 4 })
545---   :filter(function(k, v) return v % 2 == 0 end)
546---   :fold({}, function(acc, k, v)
547---     acc[k] = v
548---     return acc
549---   end) --> { b = 2, d = 4 }
550---
551--- -- Get the "maximum" item of an iterable.
552--- vim.iter({ -99, -4, 3, 42, 0, 0, 7 })
553---   :fold({}, function(acc, v)
554---     acc.max = math.max(v, acc.max or v)
555---     return acc
556---   end) --> { max = 42 }
557--- ```
558---
559---
560--- @since 12
561--- @generic A
562--- @param init A Initial value of the accumulator.
563--- @param f fun(acc: A, v: V1, ...: V...): A Accumulation function.
564--- @return A
565function Iter:fold(init, f)
566  local acc = init
567
568  --- Use a closure to handle var args returned from iterator
569  --- @param ... any
570  local function fn(...)
571    if select(1, ...) ~= nil then
572      acc = f(acc, ...)
573      return true
574    end
575  end
576
577  while fn(self:next()) do
578  end
579  return acc
580end
581
582--- @nodoc
583--- @generic A
584--- @param init A
585--- @param f fun(acc: A, v: V1, ...: V...): A
586--- @return A
587function IterArray:fold(init, f)
588  local acc = init
589  local inc = self._head < self._tail and 1 or -1
590  for i = self._head, self._tail - inc, inc do
591    acc = f(acc, unpack(self._table[i]))
592  end
593  return acc
594end
595
596--- @diagnostic disable-next-line: duplicate-set-field
597--- Gets the next value from the iterator.
598---
599--- Example:
600---
601--- ```lua
602---
603--- local it = vim.iter(string.gmatch('1 2 3', '%d+')):map(tonumber)
604--- it:next()
605--- -- 1
606--- it:next()
607--- -- 2
608--- it:next()
609--- -- 3
610---
611--- ```
612---
613--- @since 12
614--- @return V1?, V...
615function Iter:next()
616  if self._peeked then
617    local v = self._peeked
618    self._peeked = nil
619
620    return unpack(v)
621  end
622
623  return self._next()
624end
625
626--- @nodoc
627--- @return V1?, V...
628function IterArray:next()
629  if self._head ~= self._tail then
630    local v = self._table[self._head]
631    local inc = self._head < self._tail and 1 or -1
632    self._head = self._head + inc
633    return unpack(v)
634  end
635end
636
637--- @nodoc
638--- @diagnostic disable-next-line: unused
639function Iter:rev()
640  error('rev() requires an array-like table')
641end
642
643--- Reverses a |list-iterator| pipeline.
644---
645--- Example:
646---
647--- ```lua
648---
649--- local it = vim.iter({ 3, 6, 9, 12 }):rev()
650--- it:totable()
651--- -- { 12, 9, 6, 3 }
652---
653--- ```
654---
655--- @since 12
656--- @return vim.IterArray<V1, V...>
657function IterArray:rev()
658  local inc = self._head < self._tail and 1 or -1
659  self._head, self._tail = self._tail - inc, self._head - inc
660  return self
661end
662
663--- Gets the next value from the iterator without consuming it.
664---
665--- The value returned by |Iter:peek()| will be returned again by the next call
666--- to |Iter:next()|.
667---
668--- Example:
669---
670--- ```lua
671---
672--- local it = vim.iter({ 3, 6, 9, 12 })
673--- it:peek()
674--- -- 3
675--- it:peek()
676--- -- 3
677--- it:next()
678--- -- 3
679---
680--- ```
681---
682--- @since 12
683--- @return V1?, V...
684function Iter:peek()
685  if not self._peeked then
686    self._peeked = pack(self:next())
687  end
688
689  return unpack(self._peeked)
690end
691
692--- @nodoc
693--- @return V1?, V...
694function IterArray:peek()
695  if self._head ~= self._tail then
696    return unpack(self._table[self._head])
697  end
698end
699
700--- Find the first value in the iterator that satisfies the given predicate.
701---
702--- Advances the iterator. Returns nil and drains the iterator if no value is found.
703---
704--- Examples:
705---
706--- ```lua
707---
708--- local it = vim.iter({ 3, 6, 9, 12 })
709--- it:find(12)
710--- -- 12
711---
712--- local it = vim.iter({ 3, 6, 9, 12 })
713--- it:find(20)
714--- -- nil
715---
716--- local it = vim.iter({ 3, 6, 9, 12 })
717--- it:find(function(v) return v % 4 == 0 end)
718--- -- 12
719---
720--- ```
721--- @since 12
722--- @param f V1|fun(v: V1, ...: V...): any
723--- @return V1?, V...
724function Iter:find(f)
725  if type(f) ~= 'function' then
726    local val = f
727    --- @param v V1
728    f = function(v)
729      return v == val
730    end
731  end
732
733  local result = nil
734
735  --- Use a closure to handle var args returned from iterator
736  --- @param ... any
737  local function fn(...)
738    if select(1, ...) ~= nil then
739      if f(...) then
740        result = pack(...)
741      else
742        return true
743      end
744    end
745  end
746
747  while fn(self:next()) do
748  end
749  return unpack(result)
750end
751
752--- @nodoc
753--- @diagnostic disable-next-line:unused
754--- @param f V1|fun(v: V1, ...: V...): boolean
755function Iter:rfind(f)
756  error('rfind() requires an array-like table')
757end
758
759--- Gets the first value satisfying a predicate, from the end of a |list-iterator|.
760---
761--- Advances the iterator. Returns nil and drains the iterator if no value is found.
762---
763--- Examples:
764---
765--- ```lua
766---
767--- local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate()
768--- it:rfind(1)
769--- -- 5	1
770--- it:rfind(1)
771--- -- 1	1
772---
773--- ```
774---
775--- @see |Iter:find()|
776---
777--- @since 12
778--- @param f V1|fun(v: V1, ...: V...): boolean
779--- @return V1?, V...
780function IterArray:rfind(f)
781  if type(f) ~= 'function' then
782    local val = f
783    --- @param v V1
784    f = function(v)
785      return v == val
786    end
787  end
788
789  local inc = self._head < self._tail and 1 or -1
790  for i = self._tail - inc, self._head, -inc do
791    local v = self._table[i]
792    if f(unpack(v)) then
793      self._tail = i
794      return unpack(v)
795    end
796  end
797  self._head = self._tail
798end
799
800--- Transforms an iterator to yield only the first n values, or all values
801--- satisfying a predicate.
802---
803--- Example:
804---
805--- ```lua
806--- local it = vim.iter({ 1, 2, 3, 4 }):take(2)
807--- it:next()
808--- -- 1
809--- it:next()
810--- -- 2
811--- it:next()
812--- -- nil
813---
814--- local function pred(x) return x < 2 end
815--- local it2 = vim.iter({ 1, 2, 3, 4 }):take(pred)
816--- it2:next()
817--- -- 1
818--- it2:next()
819--- -- nil
820--- ```
821---
822--- @since 12
823--- @param n integer|fun(v: V1, ...: V...): boolean Number of values to take or a predicate.
824--- @return vim.Iter<V1, V...>
825--- @overload fun<V1, V...>(self: vim.IterArray<V1, V...>, n: integer|fun(v: V1, ...: V...): boolean): vim.IterArray<V1, V...>
826function Iter:take(n)
827  local i = 0
828  local pred --- @type fun(...): boolean
829  if type(n) == 'function' then
830    pred = n
831  else
832    local limit = n
833    pred = function()
834      return i < limit
835    end
836  end
837
838  local stop = false
839
840  --- @generic A...
841  --- @param ... A...
842  --- @return A...
843  local function fn(...)
844    if not stop and select(1, ...) ~= nil and pred(...) then
845      i = i + 1
846      return ...
847    else
848      stop = true
849    end
850  end
851
852  local next = self.next
853  --- @diagnostic disable-next-line:duplicate-set-field
854  self.next = function()
855    return fn(next(self))
856  end
857  return self
858end
859
860--- @nodoc
861--- @param n integer|fun(v: V1, ...: V...): boolean
862--- @return vim.IterArray<V1, V...>
863function IterArray:take(n)
864  if type(n) == 'function' then
865    local inc = self._head < self._tail and 1 or -1
866    for i = self._head, self._tail - inc, inc do
867      if not n(unpack(self._table[i])) then
868        self._tail = i
869        break
870      end
871    end
872    return self
873  end
874
875  local inc = self._head < self._tail and n or -n
876  local cmp = self._head < self._tail and math.min or math.max
877  self._tail = cmp(self._tail, self._head + inc)
878  return self
879end
880
881--- @nodoc
882--- @diagnostic disable-next-line: unused
883function Iter:pop()
884  error('pop() requires an array-like table')
885end
886
887--- "Pops" a value from a |list-iterator| (gets the last value and decrements the tail).
888---
889--- Example:
890---
891--- ```lua
892--- local it = vim.iter({1, 2, 3, 4})
893--- it:pop()
894--- -- 4
895--- it:pop()
896--- -- 3
897--- ```
898---
899--- @since 12
900--- @return V1?, V...
901function IterArray:pop()
902  if self._head ~= self._tail then
903    local inc = self._head < self._tail and 1 or -1
904    self._tail = self._tail - inc
905    return unpack(self._table[self._tail])
906  end
907end
908
909--- @nodoc
910--- @diagnostic disable-next-line: unused
911function Iter:rpeek()
912  error('rpeek() requires an array-like table')
913end
914
915--- Gets the last value of a |list-iterator| without consuming it.
916---
917--- Example:
918---
919--- ```lua
920--- local it = vim.iter({1, 2, 3, 4})
921--- it:rpeek()
922--- -- 4
923--- it:rpeek()
924--- -- 4
925--- it:pop()
926--- -- 4
927--- ```
928---
929--- @see |Iter:last()|
930---
931--- @since 12
932--- @return V1?, V...
933function IterArray:rpeek()
934  if self._head ~= self._tail then
935    local inc = self._head < self._tail and 1 or -1
936    return unpack(self._table[self._tail - inc])
937  end
938end
939
940--- Skips `n` values of an iterator pipeline, or skips values while a predicate returns |lua-truthy|.
941---
942--- When a predicate is used, skipping stops at the first value for which the
943--- predicate returns non-truthy. That value is not consumed and will be returned
944--- by the next call to |Iter:next()|
945---
946--- Example:
947---
948--- ```lua
949---
950--- local it = vim.iter({ 3, 6, 9, 12 }):skip(2)
951--- it:next()
952--- -- 9
953---
954--- local function pred(x) return x < 10 end
955--- local it2 = vim.iter({ 3, 6, 9, 12 }):skip(pred)
956--- it2:next()
957--- -- 12
958--- ```
959---
960--- @since 12
961--- @param n integer|fun(v: V1, ...: V...): boolean Number of values to skip or a predicate.
962--- @return vim.Iter<V1, V...>
963--- @overload fun<V1, V...>(self: vim.IterArray<V1, V...>, n: integer|fun(v: V1, ...: V...): boolean): vim.IterArray<V1, V...>
964function Iter:skip(n)
965  if type(n) == 'number' then
966    for _ = 1, n do
967      self._peeked = nil
968      local _ = self:next()
969    end
970  elseif type(n) == 'function' then
971    local next = self.next
972
973    --- @return V1?, V...
974    --- @diagnostic disable-next-line:duplicate-set-field
975    self.next = function()
976      while true do
977        local peeked = self._peeked or pack(next(self))
978
979        if not peeked then
980          return nil
981        end
982
983        if not n(unpack(peeked)) then
984          self._peeked = nil
985          return unpack(peeked)
986        end
987
988        self._peeked = nil
989      end
990    end
991  end
992  return self
993end
994
995--- @nodoc
996--- @param n integer|fun(v: V1, ...: V...): boolean
997--- @return vim.IterArray<V1, V...>
998function IterArray:skip(n)
999  if type(n) == 'function' then
1000    while self._head ~= self._tail do
1001      local v = self._table[self._head]
1002      if not n(unpack(v)) then
1003        break
1004      end
1005
1006      self._head = self._head + (self._head < self._tail and 1 or -1)
1007    end
1008    return self
1009  end
1010
1011  local inc = self._head < self._tail and n or -n
1012  self._head = self._head + inc
1013  if (inc > 0 and self._head > self._tail) or (inc < 0 and self._head < self._tail) then
1014    self._head = self._tail
1015  end
1016  return self
1017end
1018
1019--- @nodoc
1020--- @diagnostic disable-next-line:unused
1021--- @param n integer
1022function Iter:rskip(n)
1023  error('rskip() requires an array-like table')
1024end
1025
1026--- Discards `n` values from the end of a |list-iterator| pipeline.
1027---
1028--- Example:
1029---
1030--- ```lua
1031--- local it = vim.iter({ 1, 2, 3, 4, 5 }):rskip(2)
1032--- it:next()
1033--- -- 1
1034--- it:pop()
1035--- -- 3
1036--- ```
1037---
1038--- @since 12
1039--- @param n integer
1040--- @return vim.IterArray<V1, V...>
1041function IterArray:rskip(n)
1042  local inc = self._head < self._tail and n or vim._assert_integer(-n)
1043  self._tail = vim._assert_integer(self._tail - inc)
1044  if (inc > 0 and self._head > self._tail) or (inc < 0 and self._head < self._tail) then
1045    self._head = self._tail
1046  end
1047  return self
1048end
1049
1050--- Gets the nth value of an iterator (and advances to it).
1051---
1052--- If `n` is negative, offsets from the end of a |list-iterator|.
1053---
1054--- Example:
1055---
1056--- ```lua
1057--- local it = vim.iter({ 3, 6, 9, 12 })
1058--- it:nth(2)
1059--- -- 6
1060--- it:nth(2)
1061--- -- 12
1062---
1063--- local it2 = vim.iter({ 3, 6, 9, 12 })
1064--- it2:nth(-2)
1065--- -- 9
1066--- it2:nth(-2)
1067--- -- 3
1068--- ```
1069---
1070--- @since 12
1071--- @param n integer Index of the value to return. May be negative if the source is a |list-iterator|.
1072--- @return V1?, V...
1073function Iter:nth(n)
1074  if n > 0 then
1075    return self:skip(n - 1):next()
1076  elseif n < 0 then
1077    return self:rskip(math.abs(n) - 1):pop()
1078  end
1079end
1080
1081--- @nodoc
1082--- @diagnostic disable-next-line:unused
1083--- @param first integer
1084--- @param last integer
1085function Iter:slice(first, last)
1086  error('slice() requires an array-like table')
1087end
1088
1089--- Sets the start and end of a |list-iterator| pipeline.
1090---
1091--- Equivalent to `:skip(first - 1):rskip(len - last + 1)`.
1092---
1093--- @since 12
1094--- @param first integer
1095--- @param last integer
1096--- @return vim.IterArray<V1, V...>
1097function IterArray:slice(first, last)
1098  local left = vim._assert_integer(math.max(0, first - 1))
1099  local right = vim._assert_integer(math.max(0, self._tail - last - 1))
1100  return self:skip(left):rskip(right)
1101end
1102
1103--- Returns true if any of the items in the iterator match the given predicate.
1104---
1105--- @since 12
1106--- @param pred fun(v: V1, ...: V...): boolean Predicate function. Takes all values returned from the previous
1107---                          stage in the pipeline as arguments and returns true if the
1108---                          predicate matches.
1109function Iter:any(pred)
1110  local any = false
1111
1112  --- Use a closure to handle var args returned from iterator
1113  --- @param ... any
1114  local function fn(...)
1115    if select(1, ...) ~= nil then
1116      if pred(...) then
1117        any = true
1118      else
1119        return true
1120      end
1121    end
1122  end
1123
1124  while fn(self:next()) do
1125  end
1126  return any
1127end
1128
1129--- Returns true if all items in the iterator match the given predicate.
1130---
1131--- @since 12
1132--- @param pred fun(v: V1, ...: V...): boolean Predicate function. Takes all values returned from the previous
1133---                          stage in the pipeline as arguments and returns true if the
1134---                          predicate matches.
1135function Iter:all(pred)
1136  local all = true
1137
1138  --- @param ... any
1139  local function fn(...)
1140    if select(1, ...) ~= nil then
1141      if not pred(...) then
1142        all = false
1143      else
1144        return true
1145      end
1146    end
1147  end
1148
1149  while fn(self:next()) do
1150  end
1151  return all
1152end
1153
1154--- Drains the iterator and returns the last item.
1155---
1156--- Example:
1157---
1158--- ```lua
1159---
1160--- local it = vim.iter(vim.gsplit('abcdefg', ''))
1161--- it:last()
1162--- -- 'g'
1163---
1164--- local it = vim.iter({ 3, 6, 9, 12, 15 })
1165--- it:last()
1166--- -- 15
1167---
1168--- ```
1169---
1170--- @since 12
1171--- @see |IterArray:rpeek()|
1172--- @return V1?, V...
1173function Iter:last()
1174  local last = self:next()
1175  local cur = self:next()
1176  while cur do
1177    last = cur
1178    cur = self:next()
1179  end
1180  return last
1181end
1182
1183--- @nodoc
1184--- @return V1?, V...
1185function IterArray:last()
1186  if self._head == self._tail then
1187    return nil
1188  end
1189  local inc = self._head < self._tail and 1 or -1
1190  local v = self._table[self._tail - inc]
1191  self._head = self._tail
1192  return unpack(v)
1193end
1194
1195--- Yields the item index (count) and value for each item of an iterator pipeline.
1196---
1197--- For list tables, this is more efficient:
1198---
1199--- ```lua
1200--- vim.iter(ipairs(t))
1201--- ```
1202---
1203--- instead of:
1204---
1205--- ```lua
1206--- vim.iter(t):enumerate()
1207--- ```
1208---
1209--- Example:
1210---
1211--- ```lua
1212---
1213--- local it = vim.iter(vim.gsplit('abc', '')):enumerate()
1214--- it:next()
1215--- -- 1	'a'
1216--- it:next()
1217--- -- 2	'b'
1218--- it:next()
1219--- -- 3	'c'
1220---
1221--- ```
1222---
1223--- @since 12
1224--- @overload fun<V1, V...>(self: vim.IterArray<V1, V...>): vim.IterArray<integer, V1, V...>
1225--- @return vim.Iter<integer, V1, V...>
1226function Iter:enumerate()
1227  local i = 0
1228  return self:map(function(...)
1229    i = i + 1
1230    return i, ...
1231  end)
1232end
1233
1234--- @nodoc
1235--- @return vim.IterArray<integer, V1, V...>
1236function IterArray:enumerate()
1237  local inc = self._head < self._tail and 1 or -1
1238  local n = 0
1239  for i = self._head, self._tail - inc, inc do
1240    n = n + 1
1241    local v = self._table[i]
1242    self._table[i] = pack(n, unpack(v))
1243  end
1244  return self
1245end
1246
1247--- Drains the iterator, counting the number of iterations and returning it.
1248---
1249--- @since 15
1250--- @return integer
1251function Iter:count()
1252  return self:fold(0, function(acc)
1253    return acc + 1
1254  end)
1255end
1256
1257--- @nodoc
1258--- @return integer
1259function IterArray:count()
1260  local count = math.abs(self._tail - self._head)
1261  self._head = self._tail
1262  return count
1263end
1264
1265--- Creates a new Iter object from a table or other |iterable|.
1266---
1267--- @generic R1, R...
1268--- @param src table<R1, R>|fun(s: table, v: any): R1, R... Table or iterator to drain values from
1269--- @return vim.Iter<R1, R...>
1270--- @overload fun<T>(src: T[]): vim.IterArray<T, never>
1271--- @overload fun<K, V>(src: table<K, V>): vim.Iter<K, V>
1272--- @private
1273function Iter.new(src, ...)
1274  local it = {}
1275  if type(src) == 'table' then
1276    local mt = getmetatable(src)
1277    if mt and type(mt.__call) == 'function' then
1278      --- @private
1279      it._next = function()
1280        return mt.__call(src)
1281      end
1282
1283      return setmetatable(it, Iter)
1284    end
1285
1286    local t = {}
1287
1288    -- O(n): scan the source table to decide if it is an array (only positive integer indices).
1289    for k, v in pairs(src) do
1290      if type(k) ~= 'number' or k <= 0 or math.floor(k) ~= k then
1291        return Iter.new(pairs(src))
1292      end
1293      t[#t + 1] = v -- Coerce to list-like table.
1294    end
1295    return IterArray.new(t)
1296  elseif type(src) ~= 'function' then
1297    error('src must be a table or function')
1298  end
1299
1300  local s, var = ...
1301
1302  --- Use a closure to handle var args returned from iterator
1303  local function fn(...)
1304    -- Per the Lua 5.1 reference manual, an iterator is complete when the first returned value is
1305    -- nil (even if there are other, non-nil return values). See |for-in|.
1306    if select(1, ...) ~= nil then
1307      var = select(1, ...)
1308      return ...
1309    end
1310  end
1311
1312  --- @private
1313  it._next = function()
1314    return fn(src(s, var))
1315  end
1316
1317  return setmetatable(it, Iter)
1318end
1319
1320--- Create a new IterArray
1321---
1322--- @generic V1, V...
1323--- @param t (V1|[V1, V...])[] List-like table. Caller guarantees that this table is a valid
1324---               internal list buffer.
1325--- @return vim.IterArray<V1, V...>
1326--- @private
1327function IterArray.new(t)
1328  return setmetatable({
1329    _table = t,
1330    _head = 1,
1331    _tail = #t + 1,
1332  }, IterArray)
1333end
1334
1335setmetatable(M, {
1336  __call = function(_, ...)
1337    return Iter.new(...)
1338  end,
1339})
1340
1341-- Return M separately to work around EmmyLuaLs/emmylua-analyzer-rust#1240.
1342return M