From ed8b5d835ddf07777ad781313bb7ed38e5fa41e8 Mon Sep 17 00:00:00 2001 From: Thomas Goyne Date: Wed, 20 Jun 2018 14:42:52 -0700 Subject: [PATCH] Eliminate some copies when reading strings from node --- src/node/node_string.hpp | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/node/node_string.hpp b/src/node/node_string.hpp index dabe9d07..fe54781a 100644 --- a/src/node/node_string.hpp +++ b/src/node/node_string.hpp @@ -30,16 +30,35 @@ class String { public: String(const char* s) : m_str(s) {} String(const std::string &s) : m_str(s) {} - String(const v8::Local &s) : m_str(*Nan::Utf8String(s)) {} + String(const v8::Local &s); String(v8::Local &&s) : String(s) {} - operator std::string() const { + operator std::string() const& { return m_str; } + operator std::string() && { + return std::move(m_str); + } operator v8::Local() const { return Nan::New(m_str).ToLocalChecked(); } }; +inline String::String(const v8::Local &s) { + if (s.IsEmpty() || s->Length() == 0) { + return; + } + if (s->IsOneByte()) { + m_str.resize(s->Length()); + } + else { + // Length is in UCS-2 code units, which can take up to 3 bytes each to encode + m_str.resize(3 * s->Length()); + } + const int flags = v8::String::NO_NULL_TERMINATION | v8::String::REPLACE_INVALID_UTF8; + auto length = s->WriteUtf8(&m_str[0], m_str.size(), 0, flags); + m_str.resize(length); +} + } // js } // realm