lzw.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. if (!dojo._hasResource["dojox.encoding.tests.lzw"]) { // _hasResource checks
  2. // added by build. Do
  3. // not use _hasResource
  4. // directly in your
  5. // code.
  6. dojo._hasResource["dojox.encoding.tests.lzw"] = true;
  7. dojo.provide("dojox.encoding.tests.lzw");
  8. dojo.require("dojox.encoding.lzw");
  9. dojo.require("dojox.encoding.bits");
  10. (function() {
  11. var msg1 = "The rain in Spain falls mainly on the plain.";
  12. var msg2 = "The rain in Spain falls mainly on the plain.1";
  13. var msg3 = "The rain in Spain falls mainly on the plain.ab";
  14. var msg4 = "The rain in Spain falls mainly on the plain.!@#";
  15. var dc = dojox.encoding, dcb = dc.bits, dcl = dc.lzw;
  16. var s2b = function(s) {
  17. var b = [];
  18. for (var i = 0; i < s.length; ++i) {
  19. b.push(s.charCodeAt(i));
  20. }
  21. return b;
  22. };
  23. var b2s = function(b) {
  24. var s = [];
  25. dojo.forEach(b, function(c) {
  26. s.push(String.fromCharCode(c));
  27. });
  28. return s.join("");
  29. };
  30. var encode = function(msg) {
  31. var x = new dcb.OutputStream(), encoder = new dcl.Encoder(128);
  32. dojo.forEach(s2b(msg), function(v) {
  33. encoder.encode(v, x);
  34. });
  35. encoder.flush(x);
  36. console.debug("bits =", x.getWidth());
  37. return x.getBuffer();
  38. };
  39. var decode = function(n, buf) {
  40. var x = new dcb.InputStream(buf, buf.length * 8), decoder = new dcl.Decoder(128), t = [], w = 0;
  41. while (w < n) {
  42. var v = decoder.decode(x);
  43. t.push(v);
  44. w += v.length;
  45. }
  46. return t.join("");
  47. };
  48. tests.register("dojox.encoding.tests.lzw", [function testLzwMsg1(t) {
  49. t.assertEqual(msg1, decode(msg1.length,
  50. encode(msg1)));
  51. }, function testLzwMsg2(t) {
  52. t.assertEqual(msg2, decode(msg2.length,
  53. encode(msg2)));
  54. }, function testLzwMsg3(t) {
  55. t.assertEqual(msg3, decode(msg3.length,
  56. encode(msg3)));
  57. }, function testLzwMsg4(t) {
  58. t.assertEqual(msg4, decode(msg4.length,
  59. encode(msg4)));
  60. }]);
  61. })();
  62. }