From 0bc8dd0b0065534b2dfab53b1844a9f6cc36844e Mon Sep 17 00:00:00 2001 From: c-blake Date: Sat, 8 Aug 2020 01:26:20 -0400 Subject: [PATCH] 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. --- lib/posix/inotify.nim | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/lib/posix/inotify.nim b/lib/posix/inotify.nim index 79b4084253..db698c59ce 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: "".} ## 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):