cmus-remote: Read command results
[cmus.git] / utils.h
blobad77d3f66d7ee006b1f9eff3fb779b5ba64d263f
1 /*
2 * Copyright 2004 Timo Hirvonen
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
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
17 * 02111-1307, USA.
20 #ifndef _UTILS_H
21 #define _UTILS_H
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 #include <time.h>
29 #include <inttypes.h>
31 static inline int min(int a, int b)
33 return a < b ? a : b;
36 static inline int max(int a, int b)
38 return a > b ? a : b;
41 static inline int clamp(int val, int minval, int maxval)
43 if (val < minval)
44 return minval;
45 if (val > maxval)
46 return maxval;
47 return val;
50 static inline int scale_from_percentage(int val, int max_val)
52 if (val < 0)
53 return (val * max_val - 50) / 100;
54 return (val * max_val + 50) / 100;
57 static inline int scale_to_percentage(int val, int max_val)
59 int half = max_val / 2;
61 if (max_val <= 0)
62 return 100;
64 if (val < 0)
65 return (val * 100 - half) / max_val;
66 return (val * 100 + half) / max_val;
69 static inline int str_to_int(const char *str, long int *val)
71 char *end;
73 *val = strtol(str, &end, 10);
74 if (*str == 0 || *end != 0)
75 return -1;
76 return 0;
79 static inline time_t file_get_mtime(const char *filename)
81 struct stat s;
83 /* stat follows symlinks, lstat does not */
84 if (stat(filename, &s) == -1)
85 return -1;
86 return s.st_mtime;
89 static inline void ns_sleep(int ns)
91 struct timespec req;
93 req.tv_sec = 0;
94 req.tv_nsec = ns;
95 nanosleep(&req, NULL);
98 static inline void us_sleep(int us)
100 ns_sleep(us * 1e3);
103 static inline void ms_sleep(int ms)
105 ns_sleep(ms * 1e6);
108 static inline int is_url(const char *name)
110 return strncmp(name, "http://", 7) == 0;
113 static inline uint32_t read_le32(const char *buf)
115 const unsigned char *b = (const unsigned char *)buf;
117 return b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24);
120 static inline uint16_t read_le16(const char *buf)
122 const unsigned char *b = (const unsigned char *)buf;
124 return b[0] | (b[1] << 8);
127 #endif