2 * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 FILE_LICENCE ( GPL2_OR_LATER );
33 #include <ipxe/linebuf.h>
36 * Retrieve buffered-up line
38 * @v linebuf Line buffer
39 * @ret line Buffered line, or NULL if no line ready to read
41 char * buffered_line ( struct line_buffer *linebuf ) {
42 return ( linebuf->ready ? linebuf->data : NULL );
46 * Discard line buffer contents
48 * @v linebuf Line buffer
50 void empty_line_buffer ( struct line_buffer *linebuf ) {
51 free ( linebuf->data );
58 * Buffer up received data by lines
60 * @v linebuf Line buffer
61 * @v data New data to add
62 * @v len Length of new data to add
63 * @ret len Consumed length, or negative error number
65 * After calling line_buffer(), use buffered_line() to determine
66 * whether or not a complete line is available. Carriage returns and
67 * newlines will have been stripped, and the line will be
68 * NUL-terminated. This buffered line is valid only until the next
69 * call to line_buffer() (or to empty_line_buffer()).
71 * Note that line buffers use dynamically allocated storage; you
72 * should call empty_line_buffer() before freeing a @c struct @c
75 ssize_t line_buffer ( struct line_buffer *linebuf,
76 const char *data, size_t len ) {
82 /* Free any completed line from previous iteration */
84 empty_line_buffer ( linebuf );
86 /* Search for line terminator */
87 if ( ( eol = memchr ( data, '\n', len ) ) ) {
88 consume = ( eol - data + 1 );
93 /* Reallocate data buffer and copy in new data */
94 new_len = ( linebuf->len + consume );
95 new_data = realloc ( linebuf->data, ( new_len + 1 ) );
98 memcpy ( ( new_data + linebuf->len ), data, consume );
99 new_data[new_len] = '\0';
100 linebuf->data = new_data;
101 linebuf->len = new_len;
103 /* If we have reached end of line, trim the line and mark as ready */
105 linebuf->data[--linebuf->len] = '\0'; /* trim NL */
106 if ( linebuf->data[linebuf->len - 1] == '\r' )
107 linebuf->data[--linebuf->len] = '\0'; /* trim CR */