Debian Codegraph @

modules/lsp-runtime-lib/src/main/fmt/url.cpp

raw
1 /*
2 * Copyright (C) 2023 Linux Studio Plugins Project <https://lsp-plug.in/>
3 * (C) 2023 Vladimir Sadovnikov <[email protected]>
4 *
5 * This file is part of lsp-runtime-lib
6 * Created on: 21 дек. 2019 г.
7 *
8 * lsp-runtime-lib is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Lesser General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * any later version.
12 *
13 * lsp-runtime-lib is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with lsp-runtime-lib. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22 #include <lsp-plug.in/fmt/url.h>
23
24 namespace lsp
25 {
26 namespace url
27 {
28 static inline int decode_hex(lsp_wchar_t c)
29 {
30 if ((c >= '0') && (c <= '9'))
31 return c - '0';
32 else if ((c >= 'a') && (c <= 'f'))
33 return c - 'a' + 10;
34 else if ((c >= 'A') && (c <= 'F'))
35 return c - 'A' + 10;
36 return -1;
37 }
38
39 status_t decode(LSPString *dst, const LSPString *src)
40 {
41 return decode(dst, src, 0, src->length());
42 }
43
44 status_t decode(LSPString *dst, const LSPString *src, size_t first)
45 {
46 return decode(dst, src, first, src->length());
47 }
48
49 status_t decode(LSPString *dst, const LSPString *src, size_t first, size_t last)
50 {
51 char *buf = NULL;
52 int code;
53 size_t bcap=0, blen=0;
54 LSPString tmp;
55
56 lsp_finally {
57 if (buf != NULL)
58 free(buf);
59 };
60
61 while (first < last)
62 {
63 lsp_wchar_t c = src->char_at(first);
64 if (c == '%')
65 {
66 // Read hex codes
67 do
68 {
69 // Check availability
70 if ((last - first) < 3)
71 return STATUS_CORRUPTED;
72
73 // Fetch byte code
74 int hi = decode_hex(src->char_at(++first));
75 if (hi < 0)
76 return STATUS_CORRUPTED;
77 int lo = decode_hex(src->char_at(++first));
78 if (lo < 0)
79 return STATUS_CORRUPTED;
80
81 code = (hi << 4) | lo;
82
83 // Append code to buffer
84 if (blen >= bcap)
85 {
86 bcap += ((blen + 0x10) & ~0xf);
87 char *nbuf = reinterpret_cast<char *>(::realloc(buf, bcap * sizeof(char)));
88 if (nbuf == NULL)
89 return STATUS_NO_MEM;
90 buf = nbuf;
91 }
92 buf[blen++] = code;
93
94 // Read next character
95 c = src->char_at(++first);
96 } while (c == '%');
97
98 // Perform encoding
99 if (!tmp.set_utf8(buf, blen))
100 return STATUS_CORRUPTED;
101
102 // Append data
103 if (!dst->append(&tmp))
104 return STATUS_NO_MEM;
105
106 // Reset buffer length
107 blen = 0;
108 }
109 else if (!dst->append(c))
110 return STATUS_NO_MEM;
111 else
112 ++first;
113 }
114
115 return STATUS_OK;
116 }
117
118 } /* namespace url */
119 } /* namespace lsp */
120