|
| 1 | +/* |
| 2 | + * Copyright 2021-2022 by Nedim Sabic Sabic |
| 3 | + * https://www.fibratus.io |
| 4 | + * All Rights Reserved. |
| 5 | + * |
| 6 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | + * you may not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | + |
| 19 | +package utf16 |
| 20 | + |
| 21 | +import ( |
| 22 | + "github.com/stretchr/testify/require" |
| 23 | + "math/rand" |
| 24 | + "testing" |
| 25 | + "unicode/utf16" |
| 26 | +) |
| 27 | + |
| 28 | +func TestDecode(t *testing.T) { |
| 29 | + for i := 0; i < 24; i++ { |
| 30 | + buf := genbuf(1 << i) |
| 31 | + w := string(utf16.Decode(buf)) |
| 32 | + g := Decode(buf) |
| 33 | + if w != g { |
| 34 | + t.Errorf("mismatch on 1<<%d", i) |
| 35 | + } |
| 36 | + } |
| 37 | + s := []rune("Do you want café?") |
| 38 | + encoded := utf16.Encode(s) |
| 39 | + require.Equal(t, "Do you want café?", Decode(encoded)) |
| 40 | +} |
| 41 | + |
| 42 | +func BenchmarkStdlibDecode(b *testing.B) { |
| 43 | + b.ReportAllocs() |
| 44 | + b.StopTimer() |
| 45 | + buf := genbuf(b.N) |
| 46 | + b.StartTimer() |
| 47 | + _ = string(utf16.Decode(buf)) |
| 48 | +} |
| 49 | + |
| 50 | +func BenchmarkDecode(b *testing.B) { |
| 51 | + b.ReportAllocs() |
| 52 | + b.StopTimer() |
| 53 | + buf := genbuf(b.N) |
| 54 | + b.StartTimer() |
| 55 | + _ = Decode(buf) |
| 56 | +} |
| 57 | + |
| 58 | +func genbuf(n int) []uint16 { |
| 59 | + r := rand.New(rand.NewSource(int64(n))) |
| 60 | + buf := make([]rune, n) |
| 61 | + for i := 0; i < n; i++ { |
| 62 | + // simulate mostly-ASCII |
| 63 | + if r.Intn(100) == 0 { |
| 64 | + buf[i] = rune(r.Intn(0x10ffff + 1)) |
| 65 | + } else { |
| 66 | + buf[i] = rune(r.Intn(1 << 7)) |
| 67 | + } |
| 68 | + } |
| 69 | + return utf16.Encode(buf) |
| 70 | +} |
0 commit comments