xref: /illumos-gate/usr/src/lib/libdemangle/common/strview.c (revision 20a7641f9918de8574b8b3b47dbe35c4bfc78df1)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2019 Joyent, Inc.
14  */
15 
16 #include <string.h>
17 #include <sys/types.h>
18 #include <sys/debug.h>
19 #include "strview.h"
20 
21 void
22 sv_init_sv(strview_t *sv, const strview_t *src)
23 {
24 	*sv = *src;
25 }
26 
27 void
28 sv_init_sv_range(strview_t *sv, const strview_t *src, size_t len)
29 {
30 	VERIFY3U(sv_remaining(src), >=, len);
31 
32 	sv->sv_first = src->sv_first;
33 	sv->sv_last = src->sv_first + len;
34 	sv->sv_rem = len;
35 }
36 
37 void
38 sv_init_str(strview_t *sv, const char *first, const char *last)
39 {
40 	if (last == NULL)
41 		last = first + strlen(first);
42 
43 	VERIFY3P(first, <=, last);
44 	sv->sv_first = first;
45 	sv->sv_last = last;
46 	sv->sv_rem = (size_t)(uintptr_t)(sv->sv_last - sv->sv_first);
47 }
48 
49 size_t
50 sv_remaining(const strview_t *sv)
51 {
52 	return (sv->sv_rem);
53 }
54 
55 boolean_t
56 sv_consume_if_c(strview_t *sv, char c)
57 {
58 	if (sv->sv_rem < 1 || *sv->sv_first != c)
59 		return (B_FALSE);
60 
61 	sv->sv_first++;
62 	sv->sv_rem--;
63 	return (B_TRUE);
64 }
65 
66 boolean_t
67 sv_consume_if(strview_t *sv, const char *str)
68 {
69 	size_t slen = strlen(str);
70 
71 	if (sv->sv_rem < slen)
72 		return (B_FALSE);
73 	if (strncmp(sv->sv_first, str, slen) != 0)
74 		return (B_FALSE);
75 
76 	sv->sv_first += slen;
77 	sv->sv_rem -= slen;
78 	return (B_TRUE);
79 }
80 
81 char
82 sv_peek(const strview_t *sv, ssize_t n)
83 {
84 	const char *p;
85 
86 	p = (n >= 0) ? sv->sv_first + n : sv->sv_last + n;
87 	return ((p >= sv->sv_first && p < sv->sv_last) ? *p : '\0');
88 }
89 
90 char
91 sv_consume_c(strview_t *sv)
92 {
93 	char c = '\0';
94 
95 	if (sv->sv_first < sv->sv_last) {
96 		c = *sv->sv_first++;
97 		sv->sv_rem--;
98 	}
99 	return (c);
100 }
101 
102 void
103 sv_consume_n(strview_t *sv, size_t n)
104 {
105 	VERIFY3U(sv->sv_rem, >=, n);
106 	sv->sv_first += n;
107 	sv->sv_rem -= n;
108 }
109