Reduce duplicated checks in string construction
diff --git a/src/cxx.cc b/src/cxx.cc
index cbda8b9..05dc15a 100644
--- a/src/cxx.cc
+++ b/src/cxx.cc
@@ -57,25 +57,20 @@
String::~String() noexcept { cxxbridge05$string$drop(this); }
-String::String(const std::string &s) {
- if (!cxxbridge05$string$from(this, s.data(), s.length())) {
+static void initString(String *self, const char *s, size_t len) {
+ if (!cxxbridge05$string$from(self, s, len)) {
panic<std::invalid_argument>("data for rust::String is not utf-8");
}
}
-String::String(const char *s) {
- if (!cxxbridge05$string$from(this, s, std::strlen(s))) {
- panic<std::invalid_argument>("data for rust::String is not utf-8");
- }
-}
+String::String(const std::string &s) { initString(this, s.data(), s.length()); }
+
+String::String(const char *s) { initString(this, s, std::strlen(s)); }
String::String(const char *s, size_t len) {
- if (!cxxbridge05$string$from(
- this,
- s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s,
- len)) {
- panic<std::invalid_argument>("data for rust::String is not utf-8");
- }
+ initString(this,
+ s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s,
+ len);
}
String &String::operator=(const String &other) noexcept {
@@ -119,25 +114,23 @@
Str::Str(const Str &) noexcept = default;
-Str::Str(const std::string &s) : repr(Repr{s.data(), s.length()}) {
- if (!cxxbridge05$str$valid(this->repr.ptr, this->repr.len)) {
+static void initStr(Str::Repr repr) {
+ if (!cxxbridge05$str$valid(repr.ptr, repr.len)) {
panic<std::invalid_argument>("data for rust::Str is not utf-8");
}
}
-Str::Str(const char *s) : repr(Repr{s, std::strlen(s)}) {
- if (!cxxbridge05$str$valid(this->repr.ptr, this->repr.len)) {
- panic<std::invalid_argument>("data for rust::Str is not utf-8");
- }
+Str::Str(const std::string &s) : repr(Repr{s.data(), s.length()}) {
+ initStr(this->repr);
}
+Str::Str(const char *s) : repr(Repr{s, std::strlen(s)}) { initStr(this->repr); }
+
Str::Str(const char *s, size_t len)
: repr(
Repr{s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s,
len}) {
- if (!cxxbridge05$str$valid(this->repr.ptr, this->repr.len)) {
- panic<std::invalid_argument>("data for rust::Str is not utf-8");
- }
+ initStr(this->repr);
}
Str &Str::operator=(Str other) noexcept {