source: branches/samba-3.5.x/swat2/scripting/client/encoder.js

Last change on this file was 414, checked in by Herwig Bauernfeind, 15 years ago

Samba 3.5.0: Initial import

File size: 1.9 KB
Line 
1/*
2 client side js functions for encoding/decoding objects into linear strings
3
4 Copyright Andrew Tridgell 2005
5 released under the GNU GPL Version 3 or later
6*/
7/*
8 usage:
9
10 enc = encodeObject(obj);
11 obj = decodeObject(enc);
12
13 The encoded format of the object is a string that is safe to
14 use in URLs
15
16 Note that only data elements are encoded, not functions
17*/
18
19function count_members(o) {
20 var i, count = 0;
21 for (i in o) {
22 count++;
23 }
24 return count;
25}
26
27function encodeObject(o) {
28 var i, r = count_members(o) + ":";
29 for (i in o) {
30 var t = typeof(o[i]);
31 if (t == 'object') {
32 r = r + "" + i + ":" + t + ":" + encodeObject(o[i]);
33 } else if (t == 'string') {
34 var s = encodeURIComponent(o[i]).replace(/%/g,'#');
35 r = r + "" + i + ":" + t + ":" + s + ":";
36 } else if (t == 'boolean' || t == 'number') {
37 r = r + "" + i + ":" + t + ":" + o[i] + ":";
38 } else if (t == 'undefined' || t == 'null') {
39 r = r + "" + i + ":" + t + ":";
40 } else if (t != 'function') {
41 alert("Unable to encode type " + t);
42 }
43 }
44 return r;
45}
46
47function decodeObjectArray(a) {
48 var o = new Object();
49 var i, count = a[a.i]; a.i++;
50 for (i=0;i<count;i++) {
51 var name = a[a.i]; a.i++;
52 var type = a[a.i]; a.i++;
53 var value;
54 if (type == 'object') {
55 o[name] = decodeObjectArray(a);
56 } else if (type == "string") {
57 value = decodeURIComponent(a[a.i].replace(/#/g,'%')); a.i++;
58 o[name] = value;
59 } else if (type == "boolean") {
60 value = a[a.i]; a.i++;
61 if (value == 'true') {
62 o[name] = true;
63 } else {
64 o[name] = false;
65 }
66 } else if (type == "undefined") {
67 o[name] = undefined;
68 } else if (type == "null") {
69 o[name] = null;
70 } else if (type == "number") {
71 value = a[a.i]; a.i++;
72 o[name] = value * 1;
73 } else {
74 alert("Unable to delinearise type " + type);
75 }
76 }
77 return o;
78}
79
80function decodeObject(str) {
81 var a = str.split(':');
82 a.i = 0;
83 return decodeObjectArray(a);
84}
Note: See TracBrowser for help on using the repository browser.