gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/gohacks/string_test.go (about)

     1  // Copyright 2023 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package gohacks
    16  
    17  import (
    18  	"slices"
    19  	"testing"
    20  )
    21  
    22  func TestImmutableBytesFromString(t *testing.T) {
    23  	tests := []struct {
    24  		name  string
    25  		input string
    26  		want  []byte
    27  	}{
    28  		{
    29  			name:  "abc",
    30  			input: "abc",
    31  			want:  []byte("abc"),
    32  		},
    33  		{
    34  			name:  "empty",
    35  			input: "",
    36  			want:  nil,
    37  		},
    38  		{
    39  			name:  "subslice-empty",
    40  			input: "abc"[:0],
    41  			want:  []byte(""),
    42  		},
    43  	}
    44  
    45  	for _, tc := range tests {
    46  		t.Run(tc.name, func(t *testing.T) {
    47  			got := ImmutableBytesFromString(tc.input)
    48  			if !slices.Equal(got, tc.want) {
    49  				t.Errorf("got contents %v (len %d cap %d) want %v (len %d cap %d)", got, len(got), cap(got), tc.want, len(tc.want), cap(tc.want))
    50  			}
    51  		})
    52  	}
    53  }
    54  
    55  func TestStringFromImmutableBytes(t *testing.T) {
    56  	tests := []struct {
    57  		name  string
    58  		input []byte
    59  		want  string
    60  	}{
    61  		{
    62  			name:  "abc",
    63  			input: []byte("abc"),
    64  			want:  "abc",
    65  		},
    66  		{
    67  			name:  "empty",
    68  			input: []byte{},
    69  			want:  "",
    70  		},
    71  		{
    72  			name:  "nil",
    73  			input: nil,
    74  			want:  "",
    75  		},
    76  	}
    77  
    78  	for _, tc := range tests {
    79  		t.Run(tc.name, func(t *testing.T) {
    80  			got := StringFromImmutableBytes(tc.input)
    81  			if got != tc.want {
    82  				t.Errorf("got %q want %q", got, tc.want)
    83  			}
    84  		})
    85  	}
    86  }