Path: blob/main/tools/build/cross-build/fgetwln_fallback.c
39507 views
/*1* Copyright 2012 Guillem Jover <[email protected]>2*3* Redistribution and use in source and binary forms, with or without4* modification, are permitted provided that the following conditions5* are met:6* 1. Redistributions of source code must retain the above copyright7* notice, this list of conditions and the following disclaimer.8* 2. Redistributions in binary form must reproduce the above copyright9* notice, this list of conditions and the following disclaimer in the10* documentation and/or other materials provided with the distribution.11* 3. The name of the author may not be used to endorse or promote products12* derived from this software without specific prior written permission.13*14* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,15* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY16* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL17* THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,18* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,19* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;20* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,21* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR22* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF23* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.24*/2526#include <sys/cdefs.h>2728#include <stdlib.h>29#include <stdio.h>30#include <wchar.h>3132#include "local-link.h"3334struct filewbuf {35FILE *fp;36wchar_t *wbuf;37size_t len;38};3940#define FILEWBUF_INIT_LEN 12841#define FILEWBUF_POOL_ITEMS 324243static struct filewbuf fb_pool[FILEWBUF_POOL_ITEMS];44static int fb_pool_cur;4546wchar_t *47fgetwln(FILE *stream, size_t *lenp)48{49struct filewbuf *fb;50wint_t wc;51size_t wused = 0;5253/* Try to diminish the possibility of several fgetwln() calls being54* used on different streams, by using a pool of buffers per file. */55fb = &fb_pool[fb_pool_cur];56if (fb->fp != stream && fb->fp != NULL) {57fb_pool_cur++;58fb_pool_cur %= FILEWBUF_POOL_ITEMS;59fb = &fb_pool[fb_pool_cur];60}61fb->fp = stream;6263while ((wc = fgetwc(stream)) != WEOF) {64if (!fb->len || wused >= fb->len) {65wchar_t *wp;6667if (fb->len)68fb->len *= 2;69else70fb->len = FILEWBUF_INIT_LEN;7172wp = reallocarray(fb->wbuf, fb->len, sizeof(wchar_t));73if (wp == NULL) {74wused = 0;75break;76}77fb->wbuf = wp;78}7980fb->wbuf[wused++] = wc;8182if (wc == L'\n')83break;84}8586*lenp = wused;87return wused ? fb->wbuf : NULL;88}8990libbsd_link_warning(fgetwln,91"This function cannot be safely ported, use fgetwc(3) "92"instead, as it is supported by C99 and POSIX.1-2001.")939495