aboutsummaryrefslogtreecommitdiff
path: root/lib/strings/string.go
diff options
context:
space:
mode:
authorShulhan <ms@kilabit.info>2018-09-15 20:50:06 +0700
committerShulhan <ms@kilabit.info>2018-09-17 22:51:20 +0700
commite914833fa2b0a99fc726c313d594f31ab6b132ba (patch)
treebbc12a780509d1f7d084d92fb857722b5fae1e52 /lib/strings/string.go
parent0f68f37ce159c96d56b4748eee6a9a88c6b7f801 (diff)
downloadpakakeh.go-e914833fa2b0a99fc726c313d594f31ab6b132ba.tar.xz
lib: rename package "string" to "strings"
Diffstat (limited to 'lib/strings/string.go')
-rw-r--r--lib/strings/string.go52
1 files changed, 52 insertions, 0 deletions
diff --git a/lib/strings/string.go b/lib/strings/string.go
new file mode 100644
index 00000000..027db92d
--- /dev/null
+++ b/lib/strings/string.go
@@ -0,0 +1,52 @@
+// Copyright 2018, Shulhan <ms@kilabit.info>. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package strings
+
+import (
+ libbytes "github.com/shuLhan/share/lib/bytes"
+)
+
+//
+// JSONEscape escape the following character: `"` (quotation mark),
+// `\` (reverse solidus), `/` (solidus), `\b` (backspace), `\f` (formfeed),
+// `\n` (newline), `\r` (carriage return`), `\t` (horizontal tab), and control
+// character from 0 - 31.
+//
+// References
+//
+// * https://tools.ietf.org/html/rfc7159#page-8
+//
+func JSONEscape(in string) string {
+ if len(in) == 0 {
+ return in
+ }
+
+ bin := []byte(in)
+ bout := libbytes.JSONEscape(bin)
+
+ return string(bout)
+}
+
+//
+// JSONUnescape unescape JSON string, reversing what StringJSONEscape
+// do.
+//
+// If strict is true, any unknown control character will be returned as error.
+// For example, in string "\x", "x" is not valid control character, and the
+// function will return empty string and error.
+// If strict is false, it will return "x".
+//
+func JSONUnescape(in string, strict bool) (string, error) {
+ if len(in) == 0 {
+ return in, nil
+ }
+
+ bin := []byte(in)
+ bout, err := libbytes.JSONUnescape(bin, strict)
+
+ out := string(bout)
+
+ return out, err
+}