1 // Copyright 2019 The CUE 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 base64 implements base64 encoding as specified by RFC 4648. 16 package base64 17 18 import ( 19 "encoding/base64" 20 21 "cuelang.org/go/cue" 22 "cuelang.org/go/cue/errors" 23 "cuelang.org/go/cue/token" 24 ) 25 26 // EncodedLen returns the length in bytes of the base64 encoding 27 // of an input buffer of length n. Encoding needs to be set to null 28 // as only StdEncoding is supported for now. 29 func EncodedLen(encoding cue.Value, n int) (int, error) { 30 if err := encoding.Null(); err != nil { 31 return 0, errors.Wrapf(err, token.NoPos, "base64: unsupported encoding") 32 } 33 return base64.StdEncoding.EncodedLen(n), nil 34 } 35 36 // DecodedLen returns the maximum length in bytes of the decoded data 37 // corresponding to n bytes of base64-encoded data. Encoding needs to be set to 38 // null as only StdEncoding is supported for now. 39 func DecodedLen(encoding cue.Value, x int) (int, error) { 40 if err := encoding.Null(); err != nil { 41 return 0, errors.Wrapf(err, token.NoPos, "base64: unsupported encoding") 42 } 43 return base64.StdEncoding.DecodedLen(x), nil 44 } 45 46 // Encode returns the base64 encoding of src. Encoding needs to be set to null 47 // as only StdEncoding is supported for now. 48 func Encode(encoding cue.Value, src []byte) (string, error) { 49 if err := encoding.Null(); err != nil { 50 return "", errors.Wrapf(err, token.NoPos, "base64: unsupported encoding") 51 } 52 return base64.StdEncoding.EncodeToString(src), nil 53 } 54 55 // Decode returns the bytes represented by the base64 string s. Encoding needs 56 // to be set to null as only StdEncoding is supported for now. 57 func Decode(encoding cue.Value, s string) ([]byte, error) { 58 if err := encoding.Null(); err != nil { 59 return nil, errors.Wrapf(err, token.NoPos, "base64: unsupported encoding") 60 } 61 return base64.StdEncoding.DecodeString(s) 62 } 63