/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
//
// $Id: streams.h,v 1.5 2002-10-15 12:30:07 hoenicke Exp $
//
// file/buffer stream functions
//
// Copyright (c) 2001 Jochen Hoenicke under Artistic License.
//
*/

#ifndef STREAM_H
#define STREAM_H

#include "textfile.h"

#define STREAM_FLAG_BUFFER     1
#define STREAM_FLAG_NULL_FILE  2
#define STREAM_FLAG_READER     4

#define BITS_PER_UNIT (8*sizeof(unsigned long))
typedef unsigned long bitmap[256 / BITS_PER_UNIT];
#define BITMAP_COFF(c)   (((unsigned char)(c))/BITS_PER_UNIT)
#define BITMAP_CMASK(c)  ((unsigned long)1 << ((c) & (BITS_PER_UNIT-1)))
#define BITMAP_SET(b,c)   b[BITMAP_COFF(c)] |= BITMAP_CMASK(c)
#define BITMAP_GET(b,c)   (b[BITMAP_COFF(c)] & BITMAP_CMASK(c))

typedef struct tagSTREAMBUFFER {
    char  *buffer;
    ulong  offset;
    ulong  length;
} STREAMBUFFER;

typedef struct tagSTREAM {
    uint  sflags;
    uint  lineNumber;
    const char *name;
    BOOL  hasUnread;
    char  unread;
    union {
        TEXTFILE     textfile;
        STREAMBUFFER buffer;
    } u;
} STREAM;

BOOL CreateNullWriter (STREAM* stream);
BOOL CreateBufferWriter (STREAM* stream, const char *name);
BOOL CreateBufferReader (STREAM* stream, STREAM *writeStream);
BOOL FlushBufferWriter (STREAM *stream);
BOOL CreateFileReader (STREAM *stream, const char *filename);
BOOL CreateFDReader (STREAM *stream, const char *filename, int fd);
BOOL CreateFileWriter (STREAM *stream, const char *filename, BOOL append);
void CloseStream (STREAM *stream);


BOOL GetStreamChar(STREAM *stream, char *c);
BOOL UnreadStreamChar(STREAM *stream, char c);
BOOL GetStreamBlock(STREAM *stream, char *buffer, uint size, char delims[3]);

BOOL PutStreamString(STREAM *stram, const char *buffer);
BOOL StreamPrintF(STREAM *stream, const char *format, ...);

void ForceLinefeeds(STREAM *stream, BOOL forced);

#endif
