/* rbtest.c - test rb??? ring-buffer routines */

/*)BUILD
	$(FILES)	=	{ rbtest rb }
*/

#include <algol68.h>
#include <rb.h>

#define	SIZ (4)			/* size of each thing in the ring buffer */
#define NUM (20)		/* number of things in the ring buffer	*/
#define TEST (213)		/* number of inserts to test		*/

char		it[SIZ];	/* a thing				*/
char		t[SIZ];		/* another thing			*/
struct	rb	r;		/* a ring buffer header			*/
int		i;		/* test generator			*/
int		j;		/* test consumer			*/
int		k;		/* test check				*/
BOOL		trace;		/* TRUE to trace for human		*/
char *		p;
int		l;		/* count a small number of extracts	*/
extern long rand();

main(argc)
int	argc;
BEGIN

	trace = argc > 1;
	IF	(!(p = malloc(SIZ*NUM)))
	THEN	error("\7no room for struct rb, SIZ=%d. NUM=%d.",SIZ,NUM);
	FI
	rbnew(&r,p,SIZ,NUM);
	k	 =	-1;
	FOR	(i=k+1;  i<TEST; i++)
	DO	sprintf(it,"%3d",i);
		IF	(trace)
		THEN	printf("in :%s\n",it);
		FI
		IF	(!rbin(&r,it))
		THEN	/* select a 0 < random number <= 8 */
			/* if we select 0, then we do no rbout(), so rbin() fails */
			l = (rand() & 0x7) + 1;
			FOR	(; l&&rbout(&r,t); l--)
			DO	IF	(trace)
				THEN	printf("out:%s\n",t);
				FI
				sscanf(t,"%d",&j);
				IF	(j!=k+1)
				THEN	error("\7j=%d.",j);
				FI
				k += 1;
			OD
			IF	(!rbin(&r,it))
			THEN	error("\7i=%d.",i);
			FI
			IF	(trace)
			THEN	printf("in+:%s\n",it);
			FI
		FI
	OD

END

/* end: rbtest.c */
