split.c (1409B)
1 /* 2 * Copyright (c) 2023 Jacob R. Edwards <jacob@jacobedwards.org> 3 * 4 * Permission to use, copy, modify, and distribute this software for any 5 * purpose with or without fee is hereby granted, provided that the above 6 * copyright notice and this permission notice appear in all copies. 7 * 8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 */ 16 17 #include <string.h> 18 19 #include "buf.h" 20 #include "list.h" 21 22 struct list * 23 split(struct buf *buf, int delim) 24 { 25 struct list *list; 26 struct item *item; 27 size_t l; 28 char *c, *n; 29 30 list = newlist(NULL); 31 if (!list) 32 return NULL; 33 34 c = buf->data; 35 l = buf->len; 36 while (c && l) { 37 n = memchr(c, delim, l); 38 if (!n) { 39 if (bufenlarge(buf, 1)) { 40 freelist(list); 41 return NULL; 42 } 43 n = c + l + 1; 44 } 45 46 *n++ = 0; 47 if (n - c > l) 48 l = 0; 49 else 50 l -= n - c; 51 52 item = newitem(c); 53 if (!item) { 54 freelist(list); 55 return NULL; 56 } 57 additem(item, list, list->last); 58 c = n; 59 } 60 61 return list; 62 }