github.com/go-xe2/third@v1.0.3/golang.org/x/text/encoding/example_test.go (about)

     1  // Copyright 2013 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package encoding_test
     6  
     7  import (
     8  	"fmt"
     9  	"github.com/go-xe2/third/golang.org/x/text/encoding"
    10  	"github.com/go-xe2/third/golang.org/x/text/encoding/charmap"
    11  	"github.com/go-xe2/third/golang.org/x/text/transform"
    12  	"io"
    13  	"os"
    14  	"strings"
    15  )
    16  
    17  func ExampleDecodeWindows1252() {
    18  	sr := strings.NewReader("Gar\xe7on !")
    19  	tr := charmap.Windows1252.NewDecoder().Reader(sr)
    20  	io.Copy(os.Stdout, tr)
    21  	// Output: Garçon !
    22  }
    23  
    24  func ExampleUTF8Validator() {
    25  	for i := 0; i < 2; i++ {
    26  		var transformer transform.Transformer
    27  		transformer = unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM).NewEncoder()
    28  		if i == 1 {
    29  			transformer = transform.Chain(encoding.UTF8Validator, transformer)
    30  		}
    31  		dst := make([]byte, 256)
    32  		src := []byte("abc\xffxyz") // src is invalid UTF-8.
    33  		nDst, nSrc, err := transformer.Transform(dst, src, true)
    34  		fmt.Printf("i=%d: produced %q, consumed %q, error %v\n",
    35  			i, dst[:nDst], src[:nSrc], err)
    36  	}
    37  	// Output:
    38  	// i=0: produced "\x00a\x00b\x00c\xff\xfd\x00x\x00y\x00z", consumed "abc\xffxyz", error <nil>
    39  	// i=1: produced "\x00a\x00b\x00c", consumed "abc", error encoding: invalid UTF-8
    40  }