Browse Source

LibRegex: Add to_string method for RegexStringView

Fausto Tommasi 2 years ago
parent
commit
a24c49c18c
1 changed files with 19 additions and 0 deletions
  1. 19 0
      Userland/Libraries/LibRegex/RegexMatch.h

+ 19 - 0
Userland/Libraries/LibRegex/RegexMatch.h

@@ -8,6 +8,7 @@
 
 
 #include "Forward.h"
 #include "Forward.h"
 #include "RegexOptions.h"
 #include "RegexOptions.h"
+#include <AK/Error.h>
 
 
 #include <AK/DeprecatedFlyString.h>
 #include <AK/DeprecatedFlyString.h>
 #include <AK/DeprecatedString.h>
 #include <AK/DeprecatedString.h>
@@ -162,6 +163,11 @@ public:
     {
     {
     }
     }
 
 
+    RegexStringView(String const& string)
+        : m_view(string.bytes_as_string_view())
+    {
+    }
+
     RegexStringView(StringView const view)
     RegexStringView(StringView const view)
         : m_view(view)
         : m_view(view)
     {
     {
@@ -394,6 +400,19 @@ public:
             });
             });
     }
     }
 
 
+    ErrorOr<String> to_string() const
+    {
+        return m_view.visit(
+            [](StringView view) { return String::from_utf8(view); },
+            [](Utf16View view) { return view.to_utf8(Utf16View::AllowInvalidCodeUnits::Yes); },
+            [](auto& view) -> ErrorOr<String> {
+                StringBuilder builder;
+                for (auto it = view.begin(); it != view.end(); ++it)
+                    TRY(builder.try_append_code_point(*it));
+                return builder.to_string();
+            });
+    }
+
     // Note: index must always be the code unit offset to return.
     // Note: index must always be the code unit offset to return.
     u32 operator[](size_t index) const
     u32 operator[](size_t index) const
     {
     {