1//  Copyright (c) 2014 Couchbase, Inc.
2//  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
3//  except in compliance with the License. You may obtain a copy of the License at
4//    http://www.apache.org/licenses/LICENSE-2.0
5//  Unless required by applicable law or agreed to in writing, software distributed under the
6//  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
7//  either express or implied. See the License for the specific language governing permissions
8//  and limitations under the License.
9
10package n1ql
11
12import (
13	"encoding/json"
14	"strings"
15)
16
17// Unmarshal a double quoted string. s must begin and end with double
18// quotes.
19func UnmarshalDoubleQuoted(s string) (t string, e error) {
20	if !strings.ContainsRune(s, '\\') {
21		return s[1 : len(s)-1], nil
22	}
23
24	var rv string
25	e = json.Unmarshal([]byte(s), &rv)
26	if e == nil {
27		t = rv
28	}
29
30	return t, e
31}
32
33// Unmarshal a single-quoted string. s must begin and end with single
34// quotes.
35func UnmarshalSingleQuoted(s string) (t string, e error) {
36	s = s[1 : len(s)-1]
37	s = strings.Replace(s, "''", "'", -1) // '' escapes '
38	return UnmarshalUnquoted(s)
39}
40
41// Unmarshal a back-quoted string. s must begin and end with back
42// quotes.
43func UnmarshalBackQuoted(s string) (t string, e error) {
44	s = s[1 : len(s)-1]
45	s = strings.Replace(s, "``", "`", -1) // `` escapes `
46	return UnmarshalUnquoted(s)
47}
48
49// Unmarshal an unquoted string.
50func UnmarshalUnquoted(s string) (t string, e error) {
51	if !strings.ContainsRune(s, '\\') {
52		return s, nil
53	}
54
55	buf := make([]byte, len(s)+2)
56	buf[0], buf[len(buf)-1] = byte('"'), byte('"')
57	for i := 0; i < len(s); i++ {
58		buf[i+1] = s[i]
59	}
60
61	var rv string
62	e = json.Unmarshal(buf, &rv)
63	if e == nil {
64		t = rv
65	}
66
67	return t, e
68}
69