|
| 1 | +/* |
| 2 | + * io.c - I/O API based on vector for dynamic allocation |
| 3 | + * |
| 4 | + * SPDX-License: GPL-3.0-or-later |
| 5 | + * |
| 6 | + * Copyright (C) 2026 Dawid Papiewski |
| 7 | + * This program is free software: you can redistribute it and/or modify it |
| 8 | + * under the terms of the GNU General Public License as published by the |
| 9 | + * Free Software Foundation, either version 3 of the License, or (at your option) |
| 10 | + * any later version. |
| 11 | + * |
| 12 | + * This program is distributed in the hope that it will be useful, but WITHOUT |
| 13 | + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
| 14 | + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. |
| 15 | + * You should have received a copy of the GNU General Public License along with this |
| 16 | + * program. If not, see <https://www.gnu.org/licenses/>. |
| 17 | + * |
| 18 | + */ |
| 19 | +#include <stdio.h> |
| 20 | +#include <YAVL/vec.h> |
| 21 | +#include <YAVL/io.h> |
| 22 | +#include "namespace.h" |
| 23 | + |
| 24 | +NS(vec_res_t) NS(io_fromstream)(NS(vec_t) *const vec, FILE *const stream) { |
| 25 | + if(vec->allign != sizeof(char)) return NS_UPPER(VEC_RES_FAIL); |
| 26 | + for( |
| 27 | + size_t cr=1; |
| 28 | + cr!=0; |
| 29 | + cr=fread( |
| 30 | + /*__ptr=*/ vec->data+(vec->len*vec->allign), |
| 31 | + /*__size=*/ vec->allign, |
| 32 | + /*__n=*/ vec->reservd-vec->len, |
| 33 | + /*__stream=*/ stream |
| 34 | + ) |
| 35 | + ) { |
| 36 | + vec->len += cr; |
| 37 | + // Autoscale |
| 38 | + NS(vec_res_t) res; |
| 39 | + if(vec->reservd <= vec->len) res = NS(vec_scale)(vec, vec->reservd*2); |
| 40 | + if(res != NS_UPPER(VEC_RES_OK)) return res; |
| 41 | + } |
| 42 | + NS(vec_fit)(vec); |
| 43 | + return NS_UPPER(VEC_RES_OK); |
| 44 | +} |
| 45 | + |
| 46 | +NS(vec_res_t) NS(io_readline)(NS(vec_t) *const vec, FILE *const stream) { |
| 47 | + if(vec->allign != sizeof(char)) return NS_UPPER(VEC_RES_FAIL); |
| 48 | + for( |
| 49 | + int ch=0; |
| 50 | + ch!='\n'||ch==EOF; |
| 51 | + ch=getc(stream) |
| 52 | + ) { |
| 53 | + char c = ch; NS(vec_res_t) res; |
| 54 | + if((res = NS(vec_push)(vec,&c,1)) != NS_UPPER(VEC_RES_OK)) |
| 55 | + return res; |
| 56 | + } |
| 57 | + const char trail[] = "\n"; |
| 58 | + NS(vec_push)(vec, trail, sizeof(trail)/sizeof(trail[0])); |
| 59 | + return NS(vec_fit)(vec); |
| 60 | +} |
0 commit comments