String.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/ByteBuffer.h>
  27. #include <AK/FlyString.h>
  28. #include <AK/Format.h>
  29. #include <AK/Memory.h>
  30. #include <AK/StdLibExtras.h>
  31. #include <AK/String.h>
  32. #include <AK/StringBuilder.h>
  33. #include <AK/StringView.h>
  34. #include <AK/Vector.h>
  35. #ifndef KERNEL
  36. # include <inttypes.h>
  37. #endif
  38. namespace AK {
  39. String::String(const StringView& view)
  40. {
  41. if (view.m_impl)
  42. m_impl = *view.m_impl;
  43. else
  44. m_impl = StringImpl::create(view.characters_without_null_termination(), view.length());
  45. }
  46. bool String::operator==(const FlyString& fly_string) const
  47. {
  48. return *this == String(fly_string.impl());
  49. }
  50. bool String::operator==(const String& other) const
  51. {
  52. if (!m_impl)
  53. return !other.m_impl;
  54. if (!other.m_impl)
  55. return false;
  56. return *m_impl == *other.m_impl;
  57. }
  58. bool String::operator==(const StringView& other) const
  59. {
  60. if (!m_impl)
  61. return !other.m_characters;
  62. if (!other.m_characters)
  63. return false;
  64. if (length() != other.length())
  65. return false;
  66. return !memcmp(characters(), other.characters_without_null_termination(), length());
  67. }
  68. bool String::operator<(const String& other) const
  69. {
  70. if (!m_impl)
  71. return other.m_impl;
  72. if (!other.m_impl)
  73. return false;
  74. return strcmp(characters(), other.characters()) < 0;
  75. }
  76. bool String::operator>(const String& other) const
  77. {
  78. if (!m_impl)
  79. return other.m_impl;
  80. if (!other.m_impl)
  81. return false;
  82. return strcmp(characters(), other.characters()) > 0;
  83. }
  84. String String::empty()
  85. {
  86. return StringImpl::the_empty_stringimpl();
  87. }
  88. bool String::copy_characters_to_buffer(char* buffer, size_t buffer_size) const
  89. {
  90. // We must fit at least the NUL-terminator.
  91. ASSERT(buffer_size > 0);
  92. size_t characters_to_copy = min(length(), buffer_size - 1);
  93. __builtin_memcpy(buffer, characters(), characters_to_copy);
  94. buffer[characters_to_copy] = 0;
  95. return characters_to_copy == length();
  96. }
  97. String String::isolated_copy() const
  98. {
  99. if (!m_impl)
  100. return {};
  101. if (!m_impl->length())
  102. return empty();
  103. char* buffer;
  104. auto impl = StringImpl::create_uninitialized(length(), buffer);
  105. memcpy(buffer, m_impl->characters(), m_impl->length());
  106. return String(move(*impl));
  107. }
  108. String String::substring(size_t start, size_t length) const
  109. {
  110. if (!length)
  111. return "";
  112. ASSERT(m_impl);
  113. ASSERT(start + length <= m_impl->length());
  114. // FIXME: This needs some input bounds checking.
  115. return { characters() + start, length };
  116. }
  117. StringView String::substring_view(size_t start, size_t length) const
  118. {
  119. ASSERT(m_impl);
  120. ASSERT(start + length <= m_impl->length());
  121. // FIXME: This needs some input bounds checking.
  122. return { characters() + start, length };
  123. }
  124. Vector<String> String::split(char separator, bool keep_empty) const
  125. {
  126. return split_limit(separator, 0, keep_empty);
  127. }
  128. Vector<String> String::split_limit(char separator, size_t limit, bool keep_empty) const
  129. {
  130. if (is_empty())
  131. return {};
  132. Vector<String> v;
  133. size_t substart = 0;
  134. for (size_t i = 0; i < length() && (v.size() + 1) != limit; ++i) {
  135. char ch = characters()[i];
  136. if (ch == separator) {
  137. size_t sublen = i - substart;
  138. if (sublen != 0 || keep_empty)
  139. v.append(substring(substart, sublen));
  140. substart = i + 1;
  141. }
  142. }
  143. size_t taillen = length() - substart;
  144. if (taillen != 0 || keep_empty)
  145. v.append(substring(substart, taillen));
  146. return v;
  147. }
  148. Vector<StringView> String::split_view(const char separator, bool keep_empty) const
  149. {
  150. if (is_empty())
  151. return {};
  152. Vector<StringView> v;
  153. size_t substart = 0;
  154. for (size_t i = 0; i < length(); ++i) {
  155. char ch = characters()[i];
  156. if (ch == separator) {
  157. size_t sublen = i - substart;
  158. if (sublen != 0 || keep_empty)
  159. v.append(substring_view(substart, sublen));
  160. substart = i + 1;
  161. }
  162. }
  163. size_t taillen = length() - substart;
  164. if (taillen != 0 || keep_empty)
  165. v.append(substring_view(substart, taillen));
  166. return v;
  167. }
  168. ByteBuffer String::to_byte_buffer() const
  169. {
  170. if (!m_impl)
  171. return nullptr;
  172. return ByteBuffer::copy(reinterpret_cast<const u8*>(characters()), length());
  173. }
  174. Optional<int> String::to_int() const
  175. {
  176. return StringUtils::convert_to_int(view());
  177. }
  178. Optional<unsigned> String::to_uint() const
  179. {
  180. return StringUtils::convert_to_uint(view());
  181. }
  182. template<typename T>
  183. String String::number(T value) { return formatted("{}", value); }
  184. template String String::number(unsigned char);
  185. template String String::number(unsigned short);
  186. template String String::number(unsigned int);
  187. template String String::number(unsigned long);
  188. template String String::number(unsigned long long);
  189. template String String::number(char);
  190. template String String::number(short);
  191. template String String::number(int);
  192. template String String::number(long);
  193. template String String::number(long long);
  194. template String String::number(signed char);
  195. String String::format(const char* fmt, ...)
  196. {
  197. StringBuilder builder;
  198. va_list ap;
  199. va_start(ap, fmt);
  200. builder.appendvf(fmt, ap);
  201. va_end(ap);
  202. return builder.to_string();
  203. }
  204. bool String::starts_with(const StringView& str, CaseSensitivity case_sensitivity) const
  205. {
  206. return StringUtils::starts_with(*this, str, case_sensitivity);
  207. }
  208. bool String::starts_with(char ch) const
  209. {
  210. if (is_empty())
  211. return false;
  212. return characters()[0] == ch;
  213. }
  214. bool String::ends_with(const StringView& str, CaseSensitivity case_sensitivity) const
  215. {
  216. return StringUtils::ends_with(*this, str, case_sensitivity);
  217. }
  218. bool String::ends_with(char ch) const
  219. {
  220. if (is_empty())
  221. return false;
  222. return characters()[length() - 1] == ch;
  223. }
  224. String String::repeated(char ch, size_t count)
  225. {
  226. if (!count)
  227. return empty();
  228. char* buffer;
  229. auto impl = StringImpl::create_uninitialized(count, buffer);
  230. memset(buffer, ch, count);
  231. return *impl;
  232. }
  233. bool String::matches(const StringView& mask, Vector<MaskSpan>& mask_spans, CaseSensitivity case_sensitivity) const
  234. {
  235. return StringUtils::matches(*this, mask, case_sensitivity, &mask_spans);
  236. }
  237. bool String::matches(const StringView& mask, CaseSensitivity case_sensitivity) const
  238. {
  239. return StringUtils::matches(*this, mask, case_sensitivity);
  240. }
  241. bool String::contains(const StringView& needle, CaseSensitivity case_sensitivity) const
  242. {
  243. return StringUtils::contains(*this, needle, case_sensitivity);
  244. }
  245. Optional<size_t> String::index_of(const String& needle, size_t start) const
  246. {
  247. if (is_null() || needle.is_null())
  248. return {};
  249. const char* self_characters = characters();
  250. const char* result = strstr(self_characters + start, needle.characters());
  251. if (!result)
  252. return {};
  253. return Optional<size_t> { result - self_characters };
  254. }
  255. bool String::equals_ignoring_case(const StringView& other) const
  256. {
  257. return StringUtils::equals_ignoring_case(view(), other);
  258. }
  259. int String::replace(const String& needle, const String& replacement, bool all_occurrences)
  260. {
  261. if (is_empty())
  262. return 0;
  263. Vector<size_t> positions;
  264. size_t start = 0, pos;
  265. for (;;) {
  266. const char* ptr = strstr(characters() + start, needle.characters());
  267. if (!ptr)
  268. break;
  269. pos = ptr - characters();
  270. positions.append(pos);
  271. if (!all_occurrences)
  272. break;
  273. start = pos + 1;
  274. }
  275. if (!positions.size())
  276. return 0;
  277. StringBuilder b;
  278. size_t lastpos = 0;
  279. for (auto& pos : positions) {
  280. b.append(substring_view(lastpos, pos - lastpos));
  281. b.append(replacement);
  282. lastpos = pos + needle.length();
  283. }
  284. b.append(substring_view(lastpos, length() - lastpos));
  285. m_impl = StringImpl::create(b.build().characters());
  286. return positions.size();
  287. }
  288. String escape_html_entities(const StringView& html)
  289. {
  290. StringBuilder builder;
  291. for (size_t i = 0; i < html.length(); ++i) {
  292. if (html[i] == '<')
  293. builder.append("&lt;");
  294. else if (html[i] == '>')
  295. builder.append("&gt;");
  296. else if (html[i] == '&')
  297. builder.append("&amp;");
  298. else
  299. builder.append(html[i]);
  300. }
  301. return builder.to_string();
  302. }
  303. String::String(const FlyString& string)
  304. : m_impl(string.impl())
  305. {
  306. }
  307. String String::to_lowercase() const
  308. {
  309. if (!m_impl)
  310. return {};
  311. return m_impl->to_lowercase();
  312. }
  313. String String::to_uppercase() const
  314. {
  315. if (!m_impl)
  316. return {};
  317. return m_impl->to_uppercase();
  318. }
  319. bool operator<(const char* characters, const String& string)
  320. {
  321. if (!characters)
  322. return !string.is_null();
  323. if (string.is_null())
  324. return false;
  325. return __builtin_strcmp(characters, string.characters()) < 0;
  326. }
  327. bool operator>=(const char* characters, const String& string)
  328. {
  329. return !(characters < string);
  330. }
  331. bool operator>(const char* characters, const String& string)
  332. {
  333. if (!characters)
  334. return !string.is_null();
  335. if (string.is_null())
  336. return false;
  337. return __builtin_strcmp(characters, string.characters()) > 0;
  338. }
  339. bool operator<=(const char* characters, const String& string)
  340. {
  341. return !(characters > string);
  342. }
  343. bool String::operator==(const char* cstring) const
  344. {
  345. if (is_null())
  346. return !cstring;
  347. if (!cstring)
  348. return false;
  349. return !__builtin_strcmp(characters(), cstring);
  350. }
  351. StringView String::view() const
  352. {
  353. return { characters(), length() };
  354. }
  355. InputStream& operator>>(InputStream& stream, String& string)
  356. {
  357. StringBuilder builder;
  358. for (;;) {
  359. char next_char;
  360. stream >> next_char;
  361. if (stream.has_any_error()) {
  362. stream.set_fatal_error();
  363. string = nullptr;
  364. return stream;
  365. }
  366. if (next_char) {
  367. builder.append(next_char);
  368. } else {
  369. string = builder.to_string();
  370. return stream;
  371. }
  372. }
  373. }
  374. String String::vformatted(StringView fmtstr, TypeErasedFormatParams params)
  375. {
  376. StringBuilder builder;
  377. vformat(builder, fmtstr, params);
  378. return builder.to_string();
  379. }
  380. }