home *** CD-ROM | disk | FTP | other *** search
/ Minami 83 / MINAMI83.iso / Extra / DivXInstaller.exe / $PLUGINSDIR / GoogleToolbarFirefox.msi / xpi / amulet-jslib / firefox / protocol4.js < prev    next >
Text File  |  2006-08-07  |  2KB  |  64 lines

  1. function G_Protocol4Parser() {
  2. this.debugZone = "protocol4";
  3. this.protocol4RegExp_ = new RegExp("([^:]+):\\d+:(.*)$");
  4. this.newlineRegExp_ = new RegExp("(\\r)?\\n");
  5. }
  6. G_Protocol4Parser.prototype.parse = function(text) {
  7. var response = {};
  8. if (!text)
  9. return response;
  10. var lines = text.split(this.newlineRegExp_);
  11. for (var i = 0; i < lines.length; i++)
  12. if (this.protocol4RegExp_.exec(lines[i]))
  13. response[RegExp.$1] = RegExp.$2;
  14. return response;
  15. }
  16. G_Protocol4Parser.prototype.serialize = function(map) {
  17. if (typeof map != "object")
  18. throw new Error("map must be an object");
  19. var text = "";
  20. for (var key in map) {
  21. if (typeof map[key] != "string")
  22. throw new Error("Keys and values must be strings");
  23. text += key + ":" + map[key].length + ":" + map[key] + "\n";
  24. }
  25. return text;
  26. }
  27. function TEST_G_Protocol4Parser() {
  28. if (G_GDEBUG) {
  29. var z = "protocol4 UNITTEST";
  30. G_debugService.enableZone(z);
  31. G_Debug(z, "Starting");
  32. var p = new G_Protocol4Parser();
  33. function isEmpty(map) {
  34. for (var key in map)
  35. return false;
  36. return true;
  37. };
  38. G_Assert(z, isEmpty(p.parse(null)), "Parsing null broken");
  39. G_Assert(z, isEmpty(p.parse("")), "Parsing nothing broken");
  40. var t = "foo:3:bar";
  41. G_Assert(z, p.parse(t)["foo"] === "bar", "Parsing one line broken");
  42. t = "foo:3:bar\n";
  43. G_Assert(z, p.parse(t)["foo"] === "bar", "Parsing line with lf broken");
  44. t = "foo:3:bar\r\n";
  45. G_Assert(z, p.parse(t)["foo"] === "bar", "Parsing with crlf broken");
  46. t = "foo:3:bar\nbar:3:baz\r\nbom:3:yaz\n";
  47. G_Assert(z, p.parse(t)["foo"] === "bar", "First in multiline");
  48. G_Assert(z, p.parse(t)["bar"] === "baz", "Second in multiline");
  49. G_Assert(z, p.parse(t)["bom"] === "yaz", "Third in multiline");
  50. G_Assert(z, p.parse(t)[""] === undefined, "Non-existent in multiline");
  51. var original = {
  52. "1": "1",
  53. "2": "2",
  54. "foobar": "baz",
  55. "hello there": "how are you?" ,
  56. };
  57. var deserialized = p.parse(p.serialize(original));
  58. for (var key in original)
  59. G_Assert(z, original[key] === deserialized[key],
  60. "Trouble (de)serializing " + key);
  61. G_Debug(z, "PASSED");
  62. }
  63. }
  64.