├── go.mod ├── README.md ├── fold_test.go ├── fields.go ├── fields_test.go ├── fold.go ├── mem_test.go ├── LICENSE └── mem.go /go.mod: -------------------------------------------------------------------------------- 1 | module go4.org/mem 2 | 3 | go 1.14 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go4.org/mem 2 | 3 | See https://godoc.org/go4.org/mem 4 | -------------------------------------------------------------------------------- /fold_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2020 The Go4 AUTHORS 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package mem // import "go4.org/mem" 18 | 19 | import "testing" 20 | 21 | type foldTest struct { 22 | a, b string 23 | want bool 24 | } 25 | 26 | func TestContainsFold(t *testing.T) { 27 | runFoldTests(t, ContainsFold, "ContainsFold", []foldTest{ 28 | {"foo", "", true}, 29 | {"", "", true}, 30 | {"", "foo", false}, 31 | {"foo", "foo", true}, 32 | {"FOO", "foo", true}, 33 | {"foo", "FOO", true}, 34 | {"foo ", "FOO", true}, 35 | {" foo", "FOO", true}, 36 | {" foo ", "FOO", true}, 37 | {"FOO ", "foo", true}, 38 | {" FOO", "foo", true}, 39 | {" FOO ", "foo", true}, 40 | {" FOO ", "bar", false}, 41 | }) 42 | } 43 | 44 | func TestHasPrefixFold(t *testing.T) { 45 | runFoldTests(t, HasPrefixFold, "HasPrefixFold", []foldTest{ 46 | {"foo", "", true}, 47 | {"", "", true}, 48 | {"", "foo", false}, 49 | {"foo", "foo", true}, 50 | {"FOO", "foo", true}, 51 | {"foo", "FOO", true}, 52 | {"foo", "food", false}, 53 | }) 54 | } 55 | 56 | func TestHasSuffixFold(t *testing.T) { 57 | runFoldTests(t, HasSuffixFold, "HasSuffixFold", []foldTest{ 58 | {"foo", "", true}, 59 | {"", "", true}, 60 | {"", "foo", false}, 61 | {"foo", "foo", true}, 62 | {"FOO", "foo", true}, 63 | {"foo", "FOO", true}, 64 | {" foo", "FOO", true}, 65 | {" foo", "FoO", true}, 66 | }) 67 | } 68 | 69 | func runFoldTests(t *testing.T, fn func(RO, RO) bool, funcName string, tests []foldTest) { 70 | t.Helper() 71 | for _, tt := range tests { 72 | got := fn(S(tt.a), S(tt.b)) 73 | if got != tt.want { 74 | t.Errorf("%s(%q, %q) = %v; want %v", funcName, tt.a, tt.b, got, tt.want) 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /fields.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2020 The Go4 AUTHORS 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package mem 18 | 19 | import ( 20 | "unicode" 21 | "unicode/utf8" 22 | ) 23 | 24 | var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1} 25 | 26 | // AppendFields is like strings.Fields, but is append-like and uses a mem.RO instead of a string. 27 | func AppendFields(dst []RO, m RO) []RO { 28 | s := m.m 29 | 30 | // Copied from the Go standard library (BSD license). 31 | 32 | // First count the fields. 33 | // This is an exact count if s is ASCII, otherwise it is an approximation. 34 | n := 0 35 | wasSpace := 1 36 | // setBits is used to track which bits are set in the bytes of s. 37 | setBits := uint8(0) 38 | for i := 0; i < len(s); i++ { 39 | r := s[i] 40 | setBits |= r 41 | isSpace := int(asciiSpace[r]) 42 | n += wasSpace & ^isSpace 43 | wasSpace = isSpace 44 | } 45 | 46 | if setBits >= utf8.RuneSelf { 47 | // Some runes in the input string are not ASCII. 48 | return AppendFieldsFunc(dst, m, unicode.IsSpace) 49 | } 50 | // ASCII fast path 51 | fieldStart := 0 52 | i := 0 53 | // Skip spaces in the front of the input. 54 | for i < len(s) && asciiSpace[s[i]] != 0 { 55 | i++ 56 | } 57 | fieldStart = i 58 | for i < len(s) { 59 | if asciiSpace[s[i]] == 0 { 60 | i++ 61 | continue 62 | } 63 | dst = append(dst, RO{m: s[fieldStart:i]}) 64 | i++ 65 | // Skip spaces in between fields. 66 | for i < len(s) && asciiSpace[s[i]] != 0 { 67 | i++ 68 | } 69 | fieldStart = i 70 | } 71 | if fieldStart < len(s) { // Last field might end at EOF. 72 | dst = append(dst, RO{m: s[fieldStart:]}) 73 | } 74 | return dst 75 | } 76 | 77 | // AppendFieldsFunc is like strings.FieldsFunc, but is append-like and uses a mem.RO instead of a string. 78 | func AppendFieldsFunc(dst []RO, m RO, f func(rune) bool) []RO { 79 | s := string(m.m) 80 | 81 | // Find the field start and end indices. 82 | wasField := false 83 | fromIndex := 0 84 | for i, rune := range s { 85 | if f(rune) { 86 | if wasField { 87 | dst = append(dst, RO{m: unsafeString(s[fromIndex:i])}) 88 | wasField = false 89 | } 90 | } else { 91 | if !wasField { 92 | fromIndex = i 93 | wasField = true 94 | } 95 | } 96 | } 97 | 98 | // Last field might end at EOF. 99 | if wasField { 100 | dst = append(dst, RO{m: unsafeString(s[fromIndex:len(s)])}) 101 | } 102 | return dst 103 | } 104 | -------------------------------------------------------------------------------- /fields_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2020 The Go4 AUTHORS 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | // Tests copied from Go's strings package. (BSD license) 18 | 19 | package mem 20 | 21 | import ( 22 | "testing" 23 | "unicode" 24 | ) 25 | 26 | var faces = "☺☻☹" 27 | 28 | type FieldsTest struct { 29 | s string 30 | a []string 31 | } 32 | 33 | var fieldstests = []FieldsTest{ 34 | {"", []string{}}, 35 | {" ", []string{}}, 36 | {" \t ", []string{}}, 37 | {"\u2000", []string{}}, 38 | {" abc ", []string{"abc"}}, 39 | {"1 2 3 4", []string{"1", "2", "3", "4"}}, 40 | {"1 2 3 4", []string{"1", "2", "3", "4"}}, 41 | {"1\t\t2\t\t3\t4", []string{"1", "2", "3", "4"}}, 42 | {"1\u20002\u20013\u20024", []string{"1", "2", "3", "4"}}, 43 | {"\u2000\u2001\u2002", []string{}}, 44 | {"\n™\t™\n", []string{"™", "™"}}, 45 | {"\n\u20001™2\u2000 \u2001 ™", []string{"1™2", "™"}}, 46 | {"\n1\uFFFD \uFFFD2\u20003\uFFFD4", []string{"1\uFFFD", "\uFFFD2", "3\uFFFD4"}}, 47 | {"1\xFF\u2000\xFF2\xFF \xFF", []string{"1\xFF", "\xFF2\xFF", "\xFF"}}, 48 | {faces, []string{faces}}, 49 | } 50 | 51 | func eq(a []RO, b []string) bool { 52 | if len(a) != len(b) { 53 | return false 54 | } 55 | for i := 0; i < len(a); i++ { 56 | if !a[i].EqualString(b[i]) { 57 | return false 58 | } 59 | } 60 | return true 61 | } 62 | 63 | func TestFields(t *testing.T) { 64 | for _, tt := range fieldstests { 65 | a := AppendFields(nil, S(tt.s)) 66 | if !eq(a, tt.a) { 67 | t.Errorf("Fields(%q) = %v; want %v", tt.s, a, tt.a) 68 | continue 69 | } 70 | } 71 | } 72 | 73 | var FieldsFuncTests = []FieldsTest{ 74 | {"", []string{}}, 75 | {"XX", []string{}}, 76 | {"XXhiXXX", []string{"hi"}}, 77 | {"aXXbXXXcX", []string{"a", "b", "c"}}, 78 | } 79 | 80 | func TestFieldsFunc(t *testing.T) { 81 | for _, tt := range fieldstests { 82 | a := AppendFieldsFunc(nil, S(tt.s), unicode.IsSpace) 83 | if !eq(a, tt.a) { 84 | t.Errorf("FieldsFunc(%q, unicode.IsSpace) = %v; want %v", tt.s, a, tt.a) 85 | continue 86 | } 87 | } 88 | pred := func(c rune) bool { return c == 'X' } 89 | for _, tt := range FieldsFuncTests { 90 | a := AppendFieldsFunc(nil, S(tt.s), pred) 91 | if !eq(a, tt.a) { 92 | t.Errorf("FieldsFunc(%q) = %v, want %v", tt.s, a, tt.a) 93 | } 94 | } 95 | } 96 | 97 | func TestFieldsAllocs(t *testing.T) { 98 | var f []RO 99 | n := int(testing.AllocsPerRun(1000, func() { 100 | f = AppendFields(f[:0], S(" foo bar baz")) 101 | if len(f) != 3 { 102 | panic("wrong result") 103 | } 104 | })) 105 | if n != 0 { 106 | t.Fatalf("allocs = %d; want 0", n) 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /fold.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2020 The Go4 AUTHORS 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package mem // import "go4.org/mem" 18 | 19 | import ( 20 | "strings" 21 | "unicode" 22 | "unicode/utf8" 23 | ) 24 | 25 | // equalFoldRune compares a and b runes whether they fold equally. 26 | // 27 | // The code comes from strings.EqualFold, but shortened to only one rune. 28 | func equalFoldRune(sr, tr rune) bool { 29 | if sr == tr { 30 | return true 31 | } 32 | // Make sr < tr to simplify what follows. 33 | if tr < sr { 34 | sr, tr = tr, sr 35 | } 36 | // Fast check for ASCII. 37 | if tr < utf8.RuneSelf && 'A' <= sr && sr <= 'Z' { 38 | // ASCII, and sr is upper case. tr must be lower case. 39 | if tr == sr+'a'-'A' { 40 | return true 41 | } 42 | return false 43 | } 44 | 45 | // General case. SimpleFold(x) returns the next equivalent rune > x 46 | // or wraps around to smaller values. 47 | r := unicode.SimpleFold(sr) 48 | for r != sr && r < tr { 49 | r = unicode.SimpleFold(r) 50 | } 51 | if r == tr { 52 | return true 53 | } 54 | return false 55 | } 56 | 57 | // HasPrefixFold is like HasPrefix but uses Unicode case-folding, 58 | // matching case insensitively. 59 | func HasPrefixFold(s, prefix RO) bool { 60 | if strings.HasPrefix(s.str(), prefix.str()) { 61 | // Exact case fast path. 62 | return true 63 | } 64 | for _, pr := range prefix.str() { 65 | if s.Len() == 0 { 66 | return false 67 | } 68 | // step with s, too 69 | sr, size := utf8.DecodeRuneInString(s.str()) 70 | if sr == utf8.RuneError { 71 | return false 72 | } 73 | s = s.SliceFrom(size) 74 | if !equalFoldRune(sr, pr) { 75 | return false 76 | } 77 | } 78 | return true 79 | } 80 | 81 | // HasSuffixFold is like HasSuffix but uses Unicode case-folding, 82 | // matching case insensitively. 83 | func HasSuffixFold(s, suffix RO) bool { 84 | if suffix.Len() == 0 { 85 | return true 86 | } 87 | if strings.HasSuffix(s.str(), suffix.str()) { 88 | // Exact case fast path. 89 | return true 90 | } 91 | // count the runes and bytes in s, but only until rune count of suffix 92 | bo, so := s.Len(), suffix.Len() 93 | for bo > 0 && so > 0 { 94 | r, size := utf8.DecodeLastRuneInString(s.str()[:bo]) 95 | if r == utf8.RuneError { 96 | return false 97 | } 98 | bo -= size 99 | 100 | sr, size := utf8.DecodeLastRuneInString(suffix.str()[:so]) 101 | if sr == utf8.RuneError { 102 | return false 103 | } 104 | so -= size 105 | 106 | if !equalFoldRune(r, sr) { 107 | return false 108 | } 109 | } 110 | return so == 0 111 | } 112 | 113 | // ContainsFold is like Contains but uses Unicode case-folding for a case insensitive substring search. 114 | func ContainsFold(s, substr RO) bool { 115 | if substr.Len() == 0 || strings.Contains(s.str(), substr.str()) { 116 | // Easy cases. 117 | return true 118 | } 119 | if s.Len() == 0 { 120 | return false 121 | } 122 | firstRune := rune(substr.At(0)) // Len != 0 checked above 123 | if firstRune >= utf8.RuneSelf { 124 | firstRune, _ = utf8.DecodeRuneInString(substr.str()) 125 | } 126 | for i, rune := range s.str() { 127 | if equalFoldRune(rune, firstRune) && HasPrefixFold(s.SliceFrom(i), substr) { 128 | return true 129 | } 130 | } 131 | return false 132 | } 133 | -------------------------------------------------------------------------------- /mem_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2020 The Go4 AUTHORS 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package mem 18 | 19 | import "testing" 20 | 21 | func TestRO(t *testing.T) { 22 | b := []byte("some memory.") 23 | s := "some memory." 24 | rb := B(b) 25 | rs := S(s) 26 | if !rb.Equal(rs) { 27 | t.Fatal("rb != rs") 28 | } 29 | if !rb.EqualString(s) { 30 | t.Errorf("not equal string") 31 | } 32 | if !rs.EqualBytes(b) { 33 | t.Errorf("not equal byte") 34 | } 35 | if !rb.EqualBytes(b) { 36 | t.Errorf("not equal bytes") 37 | } 38 | if !rs.EqualString(s) { 39 | t.Errorf("not equal string") 40 | } 41 | if rb.Less(rs) { 42 | t.Errorf("bad less") 43 | } 44 | if rs.Less(rb) { 45 | t.Errorf("bad less") 46 | } 47 | if !rs.Less(S("~")) { 48 | t.Errorf("bad less") 49 | } 50 | if !rb.Less(S("~")) { 51 | t.Errorf("bad less") 52 | } 53 | 54 | if rb.At(0) != 's' { 55 | t.Fatalf("[0] = %q; want 's'", rb.At(0)) 56 | } 57 | b[0] = 'z' 58 | if rb.At(0) != 'z' { 59 | t.Fatalf("[0] = %q; want 'z'", rb.At(0)) 60 | } 61 | 62 | var got []byte 63 | got = Append(got, rb) 64 | got = Append(got, rs) 65 | want := "zome memory.some memory." 66 | if string(got) != want { 67 | t.Errorf("got %q; want %q", got, want) 68 | } 69 | 70 | } 71 | 72 | func TestAllocs(t *testing.T) { 73 | b := []byte("some memory.") 74 | n := uint(testing.AllocsPerRun(5000, func() { 75 | ro := B(b) 76 | if ro.Len() != len(b) { 77 | t.Fatal("wrong length") 78 | } 79 | })) 80 | if n != 0 { 81 | t.Errorf("B: unexpected allocs (%d)", n) 82 | } 83 | 84 | ro := B(b) 85 | s := string(b) 86 | n = uint(testing.AllocsPerRun(5000, func() { 87 | globalString = ro.StringCopy() 88 | if globalString != s { 89 | t.Fatal("wrong string") 90 | } 91 | })) 92 | if n != 1 { 93 | t.Errorf("StringCopy: unexpected allocs (%d)", n) 94 | } 95 | } 96 | 97 | var globalString string 98 | 99 | func TestStrconv(t *testing.T) { 100 | b := []byte("1234") 101 | i, err := ParseInt(B(b), 10, 64) 102 | if err != nil { 103 | t.Fatal(err) 104 | } 105 | if i != 1234 { 106 | t.Errorf("got %d; want 1234", i) 107 | } 108 | } 109 | 110 | var cutTests = []struct { 111 | s, sep string 112 | before, after string 113 | found bool 114 | }{ 115 | {"abc", "b", "a", "c", true}, 116 | {"abc", "a", "", "bc", true}, 117 | {"abc", "c", "ab", "", true}, 118 | {"abc", "abc", "", "", true}, 119 | {"abc", "", "", "abc", true}, 120 | {"abc", "d", "abc", "", false}, 121 | {"", "d", "", "", false}, 122 | {"", "", "", "", true}, 123 | } 124 | 125 | func TestCut(t *testing.T) { 126 | for _, tt := range cutTests { 127 | if before, after, found := Cut(S(tt.s), S(tt.sep)); !before.Equal(S(tt.before)) || !after.Equal(S(tt.after)) || found != tt.found { 128 | t.Errorf("Cut(%q, %q) = %q, %q, %v, want %q, %q, %v", tt.s, tt.sep, before.StringCopy(), after.StringCopy(), found, tt.before, tt.after, tt.found) 129 | } 130 | } 131 | } 132 | 133 | var cutPrefixTests = []struct { 134 | s, sep string 135 | after string 136 | found bool 137 | }{ 138 | {"abc", "a", "bc", true}, 139 | {"abc", "abc", "", true}, 140 | {"abc", "", "abc", true}, 141 | {"abc", "d", "abc", false}, 142 | {"", "d", "", false}, 143 | {"", "", "", true}, 144 | } 145 | 146 | func TestCutPrefix(t *testing.T) { 147 | for _, tt := range cutPrefixTests { 148 | s, sep := S(tt.s), S(tt.sep) 149 | if after, found := CutPrefix(s, sep); !after.Equal(S(tt.after)) || found != tt.found { 150 | t.Errorf("CutPrefix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, after.StringCopy(), found, tt.after, tt.found) 151 | } 152 | } 153 | } 154 | 155 | var cutSuffixTests = []struct { 156 | s, sep string 157 | after string 158 | found bool 159 | }{ 160 | {"abc", "bc", "a", true}, 161 | {"abc", "abc", "", true}, 162 | {"abc", "", "abc", true}, 163 | {"abc", "d", "abc", false}, 164 | {"", "d", "", false}, 165 | {"", "", "", true}, 166 | } 167 | 168 | func TestCutSuffix(t *testing.T) { 169 | for _, tt := range cutSuffixTests { 170 | if after, found := CutSuffix(S(tt.s), S(tt.sep)); !after.Equal(S(tt.after)) || found != tt.found { 171 | t.Errorf("CutSuffix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, after.StringCopy(), found, tt.after, tt.found) 172 | } 173 | } 174 | } 175 | 176 | func BenchmarkStringCopy(b *testing.B) { 177 | b.ReportAllocs() 178 | ro := S("only a fool starts a large fire.") 179 | for i := 0; i < b.N; i++ { 180 | globalString = ro.StringCopy() 181 | } 182 | } 183 | 184 | func BenchmarkHash(b *testing.B) { 185 | b.ReportAllocs() 186 | ro := S("A man with a beard was always a little suspect anyway.") 187 | x := ro.MapHash() 188 | for i := 0; i < b.N; i++ { 189 | if x != ro.MapHash() { 190 | b.Fatal("hash changed") 191 | } 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /mem.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2020 The Go4 AUTHORS 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | // Package mem provides the mem.RO type that allows you to cheaply pass & 18 | // access either a read-only []byte or a string. 19 | package mem // import "go4.org/mem" 20 | 21 | import ( 22 | "hash/maphash" 23 | "strconv" 24 | "strings" 25 | "sync" 26 | "unicode/utf8" 27 | "unsafe" 28 | ) 29 | 30 | // RO is a read-only view of some bytes of memory. It may be be backed 31 | // by a string or []byte. Notably, unlike a string, the memory is not 32 | // guaranteed to be immutable. While the length is fixed, the 33 | // underlying bytes might change if interleaved with code that's 34 | // modifying the underlying memory. 35 | // 36 | // RO is a value type that's the same size of a Go string. Its various 37 | // methods should inline & compile to the equivalent operations 38 | // working on a string or []byte directly. 39 | // 40 | // Unlike a Go string, RO is not 'comparable' (it can't be a map key 41 | // or support ==). Use its Equal method to compare. This is done so an 42 | // RO backed by a later-mutating []byte doesn't break invariants in 43 | // Go's map implementation. 44 | type RO struct { 45 | _ [0]func() // not comparable; don't want to be a map key or support == 46 | m unsafeString 47 | } 48 | 49 | // str returns the unsafeString as a string. Only for use with standard 50 | // library funcs known to not let the string escape, as it doesn't 51 | // obey the language/runtime's expectations of a real string (it can 52 | // change underfoot). 53 | func (r RO) str() string { return string(r.m) } 54 | 55 | // Len returns len(r). 56 | func (r RO) Len() int { return len(r.m) } 57 | 58 | // At returns r[i]. 59 | func (r RO) At(i int) byte { return r.m[i] } 60 | 61 | // Slice returns r[from:to]. 62 | func (r RO) Slice(from, to int) RO { return RO{m: r.m[from:to]} } 63 | 64 | // SliceFrom returns r[from:]. 65 | func (r RO) SliceFrom(from int) RO { return RO{m: r.m[from:]} } 66 | 67 | // SliceTo returns r[:to]. 68 | func (r RO) SliceTo(to int) RO { return RO{m: r.m[:to]} } 69 | 70 | // Copy copies up to len(dest) bytes into dest from r and returns the 71 | // number of bytes copied, the min(r.Len(), len(dest)). 72 | func (r RO) Copy(dest []byte) int { return copy(dest, r.m) } 73 | 74 | // Equal reports whether r and r2 are the same length and contain the 75 | // same bytes. 76 | func (r RO) Equal(r2 RO) bool { return r.m == r2.m } 77 | 78 | // EqualString reports whether r and s are the same length and contain 79 | // the same bytes. 80 | func (r RO) EqualString(s string) bool { return r.str() == s } 81 | 82 | // EqualBytes reports whether r and b are the same length and contain 83 | // the same bytes. 84 | func (r RO) EqualBytes(b []byte) bool { return r.str() == string(b) } 85 | 86 | // Less reports whether r < r2. 87 | func (r RO) Less(r2 RO) bool { return r.str() < r2.str() } 88 | 89 | var builderPool = sync.Pool{ 90 | New: func() interface{} { 91 | return new(strings.Builder) 92 | }, 93 | } 94 | 95 | // StringCopy returns m's contents in a newly allocated string. 96 | func (r RO) StringCopy() string { 97 | buf := builderPool.Get().(*strings.Builder) 98 | defer builderPool.Put(buf) 99 | defer buf.Reset() 100 | buf.WriteString(r.str()) 101 | return buf.String() 102 | } 103 | 104 | var seed = maphash.MakeSeed() 105 | 106 | // MapHash returns a hash of r's contents using runtime/maphash. 107 | // The hash is stable for the lifetime of a process. 108 | func (r RO) MapHash() uint64 { 109 | var hash maphash.Hash 110 | hash.SetSeed(seed) 111 | hash.WriteString(r.str()) 112 | return hash.Sum64() 113 | } 114 | 115 | // ParseInt returns a signed integer from m, using strconv.ParseInt. 116 | func ParseInt(m RO, base, bitSize int) (int64, error) { 117 | return strconv.ParseInt(m.str(), base, bitSize) 118 | } 119 | 120 | // ParseUint returns a unsigned integer from m, using strconv.ParseUint. 121 | func ParseUint(m RO, base, bitSize int) (uint64, error) { 122 | return strconv.ParseUint(m.str(), base, bitSize) 123 | } 124 | 125 | // ParseFloat returns a float from, using strconv.ParseFloat. 126 | func ParseFloat(m RO, bitSize int) (float64, error) { 127 | return strconv.ParseFloat(m.str(), bitSize) 128 | } 129 | 130 | // Append appends m to dest, and returns the possibly-reallocated 131 | // dest. 132 | func Append(dest []byte, m RO) []byte { return append(dest, m.m...) } 133 | 134 | // Contains reports whether substr is within m. 135 | func Contains(m, substr RO) bool { return strings.Contains(m.str(), substr.str()) } 136 | 137 | // EqualFold reports whether s and t, interpreted as UTF-8 strings, 138 | // are equal under Unicode case-folding, which is a more general form 139 | // of case-insensitivity. 140 | func EqualFold(m, m2 RO) bool { return strings.EqualFold(m.str(), m2.str()) } 141 | 142 | // HasPrefix reports whether m starts with prefix. 143 | func HasPrefix(m, prefix RO) bool { return strings.HasPrefix(m.str(), prefix.str()) } 144 | 145 | // HasSuffix reports whether m ends with suffix. 146 | func HasSuffix(m, suffix RO) bool { return strings.HasSuffix(m.str(), suffix.str()) } 147 | 148 | // Index returns the index of the first instance of substr in m, or -1 149 | // if substr is not present in m. 150 | func Index(m, substr RO) int { return strings.Index(m.str(), substr.str()) } 151 | 152 | // IndexByte returns the index of the first instance of c in m, or -1 153 | // if c is not present in m. 154 | func IndexByte(m RO, c byte) int { return strings.IndexByte(m.str(), c) } 155 | 156 | // LastIndexByte returns the index into m of the last Unicode code 157 | // point satisfying f(c), or -1 if none do. 158 | func LastIndexByte(m RO, c byte) int { return strings.LastIndexByte(m.str(), c) } 159 | 160 | // LastIndex returns the index of the last instance of substr in m, or 161 | // -1 if substr is not present in m. 162 | func LastIndex(m, substr RO) int { return strings.LastIndex(m.str(), substr.str()) } 163 | 164 | // TrimSpace returns a slice of the string s, with all leading and 165 | // trailing white space removed, as defined by Unicode. 166 | func TrimSpace(m RO) RO { return S(strings.TrimSpace(m.str())) } 167 | 168 | // TrimSuffix returns m without the provided trailing suffix. 169 | // If m doesn't end with suffix, m is returned unchanged. 170 | func TrimSuffix(m, suffix RO) RO { 171 | return S(strings.TrimSuffix(m.str(), suffix.str())) 172 | } 173 | 174 | // TrimPrefix returns m without the provided leading prefix. 175 | // If m doesn't start with prefix, m is returned unchanged. 176 | func TrimPrefix(m, prefix RO) RO { 177 | return S(strings.TrimPrefix(m.str(), prefix.str())) 178 | } 179 | 180 | // TrimRightCutset returns a slice of m with all trailing Unicode code 181 | // points contained in cutset removed. 182 | // 183 | // To remove a suffix, use TrimSuffix instead. 184 | func TrimRightCutset(m, cutset RO) RO { 185 | return S(strings.TrimRight(m.str(), cutset.str())) 186 | } 187 | 188 | // TrimLeftCutset returns a slice of m with all leading Unicode code 189 | // points contained in cutset removed. 190 | // 191 | // To remove a prefix, use TrimPrefix instead. 192 | func TrimLeftCutset(m, cutset RO) RO { 193 | return S(strings.TrimLeft(m.str(), cutset.str())) 194 | } 195 | 196 | // TrimCutset returns a slice of the string s with all leading and 197 | // trailing Unicode code points contained in cutset removed. 198 | func TrimCutset(m, cutset RO) RO { 199 | return S(strings.Trim(m.str(), cutset.str())) 200 | } 201 | 202 | // TrimFunc returns a slice of m with all leading and trailing Unicode 203 | // code points c satisfying f(c) removed. 204 | func TrimFunc(m RO, f func(rune) bool) RO { 205 | return S(strings.TrimFunc(m.str(), f)) 206 | } 207 | 208 | // TrimRightFunc returns a slice of m with all trailing Unicode 209 | // code points c satisfying f(c) removed. 210 | func TrimRightFunc(m RO, f func(rune) bool) RO { 211 | return S(strings.TrimRightFunc(m.str(), f)) 212 | } 213 | 214 | // TrimLeftFunc returns a slice of m with all leading Unicode 215 | // code points c satisfying f(c) removed. 216 | func TrimLeftFunc(m RO, f func(rune) bool) RO { 217 | return S(strings.TrimLeftFunc(m.str(), f)) 218 | } 219 | 220 | // Documentation for UTF-8 related functions copied from Go's unicode/utf8 package. (BSD license) 221 | 222 | // DecodeRune unpacks the first UTF-8 encoding in m and returns the rune and 223 | // its width in bytes. If m is empty it returns (utf8.RuneError, 0). Otherwise, if 224 | // the encoding is invalid, it returns (utf8.RuneError, 1). Both are impossible 225 | // results for correct, non-empty UTF-8. 226 | // 227 | // An encoding is invalid if it is incorrect UTF-8, encodes a rune that is 228 | // out of range, or is not the shortest possible UTF-8 encoding for the 229 | // value. No other validation is performed. 230 | func DecodeRune(m RO) (r rune, size int) { 231 | return utf8.DecodeRuneInString(m.str()) 232 | } 233 | 234 | // DecodeLastRune unpacks the last UTF-8 encoding in m and returns the rune and 235 | // its width in bytes. If m is empty it returns (utf8.RuneError, 0). Otherwise, if 236 | // the encoding is invalid, it returns (utf8.RuneError, 1). Both are impossible 237 | // results for correct, non-empty UTF-8. 238 | // 239 | // An encoding is invalid if it is incorrect UTF-8, encodes a rune that is 240 | // out of range, or is not the shortest possible UTF-8 encoding for the 241 | // value. No other validation is performed. 242 | func DecodeLastRune(m RO) (r rune, size int) { 243 | return utf8.DecodeLastRuneInString(m.str()) 244 | } 245 | 246 | // FullRune reports whether the bytes in m begin with a full UTF-8 encoding of a rune. 247 | // An invalid encoding is considered a full Rune since it will convert as a width-1 error rune. 248 | func FullRune(m RO) bool { 249 | return utf8.FullRuneInString(m.str()) 250 | } 251 | 252 | // RuneCount returns the number of UTF-8 encoded runes in m. Erroneous and short 253 | // encodings are treated as single runes of width 1 byte. 254 | func RuneCount(m RO) int { 255 | return utf8.RuneCountInString(m.str()) 256 | } 257 | 258 | // ValidUTF8 reports whether m consists entirely of valid UTF-8 encoded runes. 259 | func ValidUTF8(m RO) bool { 260 | return utf8.ValidString(m.str()) 261 | } 262 | 263 | // NewReader returns a new Reader that reads from m. 264 | func NewReader(m RO) *Reader { 265 | return &Reader{sr: strings.NewReader(m.str())} 266 | } 267 | 268 | // Cut works like strings.Cut, but takes and returns ROs. 269 | func Cut(m, sep RO) (before, after RO, found bool) { 270 | if i := Index(m, sep); i >= 0 { 271 | return m.SliceTo(i), m.SliceFrom(i + sep.Len()), true 272 | } 273 | return m, S(""), false 274 | } 275 | 276 | // CutPrefix works like strings.CutPrefix, but takes and returns ROs. 277 | func CutPrefix(m, prefix RO) (after RO, found bool) { 278 | if !HasPrefix(m, prefix) { 279 | return m, false 280 | } 281 | return m.SliceFrom(prefix.Len()), true 282 | } 283 | 284 | // CutSuffix works like strings.CutSuffix, but takes and returns ROs. 285 | func CutSuffix(m, suffix RO) (before RO, found bool) { 286 | if !HasSuffix(m, suffix) { 287 | return m, false 288 | } 289 | return m.SliceTo(m.Len() - suffix.Len()), true 290 | } 291 | 292 | // Reader is like a bytes.Reader or strings.Reader. 293 | type Reader struct { 294 | sr *strings.Reader 295 | } 296 | 297 | func (r *Reader) Len() int { return r.sr.Len() } 298 | func (r *Reader) Size() int64 { return r.sr.Size() } 299 | func (r *Reader) Read(b []byte) (int, error) { return r.sr.Read(b) } 300 | func (r *Reader) ReadAt(b []byte, off int64) (int, error) { return r.sr.ReadAt(b, off) } 301 | func (r *Reader) ReadByte() (byte, error) { return r.sr.ReadByte() } 302 | func (r *Reader) ReadRune() (ch rune, size int, err error) { return r.sr.ReadRune() } 303 | func (r *Reader) Seek(offset int64, whence int) (int64, error) { return r.sr.Seek(offset, whence) } 304 | 305 | // TODO: add Reader.WriteTo, but don't use strings.Reader.WriteTo because it uses io.WriteString, leaking our unsafe string 306 | 307 | // unsafeString is a string that's not really a Go string. 308 | // It might be pointing into a []byte. Don't let it escape to callers. 309 | // We contain the unsafety to this package. 310 | type unsafeString string 311 | 312 | // stringHeader is a safer version of reflect.StringHeader. 313 | // See https://github.com/golang/go/issues/40701. 314 | type stringHeader struct { 315 | P *byte 316 | Len int 317 | } 318 | 319 | // S returns a read-only view of the string s. 320 | // 321 | // The compiler should compile this call to nothing. Think of it as a 322 | // free type conversion. The returned RO view is the same size as a 323 | // string. 324 | func S(s string) RO { return RO{m: unsafeString(s)} } 325 | 326 | // B returns a read-only view of the byte slice b. 327 | // 328 | // The compiler should compile this call to nothing. Think of it as a 329 | // free type conversion. The returned value is actually smaller than a 330 | // []byte though (16 bytes instead of 24 bytes on 64-bit 331 | // architectures). 332 | func B(b []byte) RO { 333 | if len(b) == 0 { 334 | return RO{m: ""} 335 | } 336 | return RO{m: *(*unsafeString)(unsafe.Pointer(&stringHeader{&b[0], len(b)}))} 337 | } 338 | --------------------------------------------------------------------------------