2 #include "node_buffer.h"
7 #include "string_bytes.h"
8 #include "v8-profiler.h"
14 #define MIN(a, b) ((a) < (b) ? (a) : (b))
16 #define CHECK_NOT_OOB(r) \
18 if (!(r)) return env->ThrowRangeError("out of range index"); \
21 #define ARGS_THIS(argT) \
22 Local<Object> obj = argT; \
23 size_t obj_length = obj->GetIndexedPropertiesExternalArrayDataLength(); \
24 char* obj_data = static_cast<char*>( \
25 obj->GetIndexedPropertiesExternalArrayData()); \
27 CHECK_NE(obj_data, nullptr);
29 #define SLICE_START_END(start_arg, end_arg, end_max) \
32 CHECK_NOT_OOB(ParseArrayIndex(start_arg, 0, &start)); \
33 CHECK_NOT_OOB(ParseArrayIndex(end_arg, end_max, &end)); \
34 if (end < start) end = start; \
35 CHECK_NOT_OOB(end <= end_max); \
36 size_t length = end - start;
42 using v8::EscapableHandleScope;
44 using v8::FunctionCallbackInfo;
45 using v8::FunctionTemplate;
47 using v8::HandleScope;
57 bool HasInstance(Handle<Value> val) {
58 return val->IsObject() && HasInstance(val.As<Object>());
62 bool HasInstance(Handle<Object> obj) {
63 if (!obj->HasIndexedPropertiesInExternalArrayData())
65 v8::ExternalArrayType type = obj->GetIndexedPropertiesExternalArrayDataType();
66 return type == v8::kExternalUint8Array;
70 char* Data(Handle<Value> val) {
71 CHECK(val->IsObject());
72 // Use a fully qualified name here to work around a bug in gcc 4.2.
73 // It mistakes an unadorned call to Data() for the v8::String::Data type.
74 return node::Buffer::Data(val.As<Object>());
78 char* Data(Handle<Object> obj) {
79 CHECK(obj->HasIndexedPropertiesInExternalArrayData());
80 return static_cast<char*>(obj->GetIndexedPropertiesExternalArrayData());
84 size_t Length(Handle<Value> val) {
85 CHECK(val->IsObject());
86 return Length(val.As<Object>());
90 size_t Length(Handle<Object> obj) {
91 CHECK(obj->HasIndexedPropertiesInExternalArrayData());
92 return obj->GetIndexedPropertiesExternalArrayDataLength();
96 Local<Object> New(Isolate* isolate, Handle<String> string, enum encoding enc) {
97 EscapableHandleScope scope(isolate);
99 size_t length = StringBytes::Size(isolate, string, enc);
101 Local<Object> buf = New(length);
102 char* data = Buffer::Data(buf);
103 StringBytes::Write(isolate, data, length, string, enc);
105 return scope.Escape(buf);
109 Local<Object> New(Isolate* isolate, size_t length) {
110 EscapableHandleScope handle_scope(isolate);
111 Local<Object> obj = Buffer::New(Environment::GetCurrent(isolate), length);
112 return handle_scope.Escape(obj);
116 // TODO(trevnorris): these have a flaw by needing to call the Buffer inst then
117 // Alloc. continue to look for a better architecture.
118 Local<Object> New(Environment* env, size_t length) {
119 EscapableHandleScope scope(env->isolate());
121 CHECK_LE(length, kMaxLength);
123 Local<Value> arg = Uint32::NewFromUnsigned(env->isolate(), length);
124 Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
126 // TODO(trevnorris): done like this to handle HasInstance since only checks
127 // if external array data has been set, but would like to use a better
128 // approach if v8 provided one.
131 data = static_cast<char*>(malloc(length));
133 FatalError("node::Buffer::New(size_t)", "Out Of Memory");
137 smalloc::Alloc(env, obj, data, length);
139 return scope.Escape(obj);
143 Local<Object> New(Isolate* isolate, const char* data, size_t length) {
144 Environment* env = Environment::GetCurrent(isolate);
145 EscapableHandleScope handle_scope(env->isolate());
146 Local<Object> obj = Buffer::New(env, data, length);
147 return handle_scope.Escape(obj);
151 // TODO(trevnorris): for backwards compatibility this is left to copy the data,
152 // but for consistency w/ the other should use data. And a copy version renamed
153 // to something else.
154 Local<Object> New(Environment* env, const char* data, size_t length) {
155 EscapableHandleScope scope(env->isolate());
157 CHECK_LE(length, kMaxLength);
159 Local<Value> arg = Uint32::NewFromUnsigned(env->isolate(), length);
160 Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
162 // TODO(trevnorris): done like this to handle HasInstance since only checks
163 // if external array data has been set, but would like to use a better
164 // approach if v8 provided one.
167 new_data = static_cast<char*>(malloc(length));
168 if (new_data == nullptr)
169 FatalError("node::Buffer::New(const char*, size_t)", "Out Of Memory");
170 memcpy(new_data, data, length);
175 smalloc::Alloc(env, obj, new_data, length);
177 return scope.Escape(obj);
181 Local<Object> New(Isolate* isolate,
184 smalloc::FreeCallback callback,
186 Environment* env = Environment::GetCurrent(isolate);
187 EscapableHandleScope handle_scope(env->isolate());
188 Local<Object> obj = Buffer::New(env, data, length, callback, hint);
189 return handle_scope.Escape(obj);
193 Local<Object> New(Environment* env,
196 smalloc::FreeCallback callback,
198 EscapableHandleScope scope(env->isolate());
200 CHECK_LE(length, kMaxLength);
202 Local<Value> arg = Uint32::NewFromUnsigned(env->isolate(), length);
203 Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
205 smalloc::Alloc(env, obj, data, length, callback, hint);
207 return scope.Escape(obj);
211 Local<Object> Use(Isolate* isolate, char* data, uint32_t length) {
212 Environment* env = Environment::GetCurrent(isolate);
213 EscapableHandleScope handle_scope(env->isolate());
214 Local<Object> obj = Buffer::Use(env, data, length);
215 return handle_scope.Escape(obj);
219 Local<Object> Use(Environment* env, char* data, uint32_t length) {
220 EscapableHandleScope scope(env->isolate());
222 CHECK_LE(length, kMaxLength);
224 Local<Value> arg = Uint32::NewFromUnsigned(env->isolate(), length);
225 Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
227 smalloc::Alloc(env, obj, data, length);
229 return scope.Escape(obj);
233 template <encoding encoding>
234 void StringSlice(const FunctionCallbackInfo<Value>& args) {
235 Environment* env = Environment::GetCurrent(args);
237 ARGS_THIS(args.This())
238 SLICE_START_END(args[0], args[1], obj_length)
240 args.GetReturnValue().Set(
241 StringBytes::Encode(env->isolate(), obj_data + start, length, encoding));
246 void StringSlice<UCS2>(const FunctionCallbackInfo<Value>& args) {
247 Environment* env = Environment::GetCurrent(args);
249 ARGS_THIS(args.This())
250 SLICE_START_END(args[0], args[1], obj_length)
253 const char* data = obj_data + start;
255 bool release = false;
257 // Node's "ucs2" encoding expects LE character data inside a Buffer, so we
258 // need to reorder on BE platforms. See http://nodejs.org/api/buffer.html
259 // regarding Node's "ucs2" encoding specification.
260 const bool aligned = (reinterpret_cast<uintptr_t>(data) % sizeof(*buf) == 0);
261 if (IsLittleEndian() && aligned) {
262 buf = reinterpret_cast<const uint16_t*>(data);
264 // Make a copy to avoid unaligned accesses in v8::String::NewFromTwoByte().
265 uint16_t* copy = new uint16_t[length];
266 for (size_t i = 0, k = 0; i < length; i += 1, k += 2) {
267 // Assumes that the input is little endian.
268 const uint8_t lo = static_cast<uint8_t>(data[k + 0]);
269 const uint8_t hi = static_cast<uint8_t>(data[k + 1]);
270 copy[i] = lo | hi << 8;
276 args.GetReturnValue().Set(StringBytes::Encode(env->isolate(), buf, length));
283 void BinarySlice(const FunctionCallbackInfo<Value>& args) {
284 StringSlice<BINARY>(args);
288 void AsciiSlice(const FunctionCallbackInfo<Value>& args) {
289 StringSlice<ASCII>(args);
293 void Utf8Slice(const FunctionCallbackInfo<Value>& args) {
294 StringSlice<UTF8>(args);
298 void Ucs2Slice(const FunctionCallbackInfo<Value>& args) {
299 StringSlice<UCS2>(args);
303 void HexSlice(const FunctionCallbackInfo<Value>& args) {
304 StringSlice<HEX>(args);
308 void Base64Slice(const FunctionCallbackInfo<Value>& args) {
309 StringSlice<BASE64>(args);
313 // bytesCopied = buffer.copy(target[, targetStart][, sourceStart][, sourceEnd]);
314 void Copy(const FunctionCallbackInfo<Value> &args) {
315 Environment* env = Environment::GetCurrent(args);
317 Local<Object> target = args[0]->ToObject(env->isolate());
319 if (!HasInstance(target))
320 return env->ThrowTypeError("first arg should be a Buffer");
322 ARGS_THIS(args.This())
323 size_t target_length = target->GetIndexedPropertiesExternalArrayDataLength();
324 char* target_data = static_cast<char*>(
325 target->GetIndexedPropertiesExternalArrayData());
330 CHECK_NOT_OOB(ParseArrayIndex(args[1], 0, &target_start));
331 CHECK_NOT_OOB(ParseArrayIndex(args[2], 0, &source_start));
332 CHECK_NOT_OOB(ParseArrayIndex(args[3], obj_length, &source_end));
334 // Copy 0 bytes; we're done
335 if (target_start >= target_length || source_start >= source_end)
336 return args.GetReturnValue().Set(0);
338 if (source_start > obj_length)
339 return env->ThrowRangeError("out of range index");
341 if (source_end - source_start > target_length - target_start)
342 source_end = source_start + target_length - target_start;
344 uint32_t to_copy = MIN(MIN(source_end - source_start,
345 target_length - target_start),
346 obj_length - source_start);
348 memmove(target_data + target_start, obj_data + source_start, to_copy);
349 args.GetReturnValue().Set(to_copy);
353 void Fill(const FunctionCallbackInfo<Value>& args) {
354 ARGS_THIS(args[0].As<Object>())
356 size_t start = args[2]->Uint32Value();
357 size_t end = args[3]->Uint32Value();
358 size_t length = end - start;
359 CHECK(length + start <= obj_length);
361 if (args[1]->IsNumber()) {
362 int value = args[1]->Uint32Value() & 255;
363 memset(obj_data + start, value, length);
367 node::Utf8Value str(args.GetIsolate(), args[1]);
368 size_t str_length = str.length();
369 size_t in_there = str_length;
370 char* ptr = obj_data + start + str_length;
375 memcpy(obj_data + start, *str, MIN(str_length, length));
377 if (str_length >= length)
380 while (in_there < length - in_there) {
381 memcpy(ptr, obj_data + start, in_there);
386 if (in_there < length) {
387 memcpy(ptr, obj_data + start, length - in_there);
393 template <encoding encoding>
394 void StringWrite(const FunctionCallbackInfo<Value>& args) {
395 Environment* env = Environment::GetCurrent(args);
397 ARGS_THIS(args.This())
399 if (!args[0]->IsString())
400 return env->ThrowTypeError("Argument must be a string");
402 Local<String> str = args[0]->ToString(env->isolate());
404 if (encoding == HEX && str->Length() % 2 != 0)
405 return env->ThrowTypeError("Invalid hex string");
410 CHECK_NOT_OOB(ParseArrayIndex(args[1], 0, &offset));
411 CHECK_NOT_OOB(ParseArrayIndex(args[2], obj_length - offset, &max_length));
413 max_length = MIN(obj_length - offset, max_length);
416 return args.GetReturnValue().Set(0);
418 if (encoding == UCS2)
419 max_length = max_length / 2;
421 if (offset >= obj_length)
422 return env->ThrowRangeError("Offset is out of bounds");
424 uint32_t written = StringBytes::Write(env->isolate(),
430 args.GetReturnValue().Set(written);
434 void Base64Write(const FunctionCallbackInfo<Value>& args) {
435 StringWrite<BASE64>(args);
439 void BinaryWrite(const FunctionCallbackInfo<Value>& args) {
440 StringWrite<BINARY>(args);
444 void Utf8Write(const FunctionCallbackInfo<Value>& args) {
445 StringWrite<UTF8>(args);
449 void Ucs2Write(const FunctionCallbackInfo<Value>& args) {
450 StringWrite<UCS2>(args);
454 void HexWrite(const FunctionCallbackInfo<Value>& args) {
455 StringWrite<HEX>(args);
459 void AsciiWrite(const FunctionCallbackInfo<Value>& args) {
460 StringWrite<ASCII>(args);
464 static inline void Swizzle(char* start, unsigned int len) {
465 char* end = start + len - 1;
466 while (start < end) {
474 template <typename T, enum Endianness endianness>
475 void ReadFloatGeneric(const FunctionCallbackInfo<Value>& args) {
476 ARGS_THIS(args[0].As<Object>());
478 uint32_t offset = args[1]->Uint32Value();
479 CHECK_LE(offset + sizeof(T), obj_length);
483 char bytes[sizeof(T)];
487 const char* ptr = static_cast<const char*>(obj_data) + offset;
488 memcpy(na.bytes, ptr, sizeof(na.bytes));
489 if (endianness != GetEndianness())
490 Swizzle(na.bytes, sizeof(na.bytes));
492 args.GetReturnValue().Set(na.val);
496 void ReadFloatLE(const FunctionCallbackInfo<Value>& args) {
497 ReadFloatGeneric<float, kLittleEndian>(args);
501 void ReadFloatBE(const FunctionCallbackInfo<Value>& args) {
502 ReadFloatGeneric<float, kBigEndian>(args);
506 void ReadDoubleLE(const FunctionCallbackInfo<Value>& args) {
507 ReadFloatGeneric<double, kLittleEndian>(args);
511 void ReadDoubleBE(const FunctionCallbackInfo<Value>& args) {
512 ReadFloatGeneric<double, kBigEndian>(args);
516 template <typename T, enum Endianness endianness>
517 uint32_t WriteFloatGeneric(const FunctionCallbackInfo<Value>& args) {
518 ARGS_THIS(args[0].As<Object>())
520 T val = args[1]->NumberValue();
521 uint32_t offset = args[2]->Uint32Value();
522 CHECK_LE(offset + sizeof(T), obj_length);
526 char bytes[sizeof(T)];
529 union NoAlias na = { val };
530 char* ptr = static_cast<char*>(obj_data) + offset;
531 if (endianness != GetEndianness())
532 Swizzle(na.bytes, sizeof(na.bytes));
533 memcpy(ptr, na.bytes, sizeof(na.bytes));
534 return offset + sizeof(na.bytes);
538 void WriteFloatLE(const FunctionCallbackInfo<Value>& args) {
539 args.GetReturnValue().Set(WriteFloatGeneric<float, kLittleEndian>(args));
543 void WriteFloatBE(const FunctionCallbackInfo<Value>& args) {
544 args.GetReturnValue().Set(WriteFloatGeneric<float, kBigEndian>(args));
548 void WriteDoubleLE(const FunctionCallbackInfo<Value>& args) {
549 args.GetReturnValue().Set(WriteFloatGeneric<double, kLittleEndian>(args));
553 void WriteDoubleBE(const FunctionCallbackInfo<Value>& args) {
554 args.GetReturnValue().Set(WriteFloatGeneric<double, kBigEndian>(args));
558 void ByteLength(const FunctionCallbackInfo<Value> &args) {
559 Environment* env = Environment::GetCurrent(args);
561 if (!args[0]->IsString())
562 return env->ThrowTypeError("Argument must be a string");
564 Local<String> s = args[0]->ToString(env->isolate());
565 enum encoding e = ParseEncoding(env->isolate(), args[1], UTF8);
567 uint32_t size = StringBytes::Size(env->isolate(), s, e);
568 args.GetReturnValue().Set(size);
572 void Compare(const FunctionCallbackInfo<Value> &args) {
573 Local<Object> obj_a = args[0].As<Object>();
575 static_cast<char*>(obj_a->GetIndexedPropertiesExternalArrayData());
576 size_t obj_a_len = obj_a->GetIndexedPropertiesExternalArrayDataLength();
578 Local<Object> obj_b = args[1].As<Object>();
580 static_cast<char*>(obj_b->GetIndexedPropertiesExternalArrayData());
581 size_t obj_b_len = obj_b->GetIndexedPropertiesExternalArrayDataLength();
583 size_t cmp_length = MIN(obj_a_len, obj_b_len);
585 int32_t val = memcmp(obj_a_data, obj_b_data, cmp_length);
587 // Normalize val to be an integer in the range of [1, -1] since
588 // implementations of memcmp() can vary by platform.
590 if (obj_a_len > obj_b_len)
592 else if (obj_a_len < obj_b_len)
601 args.GetReturnValue().Set(val);
605 int32_t IndexOf(const char* haystack,
609 CHECK_GE(h_length, n_length);
610 // TODO(trevnorris): Implement Boyer-Moore string search algorithm.
611 for (size_t i = 0; i < h_length - n_length + 1; i++) {
612 if (haystack[i] == needle[0]) {
613 if (memcmp(haystack + i, needle, n_length) == 0)
621 void IndexOfString(const FunctionCallbackInfo<Value>& args) {
622 ASSERT(args[0]->IsObject());
623 ASSERT(args[1]->IsString());
624 ASSERT(args[2]->IsNumber());
626 ARGS_THIS(args[0].As<Object>());
627 node::Utf8Value str(args.GetIsolate(), args[1]);
628 int32_t offset_i32 = args[2]->Int32Value();
631 if (offset_i32 < 0) {
632 if (offset_i32 + static_cast<int32_t>(obj_length) < 0)
635 offset = static_cast<uint32_t>(obj_length + offset_i32);
637 offset = static_cast<uint32_t>(offset_i32);
640 if (str.length() == 0 ||
642 (offset != 0 && str.length() + offset <= str.length()) ||
643 str.length() + offset > obj_length)
644 return args.GetReturnValue().Set(-1);
647 IndexOf(obj_data + offset, obj_length - offset, *str, str.length());
648 args.GetReturnValue().Set(r == -1 ? -1 : static_cast<int32_t>(r + offset));
652 void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
653 ASSERT(args[0]->IsObject());
654 ASSERT(args[1]->IsObject());
655 ASSERT(args[2]->IsNumber());
657 ARGS_THIS(args[0].As<Object>());
658 Local<Object> buf = args[1].As<Object>();
659 int32_t offset_i32 = args[2]->Int32Value();
660 size_t buf_length = buf->GetIndexedPropertiesExternalArrayDataLength();
662 static_cast<char*>(buf->GetIndexedPropertiesExternalArrayData());
666 CHECK_NE(buf_data, nullptr);
668 if (offset_i32 < 0) {
669 if (offset_i32 + static_cast<int32_t>(obj_length) < 0)
672 offset = static_cast<uint32_t>(obj_length + offset_i32);
674 offset = static_cast<uint32_t>(offset_i32);
677 if (buf_length == 0 ||
679 (offset != 0 && buf_length + offset <= buf_length) ||
680 buf_length + offset > obj_length)
681 return args.GetReturnValue().Set(-1);
684 IndexOf(obj_data + offset, obj_length - offset, buf_data, buf_length);
685 args.GetReturnValue().Set(r == -1 ? -1 : static_cast<int32_t>(r + offset));
689 void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
690 ASSERT(args[0]->IsObject());
691 ASSERT(args[1]->IsNumber());
692 ASSERT(args[2]->IsNumber());
694 ARGS_THIS(args[0].As<Object>());
695 uint32_t needle = args[1]->Uint32Value();
696 int32_t offset_i32 = args[2]->Int32Value();
699 if (offset_i32 < 0) {
700 if (offset_i32 + static_cast<int32_t>(obj_length) < 0)
703 offset = static_cast<uint32_t>(obj_length + offset_i32);
705 offset = static_cast<uint32_t>(offset_i32);
708 if (obj_length == 0 || offset + 1 > obj_length)
709 return args.GetReturnValue().Set(-1);
711 void* ptr = memchr(obj_data + offset, needle, obj_length - offset);
712 char* ptr_char = static_cast<char*>(ptr);
713 args.GetReturnValue().Set(
714 ptr ? static_cast<int32_t>(ptr_char - obj_data) : -1);
718 // pass Buffer object to load prototype methods
719 void SetupBufferJS(const FunctionCallbackInfo<Value>& args) {
720 Environment* env = Environment::GetCurrent(args);
722 CHECK(args[0]->IsFunction());
724 Local<Function> bv = args[0].As<Function>();
725 env->set_buffer_constructor_function(bv);
726 Local<Value> proto_v = bv->Get(env->prototype_string());
728 CHECK(proto_v->IsObject());
730 Local<Object> proto = proto_v.As<Object>();
732 env->SetMethod(proto, "asciiSlice", AsciiSlice);
733 env->SetMethod(proto, "base64Slice", Base64Slice);
734 env->SetMethod(proto, "binarySlice", BinarySlice);
735 env->SetMethod(proto, "hexSlice", HexSlice);
736 env->SetMethod(proto, "ucs2Slice", Ucs2Slice);
737 env->SetMethod(proto, "utf8Slice", Utf8Slice);
739 env->SetMethod(proto, "asciiWrite", AsciiWrite);
740 env->SetMethod(proto, "base64Write", Base64Write);
741 env->SetMethod(proto, "binaryWrite", BinaryWrite);
742 env->SetMethod(proto, "hexWrite", HexWrite);
743 env->SetMethod(proto, "ucs2Write", Ucs2Write);
744 env->SetMethod(proto, "utf8Write", Utf8Write);
746 env->SetMethod(proto, "copy", Copy);
748 // for backwards compatibility
749 proto->ForceSet(env->offset_string(),
750 Uint32::New(env->isolate(), 0),
755 void Initialize(Handle<Object> target,
756 Handle<Value> unused,
757 Handle<Context> context) {
758 Environment* env = Environment::GetCurrent(context);
760 env->SetMethod(target, "setupBufferJS", SetupBufferJS);
762 env->SetMethod(target, "byteLength", ByteLength);
763 env->SetMethod(target, "byteLength", ByteLength);
764 env->SetMethod(target, "compare", Compare);
765 env->SetMethod(target, "fill", Fill);
766 env->SetMethod(target, "indexOfBuffer", IndexOfBuffer);
767 env->SetMethod(target, "indexOfNumber", IndexOfNumber);
768 env->SetMethod(target, "indexOfString", IndexOfString);
770 env->SetMethod(target, "readDoubleBE", ReadDoubleBE);
771 env->SetMethod(target, "readDoubleLE", ReadDoubleLE);
772 env->SetMethod(target, "readFloatBE", ReadFloatBE);
773 env->SetMethod(target, "readFloatLE", ReadFloatLE);
775 env->SetMethod(target, "writeDoubleBE", WriteDoubleBE);
776 env->SetMethod(target, "writeDoubleLE", WriteDoubleLE);
777 env->SetMethod(target, "writeFloatBE", WriteFloatBE);
778 env->SetMethod(target, "writeFloatLE", WriteFloatLE);
782 } // namespace Buffer
785 NODE_MODULE_CONTEXT_AWARE_BUILTIN(buffer, node::Buffer::Initialize)