oceans_s1_common.c (1771B)
1 /* 2 * libdivecomputer 3 * 4 * Copyright (C) 2022 Jef Driesen 5 * 6 * This library is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU Lesser General Public 8 * License as published by the Free Software Foundation; either 9 * version 2.1 of the License, or (at your option) any later version. 10 * 11 * This library 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 GNU 14 * Lesser General Public License for more details. 15 * 16 * You should have received a copy of the GNU Lesser General Public 17 * License along with this library; if not, write to the Free Software 18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 19 * MA 02110-1301 USA 20 */ 21 22 #include <string.h> // memcmp, memcpy 23 #include <stdlib.h> // malloc, free 24 #include <stddef.h> 25 26 #include "oceans_s1_common.h" 27 28 int 29 oceans_s1_getline (char **line, size_t *linelen, const unsigned char **data, size_t *size) 30 { 31 if (line == NULL || linelen == NULL || data == NULL || size == NULL) 32 return -1; 33 34 if (*size == 0) 35 return -1; 36 37 // Find the end of the line. 38 unsigned int strip = 0; 39 const unsigned char *p = *data, *end = p + *size; 40 while (p != end) { 41 unsigned char c = *p++; 42 if (c == '\r' || c == '\n') { 43 strip = 1; 44 break; 45 } 46 } 47 48 // Get the length of the line. 49 size_t len = p - *data; 50 51 // Resize the buffer (if necessary). 52 if (*line == NULL || len + 1 > *linelen) { 53 char *buf = (char *) malloc (len + 1); 54 if (buf == NULL) 55 return -1; 56 free (*line); 57 *line = buf; 58 *linelen = len + 1; 59 } 60 61 // Copy the data. 62 memcpy (*line, *data, len - strip); 63 (*line)[len - strip] = 0; 64 *data += len; 65 *size -= len; 66 67 return len - strip; 68 }