Created
April 14, 2013 10:51
-
-
Save bodokaiser/5382281 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "parser.h" | |
Handle<Value> CalcHeadSize(const Arguments &args) { | |
HandleScope scope; | |
Local<Object> object = args[0]->ToObject(); | |
if (node::Buffer::HasInstance(object)) { | |
if (node::Buffer::Length(object) < 2) { | |
ThrowException(Exception::TypeError( | |
String::New("Buffer must have at least two bytes."))); | |
return scope.Close(Undefined()); | |
} | |
return scope.Close(Number::New(calcHeadSizeFromBuffer(object))); | |
} | |
if (object->IsObject() && !object->IsArray()) { | |
if (!object->Has(String::New("length"))) { | |
ThrowException(Exception::TypeError( | |
String::New("State must have property length."))); | |
return scope.Close(Undefined()); | |
} | |
return scope.Close(Number::New(calcHeadSizeFromBuffer(object))); | |
} | |
ThrowException(Exception::TypeError( | |
String::New("Argument must be a either object or buffer."))); | |
return scope.Close(Undefined()); | |
} | |
bool isMasking(Local<Object> masking) { | |
if (masking->IsUndefined()) | |
return false; | |
if (!node::Buffer::HasInstance(masking)) | |
return false; | |
if (node::Buffer::Length(masking) != 4) | |
return false; | |
return true; | |
} | |
int calcHeadSizeFromObject(Local<Object> state) { | |
int size = 2; | |
bool mask = state->Get(String::New("mask")) | |
->BooleanValue(); | |
int length = state->Get(String::New("length")) | |
->NumberValue(); | |
Local<Object> masking = state->Get(String::New("masking")) | |
->ToObject(); | |
if (length > 125 && length < 0x10000) { | |
size += 2; | |
} else if (length > 0xffff) { | |
size += 8; | |
} | |
if (mask || isMasking(masking)) { | |
size += 4; | |
} | |
return size; | |
} | |
int calcHeadSizeFromBuffer(Local<Object> chunk) { | |
int length = 2; | |
byte* head = (byte*) node::Buffer::Data(chunk); | |
if (head[1] & 0x80) | |
length += 4; | |
switch (head[1] & 0x7f) { | |
case 126: | |
length += 2; | |
break; | |
case 127: | |
length += 8; | |
break; | |
} | |
return length; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment