1 /*	$OpenBSD$	*/
2 /*
3  * Copyright (c) 2011 Alexandre Ratchov <alex@caoua.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <unistd.h>
21 
22 #include "debug.h"
23 #include "bsd-compat.h"
24 
25 #ifdef DEBUG
26 /*
27  * debug level, -1 means uninitialized
28  */
29 int _sndio_debug = -1;
30 
31 void
_sndio_debug_init(void)32 _sndio_debug_init(void)
33 {
34 	char *dbg;
35 
36 	if (_sndio_debug < 0) {
37 		dbg = issetugid() ? NULL : getenv("SNDIO_DEBUG");
38 		if (!dbg || sscanf(dbg, "%u", &_sndio_debug) != 1)
39 			_sndio_debug = 0;
40 	}
41 }
42 #endif
43 
44 const char *
_sndio_parsetype(const char * str,char * type)45 _sndio_parsetype(const char *str, char *type)
46 {
47 	while (*type) {
48 		if (*type != *str)
49 			return NULL;
50 		type++;
51 		str++;
52 	}
53 	if (*str >= 'a' && *str <= 'z')
54 		return NULL;
55 	return str;
56 }
57 
58 const char *
_sndio_parsenum(const char * str,unsigned int * num,unsigned int max)59 _sndio_parsenum(const char *str, unsigned int *num, unsigned int max)
60 {
61 	const char *p = str;
62 	unsigned int dig, maxq, maxr, val;
63 
64 	val = 0;
65 	maxq = max / 10;
66 	maxr = max % 10;
67 	for (;;) {
68 		dig = *p - '0';
69 		if (dig >= 10)
70 			break;
71 		if (val > maxq || (val == maxq && dig > maxr)) {
72 			DPRINTF("%s: number too large\n", str);
73 			return NULL;
74 		}
75 		val = val * 10 + dig;
76 		p++;
77 	}
78 	if (p == str) {
79 		DPRINTF("%s: number expected\n", str);
80 		return NULL;
81 	}
82 	*num = val;
83 	return p;
84 }
85