qt_string_view.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #pragma once
  8. #include <QtCore/QString>
  9. namespace base {
  10. namespace details {
  11. struct ContainerImplHelper {
  12. enum CutResult { Null, Empty, Full, Subset };
  13. static constexpr CutResult mid(
  14. qsizetype originalLength,
  15. qsizetype *_position,
  16. qsizetype *_length) {
  17. qsizetype &position = *_position;
  18. qsizetype &length = *_length;
  19. if (position > originalLength) {
  20. position = 0;
  21. length = 0;
  22. return Null;
  23. }
  24. if (position < 0) {
  25. if (length < 0 || length + position >= originalLength) {
  26. position = 0;
  27. length = originalLength;
  28. return Full;
  29. }
  30. if (length + position <= 0) {
  31. position = length = 0;
  32. return Null;
  33. }
  34. length += position;
  35. position = 0;
  36. } else if (size_t(length) > size_t(originalLength - position)) {
  37. length = originalLength - position;
  38. }
  39. if (position == 0 && length == originalLength)
  40. return Full;
  41. return length > 0 ? Subset : Empty;
  42. }
  43. };
  44. } // namespace details
  45. [[nodiscard]] inline QStringView StringViewMid(
  46. QStringView view,
  47. qsizetype pos,
  48. qsizetype n = -1) {
  49. const auto result = details::ContainerImplHelper::mid(
  50. view.size(),
  51. &pos,
  52. &n);
  53. return (result == details::ContainerImplHelper::Null)
  54. ? QStringView()
  55. : view.mid(pos, n);
  56. }
  57. } // namespace base