github.com/bytedance/sonic@v1.11.7-0.20240517092252-d2edb31b167b/ast/decode_test.go (about)

     1  /*
     2   * Copyright 2022 ByteDance Inc.
     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 ast
    18  
    19  import (
    20  	"testing"
    21  	"unicode/utf8"
    22  
    23  	"github.com/bytedance/sonic/internal/rt"
    24  )
    25  
    26  func Test_DecodeString(t *testing.T) {
    27  	type args struct {
    28  		src      string
    29  		pos      int
    30  		needEsc  bool
    31  		validStr bool
    32  	}
    33  	invalidstr := rt.Mem2Str([]byte{'"',193,255,'"'})
    34  	println(utf8.ValidString(invalidstr))
    35  
    36  	tests := []struct {
    37  		name       string
    38  		args       args
    39  		wantV      string
    40  		wantRet    int
    41  		wantHasEsc bool
    42  	}{
    43  		{"empty", args{`""`, 0, false, false}, "", 2, false},
    44  		{"one", args{`"1"`, 0, false, false}, "1", 3, false},
    45  		{"escape", args{`"\\"`, 0, false, false}, `\\`, 4, true},
    46  		{"escape", args{`"\\"`, 0, true, true}, `\`, 4, true},
    47  		{"uft8", args{`"\u263a"`, 0, false, false}, `\u263a`, 8, true},
    48  		{"uft8", args{`"\u263a"`, 0, true, true}, `☺`, 8, true},
    49  		{"invalid uft8", args{`"\xx"`, 0, false, false}, `\xx`, 5, true},
    50  		{"invalid escape", args{`"\xx"`, 0, false, true}, `\xx`, 5, true},
    51  		{"invalid escape", args{`"\xx"`, 0, true, true}, ``, -3, true},
    52  		{"invalid string", args{invalidstr, 0, false, false}, invalidstr[1:3], 4, false},
    53  		{"invalid string", args{invalidstr, 0, true, true}, "", -10, false},
    54  	}
    55  	for _, tt := range tests {
    56  		t.Run(tt.name, func(t *testing.T) {
    57  			gotV, gotRet, gotHasEsc := _DecodeString(tt.args.src, tt.args.pos, tt.args.needEsc, tt.args.validStr)
    58  			if gotV != tt.wantV {
    59  				t.Errorf("_DecodeString() gotV = %v, want %v", gotV, tt.wantV)
    60  			}
    61  			if gotRet != tt.wantRet {
    62  				t.Errorf("_DecodeString() gotRet = %v, want %v", gotRet, tt.wantRet)
    63  			}
    64  			if gotHasEsc != tt.wantHasEsc {
    65  				t.Errorf("_DecodeString() gotHasEsc = %v, want %v", gotHasEsc, tt.wantHasEsc)
    66  			}
    67  		})
    68  	}
    69  }