...

Source file src/github.com/gdamore/encoding/common_test.go

Documentation: github.com/gdamore/encoding

     1  // Copyright 2018 Garrett D'Amore
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use 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 encoding
    16  
    17  import (
    18  	"bytes"
    19  	"testing"
    20  	"unicode/utf8"
    21  
    22  	"golang.org/x/text/encoding"
    23  )
    24  
    25  func verifyMap(t *testing.T, enc encoding.Encoding, b byte, r rune) {
    26  	verifyFromUTF(t, enc, b, r)
    27  	verifyToUTF(t, enc, b, r)
    28  }
    29  
    30  func verifyFromUTF(t *testing.T, enc encoding.Encoding, b byte, r rune) {
    31  
    32  	encoder := enc.NewEncoder()
    33  
    34  	out := make([]byte, 6)
    35  	utf := make([]byte, utf8.RuneLen(r))
    36  	utf8.EncodeRune(utf, r)
    37  
    38  	ndst, nsrc, err := encoder.Transform(out, utf, true)
    39  	if err != nil {
    40  		t.Errorf("Transform failed: %v", err)
    41  	}
    42  	if nsrc != len(utf) {
    43  		t.Errorf("Length of source incorrect: %d != %d", nsrc, len(utf))
    44  	}
    45  	if ndst != 1 {
    46  		t.Errorf("Dest length (%d) != 1", ndst)
    47  	}
    48  	if b != out[0] {
    49  		t.Errorf("From UTF incorrect map %v != %v", b, out[0])
    50  	}
    51  }
    52  
    53  func verifyToUTF(t *testing.T, enc encoding.Encoding, b byte, r rune) {
    54  	decoder := enc.NewDecoder()
    55  
    56  	out := make([]byte, 6)
    57  	nat := []byte{b}
    58  	utf := make([]byte, utf8.RuneLen(r))
    59  	utf8.EncodeRune(utf, r)
    60  
    61  	ndst, nsrc, err := decoder.Transform(out, nat, true)
    62  	if err != nil {
    63  		t.Errorf("Transform failed: %v", err)
    64  	}
    65  	if nsrc != 1 {
    66  		t.Errorf("Src length (%d) != 1", nsrc)
    67  	}
    68  	if !bytes.Equal(utf, out[:ndst]) {
    69  		t.Errorf("UTF expected %v, but got %v for %x\n", utf, out, b)
    70  	}
    71  }
    72  

View as plain text