]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/encoding/hex/hex.go
encoding: add AppendEncode and AppendDecode
[gostls13.git] / src / encoding / hex / hex.go
index 375f5831709bb7764f73f909c541bb7830bacc0a..ccc395e2f704351bbcf208e6fa32b0f3e0c150e0 100644 (file)
@@ -9,6 +9,7 @@ import (
        "errors"
        "fmt"
        "io"
+       "slices"
        "strings"
 )
 
@@ -51,6 +52,15 @@ func Encode(dst, src []byte) int {
        return len(src) * 2
 }
 
+// AppendEncode appends the hexadecimally encoded src to dst
+// and returns the extended buffer.
+func AppendEncode(dst, src []byte) []byte {
+       n := EncodedLen(len(src))
+       dst = slices.Grow(dst, n)
+       Encode(dst[len(dst):][:n], src)
+       return dst[:len(dst)+n]
+}
+
 // ErrLength reports an attempt to decode an odd-length input
 // using Decode or DecodeString.
 // The stream-based Decoder returns io.ErrUnexpectedEOF instead of ErrLength.
@@ -102,6 +112,16 @@ func Decode(dst, src []byte) (int, error) {
        return i, nil
 }
 
+// AppendDecode appends the hexadecimally decoded src to dst
+// and returns the extended buffer.
+// If the input is malformed, it returns the partially decoded src and an error.
+func AppendDecode(dst, src []byte) ([]byte, error) {
+       n := DecodedLen(len(src))
+       dst = slices.Grow(dst, n)
+       n, err := Decode(dst[len(dst):][:n], src)
+       return dst[:len(dst)+n], err
+}
+
 // EncodeToString returns the hexadecimal encoding of src.
 func EncodeToString(src []byte) string {
        dst := make([]byte, EncodedLen(len(src)))