linebuf.c
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 FILE_LICENCE ( GPL2_OR_LATER );
00020
00021
00022
00023
00024
00025
00026
00027
00028 #include <stdint.h>
00029 #include <string.h>
00030 #include <stdlib.h>
00031 #include <errno.h>
00032 #include <gpxe/linebuf.h>
00033
00034
00035
00036
00037
00038
00039
00040 char * buffered_line ( struct line_buffer *linebuf ) {
00041 return ( linebuf->ready ? linebuf->data : NULL );
00042 }
00043
00044
00045
00046
00047
00048
00049 void empty_line_buffer ( struct line_buffer *linebuf ) {
00050 free ( linebuf->data );
00051 linebuf->data = NULL;
00052 linebuf->len = 0;
00053 linebuf->ready = 0;
00054 }
00055
00056
00057
00058
00059
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074 ssize_t line_buffer ( struct line_buffer *linebuf,
00075 const char *data, size_t len ) {
00076 const char *eol;
00077 size_t consume;
00078 size_t new_len;
00079 char *new_data;
00080
00081
00082 if ( linebuf->ready )
00083 empty_line_buffer ( linebuf );
00084
00085
00086 if ( ( eol = memchr ( data, '\n', len ) ) ) {
00087 consume = ( eol - data + 1 );
00088 } else {
00089 consume = len;
00090 }
00091
00092
00093 new_len = ( linebuf->len + consume );
00094 new_data = realloc ( linebuf->data, ( new_len + 1 ) );
00095 if ( ! new_data )
00096 return -ENOMEM;
00097 memcpy ( ( new_data + linebuf->len ), data, consume );
00098 new_data[new_len] = '\0';
00099 linebuf->data = new_data;
00100 linebuf->len = new_len;
00101
00102
00103 if ( eol ) {
00104 linebuf->data[--linebuf->len] = '\0';
00105 if ( linebuf->data[linebuf->len - 1] == '\r' )
00106 linebuf->data[--linebuf->len] = '\0';
00107 linebuf->ready = 1;
00108 }
00109
00110 return consume;
00111 }