On Jun 29, 2011, at 07:08, Wilker wrote:

>     char buffer[CHUNK_SIZE];

>     [fileData getBytes:buffer range:NSMakeRange(0, CHUNK_SIZE)];
>     CC_MD5_Update(&md5, buffer, CHUNK_SIZE);
>     [fileData getBytes:buffer range:NSMakeRange(MAX(0, [fileData length] - 
> CHUNK_SIZE), CHUNK_SIZE)];
>     CC_MD5_Update(&md5, buffer, CHUNK_SIZE);

Personally, having tried to get the file reads as cheaply as possible**, I'd 
just do this:

        const uint8_t* buffer = [fileData bytes];
        // calculate byteLength and byteOffset (see below)

        CC_MD5_Update(&md5, buffer, byteLength);
        CC_MD5_Update(&md5, buffer + byteOffset, byteLength);

        [fileData self];

to avoid copying the raw data unnecessarily.

Your code still has the bug in the MAX parameters (if [fileData length] > 
CHUNK_SIZE, then [fileData length] - CHUNK_SIZE is a *very* large positive 
number), and you've introduced a new one -- 'getBytes:range:' will crash if the 
range goes past the end of the NSData data, so I'd calculate the length and 
offset like this:

        NSUInteger byteLength = [fileData length];
        NSUInteger byteOffset = 0;

        if (byteLength > CHUNK_SIZE) { // ***
                byteLength = CHUNK_SIZE;
                byteOffset = byteLength - CHUNK_SIZE;
        }



** There are some drawbacks to using very large stack-based structures. At 
least:

a. If this code is ever part of a background thread, the default maximum stack 
size isn't large enough to accommodate 65K data structures.

b. If this is running under garbage collection, the collector must scan the 
entire 65K every time it runs, uselessly and wastefully.

What's the usual way to solve these problems? To move the data structure off 
the stack into the heap. But you already have the data in the heap, in your 
NSData object.

*** Someone once pointed out on this list that you should never use MIN and MAX 
(and other such convenience macros) in production code, because you are never 
quite certain how they're implemented (in terms of handling mismatched sign 
expressions, for example) and how they might be implemented on some future 
platform you might want to port this code to. Therefore, he said, you should 
write the code you want, not hope for the code you need. I think maybe his 
point was a little obsessive, but I have to admit I now cringe and hesitate 
before writing MIN or MAX. :)_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to