Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
StringView.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "../Foundation/Span.h"
5#include "../Strings/StringIterator.h"
6#include "StringsExport.h"
7
8namespace SC
9{
10struct SC_STRINGS_EXPORT StringView;
11struct SC_STRINGS_EXPORT StringViewTokenizer;
12struct SC_STRINGS_EXPORT StringAlgorithms;
13
14} // namespace SC
15
18
21
45
47{
48 StringView() : StringSpan() {}
49
51
52 constexpr StringView(StringSpan ssv) : StringSpan(ssv) {}
53
54 static constexpr StringView fromNullTerminated(const char* text, StringEncoding encoding)
55 {
56 return StringSpan::fromNullTerminated(text, encoding);
57 }
58
59#if SC_PLATFORM_WINDOWS
60 static constexpr StringView fromNullTerminated(const wchar_t* text, StringEncoding encoding)
61 {
62 return StringSpan::fromNullTerminated(text, encoding);
63 }
64#endif
65
68 Span<const uint8_t> toBytesSpan() const SC_LANGUAGE_LIFETIME_BOUND
69 {
70 return Span<const uint8_t>::reinterpret_bytes(text, textSizeInBytes);
71 }
72
79 template <typename Func>
80 [[nodiscard]] constexpr auto withIterator(Func&& func) const;
81
90 template <typename Func>
91 [[nodiscard]] static constexpr auto withIterators(StringView s1, StringView s2, Func&& func);
92
96 template <typename StringIterator>
97 constexpr StringIterator getIterator() const;
98
102 [[nodiscard]] constexpr bool operator!=(StringView other) const { return not operator==(other); }
103
107 [[nodiscard]] constexpr bool operator==(StringView other) const;
108
121 [[nodiscard]] constexpr bool fullyOverlaps(StringView other, size_t& commonOverlappingPoints) const;
122
125 [[nodiscard]] constexpr bool isEmpty() const { return text == nullptr or textSizeInBytes == 0; }
126
129 [[nodiscard]] constexpr bool isNullTerminated() const { return hasNullTerm; }
130
133 [[nodiscard]] constexpr size_t sizeInBytes() const { return textSizeInBytes; }
134
143 [[nodiscard]] bool endsWithAnyOf(Span<const StringCodePoint> codePoints) const;
144
153 [[nodiscard]] bool startsWithAnyOf(Span<const StringCodePoint> codePoints) const;
154
163 [[nodiscard]] bool startsWith(const StringView str) const;
164
173 [[nodiscard]] bool endsWith(const StringView str) const;
174
187 [[nodiscard]] bool containsString(const StringView str) const;
188
201 [[nodiscard]] bool splitAfter(const StringView stringToMatch, StringView& remainingAfterSplit) const;
202
215 [[nodiscard]] bool splitBefore(const StringView stringToMatch, StringView& stringBeforeSplit) const;
216
220 [[nodiscard]] bool containsCodePoint(StringCodePoint c) const;
221
226 [[nodiscard]] constexpr bool hasCompatibleEncoding(StringView str) const;
227
236 template <typename StringIterator>
238 StringEncoding encoding = StringIterator::getEncoding());
239
245 template <typename StringIterator>
246 static StringView fromIteratorUntilEnd(StringIterator it, StringEncoding encoding = StringIterator::getEncoding());
247
253 template <typename StringIterator>
255 StringEncoding encoding = StringIterator::getEncoding());
256
268 [[nodiscard]] StringView sliceStartEnd(size_t start, size_t end) const;
269
281 [[nodiscard]] StringView sliceStartLength(size_t start, size_t length) const;
282
292 [[nodiscard]] StringView sliceStart(size_t offset) const;
293
303 [[nodiscard]] StringView sliceEnd(size_t offset) const;
304
314 [[nodiscard]] StringView trimEndAnyOf(Span<const StringCodePoint> codePoints) const;
315
326
336 [[nodiscard]] StringView trimAnyOf(Span<const StringCodePoint> codePoints) const;
337
346 [[nodiscard]] StringView trimWhiteSpaces() const;
347
349
359 [[nodiscard]] bool isIntegerNumber() const;
360
373 [[nodiscard]] bool isFloatingNumber() const;
374
388 [[nodiscard]] bool parseInt32(int32_t& value) const;
389
403 [[nodiscard]] bool parseFloat(float& value) const;
404
418 [[nodiscard]] bool parseDouble(double& value) const;
419
420 private:
421 template <typename T>
422 struct identity
423 {
424 };
425 template <typename Type>
426 constexpr StringIteratorASCII getIterator(identity<Type>) const;
427 constexpr StringIteratorUTF8 getIterator(identity<StringIteratorUTF8>) const;
428 constexpr StringIteratorUTF16 getIterator(identity<StringIteratorUTF16>) const;
429 template <typename StringIterator1, typename StringIterator2>
430 static constexpr bool equalsIterator(StringIterator1 t1, StringIterator2 t2, size_t& points);
431
432 template <typename StringIterator>
433 constexpr bool equalsIterator(StringView other, size_t& points) const;
434};
435
438{
440
441 size_t numSplitsNonEmpty = 0;
442 size_t numSplitsTotal = 0;
443
447
453
455 StringViewTokenizer(StringView text) : remaining(text), originalText(text) {}
456
470 [[nodiscard]] bool tokenizeNext(Span<const StringCodePoint> separators, Options options = Options::SkipEmpty);
471
487 [[nodiscard]] bool tokenizeNextLine() { return tokenizeNext({'\n'}); }
488
501
503 [[nodiscard]] bool isFinished() const;
504
505 private:
506 StringView originalText; // Original text as passed in the constructor
507};
508
528{
529 [[nodiscard]] static bool matchWildcard(StringView s1, StringView s2);
530
531 private:
532 template <typename StringIterator1, typename StringIterator2>
533 [[nodiscard]] static bool matchWildcardIterator(StringIterator1 pattern, StringIterator2 text);
534};
535
537
538//-----------------------------------------------------------------------------------------------------------------------
539// Implementations Details
540//-----------------------------------------------------------------------------------------------------------------------
541namespace SC
542{
543constexpr SC::StringView operator""_a8(const char* txt, size_t sz)
544{
545 return StringView({txt, sz}, true, StringEncoding::Ascii);
546}
547constexpr StringView operator""_u8(const char* txt, size_t sz)
548{
549 return StringView({txt, sz}, true, StringEncoding::Utf8);
550}
551constexpr StringView operator""_u16(const char* txt, size_t sz)
552{
553 const bool isNullTerminated = sz > 0 and sz % 2 == 1 and txt[sz - 1] == 0;
554 return StringView({txt, isNullTerminated ? sz - 1 : sz}, isNullTerminated, StringEncoding::Utf16);
555}
556} // namespace SC
557
558template <typename StringIterator>
560{
561 // For GCC complaining about specialization in non-namespace scope
562 return getIterator(identity<StringIterator>());
563}
564
565template <typename Type>
566constexpr SC::StringIteratorASCII SC::StringView::getIterator(identity<Type>) const
567{
568 return StringIteratorASCII(text, text + textSizeInBytes);
569}
570constexpr SC::StringIteratorUTF8 SC::StringView::getIterator(identity<StringIteratorUTF8>) const
571{
572 return StringIteratorUTF8(text, text + textSizeInBytes);
573}
574constexpr SC::StringIteratorUTF16 SC::StringView::getIterator(identity<StringIteratorUTF16>) const
575{
576 return StringIteratorUTF16(text, text + textSizeInBytes);
577}
578
579template <typename StringIterator1, typename StringIterator2>
580constexpr bool SC::StringView::equalsIterator(StringIterator1 t1, StringIterator2 t2, size_t& points)
581{
582 StringCodePoint c1 = 0;
583 StringCodePoint c2 = 0;
584 while (t1.advanceRead(c1) and t2.advanceRead(c2))
585 {
586 if (c1 != c2)
587 {
588 return false;
589 }
590 points++;
591 }
592 return t1.isAtEnd() and t2.isAtEnd();
593}
594
595template <typename StringIterator>
596constexpr bool SC::StringView::equalsIterator(StringView other, size_t& points) const
597{
598 auto it = getIterator<StringIterator>();
599 switch (other.getEncoding())
600 {
601 case StringEncoding::Ascii: return equalsIterator(it, other.getIterator<StringIteratorASCII>(), points);
602 case StringEncoding::Utf8: return equalsIterator(it, other.getIterator<StringIteratorUTF8>(), points);
603 case StringEncoding::Utf16: return equalsIterator(it, other.getIterator<StringIteratorUTF16>(), points);
604 }
605 Assert::unreachable();
606}
607
608[[nodiscard]] constexpr bool SC::StringView::operator==(StringView other) const
609{
610#if defined(__clang__)
611#pragma clang diagnostic push
612#pragma clang diagnostic ignored "-Wunreachable-code"
613#endif
614 if (__builtin_is_constant_evaluated())
615 {
616 if (not hasCompatibleEncoding(other))
617 return false;
618 auto it1 = text;
619 auto it2 = other.text;
620 auto sz = textSizeInBytes;
621 for (size_t idx = 0; idx < sz; ++idx)
622 if (it1[idx] != it2[idx])
623 return false;
624 return true;
625 }
626 else
627 {
628 return StringSpan::operator==(other);
629 }
630#if defined(__clang__)
631#pragma clang diagnostic pop
632#endif
633}
634
635constexpr bool SC::StringView::fullyOverlaps(StringView other, size_t& commonOverlappingPoints) const
636{
637 commonOverlappingPoints = 0;
638 switch (getEncoding())
639 {
640 case StringEncoding::Ascii: return equalsIterator<StringIteratorASCII>(other, commonOverlappingPoints);
641 case StringEncoding::Utf8: return equalsIterator<StringIteratorUTF8>(other, commonOverlappingPoints);
642 case StringEncoding::Utf16: return equalsIterator<StringIteratorUTF16>(other, commonOverlappingPoints);
643 }
644 Assert::unreachable();
645}
646
647template <typename Func>
648constexpr auto SC::StringView::withIterator(Func&& func) const
649{
650 switch (getEncoding())
651 {
652 case StringEncoding::Ascii: return func(getIterator<StringIteratorASCII>());
653 case StringEncoding::Utf8: return func(getIterator<StringIteratorUTF8>());
654 case StringEncoding::Utf16: return func(getIterator<StringIteratorUTF16>());
655 }
656 Assert::unreachable();
657}
658
659template <typename Func>
660constexpr auto SC::StringView::withIterators(StringView s1, StringView s2, Func&& func)
661{
662 return s1.withIterator([&s2, &func](auto it1)
663 { return s2.withIterator([&it1, &func](auto it2) { return func(it1, it2); }); });
664}
665
667{
668 return StringEncodingAreBinaryCompatible(getEncoding(), str.getEncoding());
669}
670
671template <typename StringIterator>
672inline SC::StringView SC::StringView::fromIterators(StringIterator from, StringIterator to, StringEncoding encoding)
673{
674 const ssize_t numBytes = to.bytesDistanceFrom(from);
675 if (numBytes >= 0)
676 {
677 StringIterator fromEnd = from;
678 fromEnd.setToEnd();
679 if (fromEnd.bytesDistanceFrom(to) >= 0) // If current iterator of to is inside from range
680 return StringView({from.it, static_cast<size_t>(numBytes)}, false, encoding);
681 }
682 return StringView(encoding); // TODO: Make StringView::fromIterators return bool to make it fallible
683}
684
685template <typename StringIterator>
686inline SC::StringView SC::StringView::fromIteratorUntilEnd(StringIterator it, StringEncoding encoding)
687{
688 StringIterator endIt = it;
689 endIt.setToEnd();
690 const size_t numBytes = static_cast<size_t>(endIt.bytesDistanceFrom(it));
691 return StringView({it.it, numBytes}, false, encoding);
692}
693
694template <typename StringIterator>
695constexpr SC::StringView SC::StringView::fromIteratorFromStart(StringIterator it, StringEncoding encoding)
696{
697 StringIterator start = it;
698 start.setToStart();
699 const size_t numBytes = static_cast<size_t>(it.bytesDistanceFrom(start));
700 return StringView({start.it, numBytes}, false, encoding);
701}
decltype(static_cast< char * >(nullptr) - static_cast< char * >(nullptr)) ssize_t
Platform independent signed size type.
Definition PrimitiveTypes.h:46
int int32_t
Platform independent (4) bytes signed int.
Definition PrimitiveTypes.h:37
constexpr bool StringEncodingAreBinaryCompatible(StringEncoding encoding1, StringEncoding encoding2)
Checks if two encodings have the same utf unit size.
Definition StringIterator.h:21
uint32_t StringCodePoint
UTF code point (32 bit)
Definition StringIterator.h:15
View over a contiguous sequence of items (pointer + size in elements).
Definition Span.h:29
static Span< Type > reinterpret_bytes(VoidType *rawMemory, SizeType sizeInBytes)
Construct a span reinterpreting raw memory (void* or const void*) to Type or const Type
Definition Span.h:81
Algorithms operating on strings (glob / wildcard).
Definition StringView.h:528
A string iterator for ASCII strings.
Definition StringIterator.h:240
A string iterator for UTF16 strings.
Definition StringIterator.h:263
A string iterator for UTF8 strings.
Definition StringIterator.h:281
A position inside a fixed range [start, end) of UTF code points.
Definition StringIterator.h:37
constexpr ssize_t bytesDistanceFrom(StringIterator other) const
Get distance in bytes from current position to another StringIterator current position.
Definition StringIterator.h:407
constexpr void setToEnd()
Set current position to end of iterator range.
Definition StringIterator.h:47
An read-only view over a string (to avoid including Strings library when parsing is not needed).
Definition StringSpan.h:37
static constexpr StringSpan fromNullTerminated(const char *text, StringEncoding encoding)
Constructs a StringView from a null terminated string.
Definition StringSpan.h:54
constexpr StringEncoding getEncoding() const
Get encoding of this StringView.
Definition StringSpan.h:98
constexpr StringSpan(StringEncoding encoding=StringEncoding::Ascii)
Construct an empty StringView.
Definition StringSpan.h:41
Splits a StringView in tokens according to separators.
Definition StringView.h:438
StringViewTokenizer(StringView text)
Build a tokenizer operating on the given text string view.
Definition StringView.h:455
StringView component
Current component that has been tokenized by tokenizeNext.
Definition StringView.h:444
bool isFinished() const
Check if the tokenizer has processed the entire the string view passed in the constructor.
bool tokenizeNextLine()
Tokenizes from current position to first newline.
Definition StringView.h:487
StringViewTokenizer & countTokens(Span< const StringCodePoint > separators)
Count the number of tokens that exist in the string view passed in constructor, when splitted along t...
size_t numSplitsNonEmpty
How many non-empty splits have occurred in current tokenization.
Definition StringView.h:441
StringView processed
Substring of original string passed in constructor processed so far.
Definition StringView.h:445
size_t numSplitsTotal
How many total splits have occurred in current tokenization.
Definition StringView.h:442
bool tokenizeNext(Span< const StringCodePoint > separators, Options options=Options::SkipEmpty)
Splits the string along a list of separators.
StringView remaining
Substring from current position until the end of original text.
Definition StringView.h:446
Options
Definition StringView.h:449
@ IncludeEmpty
If to tokenizeNext should return also empty tokens.
Definition StringView.h:450
@ SkipEmpty
If to tokenizeNext should NOT return also empty tokens.
Definition StringView.h:451
StringCodePoint splittingCharacter
The last splitting character matched in current tokenization.
Definition StringView.h:439
Non-owning view over a range of characters with UTF Encoding.
Definition StringView.h:47
bool startsWithAnyOf(Span< const StringCodePoint > codePoints) const
Check if StringView starts with any utf code point in the given span.
constexpr bool isNullTerminated() const
Check if StringView is immediately followed by a null termination character.
Definition StringView.h:129
constexpr bool operator==(StringView other) const
Compare this StringView with another StringView for equality.
Definition StringView.h:608
constexpr StringIterator getIterator() const
Returns a StringIterator from current StringView.
Definition StringView.h:559
StringView trimEndAnyOf(Span< const StringCodePoint > codePoints) const
Returns a shortened StringView removing ending utf code points matching the codePoints span.
bool startsWith(const StringView str) const
Check if StringView starts with another StringView.
static constexpr StringView fromIteratorFromStart(StringIterator it, StringEncoding encoding=StringIterator::getEncoding())
Returns a section of a string, from start of StringView to it.
Span< const uint8_t > toBytesSpan() const SC_LANGUAGE_LIFETIME_BOUND
Obtain a const uint8_t Span from this StringView.
Definition StringView.h:68
bool parseFloat(float &value) const
Try parsing current StringView as a floating point number.
constexpr bool operator!=(StringView other) const
Compare this StringView with another StringView for inequality.
Definition StringView.h:102
bool containsCodePoint(StringCodePoint c) const
Check if StringView contains given utf code point.
constexpr bool hasCompatibleEncoding(StringView str) const
Check if current StringView has compatible encoding with str.
Definition StringView.h:666
static constexpr auto withIterators(StringView s1, StringView s2, Func &&func)
Call given lambda with one of StringIteratorASCII, StringIteratorUTF8, StringIteratorUTF16 depending ...
Definition StringView.h:660
constexpr StringSpan(StringEncoding encoding=StringEncoding::Ascii)
Construct an empty StringView.
Definition StringSpan.h:41
StringView sliceStartEnd(size_t start, size_t end) const
Get slice [start, end) starting at offset start and ending at end (measured in utf code points)
bool endsWith(const StringView str) const
Check if StringView ends with another StringView.
static StringView fromIteratorUntilEnd(StringIterator it, StringEncoding encoding=StringIterator::getEncoding())
Returns a section of a string, from it to end of StringView.
StringView sliceStartLength(size_t start, size_t length) const
Get slice [start, start+length] starting at offset start and of length code points.
StringView sliceStart(size_t offset) const
Get slice [offset, end] measured in utf code points.
bool endsWithAnyOf(Span< const StringCodePoint > codePoints) const
Check if StringView ends with any utf code point in the given span.
StringView trimWhiteSpaces() const
Returns a shortened StringView without starting/ending utf code points inside {'\r',...
bool parseDouble(double &value) const
Try parsing current StringView as a double precision floating point number.
constexpr bool fullyOverlaps(StringView other, size_t &commonOverlappingPoints) const
Check if this StringView is equal to other StringView (operates on code points, not on utf graphemes)...
Definition StringView.h:635
StringView trimStartAnyOf(Span< const StringCodePoint > codePoints) const
Returns a shortened StringView removing starting utf code points matching the codePoints span.
bool isIntegerNumber() const
If the current view is an integer number, returns true.
bool splitBefore(const StringView stringToMatch, StringView &stringBeforeSplit) const
Returns the part of the string before matching stringToMatch.
StringView sliceEnd(size_t offset) const
Get slice [end-offset, end] measured in utf code points.
bool splitAfter(const StringView stringToMatch, StringView &remainingAfterSplit) const
Returns the remaining part of the string after matching stringToMatch.
constexpr auto withIterator(Func &&func) const
Call given lambda with one of StringIteratorASCII, StringIteratorUTF8, StringIteratorUTF16 depending ...
Definition StringView.h:648
constexpr bool isEmpty() const
Check if StringView is empty.
Definition StringView.h:125
bool containsString(const StringView str) const
Check if StringView contains another StringView.
constexpr size_t sizeInBytes() const
Get size of the StringView in bytes.
Definition StringView.h:133
bool parseInt32(int32_t &value) const
Try parsing current StringView as a 32 bit integer.
StringView trimAnyOf(Span< const StringCodePoint > codePoints) const
Returns a shortened StringView removing starting and ending utf code points inside the codePoints spa...
bool isFloatingNumber() const
Check if StringView can be parsed as an floating point number.
static StringView fromIterators(StringIterator from, StringIterator to, StringEncoding encoding=StringIterator::getEncoding())
Returns a StringView starting at from and ending at to.