MCPcopy Create free account
hub / github.com/coreutils/coreutils / mbs_logical_substr

Function mbs_logical_substr

src/expr.c:165–205  ·  view source on GitHub ↗

Extract the substring of S, from logical character position POS and LEN characters. first character position is 1. POS and LEN refer to logical characters, not octets. Upon exit, sets v->s to the new string. The new string might be empty if POS/LEN are invalid. */

Source from the content-addressed store, hash-verified

163 Upon exit, sets v->s to the new string.
164 The new string might be empty if POS/LEN are invalid. */
165static char *
166mbs_logical_substr (char const *s, size_t pos, size_t len)
167{
168 size_t mb_cur_max = MB_CUR_MAX;
169 idx_t llen = mb_cur_max <= 1 ? strlen (s) : mbslen (s); /* logical length */
170
171 /* characters to copy */
172 size_t vlen = MIN (len, pos <= llen ? llen - pos + 1 : 0);
173
174 char const *substart = s;
175 idx_t sublen = 0;
176 if (pos == 0 || len == SIZE_MAX)
177 {
178 /* The request is invalid. Silently yield an empty string. */
179 }
180 else if (mb_cur_max <= 1)
181 {
182 substart += pos - 1;
183 sublen = vlen;
184 }
185 else
186 for (idx_t idx = 1; *s && vlen; idx++)
187 {
188 idx_t char_bytes = mcel_scanz (s).len;
189
190 /* Skip until we reach the starting position. */
191 if (pos <= idx)
192 {
193 if (pos == idx)
194 substart = s;
195
196 /* Add one character's length in bytes. */
197 vlen--;
198 sublen += char_bytes;
199 }
200
201 s += char_bytes;
202 }
203
204 return ximemdup0 (substart, sublen);
205}
206
207/* Return the number of logical characters (possibly multibyte)
208 that are in string S in the first OFS octets.

Callers 1

eval6Function · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected