Jörg wrote: > I believe that strnlen is something like: > > p2 = memchr(p, o, len); > if (p == 0 || p2 - p > len) > return (len); > return (p2 - p); > > Why do you like to start with strlen()?
What you posted resembles (although is not identical to) an LGPL implementation*, and str*() functions don't typically need to check for a NULL pointer (p == 0). I wanted to be sure the provenance was ok. Also Casper said that there's no platform optimized versions of memchr() anyway, and I usually take it for granted that he's _Right_ (although checking now, I do see platform-specific assembler versions of memchr() that look like they'd be a good bit faster than my code, which in turn means your code is faster than mine, at least for strings of more than a very few characters). Object lession: some of the unused (in favor of platform-specific versions) "portable" functions in libc/port/gen are seriously (and historically) _lame_ in terms of performance, and may constitute rather poor examples. Noted... * http://www.koders.com/c/fidAD1A672EDB32918BE39431641069CFEF5A6C644E.aspx as an example of the generic LGPL implementation (apparently they're rearranging to allow for platform-specific versions of strnlen since then). As far as that goes, there's also a similar private implementation as part of apptrace: http://cvs.opensolaris.org/source/xref/on/usr/src/lib/abi/apptrace/common/interceptlib.c#52 Except for the NULL check, I like that at least as well as yours (but the +1 at the end is _wrong_ and should be removed). What you posted appears correct (give or take the need for the p == 0 test). At least it passes the tests** I had for boundary conditions (attached), not looking where it shouldn't (past p+len), not writing to any of the string at p, correct results on termination either due to NUL byte or hitting len, etc. ** I'd attach my test program, except I can't get attachments to work in mozilla, and I'm too tired to go to a Windows box and try Explod^Hrer. If you want to do the contribution to get it into libc, I'd be every bit as happy with that as much as attempting it myself. I actually dislike having my name on things; all I care is that it gets in there reasonably soon, i.e. before proposed extensions to POSIX (http://www.opengroup.org/austin/plato/uploads/40/9756/NAPI_overview.txt) actually require it. If not, I think I'll use the interceptlib.c version rather than what I had, but with the NULL pointer test yanked out (some people like NULL pointer safe functions, but AFAIK that's actually wrong and it's better to get core dumps than hide a caller's mistake; this has been discussed before e.g. for null pointer corresponding to %s passed to printf() and friends) and the + 1 yanked out. This message posted from opensolaris.org _______________________________________________ opensolaris-code mailing list [email protected] http://mail.opensolaris.org/mailman/listinfo/opensolaris-code
