Advertisement
Guest User

Untitled

a guest
Apr 17th, 2014
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. #include <node.h>
  2. #include <vector>
  3. #include <string>
  4. #include <sstream>
  5. #include <iostream>
  6.  
  7. using namespace v8;
  8.  
  9. short tagDetect(char * ptr){
  10. if (*ptr == '/') {
  11. return 0;
  12. }
  13.  
  14. if (*ptr == 'p') {
  15. return 1;
  16. }
  17.  
  18. if (*(ptr + 1) == '2' || *(ptr + 1) == '3')
  19. return 2;
  20.  
  21. return -1;
  22. }
  23.  
  24. Handle<Value> Callback(const Arguments& args) {
  25. HandleScope scope;
  26.  
  27. if (!args[0]->IsString() || !args[1]->IsFunction()) {
  28. return ThrowException(Exception::TypeError(
  29. String::New("Invalid arguments! First parameter must be [string], second must be a callback [function].")));
  30. }
  31.  
  32. Local<Function> callback = Local<Function>::Cast(args[1]);
  33. String::Utf8Value param1(args[0]->ToString());
  34. std::string input = std::string(*param1);
  35.  
  36. // </p>\n<p> -> ""
  37.  
  38. static Persistent<String> data_symbol = NODE_PSYMBOL("data");
  39. static Persistent<String> tag_symbol = NODE_PSYMBOL("tag");
  40.  
  41. /* ALGORITHM */
  42.  
  43. std::string::size_type pos = 0;
  44.  
  45. int openPos;
  46. short tagID, lastTag, id = 0;
  47.  
  48. Local<Array> nodes = Array::New();
  49.  
  50. while ((pos = input.find('<', pos)) != std::string::npos) {
  51. pos++;
  52. tagID = tagDetect(&input[pos]);
  53. switch (tagID) {
  54. case 0:
  55. if (tagID = tagDetect(&input[pos + 1]) == lastTag && (pos - openPos > 10 || lastTag != 1)) {
  56. Local<Object> node_obj = Object::New();
  57. node_obj->Set(data_symbol, String::New(input.substr(openPos + (lastTag > 1 ? 3 : 2), pos - openPos - (lastTag > 1 ? 3 : 2) - 1).c_str()));
  58. node_obj->Set(tag_symbol, Integer::New(lastTag));
  59. nodes->Set(id, node_obj);
  60. id++;
  61. }
  62.  
  63. break;
  64. case 1:
  65. case 2:
  66. case 3:
  67. openPos = pos;
  68. lastTag = tagID;
  69. break;
  70. }
  71. }
  72.  
  73.  
  74. const unsigned argc = 2;
  75. Local<Value> argv[argc] = {
  76. Local<Value>::New(Null()),
  77. nodes
  78. };
  79.  
  80. callback->Call(Context::GetCurrent()->Global(), argc, argv);
  81.  
  82. return Undefined();
  83. }
  84.  
  85. void RegisterModule(Handle<Object> target) {
  86. target->Set(String::NewSymbol("parse"),
  87. FunctionTemplate::New(Callback)->GetFunction());
  88. }
  89.  
  90. NODE_MODULE(smartparser, RegisterModule);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement