git ssb

1+

cel / wpa-conf-codec



Commit 5de6dc909e2df98bd080c4899ef2b265a415ab3d

Implement encode

Test by encoding and then decoding again, because the codec is not
bijective
cel committed on 2/13/2017, 8:32:07 AM
Parent: f1015df18e879cbad5fe6cb3f49e783d6063f2c3

Files changed

lib/encode.jschanged
test/index.jschanged
lib/encode.jsView
@@ -1,3 +1,72 @@
1-module.exports = function (obj) {
2- throw new Error('not implemented')
1 +module.exports = function encodeConfig(conf) {
2 + if (!conf) return ''
3 + switch (typeof conf) {
4 + case 'object':
5 + var lines = []
6 + for (var k in conf) {
7 + var value = conf[k]
8 + if (k === 'networks' && Array.isArray(value)) {
9 + value.forEach(function (network) {
10 + lines.push('', encodeNetwork(network))
11 + })
12 + } else {
13 + lines.push(encodeProperty(k, value))
14 + }
15 + }
16 + return lines.join('\n')
17 + case 'string':
18 + // fallthrough
19 + case 'number':
20 + return JSON.stringify(conf)
21 + case 'boolean':
22 + return conf ? '1' : '0'
23 + default:
24 + throw new Error("weird value: " + conf)
25 + }
326 }
27 +
28 +function encodeNetwork(network) {
29 + if (!network) return
30 + var lines = []
31 + if (network._comment) {
32 + lines.push('#' + network._comment)
33 + var a = {}
34 + for (var k in network) {
35 + if (k !== '_comment')
36 + a[k] = network[k]
37 + }
38 + network = a
39 + }
40 + lines.push('network={')
41 + for (var k in network) {
42 + lines.push('\t' + encodeProperty(k, network[k]))
43 + }
44 + lines.push('}')
45 + return lines.join('\n')
46 +}
47 +
48 +function encodeProperty(key, value) {
49 + return key + '=' + encodeValue(value)
50 +}
51 +
52 +function encodeValue(value) {
53 + if (!value) return ''
54 + switch (typeof value) {
55 + case 'object':
56 + if (Array.isArray(value)) {
57 + return value.join(' ')
58 + }
59 + var items = []
60 + for (var k in value) {
61 + items.push(encodeProperty(k, value[k]))
62 + }
63 + return items.join(' ')
64 + case 'string':
65 + case 'number':
66 + return JSON.stringify(value)
67 + case 'boolean':
68 + return value ? '1' : '0'
69 + default:
70 + throw new Error("weird value: " + value)
71 + }
72 +}
test/index.jsView
@@ -12,7 +12,8 @@
1212 t.end()
1313 })
1414
1515 test('encode', function (t) {
16- t.deepEquals(wpa.encode(networksObj), networksTxt)
16 + var txt = wpa.encode(networksObj)
17 + t.deepEquals(wpa.decode(txt), networksObj)
1718 t.end()
1819 })

Built with git-ssb-web