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/debug.h>
18 #include "strview.h"
19 
20 void
21 sv_init_sv(strview_t *sv, const strview_t *src)
22 {
23 	*sv = *src;
24 }
25 
26 void
27 sv_init_sv_range(strview_t *sv, const strview_t *src, size_t len)
28 {
29 	VERIFY3U(sv_remaining(src), >=, len);
30 
31 	sv->sv_first = src->sv_first;
32 	sv->sv_last = src->sv_first + len;
33 	sv->sv_rem = len;
34 }
35 
36 void
37 sv_init_str(strview_t *sv, const char *first, const char *last)
38 {
39 	if (last == NULL)
40 		last = first + strlen(first);
41 
42 	VERIFY3P(first, <=, last);
43 	sv->sv_first = first;
44 	sv->sv_last = last;
45 	sv->sv_rem = (size_t)(uintptr_t)(sv->sv_last - sv->sv_first);
46 }
47 
48 size_t
49 sv_remaining(const strview_t *sv)
50 {
51 	return (sv->sv_rem);
52 }
53 
54 boolean_t
55 sv_consume_if_c(strview_t *sv, char c)
56 {
57 	if (sv->sv_rem < 1 || *sv->sv_first != c)
58 		return (B_FALSE);
59 
60 	sv->sv_first++;
61 	sv->sv_rem--;
62 	return (B_TRUE);
63 }
64 
65 boolean_t
66 sv_consume_if(strview_t *sv, const char *str)
67 {
68 	size_t slen = strlen(str);
69 
70 	if (sv->sv_rem < slen)
71 		return (B_FALSE);
72 	if (strncmp(sv->sv_first, str, slen) != 0)
73 		return (B_FALSE);
74 
75 	sv->sv_first += slen;
76 	sv->sv_rem -= slen;
77 	return (B_TRUE);
78 }
79 
80 char
81 sv_peek(const strview_t *sv, ssize_t n)
82 {
83 	const char *p;
84 
85 	p = (n >= 0) ? sv->sv_first + n : sv->sv_last + n;
86 	return ((p >= sv->sv_first && p < sv->sv_last) ? *p : '\0');
87 }
88 
89 char
90 sv_consume_c(strview_t *sv)
91 {
92 	char c = '\0';
93 
94 	if (sv->sv_first < sv->sv_last) {
95 		c = *sv->sv_first++;
96 		sv->sv_rem--;
97 	}
98 	return (c);
99 }
100 
101 void
102 sv_consume_n(strview_t *sv, size_t n)
103 {
104 	VERIFY3U(sv->sv_rem, >=, n);
105 	sv->sv_first += n;
106 	sv->sv_rem -= n;
107 }
108