X-Git-Url: https://pd.if.org/git/?p=pdclib.old;a=blobdiff_plain;f=functions%2Fstdio%2F_PDCLIB_flushbuffer.c;h=44066d87dbd24099d40fe16ca657f25ef786c858;hp=7ee0d93c35730aa08b1baaa28128d2e735f23f16;hb=cd6cfe0f578c4f744ddc9a342243aff6b42f8027;hpb=29bef599b18dd551f96520ae051994706805157c diff --git a/functions/stdio/_PDCLIB_flushbuffer.c b/functions/stdio/_PDCLIB_flushbuffer.c index 7ee0d93..44066d8 100644 --- a/functions/stdio/_PDCLIB_flushbuffer.c +++ b/functions/stdio/_PDCLIB_flushbuffer.c @@ -11,34 +11,72 @@ #include <_PDCLIB_glue.h> #include <_PDCLIB_io.h> -int _PDCLIB_flushbuffer( FILE * stream ) +static int flushsubbuffer( FILE * stream, size_t length ) { - if ( ! ( stream->status & _PDCLIB_FBIN ) ) - { - /* TODO: Text stream conversion here */ - } - size_t written = 0; + int rv = 0; - - while(written != stream->bufidx) { + while( written != length ) + { size_t justWrote; - size_t toWrite = stream->bufidx - written; - bool res = stream->ops->write( stream->handle, stream->buffer + written, + size_t toWrite = length - written; + bool res = stream->ops->write( stream->handle, stream->buffer + written, toWrite, &justWrote); written += justWrote; stream->pos.offset += justWrote; - if(!res) { + if (!res) + { stream->status |=_PDCLIB_ERRORFLAG; - stream->bufidx -= written; - memmove( stream->buffer, stream->buffer + written, stream->bufidx ); - return EOF; + rv = EOF; + break; + } + } + + stream->bufidx -= written; + memmove( stream->buffer, stream->buffer + written, stream->bufidx ); + + return rv; +} + +#if defined(_PDCLIB_NEED_EOL_TRANSLATION) +#undef _PDCLIB_NEED_EOL_TRANSLATION +#define _PDCLIB_NEED_EOL_TRANSLATION 1 +#else +#define _PDCLIB_NEED_EOL_TRANSLATION 0 +#endif + +int _PDCLIB_flushbuffer( FILE * stream ) +{ + // if a text stream, and this platform needs EOL translation, well... + if ( ! ( stream->status & _PDCLIB_FBIN ) && _PDCLIB_NEED_EOL_TRANSLATION ) + { + size_t pos; + for ( pos = 0; pos < stream->bufidx; pos++ ) + { + if (stream->buffer[pos] == '\n' ) { + if ( stream->bufidx == stream->bufend ) { + // buffer is full. Need to print out everything up till now + if( flushsubbuffer( stream, pos ) ) + { + return EOF; + } + + pos = 0; + } + + // we have spare space in buffer. Shift everything 1char and + // insert \r + memmove( &stream->buffer[pos+1], &stream->buffer[pos], stream->bufidx - pos ); + stream->buffer[pos] = '\r'; + + pos += 2; + stream->bufidx++; + } } } - stream->bufidx = 0; - return 0; + return flushsubbuffer( stream, stream->bufidx ); } #endif