smalloc: length is byte size, not array length

The C++ API has been changed so the passed length is the byte size of
the data, not the length of the array.

This was done so users need to explicitly define how much memory they
want allocated.
This commit is contained in:
Trevor Norris 2013-08-20 10:30:40 -07:00
parent ed0677f427
commit 6b5c43ed18
2 changed files with 30 additions and 11 deletions

View File

@ -224,10 +224,14 @@ void Alloc(const FunctionCallbackInfo<Value>& args) {
enum ExternalArrayType array_type;
// it's faster to not pass the default argument then use Uint32Value
if (args[2]->IsUndefined())
if (args[2]->IsUndefined()) {
array_type = kExternalUnsignedByteArray;
else
} else {
array_type = static_cast<ExternalArrayType>(args[2]->Uint32Value());
size_t type_length = ExternalArraySize(array_type);
assert(type_length * length >= length);
length *= type_length;
}
Alloc(obj, length, array_type);
args.GetReturnValue().Set(obj);
@ -235,14 +239,10 @@ void Alloc(const FunctionCallbackInfo<Value>& args) {
void Alloc(Handle<Object> obj, size_t length, enum ExternalArrayType type) {
assert(length <= kMaxLength);
size_t type_size = ExternalArraySize(type);
assert(length <= kMaxLength);
assert(type_size > 0);
assert(length * type_size >= length);
length *= type_size;
if (length == 0)
return Alloc(obj, NULL, length, type);

View File

@ -47,11 +47,30 @@ NODE_EXTERN typedef void (*FreeCallback)(char* data, void* hint);
NODE_EXTERN size_t ExternalArraySize(enum v8::ExternalArrayType type);
/**
* Allocate external memory and set to passed object. If data is passed then
* will use that instead of allocating new.
* Allocate external array data onto obj.
*
* When you pass an ExternalArrayType and data, Alloc assumes data length is
* the same as data length * ExternalArrayType length.
* Passed data transfers ownership, and if no callback is passed then memory
* will automatically be free'd using free() (not delete[]).
*
* length is always the byte size of the data. Not the length of the external
* array. This intentionally differs from the JS API so users always know
* exactly how much memory is being allocated, regardless of the external array
* type. For this reason the helper function ExternalArraySize is provided to
* help determine the appropriate byte size to be allocated.
*
* In the following example we're allocating a Float array and setting the
* "length" property on the Object:
*
* \code
* size_t array_length = 8;
* size_t byte_length = node::smalloc::ExternalArraySize(
* v8::kExternalFloatArray);
* v8::Local<v8::Object> obj = v8::Object::New();
* char* data = static_cast<char*>(malloc(byte_length * array_length));
* node::smalloc::Alloc(obj, data, byte_length, v8::kExternalFloatArray);
* obj->Set(v8::String::NewFromUtf8("length"),
* v8::Integer::NewFromUnsigned(array_length));
* \code
*/
NODE_EXTERN void Alloc(v8::Handle<v8::Object> obj,
size_t length,