go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/data/lex64/encoding_utils.go (about)

     1  // Copyright 2022 The LUCI 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 lex64
    16  
    17  import (
    18  	"bytes"
    19  	"encoding/base64"
    20  	"io"
    21  
    22  	"go.chromium.org/luci/common/errors"
    23  )
    24  
    25  // doEncode is a utility method that takes an encoding and a message and encodes
    26  // it if possible.
    27  func doEncode(encoding *base64.Encoding, input []byte) ([]byte, error) {
    28  	buf := new(bytes.Buffer)
    29  	encoder := base64.NewEncoder(encoding, buf)
    30  	_, err := io.Copy(encoder, bytes.NewReader(input))
    31  	if err := errors.Append(err, encoder.Close()); err != nil {
    32  		return nil, err
    33  	}
    34  	return buf.Bytes(), nil
    35  }
    36  
    37  // doDecode is a utility method that takes an encoded message and decodes it if possible.
    38  func doDecode(encoding *base64.Encoding, encoded []byte) ([]byte, error) {
    39  	buf := new(bytes.Buffer)
    40  	decoder := base64.NewDecoder(encoding, bytes.NewReader(encoded))
    41  	if _, err := io.Copy(buf, decoder); err != nil {
    42  		return nil, err
    43  	}
    44  	return buf.Bytes(), nil
    45  }