base64

Fast Haskell base64 encoding/decoding (docs.ppad.tech/base64).
git clone git://git.ppad.tech/base64.git
Log | Files | Refs | README | LICENSE

Pure.hs (10197B)


      1 {-# OPTIONS_HADDOCK hide #-}
      2 {-# LANGUAGE BangPatterns #-}
      3 {-# LANGUAGE OverloadedStrings #-}
      4 
      5 -- |
      6 -- Module: Data.ByteString.Base64.Pure
      7 -- Copyright: (c) 2026 Jared Tobin
      8 -- License: MIT
      9 -- Maintainer: Jared Tobin <jared@ppad.tech>
     10 --
     11 -- Pure Haskell base64 encoding and decoding of strict bytestrings.
     12 
     13 module Data.ByteString.Base64.Pure (
     14     encode
     15   , decode
     16   ) where
     17 
     18 import qualified Data.Bits as B
     19 import Data.Bits ((.&.), (.|.))
     20 import qualified Data.ByteString as BS
     21 import qualified Data.ByteString.Internal as BI
     22 import Data.Word (Word8)
     23 import Foreign.ForeignPtr (withForeignPtr)
     24 import Foreign.Ptr (Ptr, plusPtr)
     25 import Foreign.Storable (peekElemOff, pokeElemOff)
     26 import System.IO.Unsafe (unsafeDupablePerformIO)
     27 
     28 fi :: (Num a, Integral b) => b -> a
     29 fi = fromIntegral
     30 {-# INLINE fi #-}
     31 
     32 -- 64-byte table.  Indexed by 6-bit value (0..63), yields the
     33 -- corresponding base64 alphabet character.  All-ASCII content means
     34 -- the bytestring 'IsString' rule rewrites this to 'unsafePackAddress'
     35 -- and the bytes live in static rodata.
     36 enc_tab :: BS.ByteString
     37 enc_tab =
     38   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
     39 {-# NOINLINE enc_tab #-}
     40 
     41 -- 256-byte table.  Index by an ASCII byte to obtain its 6-bit value;
     42 -- valid base64 chars ('A'..'Z', 'a'..'z', '0'..'9', '+', '/') map to
     43 -- 0x40..0x7f, every other byte (including '=') maps to 0x80.
     44 --
     45 -- The encoding is chosen so the literal is strictly ASCII and contains
     46 -- no embedded NUL, which is what the bytestring 'IsString' rule needs
     47 -- to rewrite it into 'unsafePackAddress' (cf. 'enc_tab') — the bytes
     48 -- end up in static rodata, with no CAF allocation.
     49 --
     50 -- The 0x80 sentinel is distinguished by bit 7; no value 0x40..0x7f
     51 -- carries that bit, so 'decode' OR-folds every lookup into an
     52 -- accumulator and tests 'acc .&. 0x80 == 0' once at the end.  The
     53 -- low 6 bits of each entry are the 6-bit value, possibly contaminated
     54 -- by the 0x40 flag bit; the b0/b1/b2 formulas mask each subexpression
     55 -- before combining so the flag never bleeds into the output bytes.
     56 dec_tab :: BS.ByteString
     57 dec_tab =
     58   "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\
     59   \\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\
     60   \\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7E\x80\x80\x80\x7F\
     61   \\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x80\x80\x80\x80\x80\x80\
     62   \\x80\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\
     63   \\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x80\x80\x80\x80\x80\
     64   \\x80\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\
     65   \\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x80\x80\x80\x80\x80\
     66   \\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\
     67   \\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\
     68   \\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\
     69   \\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\
     70   \\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\
     71   \\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\
     72   \\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\
     73   \\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80"
     74 {-# NOINLINE dec_tab #-}
     75 
     76 -- | Encode a base256 'ByteString' as base64.
     77 encode :: BS.ByteString -> BS.ByteString
     78 encode (BI.PS sfp soff l) =
     79   case enc_tab of
     80     BI.PS tfp toff _ ->
     81       BI.unsafeCreate ((l + 2) `quot` 3 * 4) $ \dst ->
     82         withForeignPtr sfp $ \sp0 ->
     83         withForeignPtr tfp $ \tp0 -> do
     84           let !sp = sp0 `plusPtr` soff :: Ptr Word8
     85               !tp = tp0 `plusPtr` toff :: Ptr Word8
     86               !nfull = l `quot` 3
     87               !rmn   = l - nfull * 3
     88               loop !i
     89                 | i == nfull = pure ()
     90                 | otherwise = do
     91                     let !ii = i * 3
     92                         !oo = i * 4
     93                     b0 <- peekElemOff sp ii
     94                     b1 <- peekElemOff sp (ii + 1)
     95                     b2 <- peekElemOff sp (ii + 2)
     96                     c0 <- peekElemOff tp (fi (b0 `B.shiftR` 2))
     97                     c1 <- peekElemOff tp (fi
     98                             (((b0 .&. 0x03) `B.shiftL` 4)
     99                          .|.  (b1 `B.shiftR` 4)))
    100                     c2 <- peekElemOff tp (fi
    101                             (((b1 .&. 0x0F) `B.shiftL` 2)
    102                          .|.  (b2 `B.shiftR` 6)))
    103                     c3 <- peekElemOff tp (fi (b2 .&. 0x3F))
    104                     pokeElemOff dst  oo      (c0 :: Word8)
    105                     pokeElemOff dst (oo + 1) c1
    106                     pokeElemOff dst (oo + 2) c2
    107                     pokeElemOff dst (oo + 3) c3
    108                     loop (i + 1)
    109           loop 0
    110           case rmn of
    111             0 -> pure ()
    112             1 -> do
    113               let !ii = nfull * 3
    114                   !oo = nfull * 4
    115               b0 <- peekElemOff sp ii
    116               c0 <- peekElemOff tp (fi (b0 `B.shiftR` 2))
    117               c1 <- peekElemOff tp (fi ((b0 .&. 0x03) `B.shiftL` 4))
    118               pokeElemOff dst  oo      (c0 :: Word8)
    119               pokeElemOff dst (oo + 1) c1
    120               pokeElemOff dst (oo + 2) 0x3D
    121               pokeElemOff dst (oo + 3) 0x3D
    122             _ -> do
    123               let !ii = nfull * 3
    124                   !oo = nfull * 4
    125               b0 <- peekElemOff sp ii
    126               b1 <- peekElemOff sp (ii + 1)
    127               c0 <- peekElemOff tp (fi (b0 `B.shiftR` 2))
    128               c1 <- peekElemOff tp (fi
    129                       (((b0 .&. 0x03) `B.shiftL` 4)
    130                    .|.  (b1 `B.shiftR` 4)))
    131               c2 <- peekElemOff tp (fi ((b1 .&. 0x0F) `B.shiftL` 2))
    132               pokeElemOff dst  oo      (c0 :: Word8)
    133               pokeElemOff dst (oo + 1) c1
    134               pokeElemOff dst (oo + 2) c2
    135               pokeElemOff dst (oo + 3) 0x3D
    136 
    137 -- | Decode a base64 'ByteString' to base256.  Invalid inputs
    138 --   (including incorrectly-padded or non-canonical inputs) will
    139 --   produce 'Nothing'.
    140 decode :: BS.ByteString -> Maybe BS.ByteString
    141 decode (BI.PS sfp soff l)
    142   | l == 0          = Just BS.empty
    143   | l .&. 0x03 /= 0 = Nothing
    144   | otherwise = case dec_tab of
    145       BI.PS tfp toff _ -> unsafeDupablePerformIO $
    146         withForeignPtr sfp $ \sp0 ->
    147         withForeignPtr tfp $ \tp0 -> do
    148           let !sp = sp0 `plusPtr` soff :: Ptr Word8
    149               !tp = tp0 `plusPtr` toff :: Ptr Word8
    150           c_pre <- peekElemOff sp (l - 2)
    151           c_end <- peekElemOff sp (l - 1)
    152           let !pad_pre = c_pre == 0x3D
    153               !pad_end = c_end == 0x3D
    154           if pad_pre && not pad_end
    155             then pure Nothing
    156             else do
    157               let !pad = (if pad_pre then 2 else if pad_end then 1 else 0)
    158                        :: Int
    159                   !nfull  = l `B.shiftR` 2
    160                   !nbody  = if pad > 0 then nfull - 1 else nfull
    161                   !outlen = nfull * 3 - pad
    162               fp <- BI.mallocByteString outlen
    163               ok <- withForeignPtr fp $ \dst -> do
    164                 let body_loop !acc !i
    165                       | i == nbody = pure acc
    166                       | otherwise = do
    167                           let !ii = i `B.shiftL` 2
    168                               !oo = i * 3
    169                           c0 <- peekElemOff sp  ii
    170                           c1 <- peekElemOff sp (ii + 1)
    171                           c2 <- peekElemOff sp (ii + 2)
    172                           c3 <- peekElemOff sp (ii + 3)
    173                           v0 <- peekElemOff tp (fi c0)
    174                           v1 <- peekElemOff tp (fi c1)
    175                           v2 <- peekElemOff tp (fi c2)
    176                           v3 <- peekElemOff tp (fi c3)
    177                           let !b0 = (v0 `B.shiftL` 2)
    178                                 .|. ((v1 `B.shiftR` 4) .&. 0x03)
    179                               !b1 = ((v1 .&. 0x0F) `B.shiftL` 4)
    180                                 .|. ((v2 `B.shiftR` 2) .&. 0x0F)
    181                               !b2 = ((v2 .&. 0x03) `B.shiftL` 6)
    182                                 .|. (v3 .&. 0x3F)
    183                           pokeElemOff dst  oo      b0
    184                           pokeElemOff dst (oo + 1) b1
    185                           pokeElemOff dst (oo + 2) b2
    186                           body_loop
    187                             (acc .|. v0 .|. v1 .|. v2 .|. v3) (i + 1)
    188                 acc <- body_loop 0 0
    189                 if acc .&. 0x80 /= 0
    190                   then pure False
    191                   else case pad of
    192                     0 -> pure True
    193                     1 -> do
    194                       let !ii = nbody `B.shiftL` 2
    195                           !oo = nbody * 3
    196                       c0 <- peekElemOff sp  ii
    197                       c1 <- peekElemOff sp (ii + 1)
    198                       c2 <- peekElemOff sp (ii + 2)
    199                       v0 <- peekElemOff tp (fi c0)
    200                       v1 <- peekElemOff tp (fi c1)
    201                       v2 <- peekElemOff tp (fi c2)
    202                       let !tail_acc = v0 .|. v1 .|. v2
    203                       if tail_acc .&. 0x80 /= 0 || v2 .&. 0x03 /= 0
    204                         then pure False
    205                         else do
    206                           let !b0 = (v0 `B.shiftL` 2)
    207                                 .|. ((v1 `B.shiftR` 4) .&. 0x03)
    208                               !b1 = ((v1 .&. 0x0F) `B.shiftL` 4)
    209                                 .|. ((v2 `B.shiftR` 2) .&. 0x0F)
    210                           pokeElemOff dst  oo      b0
    211                           pokeElemOff dst (oo + 1) b1
    212                           pure True
    213                     _ -> do
    214                       let !ii = nbody `B.shiftL` 2
    215                           !oo = nbody * 3
    216                       c0 <- peekElemOff sp  ii
    217                       c1 <- peekElemOff sp (ii + 1)
    218                       v0 <- peekElemOff tp (fi c0)
    219                       v1 <- peekElemOff tp (fi c1)
    220                       let !tail_acc = v0 .|. v1
    221                       if tail_acc .&. 0x80 /= 0 || v1 .&. 0x0F /= 0
    222                         then pure False
    223                         else do
    224                           let !b0 = (v0 `B.shiftL` 2)
    225                                 .|. ((v1 `B.shiftR` 4) .&. 0x03)
    226                           pokeElemOff dst oo b0
    227                           pure True
    228               pure $! if ok then Just (BI.PS fp 0 outlen) else Nothing