Debian Codegraph @

gi/string.hpp

raw symbols SCIP
1 #ifndef GI_STRING_HPP
2 #define GI_STRING_HPP
3
4 #include "base.hpp"
5
6 #ifdef __has_builtin
7 #define GI_HAS_BUILTIN(x) __has_builtin(x)
8 #else
9 #define GI_HAS_BUILTIN(x) 0
10 #endif
11
12 GI_MODULE_EXPORT
13 namespace gi
14 {
15 namespace convert
16 {
17 // generic template; specialize as needed where appropriate
18 template<typename From, typename To, class Enable = void>
19 struct converter
20 {
21 // fail in explanatory way if we end up here
22 static To convert(const From &)
23 {
24 static_assert(!std::is_void<Enable>::value, "unknown type conversion");
25 return To();
26 }
27 };
28
29 // implementation should provide some types
30 template<typename From, typename To, class Enable = void>
31 struct converter_base : public std::true_type
32 {
33 typedef From from_type;
34 typedef To to_type;
35 };
36
37 // conversion check for complete type
38 template<typename From, typename To, typename Enable = void>
39 struct is_convertible_impl : public std::false_type
40 {};
41
42 template<typename From, typename To>
43 struct is_convertible_impl<From, To,
44 typename std::enable_if<std::is_base_of<To, From>::value>::type>
45 : public std::false_type
46 {};
47
48 template<typename From, typename To>
49 struct is_convertible_impl<From, To,
50 typename std::enable_if<!std::is_base_of<To, From>::value &&
51 std::is_pointer<typename converter<From,
52 To>::from_type *>::value>::type>
53 : public std::true_type
54 {};
55
56 template<typename From, typename To, bool complete>
57 struct is_convertible_pre
58 {
59 using type = std::false_type;
60 };
61
62 template<typename From, typename To>
63 struct is_convertible_pre<From, To, true>
64 {
65 using type = is_convertible_impl<From, To>;
66 };
67
68 // check whether conversion possible
69 // reject incomplete forward declared types
70 template<typename From, typename To, typename Enable = void>
71 struct is_convertible : public is_convertible_pre<From, To,
72 gi::traits::is_type_complete<To>::value>::type
73 {};
74 } // namespace convert
75
76 namespace detail
77 {
78 // tag
79
80 struct String
81 {};
82
83 template<typename Transfer>
84 struct StringFuncs
85 {
86 static void _deleter(char *&p)
87 {
88 if (Transfer().value)
89 g_free(p);
90 p = nullptr;
91 }
92 static void _copy(const char *p)
93 {
94 return Transfer().value ? g_strdup(p) : p;
95 }
96 };
97
98 template<typename Transfer>
99 class cstr : public String
100 {
101 using self_type = cstr;
102
103 protected:
104 using _member_type =
105 typename std::conditional<std::is_same<Transfer, transfer_full_t>::value,
106 char, const char>::type;
107
108 _member_type *data_ = nullptr;
109
110 void clear()
111 {
112 if (Transfer().value && data_)
113 g_free((char *)data_);
114 data_ = nullptr;
115 }
116
117 public:
118 using traits_type = std::char_traits<char>;
119 using value_type = char;
120 using pointer = char *;
121 using const_pointer = const char *;
122 using reference = char &;
123 using const_reference = const char &;
124 using const_iterator = const char *;
125 using iterator = const_iterator;
126 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
127 using reverse_iterator = const_reverse_iterator;
128 using size_type = size_t;
129 using difference_type = std::ptrdiff_t;
130
131 using view_type = cstr<transfer_none_t>;
132 static constexpr bool is_view_type =
133 !std::is_same<Transfer, transfer_full_t>::value;
134
135 static constexpr size_type npos = static_cast<size_type>(-1);
136
137 constexpr cstr() noexcept : data_(nullptr) {}
138
139 constexpr cstr(std::nullptr_t) noexcept : data_(nullptr) {}
140
141 // const usually means none, so only on view type
142 // also, no arbitrary size is accepted here
143 template<typename Enable = void,
144 typename std::enable_if<std::is_same<Enable, void>::value &&
145 is_view_type>::type * = nullptr>
146 constexpr cstr(const char *data) : data_(data)
147 {}
148
149 // a single pointer, optionally specify ownership
150 // behave like string by default, assume no ownership of incoming pointer
151 template<typename LTransfer = transfer_none_t,
152 typename std::enable_if<
153 (std::is_same<LTransfer, transfer_full_t>::value ||
154 std::is_same<LTransfer, transfer_none_t>::value) &&
155 !is_view_type>::type * = nullptr>
156 cstr(char *data, const LTransfer &t)
157 : data_((t.value == transfer_full.value) || !data ? data : g_strdup(data))
158 {}
159
160 // pointer along with size
161 // always behave like string and make a copy
162 template<typename Enable = void,
163 typename std::enable_if<std::is_same<Enable, void>::value &&
164 !is_view_type>::type * = nullptr>
165 cstr(const char *data, size_t len = npos)
166 : data_(!data ? nullptr
167 : (len == npos ? g_strdup(data) : g_strndup(data, len)))
168 {}
169
170 // construct from any transfer variant
171 template<typename OTransfer>
172 cstr(const cstr<OTransfer> &s) : cstr(s.data())
173 {}
174
175 // accept from string, but NOT string_view as that may not be null-terminated
176 template<typename Allocator>
177 cstr(const std::basic_string<char, std::char_traits<char>, Allocator>
178 &s) noexcept
179 : cstr(s.data())
180 {}
181
182 #if __cplusplus >= 201703L
183 // some optional variants of above
184 constexpr cstr(std::nullopt_t) noexcept : data_(nullptr) {}
185
186 template<typename Allocator>
187 cstr(const std::optional<
188 std::basic_string<char, std::char_traits<char>, Allocator>> &s) noexcept
189 : cstr(s ? s.value().data() : nullptr)
190 {}
191 #endif
192
193 // hook extensible conversion
194 // (avoid instantiation and confusion with self and base types)
195 template<typename From,
196 typename NoBase = typename std::enable_if<
197 !std::is_base_of<self_type, From>::value>::type,
198 typename Enable = typename std::enable_if<
199 convert::is_convertible<From, self_type>::value>::type>
200 cstr(const From &f) : cstr(convert::converter<From, self_type>::convert(f))
201 {}
202
203 // custom
204 constexpr const_pointer gobj_() const { return data_; }
205
206 explicit constexpr operator bool() const { return data_; }
207
208 _member_type *release_()
209 {
210 auto tmp = this->data_;
211 this->data_ = nullptr;
212 return tmp;
213 }
214
215 // destruct / copy / assign
216 ~cstr() { clear(); }
217
218 cstr(const cstr &other) { *this = other; }
219
220 cstr(cstr &&other) { *this = std::move(other); }
221
222 cstr &operator=(const cstr &other)
223 {
224 if (this != &other) {
225 clear();
226 data_ = Transfer().value ? g_strdup(other.data_) : other.data_;
227 }
228 return *this;
229 }
230
231 cstr &operator=(cstr &&other)
232 {
233 if (this != &other) {
234 clear();
235 data_ = other.data_;
236 other.data_ = nullptr;
237 }
238 return *this;
239 }
240
241 // deduced conversion to string(_view)
242 template<typename Destination,
243 typename Check = typename std::enable_if<
244 convert::is_convertible<self_type, Destination>::value>::type>
245 operator Destination() const
246 {
247 return convert::converter<self_type, Destination>::convert(*this);
248 }
249
250 #if __cplusplus >= 201703L
251 // unfortunately, conversion to std::optional picks Destination = std::string
252 // (which can obviously not be excluded above, or as specialization)
253 std::optional<std::string> opt_()
254 {
255 using To = std::optional<std::string>;
256 return c_str() ? To({c_str(), size()}) : To(std::nullopt);
257 }
258 #endif
259
260 // usual string(view) stuff
261
262 // iterators
263
264 constexpr const_iterator begin() const noexcept { return data_; }
265
266 constexpr const_iterator end() const noexcept
267 {
268 return data_ ? data_ + size() : nullptr;
269 }
270
271 constexpr const_iterator cbegin() const noexcept { return begin(); }
272
273 constexpr const_iterator cend() const noexcept { return end(); }
274
275 const_reverse_iterator rbegin() const noexcept
276 {
277 return const_reverse_iterator(end());
278 }
279
280 const_reverse_iterator rend() const noexcept
281 {
282 return const_reverse_iterator(begin());
283 }
284 const_reverse_iterator crbegin() const noexcept { return rbegin(); }
285
286 const_reverse_iterator crend() const noexcept { return rend(); }
287
288 // capacity
289
290 constexpr size_type size() const noexcept
291 {
292 #if GI_HAS_BUILTIN(__builtin_strlen) || \
293 (defined(__GNUC__) && !defined(__clang__))
294 return __builtin_strlen(data_);
295 #else
296 return data_ ? strlen(data_) : 0;
297 #endif
298 }
299
300 constexpr size_type length() const noexcept { return size(); }
301
302 constexpr size_type max_size() const noexcept
303 {
304 return std::numeric_limits<size_type>::max();
305 }
306
307 constexpr bool empty() const noexcept { return !data_ || *data_ == 0; }
308
309 // access
310
311 constexpr const_reference operator[](size_type i) const { return data_[i]; }
312
313 constexpr const_reference at(size_type i) const
314 {
315 return i < size() ? data_[i]
316 : (try_throw(std::out_of_range("cstr::at")), data_[i]);
317 }
318
319 constexpr const_reference front() const { return data_[0]; }
320
321 constexpr const_reference back() const { return data_[size() - 1]; }
322
323 constexpr const_pointer data() const noexcept { return data_; }
324
325 constexpr const_pointer c_str() const noexcept { return data_; }
326
327 // modifiers
328
329 // view only
330 template<typename Enable = void,
331 typename std::enable_if<std::is_same<Enable, void>::value &&
332 is_view_type>::type * = nullptr>
333 constexpr void remove_prefix(size_type n)
334 {
335 data_ += n;
336 }
337
338 constexpr void swap(self_type &s) noexcept
339 {
340 std::swap(this->data_, s.data_);
341 }
342
343 // operations
344
345 size_type copy(char *buf, size_type n, size_type pos = 0) const
346 {
347 auto s = size();
348 if (pos > s)
349 try_throw(std::out_of_range("cstr::copy"));
350 size_type rlen = (std::min)(s - pos, n);
351 if (rlen > 0) {
352 const char *start = data_ + pos;
353 traits_type::copy(buf, start, rlen);
354 }
355 return rlen;
356 }
357
358 int compare(view_type x) const noexcept
359 {
360 return g_strcmp0(data_, x.c_str());
361 }
362
363 int compare(const char *s) const { return compare(view_type(s)); }
364
365 // find
366
367 size_type find(view_type n, size_type pos = 0) const noexcept
368 {
369 auto s = size();
370 auto os = n.size();
371 if (os > s || pos > s - os)
372 return npos;
373 if (!os)
374 return pos <= s ? pos : npos;
375 auto loc = strstr(data_ + pos, n.data());
376 return loc ? loc - data_ : npos;
377 }
378
379 size_type find(char c, size_type pos = 0) const noexcept
380 {
381 if (pos >= size())
382 return npos;
383 auto loc = strchr(data_ + pos, c);
384 return loc ? loc - data_ : npos;
385 }
386
387 size_type find(const char *s, size_type pos = 0) const
388 {
389 return find(view_type(s), pos);
390 }
391
392 size_type rfind(view_type n, size_type pos = npos) const noexcept
393 {
394 auto s = size();
395 if (!s)
396 return npos;
397 auto os = n.size();
398 if (!os)
399 return pos == npos ? s : pos;
400 auto loc = g_strrstr_len(c_str(), pos, n.c_str());
401 return loc ? loc - data_ : npos;
402 }
403
404 size_type rfind(char c, size_type pos = npos) const noexcept
405 {
406 // not quite efficient, but anyways
407 char str[] = {c, 0};
408 return rfind(str, pos);
409 }
410
411 size_type rfind(const char *s, size_type pos = npos) const
412 {
413 return rfind(view_type(s), pos);
414 }
415
416 // find_first_of variants
417 // only provide those if std helps us out
418 #if __cplusplus >= 201703L
419 size_type find_first_of(view_type s, size_type pos = 0) const noexcept
420 {
421 return std::string_view(data_).find_first_of(s.data(), pos);
422 }
423
424 size_type find_first_of(char c, size_type pos = 0) const noexcept
425 {
426 return find(c, pos);
427 }
428
429 size_type find_first_of(const char *s, size_type pos = 0) const
430 {
431 return find_first_of(view_type(s), pos);
432 }
433
434 size_type find_last_of(view_type s, size_type pos = npos) const noexcept
435 {
436 return std::string_view(data_).find_last_of(s.data(), pos);
437 }
438
439 size_type find_last_of(char c, size_type pos = npos) const noexcept
440 {
441 return rfind(c, pos);
442 }
443
444 size_type find_last_of(const char *s, size_type pos = npos) const
445 {
446 return find_last_of(view_type(s), pos);
447 }
448
449 size_type find_first_not_of(view_type s, size_type pos = 0) const noexcept
450 {
451 return std::string_view(data_).find_first_not_of(s.data(), pos);
452 }
453
454 size_type find_first_not_of(char c, size_type pos = 0) const noexcept
455 {
456 return std::string_view(data_).find_first_not_of(c, pos);
457 }
458
459 size_type find_first_not_of(const char *s, size_type pos = 0) const
460 {
461 return find_first_not_of(view_type(s), pos);
462 }
463
464 size_type find_last_not_of(view_type s, size_type pos = npos) const noexcept
465 {
466 return std::string_view(data_).find_last_not_of(s.data(), pos);
467 }
468
469 size_type find_last_not_of(char c, size_type pos = npos) const noexcept
470 {
471 return std::string_view(data_).find_last_not_of(c, pos);
472 }
473
474 size_type find_last_not_of(const char *s, size_type pos = npos) const
475 {
476 return find_last_not_of(view_type(s), pos);
477 }
478 #endif
479 };
480
481 using _string_view = cstr<transfer_none_t>;
482
483 inline bool
484 operator==(_string_view x, _string_view y) noexcept
485 {
486 return x.compare(y) == 0;
487 }
488
489 inline bool
490 operator!=(_string_view x, _string_view y) noexcept
491 {
492 return !(x == y);
493 }
494
495 inline bool
496 operator<(_string_view x, _string_view y) noexcept
497 {
498 return x.compare(y) < 0;
499 }
500
501 inline bool
502 operator>(_string_view x, _string_view y) noexcept
503 {
504 return y < x;
505 }
506
507 inline bool
508 operator<=(_string_view x, _string_view y) noexcept
509 {
510 return !(y < x);
511 }
512
513 inline bool
514 operator>=(_string_view x, _string_view y) noexcept
515 {
516 return !(x < y);
517 }
518
519 #ifndef GI_NO_STRING_IOS
520 inline std::ostream &
521 operator<<(std::ostream &o, _string_view sv)
522 {
523 // backwards compatibility; behave similar to empty string
524 return o << (sv ? sv.c_str() : "");
525 }
526 #endif
527
528 // purpose of silly Delay is to avoid gcc premature instantiation of converter
529 // (in the hook constructor of base class with cstring as From ??)
530 template<typename Delay = void>
531 class cstring_d : public cstr<transfer_full_t>
532 {
533 using self_type = cstring_d;
534 using super_type = cstr<transfer_full_t>;
535
536 public:
537 using super_type::super_type;
538
539 // if all other construction fails, try to pass through string
540 template<typename... Args,
541 typename NoConvert = typename std::enable_if<
542 !std::is_constructible<super_type, Args...>::value>::type,
543 typename Enable = typename std::enable_if<
544 std::is_constructible<std::string, Args...>::value>::type>
545 cstring_d(Args &&...args)
546 : super_type(std::string(std::forward<Args>(args)...))
547 {}
548
549 constexpr pointer gobj_() { return data_; }
550
551 // re-use string
552 template<typename... Args>
553 self_type &assign(Args &&...t)
554 {
555 return *this = std::string().assign(std::forward<Args>(t)...);
556 }
557
558 // access
559
560 using super_type::at;
561 constexpr reference at(size_type i)
562 {
563 return i < size() ? data_[i]
564 : (try_throw(std::out_of_range("cstr::at")), data_[i]);
565 }
566
567 using super_type::front;
568 constexpr reference front() { return data_[0]; }
569
570 using super_type::back;
571 constexpr reference back() { return data_[size() - 1]; }
572
573 using super_type::data;
574 constexpr pointer data() noexcept { return data_; }
575
576 // iterators
577
578 using super_type::begin;
579 constexpr iterator begin() noexcept { return data_; }
580
581 using super_type::end;
582 constexpr iterator end() noexcept { return data_ ? data_ + size() : nullptr; }
583
584 using super_type::rbegin;
585 reverse_iterator rbegin() noexcept { return reverse_iterator(end()); }
586
587 using super_type::rend;
588 reverse_iterator rend() noexcept { return reverse_iterator(begin()); }
589
590 // operations
591
592 using super_type::clear;
593
594 void push_back(char c)
595 {
596 char str[] = {c, 0};
597 self_type n{
598 g_strconcat(c_str() ? c_str() : "", str, (char *)NULL), transfer_full};
599 swap(n);
600 }
601
602 void pop_back()
603 {
604 auto s = size();
605 if (s)
606 at(s - 1) = 0;
607 }
608
609 self_type &append(const char *str)
610 {
611 self_type n{
612 g_strconcat(c_str() ? c_str() : "", str, (char *)NULL), transfer_full};
613 swap(n);
614 return *this;
615 }
616
617 template<typename Transfer>
618 self_type &append(const cstr<Transfer> &str)
619 {
620 return append(str.data());
621 }
622
623 // otherwise delegate
624 template<typename... Args>
625 self_type &append(Args &&...args)
626 {
627 std::string s;
628 s.append(std::forward<Args>(args)...);
629 // make sure to select the desired variant
630 return append((const char *)s.c_str());
631 }
632
633 // likewise for +=
634 self_type &operator+=(char c)
635 {
636 push_back(c);
637 return *this;
638 }
639
640 template<typename T>
641 self_type &operator+=(const T &o)
642 {
643 return append(o);
644 }
645
646 self_type substr(size_type pos = 0, size_type n = npos) const
647 {
648 auto l = size();
649 return (pos > l)
650 ? (try_throw(std::out_of_range("cstr::substr")), self_type())
651 : self_type(data_ + pos, std::min(n, l - pos));
652 }
653
654 // indeed some are lacking/skipped
655 // only minimal compatibility
656
657 // custom; align with other cases
658 self_type copy_() { return substr(0); }
659 };
660
661 using cstring = cstring_d<>;
662
663 // likewise; (delayed) view type
664 template<typename Delay = void>
665 class cstring_v_d : public cstr<transfer_none_t>
666 {
667 using self_type = cstring_v_d;
668 using super_type = cstr<transfer_none_t>;
669
670 public:
671 using super_type::super_type;
672
673 // primary reason for subtype
674 // provide copy/upgrade to owning variant
675 cstring copy_() { return {g_strdup(this->data()), transfer_full}; }
676 };
677
678 using cstring_v = cstring_v_d<>;
679
680 inline cstring
681 operator+(const _string_view x, const _string_view y) noexcept
682 {
683 if (!x)
684 return {g_strdup(y.c_str()), transfer_full};
685 if (!y)
686 return {g_strdup(x.c_str()), transfer_full};
687 return {g_strconcat(x.c_str(), y.c_str(), (char *)NULL), transfer_full};
688 }
689
690 inline cstring
691 operator+(const _string_view x, char y) noexcept
692 {
693 if (!x)
694 return {1, y};
695 char str[] = {y, 0};
696 return x + str;
697 }
698
699 inline cstring
700 operator+(char x, const _string_view y) noexcept
701 {
702 if (!y)
703 return {1, x};
704 char str[] = {x, 0};
705 return str + y;
706 }
707
708 // add convenient conversions
709
710 // local helper traits used below
711 namespace trait
712 {
713 template<typename T, std::size_t SIZE, typename Enable = void>
714 struct has_data_member : std::false_type
715 {};
716
717 template<typename T, std::size_t SIZE>
718 struct has_data_member<T, SIZE,
719 typename std::enable_if<
720 std::is_pointer<decltype(std::declval<T>().c_str())>::value>::type>
721 : std::integral_constant<bool, sizeof(*std::declval<T>().c_str()) == SIZE>
722 {};
723
724 template<typename T, typename Enable = void>
725 struct has_size_member : std::false_type
726 {};
727
728 template<typename T>
729 struct has_size_member<T, typename std::enable_if<std::is_integral<
730 decltype(std::declval<T>().size())>::value>::type>
731 : std::true_type
732 {};
733
734 template<typename T>
735 struct is_string_type
736 : public std::integral_constant<bool,
737 has_data_member<T, 1>::value && has_size_member<T>::value>
738 {};
739
740 } // namespace trait
741
742 } // namespace detail
743
744 namespace convert
745 {
746 template<typename From>
747 struct converter<From, detail::cstr<transfer_full_t>,
748 typename std::enable_if<detail::trait::is_string_type<From>::value>::type>
749 : public converter_base<From, detail::cstr<transfer_full_t>>
750 {
751 static detail::cstring convert(const From &v)
752 {
753 return {(char *)v.c_str(), v.size()};
754 }
755 };
756
757 // to a typical string(_view) case
758 // (avoid conflict with above)
759 // the traits_type (tries to) restricts this to std::string(_view)
760 // not doing so might conveniently allow conversion to other types as well.
761 // however, this would also allow e.g. QByteArray, which comes with an operator+
762 // in global namespace (also selected by non-ADL lookup),
763 // which then results in ambiguous overload
764 // (with the operator+ that is provided above)
765 template<typename Transfer, typename To>
766 struct converter<detail::cstr<Transfer>, To,
767 typename std::enable_if<
768 !std::is_base_of<detail::String, To>::value &&
769 !std::is_same<typename To::traits_type, void>::value &&
770 std::is_constructible<To, const char *, size_t>::value>::type>
771 : public converter_base<detail::cstr<Transfer>, To>
772 {
773 static To convert(const detail::cstr<Transfer> &v)
774 {
775 return v.c_str() ? To{(char *)v.c_str(), v.size()} : To();
776 }
777 };
778
779 #if __cplusplus >= 201703L
780 // to an std::optional string(_view) case
781 template<typename Transfer, typename To>
782 struct converter<detail::cstr<Transfer>, To,
783 typename std::enable_if<std::is_constructible<To, std::in_place_t,
784 const char *, size_t>::value>::type>
785 : public converter_base<detail::cstr<Transfer>, To>
786 {
787 static To convert(const detail::cstr<Transfer> &v)
788 {
789 abort();
790 return v.c_str() ? To{std::in_place, (char *)v.c_str(), v.size()} : To();
791 }
792 };
793 #endif
794
795 } // namespace convert
796
797 using detail::cstring;
798 using detail::cstring_v;
799
800 // sanity check; match C counterpart
801 static_assert(sizeof(cstring) == sizeof(char *), "");
802 static_assert(sizeof(cstring_v) == sizeof(char *), "");
803
804 namespace traits
805 {
806 template<>
807 struct ctype<const gi::cstring, void>
808 {
809 typedef const char *type;
810 };
811
812 template<>
813 struct ctype<gi::cstring, void>
814 {
815 typedef char *type;
816 };
817
818 template<>
819 struct ctype<const gi::cstring_v, void>
820 {
821 typedef const char *type;
822 };
823
824 template<>
825 struct ctype<gi::cstring_v, void>
826 {
827 typedef char *type;
828 };
829
830 template<>
831 struct cpptype<char *, transfer_full_t>
832 {
833 using type = gi::cstring;
834 };
835
836 template<>
837 struct cpptype<char *, transfer_none_t>
838 {
839 using type = gi::cstring_v;
840 };
841
842 } // namespace traits
843
844 } // namespace gi
845
846 // specialize std::hash for suitable use
847 GI_MODULE_EXPORT
848 namespace std
849 {
850 template<>
851 struct hash<gi::cstring>
852 {
853 typedef gi::cstring argument_type;
854 typedef std::size_t result_type;
855 result_type operator()(argument_type const &s) const
856 {
857 return s.c_str() ? g_str_hash(s.c_str()) : 0;
858 }
859 };
860
861 template<>
862 struct hash<gi::cstring_v>
863 {
864 typedef gi::cstring_v argument_type;
865 typedef std::size_t result_type;
866 result_type operator()(argument_type const &s) const
867 {
868 return s.c_str() ? g_str_hash(s.c_str()) : 0;
869 }
870 };
871
872 } // namespace std
873
874 #endif // GI_STRING_HPP