Created
August 26, 2015 17:14
-
-
Save trevnorris/d39ff9bc359d2e406faf 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 <v8.h> | |
#include <node.h> | |
#include <node_buffer.h> | |
#include <string.h> | |
using v8::FunctionCallbackInfo; | |
using v8::Handle; | |
using v8::Isolate; | |
using v8::Local; | |
using v8::Object; | |
using v8::String; | |
using v8::Value; | |
void Run(const FunctionCallbackInfo<Value>& info) { | |
assert(node::Buffer::HasInstance(info[0]) && "argument should be a buffer"); | |
assert(info[1]->IsString() && "argument should be a string"); | |
Isolate* isolate = info.GetIsolate(); | |
Local<String> str = info[1].As<String>(); | |
enum node::encoding enc = node::ParseEncoding(isolate, info[2], node::UTF8); | |
const size_t haystack_length = node::Buffer::Length(info[0]); | |
const char* haystack = node::Buffer::Data(info[0]); | |
if (enc == node::UTF8) { | |
String::Utf8Value needle(str); | |
void* ptr = memmem(haystack, haystack_length, *needle, needle.length()); | |
if (ptr == nullptr) | |
return info.GetReturnValue().Set(-1); | |
return info.GetReturnValue().Set( | |
static_cast<int32_t>(static_cast<char*>(ptr) - haystack)); | |
} | |
if (enc == node::UCS2) { | |
String::Value needle(str); | |
// TODO | |
return; | |
} | |
const size_t needle_length = str->Length(); | |
const char* needle = new char[needle_length]; | |
str->WriteOneByte(reinterpret_cast<uint8_t*>(const_cast<char*>(needle)), | |
0, | |
needle_length); | |
void* ptr = memmem(haystack, haystack_length, needle, needle_length); | |
if (ptr == nullptr) { | |
info.GetReturnValue().Set(-1); | |
} else { | |
info.GetReturnValue().Set( | |
static_cast<int32_t>(static_cast<char*>(ptr) - haystack)); | |
} | |
delete needle; | |
} | |
void Init(Handle<Object> target) { | |
NODE_SET_METHOD(target, "run", Run); | |
} | |
NODE_MODULE(addon, Init) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment