util: memstream: add fflush support

Flush support is needed by the Rust code, which will switch from
its own memstream to u_memstream in a future patch.

Signed-off-by: Daniel Almeida <daniel.almeida@collabora.com>
Reviewed-by: Faith Ekstrand <faith.ekstrand@collabora.com>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/30594>
This commit is contained in:
Daniel Almeida
2024-08-08 16:48:43 -03:00
committed by Marge Bot
parent e6c5dcd295
commit 3136d1c8c6
2 changed files with 36 additions and 13 deletions
+33 -13
View File
@@ -53,6 +53,8 @@ u_memstream_open(struct u_memstream *mem, char **bufp, size_t *sizep)
success = f != NULL;
if (success)
{
*bufp = NULL;
*sizep = 0;
mem->f = f;
mem->bufp = bufp;
mem->sizep = sizep;
@@ -68,27 +70,45 @@ u_memstream_open(struct u_memstream *mem, char **bufp, size_t *sizep)
#endif
}
#ifdef _WIN32
static void
u_memstream_update_buffer(struct u_memstream *mem)
{
FILE *const f = mem->f;
long size = ftell(f);
if (size > 0) {
/* reserve space for the null terminator as well */
if (*mem->bufp == NULL || *mem->sizep < size + 1)
*mem->bufp = realloc(*mem->bufp, size + 1);
fseek(f, 0, SEEK_SET);
fread(*mem->bufp, 1, size, f);
(*mem->bufp)[size] = '\0';
}
*mem->sizep = size;
}
#endif /* _WIN32 */
void
u_memstream_close(struct u_memstream *mem)
{
FILE *const f = mem->f;
#ifdef _WIN32
long size = ftell(f);
if (size > 0) {
/* reserve space for the null terminator */
char *buf = malloc(size + 1);
fseek(f, 0, SEEK_SET);
fread(buf, 1, size, f);
/* insert null terminator */
buf[size] = '\0';
*mem->bufp = buf;
*mem->sizep = size;
}
u_memstream_update_buffer(mem);
remove(mem->temp);
#endif
fclose(f);
}
int
u_memstream_flush(struct u_memstream *mem)
{
#ifndef _WIN32
return fflush(mem->f);
#else
u_memstream_update_buffer(mem);
return 0;
#endif /* _WIN32 */
}
+3
View File
@@ -65,6 +65,9 @@ u_memstream_get(const struct u_memstream *mem)
return mem->f;
}
int
u_memstream_flush(struct u_memstream *mem);
#ifdef __cplusplus
}
#endif