github.com/danil/iso8583@v0.21.0/codec8583/charset_codec8583.go (about)

     1  package codec8583
     2  
     3  import (
     4  	"golang.org/x/text/encoding/charmap"
     5  )
     6  
     7  var (
     8  	// ASCII encodes/decodes ASCII charset of the ISO 8583 MTI/bitmaps/fields.
     9  	ASCII = NOPCharset
    10  	// EBCDIC encodes/decodes EBCDIC charset of the ISO 8583 MTI/bitmaps/fields.
    11  	EBCDIC = Charset{EncodeEbcdic, DecodeEbcdic}
    12  	// NOPCharset is a "no operation" charset encoder/decoder.
    13  	NOPCharset = Charset{}
    14  )
    15  
    16  type (
    17  	// EncodeCharsetFunc encodes charset of the ISO 8583 MTI/bitmaps/fields.
    18  	EncodeCharsetFunc func([]byte) ([]byte, error)
    19  	// DecodeCharsetFunc decodes charset of the ISO 8583 MTI/bitmaps/fields.
    20  	DecodeCharsetFunc func([]byte) ([]byte, error)
    21  )
    22  
    23  // Charset encodes/decodes charset of the ISO 8583 MTI/bitmaps/fields.
    24  type Charset struct {
    25  	Enc EncodeCharsetFunc
    26  	Dec DecodeCharsetFunc
    27  }
    28  
    29  func (c Charset) Encode(data []byte) ([]byte, error) {
    30  	if c.Enc == nil {
    31  		return data, nil
    32  	}
    33  	return c.Enc(data)
    34  }
    35  
    36  func (c Charset) Decode(data []byte) ([]byte, error) {
    37  	if c.Dec == nil {
    38  		return data, nil
    39  	}
    40  	return c.Dec(data)
    41  }
    42  
    43  // EncodeEbcdic intends to encode all bytes in EBCDIC character encoding except the null character.
    44  func EncodeEbcdic(src []byte) ([]byte, error) {
    45  	enc := charmap.CodePage037.NewEncoder()
    46  	dst := make([]byte, len(src)) // *8)
    47  	nDst, _, err := enc.Transform(dst, src, true)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	return dst[:nDst], nil
    52  }
    53  
    54  // DecodeEbcdic intends to decode all bytes in EBCDIC character encoding except the null character.
    55  func DecodeEbcdic(src []byte) ([]byte, error) {
    56  	dec := charmap.CodePage037.NewDecoder()
    57  	dst := make([]byte, len(src)) // *8)
    58  	nDst, _, err := dec.Transform(dst, src, true)
    59  	if err != nil {
    60  		return nil, err
    61  	}
    62  	return dst[:nDst], nil
    63  }