2019-01-14 10:45:25 +00:00
# ifndef ADDON_UTILITIES_H
# define ADDON_UTILITIES_H
2019-01-18 15:33:56 +00:00
# include <v8.h>
using namespace v8 ;
2019-01-14 10:34:20 +00:00
class NativeString {
char * data ;
size_t length ;
char utf8ValueMemory [ sizeof ( String : : Utf8Value ) ] ;
String : : Utf8Value * utf8Value = nullptr ;
2019-01-18 15:33:56 +00:00
bool invalid = false ;
2019-01-14 10:34:20 +00:00
public :
NativeString ( Isolate * isolate , const Local < Value > & value ) {
if ( value - > IsUndefined ( ) ) {
data = nullptr ;
length = 0 ;
} else if ( value - > IsString ( ) ) {
utf8Value = new ( utf8ValueMemory ) String : : Utf8Value ( isolate , value ) ;
data = ( * * utf8Value ) ;
length = utf8Value - > length ( ) ;
} else if ( value - > IsTypedArray ( ) ) {
Local < ArrayBufferView > arrayBufferView = Local < ArrayBufferView > : : Cast ( value ) ;
ArrayBuffer : : Contents contents = arrayBufferView - > Buffer ( ) - > GetContents ( ) ;
length = contents . ByteLength ( ) ;
data = ( char * ) contents . Data ( ) ;
} else if ( value - > IsArrayBuffer ( ) ) {
Local < ArrayBuffer > arrayBuffer = Local < ArrayBuffer > : : Cast ( value ) ;
ArrayBuffer : : Contents contents = arrayBuffer - > GetContents ( ) ;
length = contents . ByteLength ( ) ;
data = ( char * ) contents . Data ( ) ;
} else {
2019-01-18 15:33:56 +00:00
invalid = true ;
2019-01-14 10:34:20 +00:00
}
}
2019-01-18 15:33:56 +00:00
bool isInvalid ( const FunctionCallbackInfo < Value > & args ) {
if ( invalid ) {
args . GetReturnValue ( ) . Set ( isolate - > ThrowException ( String : : NewFromUtf8 ( isolate , " Text and data can only be passed by String, ArrayBuffer or TypedArray. " ) ) ) ;
}
return invalid ;
}
std : : string_view getString ( ) {
return { data , length } ;
}
2019-01-14 10:34:20 +00:00
~ NativeString ( ) {
if ( utf8Value ) {
utf8Value - > ~ Utf8Value ( ) ;
}
}
} ;
2019-01-14 10:45:25 +00:00
# endif