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 smalloc::Alloc(env, obj, length);
128 return scope.Escape(obj);
132 Local<Object> New(Isolate* isolate, const char* data, size_t length) {
133 Environment* env = Environment::GetCurrent(isolate);
134 EscapableHandleScope handle_scope(env->isolate());
135 Local<Object> obj = Buffer::New(env, data, length);
136 return handle_scope.Escape(obj);
140 // TODO(trevnorris): for backwards compatibility this is left to copy the data,
141 // but for consistency w/ the other should use data. And a copy version renamed
142 // to something else.
143 Local<Object> New(Environment* env, const char* data, size_t length) {
144 EscapableHandleScope scope(env->isolate());
146 CHECK_LE(length, kMaxLength);
148 Local<Value> arg = Uint32::NewFromUnsigned(env->isolate(), length);
149 Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
151 // TODO(trevnorris): done like this to handle HasInstance since only checks
152 // if external array data has been set, but would like to use a better
153 // approach if v8 provided one.
156 new_data = static_cast<char*>(malloc(length));
157 if (new_data == nullptr)
158 FatalError("node::Buffer::New(const char*, size_t)", "Out Of Memory");
159 memcpy(new_data, data, length);
164 smalloc::Alloc(env, obj, new_data, length);
166 return scope.Escape(obj);
170 Local<Object> New(Isolate* isolate,
173 smalloc::FreeCallback callback,
175 Environment* env = Environment::GetCurrent(isolate);
176 EscapableHandleScope handle_scope(env->isolate());
177 Local<Object> obj = Buffer::New(env, data, length, callback, hint);
178 return handle_scope.Escape(obj);
182 Local<Object> New(Environment* env,
185 smalloc::FreeCallback callback,
187 EscapableHandleScope scope(env->isolate());
189 CHECK_LE(length, kMaxLength);
191 Local<Value> arg = Uint32::NewFromUnsigned(env->isolate(), length);
192 Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
194 smalloc::Alloc(env, obj, data, length, callback, hint);
196 return scope.Escape(obj);
200 Local<Object> Use(Isolate* isolate, char* data, uint32_t length) {
201 Environment* env = Environment::GetCurrent(isolate);
202 EscapableHandleScope handle_scope(env->isolate());
203 Local<Object> obj = Buffer::Use(env, data, length);
204 return handle_scope.Escape(obj);
208 Local<Object> Use(Environment* env, char* data, uint32_t length) {
209 EscapableHandleScope scope(env->isolate());
211 CHECK_LE(length, kMaxLength);
213 Local<Value> arg = Uint32::NewFromUnsigned(env->isolate(), length);
214 Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
216 smalloc::Alloc(env, obj, data, length);
218 return scope.Escape(obj);
222 template <encoding encoding>
223 void StringSlice(const FunctionCallbackInfo<Value>& args) {
224 Environment* env = Environment::GetCurrent(args);
226 ARGS_THIS(args.This())
227 SLICE_START_END(args[0], args[1], obj_length)
229 args.GetReturnValue().Set(
230 StringBytes::Encode(env->isolate(), obj_data + start, length, encoding));
235 void StringSlice<UCS2>(const FunctionCallbackInfo<Value>& args) {
236 Environment* env = Environment::GetCurrent(args);
238 ARGS_THIS(args.This())
239 SLICE_START_END(args[0], args[1], obj_length)
242 const char* data = obj_data + start;
244 bool release = false;
246 // Node's "ucs2" encoding expects LE character data inside a Buffer, so we
247 // need to reorder on BE platforms. See http://nodejs.org/api/buffer.html
248 // regarding Node's "ucs2" encoding specification.
249 const bool aligned = (reinterpret_cast<uintptr_t>(data) % sizeof(*buf) == 0);
250 if (IsLittleEndian() && aligned) {
251 buf = reinterpret_cast<const uint16_t*>(data);
253 // Make a copy to avoid unaligned accesses in v8::String::NewFromTwoByte().
254 uint16_t* copy = new uint16_t[length];
255 for (size_t i = 0, k = 0; i < length; i += 1, k += 2) {
256 // Assumes that the input is little endian.
257 const uint8_t lo = static_cast<uint8_t>(data[k + 0]);
258 const uint8_t hi = static_cast<uint8_t>(data[k + 1]);
259 copy[i] = lo | hi << 8;
265 args.GetReturnValue().Set(StringBytes::Encode(env->isolate(), buf, length));
272 void BinarySlice(const FunctionCallbackInfo<Value>& args) {
273 StringSlice<BINARY>(args);
277 void AsciiSlice(const FunctionCallbackInfo<Value>& args) {
278 StringSlice<ASCII>(args);
282 void Utf8Slice(const FunctionCallbackInfo<Value>& args) {
283 StringSlice<UTF8>(args);
287 void Ucs2Slice(const FunctionCallbackInfo<Value>& args) {
288 StringSlice<UCS2>(args);
292 void HexSlice(const FunctionCallbackInfo<Value>& args) {
293 StringSlice<HEX>(args);
297 void Base64Slice(const FunctionCallbackInfo<Value>& args) {
298 StringSlice<BASE64>(args);
302 // bytesCopied = buffer.copy(target[, targetStart][, sourceStart][, sourceEnd]);
303 void Copy(const FunctionCallbackInfo<Value> &args) {
304 Environment* env = Environment::GetCurrent(args);
306 Local<Object> target = args[0]->ToObject(env->isolate());
308 if (!HasInstance(target))
309 return env->ThrowTypeError("first arg should be a Buffer");
311 ARGS_THIS(args.This())
312 size_t target_length = target->GetIndexedPropertiesExternalArrayDataLength();
313 char* target_data = static_cast<char*>(
314 target->GetIndexedPropertiesExternalArrayData());
319 CHECK_NOT_OOB(ParseArrayIndex(args[1], 0, &target_start));
320 CHECK_NOT_OOB(ParseArrayIndex(args[2], 0, &source_start));
321 CHECK_NOT_OOB(ParseArrayIndex(args[3], obj_length, &source_end));
323 // Copy 0 bytes; we're done
324 if (target_start >= target_length || source_start >= source_end)
325 return args.GetReturnValue().Set(0);
327 if (source_start > obj_length)
328 return env->ThrowRangeError("out of range index");
330 if (source_end - source_start > target_length - target_start)
331 source_end = source_start + target_length - target_start;
333 uint32_t to_copy = MIN(MIN(source_end - source_start,
334 target_length - target_start),
335 obj_length - source_start);
337 memmove(target_data + target_start, obj_data + source_start, to_copy);
338 args.GetReturnValue().Set(to_copy);
342 void Fill(const FunctionCallbackInfo<Value>& args) {
343 ARGS_THIS(args[0].As<Object>())
345 size_t start = args[2]->Uint32Value();
346 size_t end = args[3]->Uint32Value();
347 size_t length = end - start;
348 CHECK(length + start <= obj_length);
350 if (args[1]->IsNumber()) {
351 int value = args[1]->Uint32Value() & 255;
352 memset(obj_data + start, value, length);
356 node::Utf8Value str(args.GetIsolate(), args[1]);
357 size_t str_length = str.length();
358 size_t in_there = str_length;
359 char* ptr = obj_data + start + str_length;
364 memcpy(obj_data + start, *str, MIN(str_length, length));
366 if (str_length >= length)
369 while (in_there < length - in_there) {
370 memcpy(ptr, obj_data + start, in_there);
375 if (in_there < length) {
376 memcpy(ptr, obj_data + start, length - in_there);
382 template <encoding encoding>
383 void StringWrite(const FunctionCallbackInfo<Value>& args) {
384 Environment* env = Environment::GetCurrent(args);
386 ARGS_THIS(args.This())
388 if (!args[0]->IsString())
389 return env->ThrowTypeError("Argument must be a string");
391 Local<String> str = args[0]->ToString(env->isolate());
393 if (encoding == HEX && str->Length() % 2 != 0)
394 return env->ThrowTypeError("Invalid hex string");
399 CHECK_NOT_OOB(ParseArrayIndex(args[1], 0, &offset));
400 CHECK_NOT_OOB(ParseArrayIndex(args[2], obj_length - offset, &max_length));
402 max_length = MIN(obj_length - offset, max_length);
405 return args.GetReturnValue().Set(0);
407 if (offset >= obj_length)
408 return env->ThrowRangeError("Offset is out of bounds");
410 uint32_t written = StringBytes::Write(env->isolate(),
416 args.GetReturnValue().Set(written);
420 void Base64Write(const FunctionCallbackInfo<Value>& args) {
421 StringWrite<BASE64>(args);
425 void BinaryWrite(const FunctionCallbackInfo<Value>& args) {
426 StringWrite<BINARY>(args);
430 void Utf8Write(const FunctionCallbackInfo<Value>& args) {
431 StringWrite<UTF8>(args);
435 void Ucs2Write(const FunctionCallbackInfo<Value>& args) {
436 StringWrite<UCS2>(args);
440 void HexWrite(const FunctionCallbackInfo<Value>& args) {
441 StringWrite<HEX>(args);
445 void AsciiWrite(const FunctionCallbackInfo<Value>& args) {
446 StringWrite<ASCII>(args);
450 static inline void Swizzle(char* start, unsigned int len) {
451 char* end = start + len - 1;
452 while (start < end) {
460 template <typename T, enum Endianness endianness>
461 void ReadFloatGeneric(const FunctionCallbackInfo<Value>& args) {
462 ARGS_THIS(args[0].As<Object>());
464 uint32_t offset = args[1]->Uint32Value();
465 CHECK_LE(offset + sizeof(T), obj_length);
469 char bytes[sizeof(T)];
473 const char* ptr = static_cast<const char*>(obj_data) + offset;
474 memcpy(na.bytes, ptr, sizeof(na.bytes));
475 if (endianness != GetEndianness())
476 Swizzle(na.bytes, sizeof(na.bytes));
478 args.GetReturnValue().Set(na.val);
482 void ReadFloatLE(const FunctionCallbackInfo<Value>& args) {
483 ReadFloatGeneric<float, kLittleEndian>(args);
487 void ReadFloatBE(const FunctionCallbackInfo<Value>& args) {
488 ReadFloatGeneric<float, kBigEndian>(args);
492 void ReadDoubleLE(const FunctionCallbackInfo<Value>& args) {
493 ReadFloatGeneric<double, kLittleEndian>(args);
497 void ReadDoubleBE(const FunctionCallbackInfo<Value>& args) {
498 ReadFloatGeneric<double, kBigEndian>(args);
502 template <typename T, enum Endianness endianness>
503 uint32_t WriteFloatGeneric(const FunctionCallbackInfo<Value>& args) {
504 ARGS_THIS(args[0].As<Object>())
506 T val = args[1]->NumberValue();
507 uint32_t offset = args[2]->Uint32Value();
508 CHECK_LE(offset + sizeof(T), obj_length);
512 char bytes[sizeof(T)];
515 union NoAlias na = { val };
516 char* ptr = static_cast<char*>(obj_data) + offset;
517 if (endianness != GetEndianness())
518 Swizzle(na.bytes, sizeof(na.bytes));
519 memcpy(ptr, na.bytes, sizeof(na.bytes));
520 return offset + sizeof(na.bytes);
524 void WriteFloatLE(const FunctionCallbackInfo<Value>& args) {
525 args.GetReturnValue().Set(WriteFloatGeneric<float, kLittleEndian>(args));
529 void WriteFloatBE(const FunctionCallbackInfo<Value>& args) {
530 args.GetReturnValue().Set(WriteFloatGeneric<float, kBigEndian>(args));
534 void WriteDoubleLE(const FunctionCallbackInfo<Value>& args) {
535 args.GetReturnValue().Set(WriteFloatGeneric<double, kLittleEndian>(args));
539 void WriteDoubleBE(const FunctionCallbackInfo<Value>& args) {
540 args.GetReturnValue().Set(WriteFloatGeneric<double, kBigEndian>(args));
544 void ByteLength(const FunctionCallbackInfo<Value> &args) {
545 Environment* env = Environment::GetCurrent(args);
547 if (!args[0]->IsString())
548 return env->ThrowTypeError("Argument must be a string");
550 Local<String> s = args[0]->ToString(env->isolate());
551 enum encoding e = ParseEncoding(env->isolate(), args[1], UTF8);
553 uint32_t size = StringBytes::Size(env->isolate(), s, e);
554 args.GetReturnValue().Set(size);
558 void Compare(const FunctionCallbackInfo<Value> &args) {
559 Local<Object> obj_a = args[0].As<Object>();
561 static_cast<char*>(obj_a->GetIndexedPropertiesExternalArrayData());
562 size_t obj_a_len = obj_a->GetIndexedPropertiesExternalArrayDataLength();
564 Local<Object> obj_b = args[1].As<Object>();
566 static_cast<char*>(obj_b->GetIndexedPropertiesExternalArrayData());
567 size_t obj_b_len = obj_b->GetIndexedPropertiesExternalArrayDataLength();
569 size_t cmp_length = MIN(obj_a_len, obj_b_len);
571 int32_t val = memcmp(obj_a_data, obj_b_data, cmp_length);
573 // Normalize val to be an integer in the range of [1, -1] since
574 // implementations of memcmp() can vary by platform.
576 if (obj_a_len > obj_b_len)
578 else if (obj_a_len < obj_b_len)
587 args.GetReturnValue().Set(val);
591 int32_t IndexOf(const char* haystack,
595 CHECK_GE(h_length, n_length);
596 // TODO(trevnorris): Implement Boyer-Moore string search algorithm.
597 for (size_t i = 0; i < h_length - n_length + 1; i++) {
598 if (haystack[i] == needle[0]) {
599 if (memcmp(haystack + i, needle, n_length) == 0)
607 void IndexOfString(const FunctionCallbackInfo<Value>& args) {
608 ASSERT(args[0]->IsObject());
609 ASSERT(args[1]->IsString());
610 ASSERT(args[2]->IsNumber());
612 ARGS_THIS(args[0].As<Object>());
613 node::Utf8Value str(args.GetIsolate(), args[1]);
614 int32_t offset_i32 = args[2]->Int32Value();
617 if (offset_i32 < 0) {
618 if (offset_i32 + static_cast<int32_t>(obj_length) < 0)
621 offset = static_cast<uint32_t>(obj_length + offset_i32);
623 offset = static_cast<uint32_t>(offset_i32);
626 if (str.length() == 0 ||
628 (offset != 0 && str.length() + offset <= str.length()) ||
629 str.length() + offset > obj_length)
630 return args.GetReturnValue().Set(-1);
633 IndexOf(obj_data + offset, obj_length - offset, *str, str.length());
634 args.GetReturnValue().Set(r == -1 ? -1 : static_cast<int32_t>(r + offset));
638 void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
639 ASSERT(args[0]->IsObject());
640 ASSERT(args[1]->IsObject());
641 ASSERT(args[2]->IsNumber());
643 ARGS_THIS(args[0].As<Object>());
644 Local<Object> buf = args[1].As<Object>();
645 int32_t offset_i32 = args[2]->Int32Value();
646 size_t buf_length = buf->GetIndexedPropertiesExternalArrayDataLength();
648 static_cast<char*>(buf->GetIndexedPropertiesExternalArrayData());
652 CHECK_NE(buf_data, nullptr);
654 if (offset_i32 < 0) {
655 if (offset_i32 + static_cast<int32_t>(obj_length) < 0)
658 offset = static_cast<uint32_t>(obj_length + offset_i32);
660 offset = static_cast<uint32_t>(offset_i32);
663 if (buf_length == 0 ||
665 (offset != 0 && buf_length + offset <= buf_length) ||
666 buf_length + offset > obj_length)
667 return args.GetReturnValue().Set(-1);
670 IndexOf(obj_data + offset, obj_length - offset, buf_data, buf_length);
671 args.GetReturnValue().Set(r == -1 ? -1 : static_cast<int32_t>(r + offset));
675 void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
676 ASSERT(args[0]->IsObject());
677 ASSERT(args[1]->IsNumber());
678 ASSERT(args[2]->IsNumber());
680 ARGS_THIS(args[0].As<Object>());
681 uint32_t needle = args[1]->Uint32Value();
682 int32_t offset_i32 = args[2]->Int32Value();
685 if (offset_i32 < 0) {
686 if (offset_i32 + static_cast<int32_t>(obj_length) < 0)
689 offset = static_cast<uint32_t>(obj_length + offset_i32);
691 offset = static_cast<uint32_t>(offset_i32);
694 if (obj_length == 0 || offset + 1 > obj_length)
695 return args.GetReturnValue().Set(-1);
697 void* ptr = memchr(obj_data + offset, needle, obj_length - offset);
698 char* ptr_char = static_cast<char*>(ptr);
699 args.GetReturnValue().Set(
700 ptr ? static_cast<int32_t>(ptr_char - obj_data) : -1);
704 // pass Buffer object to load prototype methods
705 void SetupBufferJS(const FunctionCallbackInfo<Value>& args) {
706 Environment* env = Environment::GetCurrent(args);
708 CHECK(args[0]->IsFunction());
710 Local<Function> bv = args[0].As<Function>();
711 env->set_buffer_constructor_function(bv);
712 Local<Value> proto_v = bv->Get(env->prototype_string());
714 CHECK(proto_v->IsObject());
716 Local<Object> proto = proto_v.As<Object>();
718 env->SetMethod(proto, "asciiSlice", AsciiSlice);
719 env->SetMethod(proto, "base64Slice", Base64Slice);
720 env->SetMethod(proto, "binarySlice", BinarySlice);
721 env->SetMethod(proto, "hexSlice", HexSlice);
722 env->SetMethod(proto, "ucs2Slice", Ucs2Slice);
723 env->SetMethod(proto, "utf8Slice", Utf8Slice);
725 env->SetMethod(proto, "asciiWrite", AsciiWrite);
726 env->SetMethod(proto, "base64Write", Base64Write);
727 env->SetMethod(proto, "binaryWrite", BinaryWrite);
728 env->SetMethod(proto, "hexWrite", HexWrite);
729 env->SetMethod(proto, "ucs2Write", Ucs2Write);
730 env->SetMethod(proto, "utf8Write", Utf8Write);
732 env->SetMethod(proto, "copy", Copy);
734 // for backwards compatibility
735 proto->ForceSet(env->offset_string(),
736 Uint32::New(env->isolate(), 0),
741 void Initialize(Handle<Object> target,
742 Handle<Value> unused,
743 Handle<Context> context) {
744 Environment* env = Environment::GetCurrent(context);
746 env->SetMethod(target, "setupBufferJS", SetupBufferJS);
748 env->SetMethod(target, "byteLength", ByteLength);
749 env->SetMethod(target, "compare", Compare);
750 env->SetMethod(target, "fill", Fill);
751 env->SetMethod(target, "indexOfBuffer", IndexOfBuffer);
752 env->SetMethod(target, "indexOfNumber", IndexOfNumber);
753 env->SetMethod(target, "indexOfString", IndexOfString);
755 env->SetMethod(target, "readDoubleBE", ReadDoubleBE);
756 env->SetMethod(target, "readDoubleLE", ReadDoubleLE);
757 env->SetMethod(target, "readFloatBE", ReadFloatBE);
758 env->SetMethod(target, "readFloatLE", ReadFloatLE);
760 env->SetMethod(target, "writeDoubleBE", WriteDoubleBE);
761 env->SetMethod(target, "writeDoubleLE", WriteDoubleLE);
762 env->SetMethod(target, "writeFloatBE", WriteFloatBE);
763 env->SetMethod(target, "writeFloatLE", WriteFloatLE);
767 } // namespace Buffer
770 NODE_MODULE_CONTEXT_AWARE_BUILTIN(buffer, node::Buffer::Initialize)