Debian Codegraph @

nih/nih.go

raw
1 /*
2 Copyright 2013-2014 Canonical Ltd.
3
4 This program is free software: you can redistribute it and/or modify it
5 under the terms of the GNU General Public License version 3, as published
6 by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful, but
9 WITHOUT ANY WARRANTY; without even the implied warranties of
10 MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 PURPOSE. See the GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License along
14 with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 // package nih reimplements libnih-dbus's nih_dbus_path's path element
18 // quoting.
19 //
20 // Reimplementing libnih is a wonderful exercise that everybody should persue
21 // at least thrice.
22 package nih
23
24 import "strconv"
25
26 // Quote() takes a byte slice and quotes it รก la libnih.
27 func Quote(s []byte) []byte {
28 if len(s) == 0 {
29 return []byte{'_'}
30 }
31 out := make([]byte, 0, 2*len(s))
32 for _, c := range s {
33 if ('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') {
34 out = append(out, c)
35 } else {
36 if c < 16 {
37 out = append(out, '_', '0')
38 } else {
39 out = append(out, '_')
40 }
41 out = strconv.AppendUint(out, uint64(c), 16)
42 }
43 }
44
45 return out
46 }
47
48 // Unquote() takes a byte slice and undoes the damage done to it by Quote().
49 func Unquote(s []byte) []byte {
50 out := make([]byte, 0, len(s))
51
52 for i := 0; i < len(s); i++ {
53 if s[i] == '_' {
54 if len(s) < i+3 {
55 break
56 }
57 num, err := strconv.ParseUint(string(s[i+1:i+3]), 16, 8)
58 if err == nil {
59 out = append(out, byte(num))
60 }
61 i += 2
62 } else {
63 out = append(out, s[i])
64 }
65 }
66
67 return out
68 }