Line data Source code
1 : #ifndef HEADER_fd_src_ballet_base64_fd_base64_h 2 : #define HEADER_fd_src_ballet_base64_fd_base64_h 3 : 4 : /* fd_base64.h provides methods for converting between binary and 5 : Base64. Uses the standard Base64 alphabet as specified in RFC 4648 6 : with padding. */ 7 : 8 : #include "../fd_ballet_base.h" 9 : 10 : /* FD_BASE64_ENC_SZ returns the number of Base64 characters required 11 : to encode a given byte count. sz in [0,0xbffffffffffffffe). 12 : Supports compile-time evaluation, and is thus suitable for use in 13 : declarations. Not homomorphic due to padding, i.e.: 14 : 15 : FD_BASE64_ENC_SZ(a)+FD_BASE64_ENC_SZ(b) >= FD_BASE64_ENC_SZ(a+b) */ 16 : 17 : #define FD_BASE64_ENC_SZ(sz) ((((sz)+2UL)/3UL)*4UL) 18 : 19 : /* FD_BASE64_DEC_SZ returns the max number of bytes required to hold a 20 : the decoding of a given number of Base64 characters. 21 : sz in [0,0xfffffffffffffffd). */ 22 : 23 0 : #define FD_BASE64_DEC_SZ(sz) ((((sz)+3UL)/4UL)*3UL) 24 : 25 : FD_PROTOTYPES_BEGIN 26 : 27 : /* fd_base64_encode encodes the given bytes [in,in+in_sz) as Base64, 28 : optionally using trailing padding. Does not write a NULL terminator 29 : to out (thus out will not be a valid cstr on return). Writes result 30 : to [out,out+FD_BASE64_ENC_SZ(in_sz)) and returns the number of writes 31 : written. */ 32 : 33 : ulong 34 : fd_base64_encode( char * out, 35 : void const * in, 36 : ulong in_sz ); 37 : 38 : /* fd_cstr_append_base64 appends Base64 encoded data to p. Assumes p 39 : is valid (non-NULL and room for at least FD_BASE64_ENC_SZ( sz ) 40 : characters and a final terminating '\0'). sz==0UL is treated as a 41 : no-op. */ 42 : 43 : static inline char * 44 : fd_cstr_append_base64( char * p, 45 : uchar const * s, 46 0 : ulong sz ) { 47 0 : if( FD_UNLIKELY( !sz ) ) return p; 48 0 : ulong n = fd_base64_encode( p, s, sz ); 49 0 : return p + n; 50 0 : } 51 : 52 : /* fd_base64_decode decodes the Base64 characters in [in+in_sz). Writes 53 : up to FD_BASE64_DEC_SZ(in_sz) bytes to out. Returns number of bytes 54 : encoded on success, or -1L on failure. Only supports trailing 55 : padding. */ 56 : 57 : long 58 : fd_base64_decode( uchar * out, 59 : char const * in, 60 : ulong in_sz ); 61 : 62 : FD_PROTOTYPES_END 63 : 64 : #endif /* HEADER_fd_src_ballet_base64_fd_base64_h */