/*
 * lines.c
 *
 * Line class
 *
 * $Id :$
 * $Log:$
 *
 */

#include "defs.h"
#include "lines.h"
#include "memory.h"
#include "errors.h"

/*
 * Line_New()
 *
 * PURPOSE: constructor for Line class
 *
 * INPUTS : string - ptr to sequence of chars to use as contents of this
 *                   line. A copy is not mode, so the source string must
 *                   exist as long as the Line object.
 *
 *          len - number of characters in this line. The source string is
 *                not necessarily NULL terminated - len specifies the end
 *                of the string. This is so we can slice up a read-only
 *                buffer into a series of lines
 *
 * RETURNS: if all goes well, a ptr to a freshly allocated Line with the
 *          contents of your choosing.Otherwise NULL.
 *          Possible causes of failure include lack of memory or trying to
 *          exceed the maximum line length (MAX_LINE_LEN). We will need to
 *          differentiate these two eventually . . .
 */

LINE_PTR
Line_New( STRPTR string, LINE_LEN_TYPE len, ULONG *err_code )
{
	LINE_PTR new_line;

	if( len > MAX_LINE_LEN )
	{
		/* line too long */
		*err_code = ERR_LINE_TOO_LONG;
		return NULL;
	}

	if( new_line = (LINE_PTR) Memory_Alloc( sizeof( LINE_TYPE ) ) )
	{
		new_line->Contents = string;
		new_line->Length = len;
	}
	else
		*err_code = ERR_NO_MEMORY;

	return new_line;
}


/*
 * Line_Dispose()
 *
 * PURPOSE: destructor for Line class.
 *
 * INPUTS:  line - the Line object to kill.
 *
 * RETURNS: None
 */

VOID
Line_Dispose( LINE_PTR line )
{
	if( line )
		Memory_Free( line, sizeof( LINE_TYPE ) );
}



/*
 * Line_GetContents()
 *
 * PURPOSE: Get a pointer to the contents of a Line object
 *
 * INPUTS : line - the Line to find the contents of.
 *
 * RETURNS: a pointer to the sequence of chars that make up this line.
 *          Although this is returned as a STRPTR, it must be noted
 *          that the 'string' is not necessarily NULL terminated.
 *          Use with care!
 */

STRPTR
Line_GetContents( LINE_PTR line )
{
	return line->Contents;
}


/*
 * Line_GetLength()
 *
 * PURPOSE: Find the length in chars of a Line.
 *
 * INPUTS : line - the Line to find the length of.
 *
 * RETURNS: the length of the desired line.
 */


LINE_LEN_TYPE
Line_GetLength( LINE_PTR line )
{
	return line->Length;
}


#ifdef DEBUG

#include <dos/dos.h>
#include <proto/dos.h>

/*
 * Line_FPuts()
 *
 * PURPOSE: Dump the contents of a line to a file. This is provided
 *          for debugging/testing purposes since Line contents may not
 *          be NULL terminated so cannot just be printed with a straight
 *          FPuts() or FPrintf().
 *
 * INPUTS:  line - the line in question.
 *
 * RETURNS: None.
 */

VOID
Line_FPuts( BPTR file, LINE_PTR line )
{
	register LINE_LEN_TYPE i      = line->Length;
	register STRPTR        string = line->Contents;

	for( ; *string && i ; string++, i-- )
		FPutC( file, *string );
}

#endif /* DEBUG */
