/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program 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.

**********************************************************************/



#include	"task.h"
#include	"memory_debug.h"
#include	"stream.h"
#include	"s_buf.h"

int s_chunk_read(STREAM * s,void * data,int len);

#define COPY_IN_MAX_SIZE	4096

int
_copy_in_sbuf_stream(STREAM_BUF * b,STREAM * s,int len,SEM lock)
{
SBUF_DATA * d;
int er;
	d = d_alloc(sizeof(*d)+len);
	er = en_do(&d->len,s_chunk_read,s,d+1,len);
	if ( d->len == 0 ) {
		d_f_ree(d);
		return er;
	}
	d->next = 0;
	d->ptr = 0;

	if ( lock )
		lock_task(lock);
	if ( b->head ) {
		b->tail->next = d;
		b->tail = d;
	}
	else	b->head = b->tail = d;
	if ( lock )
		unlock_task(lock,"_copy_in_sbuf_stream");
	if ( d->len > 0 )
		return 1;
	else 	return er;
}

int
copy_in_sbuf_stream(STREAM_BUF * b,STREAM * s,int len,SEM lock)
{
int ret;
	if ( len < 0 ) {
		ret = 1;
		for ( ; ret > 0 ; )
			ret = _copy_in_sbuf_stream(
					b,s,COPY_IN_MAX_SIZE,lock);
		return ret;
	}
	else {
		return _copy_in_sbuf_stream(b,s,len,lock);
	}
}

