Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Announcing mozilla::ArrayLength and mozilla::ArrayEnd

12 views
Skip to first unread message

Jeff Walden

unread,
Oct 20, 2011, 7:23:21 PM10/20/11
to
Historically, if you wanted to get the length of a C++ array -- that is, something like this:

static const int foo[] = { 1, 2, 5 };

You used the NS_ARRAY_LENGTH(foo) to do it. NS_ARRAY_LENGTH was a macro that used sizeof tricks to compute the length of |foo|.

The macro had a few problems. First, it was a macro with the usual problems. Second, as a macro, it was type-unsafe. That meant this would cheerfully be accepted with dangerous results:

const char* str = "long enough string";
char* copy = (char*) malloc(NS_ARRAY_LENGTH(str)); // usually 4 or 8
strcpy(copy, str); // buffer overflow!

Earlier this week in bug 693469, I implemented mozilla::ArrayLength and mozilla::ArrayEnd to address these problems. (ArrayEnd computes the end of an array -- that is, one past the last element, i.e. |ArrayEnd(arr) == arr + ArrayLength(arr)|.) You can get them using #include "mozilla/Util.h".

You should use these methods instead of the macros when possible. There are some caveats and limitations, tho, due to ISO C++ limitations, so the macros will still be needed in certain contexts like static assertions and other code that relied on the length calculation occurring at compile time. C++11 eliminates those restrictions in the mid-term, but for now we're stuck with both.

I've written a blog post with further information about the change:

https://whereswalden.com/2011/10/20/computing-the-length-or-end-of-a-compile-time-constant-length-array-jsns_array_endlength-are-out-mozillaarraylengthend-are-in/

I've also written a blog post about ideas for further improvements to all this code. Those ideas seem like good-first-bug material, however, so I've filed bug 696242 to cover them. Anyone interested in diving into moderately easy C++ coding, feel free to start on it, and ask any questions about the proposed changes in the bug.

https://whereswalden.com/2011/10/20/implementing-mozillaarraylength-and-mozillaarrayend-and-some-followup-work/
https://bugzilla.mozilla.org/show_bug.cgi?id=696242

If you have questions that don't relate to performing the followup work proposed in that bug, feel free to ask them here or at the posts themselves.

Jeff

P.S. -- There's been at least one suggestion that this change should have been announced before its landing (which happened around the start of the week). It didn't occur to me to do so this time, but I'll try to make an effort to announce pre-change, for tree-wide changes like this, in the future.

David Rajchenbach-Teller

unread,
Oct 21, 2011, 4:35:15 AM10/21/11
to Jeff Walden, dev-pl...@lists.mozilla.org
Yeah, dependent types in C++ :)
0 new messages