zenity/internal/zenutil/unescape.go

94 lines
1.6 KiB
Go
Raw Normal View History

2021-05-11 09:51:56 -04:00
package zenutil
2022-03-29 07:53:20 -04:00
import "strings"
2021-05-11 09:51:56 -04:00
// Unescape is internal.
func Unescape(s string) string {
// Apply rules described in:
2022-03-28 05:50:33 -04:00
// https://docs.gtk.org/glib/func.strescape.html
2021-05-11 09:51:56 -04:00
const (
initial = iota
escape1
escape2
escape3
)
var oct byte
2022-03-29 07:53:20 -04:00
var res strings.Builder
2021-05-11 09:51:56 -04:00
state := initial
for _, b := range []byte(s) {
switch state {
case initial:
switch b {
case '\\':
state = escape1
default:
2022-03-29 07:53:20 -04:00
res.WriteByte(b)
2021-05-11 09:51:56 -04:00
state = initial
}
case escape1:
switch b {
case '0', '1', '2', '3', '4', '5', '6', '7':
oct = b - '0'
state = escape2
case 'b':
2022-03-29 07:53:20 -04:00
res.WriteByte('\b')
2021-05-11 09:51:56 -04:00
state = initial
case 'f':
2022-03-29 07:53:20 -04:00
res.WriteByte('\f')
2021-05-11 09:51:56 -04:00
state = initial
case 'n':
2022-03-29 07:53:20 -04:00
res.WriteByte('\n')
2021-05-11 09:51:56 -04:00
state = initial
case 'r':
2022-03-29 07:53:20 -04:00
res.WriteByte('\r')
2021-05-11 09:51:56 -04:00
state = initial
case 't':
2022-03-29 07:53:20 -04:00
res.WriteByte('\t')
2021-05-11 09:51:56 -04:00
state = initial
case 'v':
2022-03-29 07:53:20 -04:00
res.WriteByte('\v')
2021-05-11 09:51:56 -04:00
state = initial
default:
2022-03-29 07:53:20 -04:00
res.WriteByte(b)
2021-05-11 09:51:56 -04:00
state = initial
}
case escape2:
switch b {
case '0', '1', '2', '3', '4', '5', '6', '7':
oct = oct<<3 | (b - '0')
state = escape3
case '\\':
2022-03-29 07:53:20 -04:00
res.WriteByte(oct)
2021-05-11 09:51:56 -04:00
state = escape1
default:
2022-03-29 07:53:20 -04:00
res.WriteByte(oct)
res.WriteByte(b)
2021-05-11 09:51:56 -04:00
state = initial
}
case escape3:
switch b {
case '0', '1', '2', '3', '4', '5', '6', '7':
oct = oct<<3 | (b - '0')
2022-03-29 07:53:20 -04:00
res.WriteByte(oct)
2021-05-11 09:51:56 -04:00
state = initial
case '\\':
2022-03-29 07:53:20 -04:00
res.WriteByte(oct)
2021-05-11 09:51:56 -04:00
state = escape1
default:
2022-03-29 07:53:20 -04:00
res.WriteByte(oct)
res.WriteByte(b)
2021-05-11 09:51:56 -04:00
state = initial
}
}
}
if state == escape2 || state == escape3 {
2022-03-29 07:53:20 -04:00
res.WriteByte(oct)
2021-05-11 09:51:56 -04:00
}
2022-03-29 07:53:20 -04:00
return res.String()
2021-05-11 09:51:56 -04:00
}