Move src to src/lib, include to src/include, test to src/test.
[deb_shairplay.git] / src / lib / utils.c
CommitLineData
2340bcd3
JVH
1#include <stdlib.h>
2#include <stdio.h>
3#include <string.h>
4
5char *
6utils_strsep(char **stringp, const char *delim)
7{
8 char *original;
9 char *strptr;
10
11 if (*stringp == NULL) {
12 return NULL;
13 }
14
15 original = *stringp;
16 strptr = strstr(*stringp, delim);
17 if (strptr == NULL) {
18 *stringp = NULL;
19 return original;
20 }
21 *strptr = '\0';
22 *stringp = strptr+strlen(delim);
23 return original;
24}
25
26int
27utils_read_file(char **dst, const char *filename)
28{
29 FILE *stream;
30 int filesize;
31 char *buffer;
32 int read_bytes;
33
34 /* Open stream for reading */
35 stream = fopen(filename, "rb");
36 if (!stream) {
37 return -1;
38 }
39
40 /* Find out file size */
41 fseek(stream, 0, SEEK_END);
42 filesize = ftell(stream);
43 fseek(stream, 0, SEEK_SET);
44
45 /* Allocate one extra byte for zero */
46 buffer = malloc(filesize+1);
47 if (!buffer) {
48 fclose(stream);
49 return -2;
50 }
51
52 /* Read data in a loop to buffer */
53 read_bytes = 0;
54 do {
55 int ret = fread(buffer+read_bytes, 1,
56 filesize-read_bytes, stream);
57 if (ret == 0) {
58 break;
59 }
60 read_bytes += ret;
61 } while (read_bytes < filesize);
62
63 /* Add final null byte and close stream */
64 buffer[read_bytes] = '\0';
65 fclose(stream);
66
67 /* If read didn't finish, return error */
68 if (read_bytes != filesize) {
69 free(buffer);
70 return -3;
71 }
72
73 /* Return buffer */
74 *dst = buffer;
75 return filesize;
76}
77
78int
79utils_hwaddr_raop(char *str, int strlen, const char *hwaddr, int hwaddrlen)
80{
81 int i,j;
82
83 /* Check that our string is long enough */
84 if (strlen == 0 || strlen < 2*hwaddrlen+1)
85 return -1;
86
87 /* Convert hardware address to hex string */
88 for (i=0,j=0; i<hwaddrlen; i++) {
89 int hi = (hwaddr[i]>>4) & 0x0f;
90 int lo = hwaddr[i] & 0x0f;
91
92 if (hi < 10) str[j++] = '0' + hi;
93 else str[j++] = 'A' + hi-10;
94 if (lo < 10) str[j++] = '0' + lo;
95 else str[j++] = 'A' + lo-10;
96 }
97
98 /* Add string terminator */
99 str[j++] = '\0';
100 return j;
101}
102
103int
104utils_hwaddr_airplay(char *str, int strlen, const char *hwaddr, int hwaddrlen)
105{
106 int i,j;
107
108 /* Check that our string is long enough */
109 if (strlen == 0 || strlen < 2*hwaddrlen+hwaddrlen)
110 return -1;
111
112 /* Convert hardware address to hex string */
113 for (i=0,j=0; i<hwaddrlen; i++) {
114 int hi = (hwaddr[i]>>4) & 0x0f;
115 int lo = hwaddr[i] & 0x0f;
116
117 if (hi < 10) str[j++] = '0' + hi;
118 else str[j++] = 'a' + hi-10;
119 if (lo < 10) str[j++] = '0' + lo;
120 else str[j++] = 'a' + lo-10;
121
122 str[j++] = ':';
123 }
124
125 /* Add string terminator */
126 if (j != 0) j--;
127 str[j++] = '\0';
128 return j;
129}
130