diff options
author | c-blake <c-blake@users.noreply.github.com> | 2020-08-08 01:26:20 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-08-08 07:26:20 +0200 |
commit | 0bc8dd0b0065534b2dfab53b1844a9f6cc36844e (patch) | |
tree | bc0392e2bcf81561e76a6712804f658510039d7b /lib/posix | |
parent | eee3b189ff867c0149434e198e89802eca4920ce (diff) | |
download | Nim-0bc8dd0b0065534b2dfab53b1844a9f6cc36844e.tar.gz |
Add `iterator inotify_events` which is *almost always* needed logic for (#15152)
client code since Linux `inotify` is much like Linux `getdents64`. Expanding on "almost always"..The only time that this `iterator` logic is ***not*** needed on the output of a `read` from inotify fd's is when one passes a length to `read` *guaranteed* to only pass one event struct in the buffer. That unusual circumstance requires (at least!) knowing the length of the delivered filename before an event occurs, and the filename itself is optional for some event types. It is *far* more common to not know lengths in advance which means one passes a buffer big enough for at least one maximum length directory entry (256 bytes) which is then also big enough for *many* "typical" length entries and therefore many events. In such more common scenarios this iterator logic is definitely needed. Further, not using this logic, yet treating the return from read as "the whole answer" can test ok on "thin" event streams (e.g. 1 event per ms), hiding a latent bug of processing only the first event.
Diffstat (limited to 'lib/posix')
-rw-r--r-- | lib/posix/inotify.nim | 14 |
1 files changed, 14 insertions, 0 deletions
diff --git a/lib/posix/inotify.nim b/lib/posix/inotify.nim index 79b408425..db698c59c 100644 --- a/lib/posix/inotify.nim +++ b/lib/posix/inotify.nim @@ -73,6 +73,20 @@ proc inotify_rm_watch*(fd: cint; wd: cint): cint {.cdecl, importc: "inotify_rm_watch", header: "<sys/inotify.h>".} ## Remove the watch specified by WD from the inotify instance FD. +iterator inotify_events*(evs: pointer, n: int): ptr InotifyEvent = + ## Abstract the packed buffer interface to yield event object pointers. + ## + ## .. code-block:: Nim + ## var evs = newSeq[byte](8192) # Already did inotify_init+add_watch + ## while (let n = read(fd, evs[0].addr, 8192); n) > 0: # read forever + ## for e in inotify_events(evs[0].addr, n): echo e[].len # echo name lens + var ev: ptr InotifyEvent = cast[ptr InotifyEvent](evs) + var n = n + while n > 0: + yield ev + let sz = InotifyEvent.sizeof + int(ev[].len) + n -= sz + ev = cast[ptr InotifyEvent](cast[uint](ev) + uint(sz)) runnableExamples: when defined(linux): |