chiark / gitweb /
Assume initial digits in a track name are a sort key even without the
[disorder] / lib / snprintf.c
... / ...
CommitLineData
1/*
2 * This file is part of DisOrder
3 * Copyright (C) 2004, 2007, 2008 Richard Kettlewell
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18 * USA
19 */
20
21#define NO_MEMORY_ALLOCATION
22/* because used from log.c */
23
24#include "common.h"
25
26#include <stdarg.h>
27#include <stddef.h>
28
29#include "printf.h"
30#include "sink.h"
31
32struct fixedstr_sink {
33 struct sink s;
34 char *buffer;
35 int nbytes;
36 size_t size;
37};
38
39static int fixedstr_write(struct sink *f, const void *buffer, int nbytes) {
40 struct fixedstr_sink *s = (struct fixedstr_sink *)f;
41 int count;
42
43 if((size_t)s->nbytes < s->size) {
44 if((size_t)nbytes > s->size - s->nbytes)
45 count = s->size - s->nbytes;
46 else
47 count = nbytes;
48 memcpy(s->buffer + s->nbytes, buffer, count);
49 }
50 s->nbytes += nbytes;
51 return 0;
52}
53
54int byte_vsnprintf(char buffer[],
55 size_t bufsize,
56 const char *fmt,
57 va_list ap) {
58 struct fixedstr_sink s;
59 int n, m;
60
61 /* We have to make a sink directly here, since we can't safely do memory
62 * allocation here (we might be formatting the error message from a failed
63 * memory allocation) */
64 s.s.write = fixedstr_write;
65 s.buffer = buffer;
66 s.nbytes = 0;
67 s.size = bufsize;
68 n = byte_vsinkprintf(&s.s, fmt, ap);
69 if(bufsize) {
70 /* add the null terminator (even if the printf failed) */
71 m = s.nbytes;
72 if((size_t)m >= bufsize) m = bufsize - 1;
73 buffer[m] = 0;
74 }
75 return n;
76}
77
78int byte_snprintf(char buffer[], size_t bufsize, const char *fmt, ...) {
79 int n;
80 va_list ap;
81
82 va_start(ap, fmt);
83 n = byte_vsnprintf(buffer, bufsize, fmt, ap);
84 va_end(ap);
85 return n;
86}
87
88/*
89Local Variables:
90c-basic-offset:2
91comment-column:40
92End:
93*/