Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <node.h>
- #include <v8.h>
- #include <string>
- #define NEW_ERROR(ar) ThrowException(Exception::TypeError(String::New(ar)))
- using namespace v8;
- int escape_chars(std::string&,int);
- Handle<Value> escape(const Arguments& args)
- {
- Local<String> arg = args[0]->ToString();
- String::Utf8Value argc(arg);
- std::string argcs(*argc);
- if (!args[1]->IsNumber())
- {
- NEW_ERROR("El segundo argumento ha de ser un número");
- }
- // call
- double rtv = escape_chars(argcs,args[1]->NumberValue());
- if (rtv == 0)
- {
- return String::New(argcs.c_str());
- }
- else
- {
- return False();
- }
- }
- int escape_chars(std::string& str, int flag)
- {
- /* flags 0: only ' and " | 1: HTML encode | 2: ', " and HTML*/
- size_t f,flast;
- if (str.length() < 1)
- {
- return 1;
- }
- if(flag == 0 || flag == 2)
- {
- // single quote
- const char sq[2] = {0x27,0x00};
- const char sqr[3] = {0x5c,0x27,0x00};
- f = str.find_first_of(sq);
- while(f != std::string::npos)
- {
- str.replace(f,1,sqr);
- if (str.length() > f+2)
- {
- f = str.find_first_of(sq,f+2);
- }
- else
- {
- break;
- }
- }
- // double quote
- const char dq[2] = {0x22,0x00};
- const char dqr[3] = {0x5c,0x22,0x00};
- f = str.find_first_of(dq);
- while(f != std::string::npos)
- {
- str.replace(f,1,dqr);
- if (str.length() > f+2){
- f = str.find_first_of(dq,f+2);
- }
- else
- {
- break;
- }
- }
- }
- if(flag == 1 || flag == 2)
- {
- // HTML
- const char n[2] = {0x0A,0x00}; // \n
- const char nr[2] = {0x0D,0x00}; // \r
- const char nrr[5] = {0x3c,0x62,0x72,0x3e,0x00}; // <br>
- f = str.find_first_of(n);
- while(f != std::string::npos)
- {
- flast = str.find_first_of( nr,f-1 );
- if (flast != std::string::npos )
- {
- str.replace(flast,2,nrr);
- }
- else
- {
- str.replace(f,1,nrr);
- }
- f = str.find_first_of(n);
- }
- f = str.find_first_of(nr);
- while(f != std::string::npos)
- {
- str.replace(f,1,nrr);
- f = str.find_first_of(nr);
- }
- }
- return 0;
- }
- void init(Handle<Object> target) {
- target->Set(String::NewSymbol("escape"),
- FunctionTemplate::New(escape)->GetFunction());
- }
- NODE_MODULE(utils2, init);
Advertisement
Add Comment
Please, Sign In to add comment