github.com/haraldrudell/parl@v0.4.176/pfs/iterator.go (about) 1 /* 2 © 2023–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package pfs 7 8 import ( 9 "github.com/haraldrudell/parl" 10 "github.com/haraldrudell/parl/iters" 11 ) 12 13 // Iterator traverses file-system entries and errors 14 type Iterator struct { 15 // traverser is the file-system traverser. 16 // Only method is [Traverser.Next] 17 traverser Traverser 18 // BaseIterator provides iterator methods: 19 // [iters.Iterator.Cancel] [iters.Iterator.Cond] [iters.Iterator.Next] 20 iters.BaseIterator[ResultEntry] 21 } 22 23 // NewIterator returns an iterator for a file-system entry and any child entries if directory 24 // - path is the initial path for the file-system walk. 25 // it may be relative or absolute, contain symlinks and 26 // point to a file, directory or special file 27 // - if symlinks and directories are not skipped, they are followed 28 // - all errors during traversal are provided as is 29 func NewIterator(path string) (iterator iters.Iterator[ResultEntry]) { 30 i := Iterator{traverser: *NewTraverser(path)} 31 i.BaseIterator = *iters.NewBaseIterator(i.iteratorAction) 32 return &i 33 } 34 35 // Init implements the right-hand side of a short variable declaration in 36 // the init statement of a Go “for” clause 37 // 38 // for i, iterator := iters.NewSlicePointerIterator(someSlice).Init(); iterator.Cond(&i); { 39 // // i is pointer to slice element 40 func (i *Iterator) Init() (result ResultEntry, iterator iters.Iterator[ResultEntry]) { 41 iterator = i 42 return 43 } 44 45 // iteratorAction provides items to the BaseIterator 46 func (t *Iterator) iteratorAction(isCancel bool) (result ResultEntry, err error) { 47 if isCancel { 48 return // cancel notify return: Tarverser has no cleanup 49 } 50 51 // get next file-system entry or error 52 result = t.traverser.Next() 53 54 //end iterator when traverser ends 55 if result.IsEnd() { 56 err = parl.ErrEndCallbacks 57 } 58 59 return 60 }