| 1 |
/* line-reader-private.h |
| 2 |
* |
| 3 |
* Copyright 2015-2023 Christian Hergert <[email protected]> |
| 4 |
* |
| 5 |
* This program is free software: you can redistribute it and/or modify |
| 6 |
* it under the terms of the GNU General Public License as published by |
| 7 |
* the Free Software Foundation, either version 3 of the License, or |
| 8 |
* (at your option) any later version. |
| 9 |
* |
| 10 |
* This program is distributed in the hope that it will be useful, |
| 11 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 |
* GNU General Public License for more details. |
| 14 |
* |
| 15 |
* You should have received a copy of the GNU General Public License |
| 16 |
* along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
* |
| 18 |
* SPDX-License-Identifier: GPL-3.0-or-later |
| 19 |
*/ |
| 20 |
|
| 21 |
#pragma once |
| 22 |
|
| 23 |
#include <glib.h> |
| 24 |
#include <string.h> |
| 25 |
|
| 26 |
G_BEGIN_DECLS |
| 27 |
|
| 28 |
typedef struct _LineReader |
| 29 |
{ |
| 30 |
char *contents; |
| 31 |
gsize length; |
| 32 |
gssize pos; |
| 33 |
} LineReader; |
| 34 |
|
| 35 |
static inline void |
| 36 |
line_reader_init (LineReader *reader, |
| 37 |
char *contents, |
| 38 |
gssize length) |
| 39 |
{ |
| 40 |
g_assert (reader != NULL); |
| 41 |
|
| 42 |
if (length < 0) |
| 43 |
length = strlen (contents); |
| 44 |
|
| 45 |
if (contents != NULL) |
| 46 |
{ |
| 47 |
reader->contents = contents; |
| 48 |
reader->length = length; |
| 49 |
reader->pos = 0; |
| 50 |
} |
| 51 |
else |
| 52 |
{ |
| 53 |
reader->contents = NULL; |
| 54 |
reader->length = 0; |
| 55 |
reader->pos = 0; |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
static inline char * |
| 60 |
line_reader_next (LineReader *reader, |
| 61 |
gsize *length) |
| 62 |
{ |
| 63 |
char *ret = NULL; |
| 64 |
|
| 65 |
g_assert (reader != NULL); |
| 66 |
g_assert (length != NULL); |
| 67 |
|
| 68 |
if ((reader->contents == NULL) || (reader->pos >= reader->length)) |
| 69 |
{ |
| 70 |
*length = 0; |
| 71 |
return NULL; |
| 72 |
} |
| 73 |
|
| 74 |
ret = &reader->contents [reader->pos]; |
| 75 |
|
| 76 |
for (; reader->pos < reader->length; reader->pos++) |
| 77 |
{ |
| 78 |
if (reader->contents [reader->pos] == '\n') |
| 79 |
{ |
| 80 |
*length = &reader->contents [reader->pos] - ret; |
| 81 |
/* Ingore the \r in \r\n if provided */ |
| 82 |
if (*length > 0 && reader->pos > 0 && reader->contents [reader->pos - 1] == '\r') |
| 83 |
(*length)--; |
| 84 |
reader->pos++; |
| 85 |
return ret; |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
*length = &reader->contents [reader->pos] - ret; |
| 90 |
|
| 91 |
return ret; |
| 92 |
} |
| 93 |
|
| 94 |
G_END_DECLS |