Skip to content

Commit d1368b0

Browse files
committed
src/api: use std::string_view in exceptions StringFromPath
1 parent 7aff8e1 commit d1368b0

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed

src/api/exceptions.cc

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include "v8.h"
99

1010
#include <cstring>
11+
#include <string_view>
1112

1213
namespace node {
1314

@@ -20,19 +21,31 @@ using v8::Object;
2021
using v8::String;
2122
using v8::Value;
2223

23-
static Local<String> StringFromPath(Isolate* isolate, const char* path) {
24+
static Local<String> StringFromPath(Isolate* isolate, std::string_view path) {
25+
auto to_v8 = [&](std::string_view s) {
26+
return String::NewFromUtf8(isolate,
27+
s.data(),
28+
v8::NewStringType::kNormal,
29+
static_cast<int>(s.size()))
30+
.ToLocalChecked();
31+
};
32+
2433
#ifdef _WIN32
25-
if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
26-
return String::Concat(
27-
isolate,
28-
FIXED_ONE_BYTE_STRING(isolate, "\\\\"),
29-
String::NewFromUtf8(isolate, path + 8).ToLocalChecked());
30-
} else if (strncmp(path, "\\\\?\\", 4) == 0) {
31-
return String::NewFromUtf8(isolate, path + 4).ToLocalChecked();
34+
constexpr std::string_view kUncPrefix = "\\\\?\\UNC\\";
35+
constexpr std::string_view kLongPrefix = "\\\\?\\";
36+
37+
if (path.starts_with(kUncPrefix)) {
38+
return String::Concat(isolate,
39+
FIXED_ONE_BYTE_STRING(isolate, "\\\\"),
40+
to_v8(path.substr(kUncPrefix.size())));
41+
}
42+
43+
if (path.starts_with(kLongPrefix)) {
44+
return to_v8(path.substr(kLongPrefix.size()));
3245
}
3346
#endif
3447

35-
return String::NewFromUtf8(isolate, path).ToLocalChecked();
48+
return to_v8(path);
3649
}
3750

3851
Local<Value> ErrnoException(Isolate* isolate,
@@ -57,7 +70,7 @@ Local<Value> ErrnoException(Isolate* isolate,
5770
Local<String> path_string;
5871
if (path != nullptr) {
5972
// FIXME(bnoordhuis) It's questionable to interpret the file path as UTF-8.
60-
path_string = StringFromPath(isolate, path);
73+
path_string = StringFromPath(isolate, std::string_view(path));
6174
}
6275

6376
if (path_string.IsEmpty() == false) {
@@ -113,7 +126,7 @@ Local<Value> UVException(Isolate* isolate,
113126
js_msg = String::Concat(isolate, js_msg, js_syscall);
114127

115128
if (path != nullptr) {
116-
js_path = StringFromPath(isolate, path);
129+
js_path = StringFromPath(isolate, std::string_view(path));
117130

118131
js_msg =
119132
String::Concat(isolate, js_msg, FIXED_ONE_BYTE_STRING(isolate, " '"));
@@ -123,7 +136,7 @@ Local<Value> UVException(Isolate* isolate,
123136
}
124137

125138
if (dest != nullptr) {
126-
js_dest = StringFromPath(isolate, dest);
139+
js_dest = StringFromPath(isolate, std::string_view(dest));
127140

128141
js_msg = String::Concat(
129142
isolate, js_msg, FIXED_ONE_BYTE_STRING(isolate, " -> '"));

0 commit comments

Comments
 (0)