2 Line based I/O over fds
4 Copyright (C) Amitay Isaacs 2018
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, see <http://www.gnu.org/licenses/>.
24 #include "lib/util/sys_rw.h"
26 #include "common/line.h"
28 struct line_read_state
{
29 line_process_fn_t callback
;
32 size_t hint
, len
, offset
;
36 static bool line_read_one(char *buf
, size_t start
, size_t len
, size_t *pos
)
40 for (i
=start
; i
<len
; i
++) {
41 if (buf
[i
] == '\n' || buf
[i
] == '\0') {
50 static int line_read_process(struct line_read_state
*state
)
59 ok
= line_read_one(state
->buf
, start
, state
->offset
, &pos
);
64 state
->buf
[pos
] = '\0';
65 state
->num_lines
+= 1;
67 ret
= state
->callback(state
->buf
+ start
, state
->private_data
);
76 if (pos
+1 < state
->offset
) {
79 state
->offset
- (pos
+1));
81 state
->offset
-= (pos
+1);
90 line_process_fn_t callback
,
94 struct line_read_state state
;
100 state
= (struct line_read_state
) {
101 .callback
= callback
,
102 .private_data
= private_data
,
110 if (state
.offset
== state
.len
) {
111 state
.len
+= state
.hint
;
112 state
.buf
= talloc_realloc_size(mem_ctx
,
115 if (state
.buf
== NULL
) {
121 state
.buf
+ state
.offset
,
122 state
.len
- state
.offset
);
132 ret
= line_read_process(&state
);
134 if (num_lines
!= NULL
) {
135 *num_lines
= state
.num_lines
;
141 if (num_lines
!= NULL
) {
142 *num_lines
= state
.num_lines
;