[cfe-dev] Fast enumeration extension proposal

David Chisnall csdavec at swan.ac.uk
Sat Apr 3 10:54:15 PDT 2010


I'd like to propose an extension to the fast enumeration behaviour for Objective-C 2.  This allows you to efficiently iterate over objects in a collection, but it would also be convenient in a great many cases to use the same mechanism to iterate over things that contain collections of primitive types, such as strings.  Indeed, the iteration method is conceptually very similar to the -getBytes:range: and getCharacters:range: methods on NSData and NSString, respectively.  

I've attached a diff (please do not commit as is!) which give a proof of concept implementation of a generalisation of fast enumeration to permit this.  This generalises the method use for fast enumeration to this:

- (NSUInteger)countByEnumeratingWithState: (NSFastEnumerationState*)state
                                   buffer: (void*)stackbuf
                                     type: (const char*)type
                                    count: (NSUInteger)len

This replaces the the object:(id*) parameter with two arguments; one a pointer to the buffer, the other an Objective-C type encoding of a single element in the array.  If you call it with something like this:

for (unichar a in @"Foobar!")

The first parameter will be an array of len unichars, the third element will be "S" (the type encoding of unichar, which is a typedef for unsigned short).  

I could add this as a GNU extension, but it would be more useful if it were supported by Apple as well.  Note that this should have no impact on existing code: currently both clang and GCC raise an error with non-object element types, and my diff generates the old method for object return types.

I'm also tempted to suggest generalising it still slightly further by permitting a range for enumeration to be specified (this would, of course, only be relevant for ordered collections), as this currently requires falling back to very slow enumeration.  I'm not sure what the best syntax for this would be though, maybe something like:

for (id a in array[1..30])

for (id a in array range 1,30)

Something else?

Comments, (constructive) criticisms, and suggestions welcome,


-------------- next part --------------
A non-text attachment was scrubbed...
Name: fenum.m
Type: application/octet-stream
Size: 1931 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20100403/20626cc5/attachment.obj>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: clang.diff
Type: application/octet-stream
Size: 3770 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20100403/20626cc5/attachment-0001.obj>
-------------- next part --------------

-- Sent from my Difference Engine

More information about the cfe-dev mailing list