Krolyxon
Commit c9a887d

Branches

Refs →

nsxivutil.c

77 lines · 1.8 KB · C

1/* sxiv: util.c
2 * Copyright (c) 2011 Bert Muennich <muennich at informatik.hu-berlin.de>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 */
18
19#include <stdlib.h>
20#include <stdio.h>
21
22#include "options.h"
23#include "util.h"
24
25void cleanup();
26
27void* s_malloc(size_t size) {
28 void *ptr;
29
30 if (!(ptr = malloc(size)))
31 die("could not allocate memory");
32 return ptr;
33}
34
35void* s_realloc(void *ptr, size_t size) {
36 if (!(ptr = realloc(ptr, size)))
37 die("could not allocate memory");
38 return ptr;
39}
40
41void warn(const char* fmt, ...) {
42 va_list args;
43
44 if (!fmt || options->quiet)
45 return;
46
47 va_start(args, fmt);
48 fprintf(stderr, "sxiv: warning: ");
49 vfprintf(stderr, fmt, args);
50 fprintf(stderr, "\n");
51 va_end(args);
52}
53
54void die(const char* fmt, ...) {
55 va_list args;
56
57 if (!fmt)
58 return;
59
60 va_start(args, fmt);
61 fprintf(stderr, "sxiv: error: ");
62 vfprintf(stderr, fmt, args);
63 fprintf(stderr, "\n");
64 va_end(args);
65
66 cleanup();
67 exit(1);
68}
69
70void size_readable(float *size, const char **unit) {
71 const char *units[] = { "", "K", "M", "G" };
72 int i;
73
74 for (i = 0; i < LEN(units) && *size > 1024; ++i)
75 *size /= 1024;
76 *unit = units[MIN(i, LEN(units) - 1)];
77}