String.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. namespace AK {
  36. String::String(const StringView& view)
  37. {
  38. if (view.m_impl)
  39. m_impl = *view.m_impl;
  40. else
  41. m_impl = StringImpl::create(view.characters_without_null_termination(), view.length());
  42. }
  43. bool String::operator==(const FlyString& fly_string) const
  44. {
  45. return *this == String(fly_string.impl());
  46. }
  47. bool String::operator==(const String& other) const
  48. {
  49. if (!m_impl)
  50. return !other.m_impl;
  51. if (!other.m_impl)
  52. return false;
  53. return *m_impl == *other.m_impl;
  54. }
  55. bool String::operator==(const StringView& other) const
  56. {
  57. if (!m_impl)
  58. return !other.m_characters;
  59. if (!other.m_characters)
  60. return false;
  61. if (length() != other.length())
  62. return false;
  63. return !memcmp(characters(), other.characters_without_null_termination(), length());
  64. }
  65. bool String::operator<(const String& other) const
  66. {
  67. if (!m_impl)
  68. return other.m_impl;
  69. if (!other.m_impl)
  70. return false;
  71. return strcmp(characters(), other.characters()) < 0;
  72. }
  73. bool String::operator>(const String& other) const
  74. {
  75. if (!m_impl)
  76. return other.m_impl;
  77. if (!other.m_impl)
  78. return false;
  79. return strcmp(characters(), other.characters()) > 0;
  80. }
  81. String String::empty()
  82. {
  83. return StringImpl::the_empty_stringimpl();
  84. }
  85. bool String::copy_characters_to_buffer(char* buffer, size_t buffer_size) const
  86. {
  87. // We must fit at least the NUL-terminator.
  88. VERIFY(buffer_size > 0);
  89. size_t characters_to_copy = min(length(), buffer_size - 1);
  90. __builtin_memcpy(buffer, characters(), characters_to_copy);
  91. buffer[characters_to_copy] = 0;
  92. return characters_to_copy == length();
  93. }
  94. String String::isolated_copy() const
  95. {
  96. if (!m_impl)
  97. return {};
  98. if (!m_impl->length())
  99. return empty();
  100. char* buffer;
  101. auto impl = StringImpl::create_uninitialized(length(), buffer);
  102. memcpy(buffer, m_impl->characters(), m_impl->length());
  103. return String(move(*impl));
  104. }
  105. String String::substring(size_t start) const
  106. {
  107. VERIFY(m_impl);
  108. VERIFY(start <= length());
  109. return { characters() + start, length() - start };
  110. }
  111. String String::substring(size_t start, size_t length) const
  112. {
  113. if (!length)
  114. return "";
  115. VERIFY(m_impl);
  116. VERIFY(start + length <= m_impl->length());
  117. // FIXME: This needs some input bounds checking.
  118. return { characters() + start, length };
  119. }
  120. StringView String::substring_view(size_t start, size_t length) const
  121. {
  122. VERIFY(m_impl);
  123. VERIFY(start + length <= m_impl->length());
  124. // FIXME: This needs some input bounds checking.
  125. return { characters() + start, length };
  126. }
  127. StringView String::substring_view(size_t start) const
  128. {
  129. VERIFY(m_impl);
  130. VERIFY(start <= length());
  131. return { characters() + start, length() - start };
  132. }
  133. Vector<String> String::split(char separator, bool keep_empty) const
  134. {
  135. return split_limit(separator, 0, keep_empty);
  136. }
  137. Vector<String> String::split_limit(char separator, size_t limit, bool keep_empty) const
  138. {
  139. if (is_empty())
  140. return {};
  141. Vector<String> v;
  142. size_t substart = 0;
  143. for (size_t i = 0; i < length() && (v.size() + 1) != limit; ++i) {
  144. char ch = characters()[i];
  145. if (ch == separator) {
  146. size_t sublen = i - substart;
  147. if (sublen != 0 || keep_empty)
  148. v.append(substring(substart, sublen));
  149. substart = i + 1;
  150. }
  151. }
  152. size_t taillen = length() - substart;
  153. if (taillen != 0 || keep_empty)
  154. v.append(substring(substart, taillen));
  155. return v;
  156. }
  157. Vector<StringView> String::split_view(const char separator, bool keep_empty) const
  158. {
  159. if (is_empty())
  160. return {};
  161. Vector<StringView> v;
  162. size_t substart = 0;
  163. for (size_t i = 0; i < length(); ++i) {
  164. char ch = characters()[i];
  165. if (ch == separator) {
  166. size_t sublen = i - substart;
  167. if (sublen != 0 || keep_empty)
  168. v.append(substring_view(substart, sublen));
  169. substart = i + 1;
  170. }
  171. }
  172. size_t taillen = length() - substart;
  173. if (taillen != 0 || keep_empty)
  174. v.append(substring_view(substart, taillen));
  175. return v;
  176. }
  177. ByteBuffer String::to_byte_buffer() const
  178. {
  179. if (!m_impl)
  180. return {};
  181. return ByteBuffer::copy(reinterpret_cast<const u8*>(characters()), length());
  182. }
  183. template<typename T>
  184. Optional<T> String::to_int() const
  185. {
  186. return StringUtils::convert_to_int<T>(view());
  187. }
  188. template Optional<i8> String::to_int() const;
  189. template Optional<i16> String::to_int() const;
  190. template Optional<i32> String::to_int() const;
  191. template Optional<i64> String::to_int() const;
  192. template<typename T>
  193. Optional<T> String::to_uint() const
  194. {
  195. return StringUtils::convert_to_uint<T>(view());
  196. }
  197. template Optional<u8> String::to_uint() const;
  198. template Optional<u16> String::to_uint() const;
  199. template Optional<u32> String::to_uint() const;
  200. template Optional<u64> String::to_uint() const;
  201. String String::format(const char* fmt, ...)
  202. {
  203. StringBuilder builder;
  204. va_list ap;
  205. va_start(ap, fmt);
  206. builder.appendvf(fmt, ap);
  207. va_end(ap);
  208. return builder.to_string();
  209. }
  210. bool String::starts_with(const StringView& str, CaseSensitivity case_sensitivity) const
  211. {
  212. return StringUtils::starts_with(*this, str, case_sensitivity);
  213. }
  214. bool String::starts_with(char ch) const
  215. {
  216. if (is_empty())
  217. return false;
  218. return characters()[0] == ch;
  219. }
  220. bool String::ends_with(const StringView& str, CaseSensitivity case_sensitivity) const
  221. {
  222. return StringUtils::ends_with(*this, str, case_sensitivity);
  223. }
  224. bool String::ends_with(char ch) const
  225. {
  226. if (is_empty())
  227. return false;
  228. return characters()[length() - 1] == ch;
  229. }
  230. String String::repeated(char ch, size_t count)
  231. {
  232. if (!count)
  233. return empty();
  234. char* buffer;
  235. auto impl = StringImpl::create_uninitialized(count, buffer);
  236. memset(buffer, ch, count);
  237. return *impl;
  238. }
  239. bool String::matches(const StringView& mask, Vector<MaskSpan>& mask_spans, CaseSensitivity case_sensitivity) const
  240. {
  241. return StringUtils::matches(*this, mask, case_sensitivity, &mask_spans);
  242. }
  243. bool String::matches(const StringView& mask, CaseSensitivity case_sensitivity) const
  244. {
  245. return StringUtils::matches(*this, mask, case_sensitivity);
  246. }
  247. bool String::contains(const StringView& needle, CaseSensitivity case_sensitivity) const
  248. {
  249. return StringUtils::contains(*this, needle, case_sensitivity);
  250. }
  251. Optional<size_t> String::index_of(const String& needle, size_t start) const
  252. {
  253. if (is_null() || needle.is_null())
  254. return {};
  255. const char* self_characters = characters();
  256. const char* result = strstr(self_characters + start, needle.characters());
  257. if (!result)
  258. return {};
  259. return Optional<size_t> { result - self_characters };
  260. }
  261. bool String::equals_ignoring_case(const StringView& other) const
  262. {
  263. return StringUtils::equals_ignoring_case(view(), other);
  264. }
  265. int String::replace(const String& needle, const String& replacement, bool all_occurrences)
  266. {
  267. if (is_empty())
  268. return 0;
  269. Vector<size_t> positions;
  270. size_t start = 0, pos;
  271. for (;;) {
  272. const char* ptr = strstr(characters() + start, needle.characters());
  273. if (!ptr)
  274. break;
  275. pos = ptr - characters();
  276. positions.append(pos);
  277. if (!all_occurrences)
  278. break;
  279. start = pos + 1;
  280. }
  281. if (!positions.size())
  282. return 0;
  283. StringBuilder b;
  284. size_t lastpos = 0;
  285. for (auto& pos : positions) {
  286. b.append(substring_view(lastpos, pos - lastpos));
  287. b.append(replacement);
  288. lastpos = pos + needle.length();
  289. }
  290. b.append(substring_view(lastpos, length() - lastpos));
  291. m_impl = StringImpl::create(b.build().characters());
  292. return positions.size();
  293. }
  294. String String::reverse() const
  295. {
  296. StringBuilder reversed_string;
  297. for (size_t i = length(); i-- > 0;) {
  298. reversed_string.append(characters()[i]);
  299. }
  300. return reversed_string.to_string();
  301. }
  302. String escape_html_entities(const StringView& html)
  303. {
  304. StringBuilder builder;
  305. for (size_t i = 0; i < html.length(); ++i) {
  306. if (html[i] == '<')
  307. builder.append("&lt;");
  308. else if (html[i] == '>')
  309. builder.append("&gt;");
  310. else if (html[i] == '&')
  311. builder.append("&amp;");
  312. else
  313. builder.append(html[i]);
  314. }
  315. return builder.to_string();
  316. }
  317. String::String(const FlyString& string)
  318. : m_impl(string.impl())
  319. {
  320. }
  321. String String::to_lowercase() const
  322. {
  323. if (!m_impl)
  324. return {};
  325. return m_impl->to_lowercase();
  326. }
  327. String String::to_uppercase() const
  328. {
  329. if (!m_impl)
  330. return {};
  331. return m_impl->to_uppercase();
  332. }
  333. String String::to_snakecase() const
  334. {
  335. return StringUtils::to_snakecase(*this);
  336. }
  337. bool operator<(const char* characters, const String& string)
  338. {
  339. if (!characters)
  340. return !string.is_null();
  341. if (string.is_null())
  342. return false;
  343. return __builtin_strcmp(characters, string.characters()) < 0;
  344. }
  345. bool operator>=(const char* characters, const String& string)
  346. {
  347. return !(characters < string);
  348. }
  349. bool operator>(const char* characters, const String& string)
  350. {
  351. if (!characters)
  352. return !string.is_null();
  353. if (string.is_null())
  354. return false;
  355. return __builtin_strcmp(characters, string.characters()) > 0;
  356. }
  357. bool operator<=(const char* characters, const String& string)
  358. {
  359. return !(characters > string);
  360. }
  361. bool String::operator==(const char* cstring) const
  362. {
  363. if (is_null())
  364. return !cstring;
  365. if (!cstring)
  366. return false;
  367. return !__builtin_strcmp(characters(), cstring);
  368. }
  369. StringView String::view() const
  370. {
  371. return { characters(), length() };
  372. }
  373. InputStream& operator>>(InputStream& stream, String& string)
  374. {
  375. StringBuilder builder;
  376. for (;;) {
  377. char next_char;
  378. stream >> next_char;
  379. if (stream.has_any_error()) {
  380. stream.set_fatal_error();
  381. string = nullptr;
  382. return stream;
  383. }
  384. if (next_char) {
  385. builder.append(next_char);
  386. } else {
  387. string = builder.to_string();
  388. return stream;
  389. }
  390. }
  391. }
  392. String String::vformatted(StringView fmtstr, TypeErasedFormatParams params)
  393. {
  394. StringBuilder builder;
  395. vformat(builder, fmtstr, params);
  396. return builder.to_string();
  397. }
  398. Optional<size_t> String::find(char c) const
  399. {
  400. return find(StringView { &c, 1 });
  401. }
  402. Optional<size_t> String::find(const StringView& view) const
  403. {
  404. return StringUtils::find(*this, view);
  405. }
  406. }