//
// $Id: DataInStream.m,v 1.7 2005/05/18 06:46:52 will_mason Exp $
//
// vi: set ft=objc:

/*
 * ObjectiveLib - a library of containers and algorithms for Objective-C
 *
 * Copyright (c) 2004
 * Will Mason
 *
 * Portions:
 *
 * Copyright (c) 1994
 * Hewlett-Packard Company
 *
 * Copyright (c) 1996,1997
 * Silicon Graphics Computer Systems, Inc.
 *
 * Copyright (c) 1997
 * Moscow Center for SPARC Technology
 *
 * Copyright (c) 1999 
 * Boris Fomitchev
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * You may contact the author at will_mason@users.sourceforge.net.
 */

#import "DataInStream.h"
#import "Macros.h"
#import <Foundation/NSData.h>
#import <Foundation/NSException.h>
#import <Foundation/NSString.h>
#import <string.h>
#import <limits.h>

@implementation OLDataInStream

+ (id) streamWithDataObject: (NSData*)data
{
    OL_BEGIN_AUTO_CTOR(OLDataInStream)
        initWithDataObject: data
    OL_END_AUTO_CTOR;
}

- (id) initWithDataObject: (NSData*)data
{
    return [self initWithBytes: [data bytes] count: [data length]];
}

- (id) initWithBytes: (const uint8_t*)buffer count: (unsigned)length
{
    return [self initWithBytes: buffer count: length allocator: [OLAllocator defaultAllocator]];
}

- (id) initWithBytes: (const uint8_t*)buffer count: (unsigned)length allocator: (OLAllocator*)alloc
{
    [super initWithAllocator: alloc];
    byteCount = length;
    bytes = [allocator allocateBytes: length];
    position = 0;
    memcpy(bytes, buffer, length);
    return self;
}

- (void) dealloc
{
    [allocator deallocateBytes: bytes];
    [super dealloc];
}

- (uint8_t) readByte
{
    if (position == byteCount)
        [NSException raise: OLEndOfStreamException format: @""];
    return bytes[position++];
}

- (unsigned) readBytes: (uint8_t*)buffer count: (unsigned)max
{
    unsigned amountToRead;

    if (position == byteCount)
    {
        amountToRead = UINT_MAX;
    }
    else
    {
        amountToRead = MIN(max, byteCount - position);
        memcpy(buffer, bytes + position, amountToRead);
        position += amountToRead;
    }
    return amountToRead;
}

@end
