#include <Cocoa/Cocoa.h>

@implementation NSBitmapImageRep (TestCopy)

+ (void) testCopy
{
    NSBitmapImageRep *origBitmap, *copy1Bitmap, *copy2Bitmap;
    
    origBitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL
                                            pixelsWide: 4
                                            pixelsHigh: 4
                                            bitsPerSample: 8
                                            samplesPerPixel: 4
                                            hasAlpha: YES
                                            isPlanar: NO
                                            colorSpaceName: NSCalibratedRGBColorSpace
                                            bytesPerRow: 0
                                            bitsPerPixel: 0];

    copy1Bitmap = [origBitmap copy];

    if ([copy1Bitmap->_imageData class] != [origBitmap->_imageData class])
    {
        NSLog(@"ERROR: -[NSBitmapImageRep copy] returned instance with wrong class for "
                "_imageData member: %@ (should be %@).", 
                [copy1Bitmap->_imageData className], [origBitmap->_imageData className]);
    }

    // Copying immutable NSData reuses the data pointer instead of allocating new memory, so 
    // copying a bitmap with immutable _imageData causes both bitmaps to point to the same memory;
    // Writing to either copy's pixels will overwrite both, corrupting the image data
    
    copy2Bitmap = [copy1Bitmap copy];
    
    if ([copy1Bitmap->_imageData bytes] == [copy2Bitmap->_imageData bytes])
    {
        NSLog(@"ERROR: Copied bitmaps have the same image data pointer - can cause image data "
                "corruption.");
    }
}

@end

int main(void)
{
    [NSBitmapImageRep testCopy];
}

