Skip to content

Commit 8b9f88b

Browse files
authored
Blob: Add factory function (#120)
- Add `CreateInstance` for other Native code to bypass copy in Blob constructor
1 parent 7964539 commit 8b9f88b

File tree

3 files changed

+41
-2
lines changed

3 files changed

+41
-2
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
11
#pragma once
22

33
#include <napi/env.h>
4+
#include <napi/napi.h>
45
#include <Babylon/Api.h>
6+
#include <vector>
7+
#include <string>
58

69
namespace Babylon::Polyfills::Blob
710
{
811
void BABYLON_API Initialize(Napi::Env env);
12+
13+
Napi::Value BABYLON_API CreateInstance(
14+
Napi::Env env,
15+
std::vector<std::byte> data,
16+
std::string type);
917
}

Polyfills/Blob/Source/Blob.cpp

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@
44

55
namespace Babylon::Polyfills::Internal
66
{
7+
static constexpr auto JS_BLOB_CONSTRUCTOR_NAME = "Blob";
8+
79
void Blob::Initialize(Napi::Env env)
810
{
9-
static constexpr auto JS_BLOB_CONSTRUCTOR_NAME = "Blob";
1011
if (env.Global().Get(JS_BLOB_CONSTRUCTOR_NAME).IsUndefined())
1112
{
1213
Napi::Function func = DefineClass(
@@ -17,13 +18,30 @@ namespace Babylon::Polyfills::Internal
1718
InstanceAccessor("type", &Blob::GetType, nullptr),
1819
InstanceMethod("text", &Blob::Text),
1920
InstanceMethod("arrayBuffer", &Blob::ArrayBuffer),
20-
InstanceMethod("bytes", &Blob::Bytes)
21+
InstanceMethod("bytes", &Blob::Bytes),
2122
});
2223

2324
env.Global().Set(JS_BLOB_CONSTRUCTOR_NAME, func);
2425
}
2526
}
2627

28+
Napi::Value Blob::CreateInstance(
29+
Napi::Env env,
30+
std::vector<std::byte> data,
31+
std::string type)
32+
{
33+
Initialize(env);
34+
35+
auto ctor{env.Global().Get(JS_BLOB_CONSTRUCTOR_NAME).As<Napi::Function>()};
36+
auto jsBlob{ctor.New({})};
37+
38+
auto blob{Blob::Unwrap(jsBlob)};
39+
blob->m_data = std::move(data);
40+
blob->m_type = std::move(type);
41+
42+
return jsBlob;
43+
}
44+
2745
Blob::Blob(const Napi::CallbackInfo& info)
2846
: Napi::ObjectWrap<Blob>(info)
2947
{
@@ -133,4 +151,12 @@ namespace Babylon::Polyfills::Blob
133151
{
134152
Internal::Blob::Initialize(env);
135153
}
154+
155+
Napi::Value BABYLON_API CreateInstance(
156+
Napi::Env env,
157+
std::vector<std::byte> data,
158+
std::string type)
159+
{
160+
return Internal::Blob::CreateInstance(env, std::move(data), std::move(type));
161+
}
136162
}

Polyfills/Blob/Source/Blob.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ namespace Babylon::Polyfills::Internal
1212
public:
1313
static void Initialize(Napi::Env env);
1414

15+
static Napi::Value CreateInstance(
16+
Napi::Env env,
17+
std::vector<std::byte> data,
18+
std::string type);
19+
1520
explicit Blob(const Napi::CallbackInfo& info);
1621

1722
private:

0 commit comments

Comments
 (0)