packages feed

memcache-0.5.1.0: Database/Memcache/Util.hs

{-|
Module      : Database.Memcache.Util
Description : Internal helpers
Copyright   : (c) David Terei, 2026
License     : BSD
Maintainer  : code@davidterei.com
Stability   : internal
Portability : GHC

Small helpers shared by the library's modules. Not exposed.
-}
module Database.Memcache.Util (
        maxValueLength,
        note,
        readDecimal,
        withDetail
    ) where

import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Char (isAscii, isPrint, showLitChar)

-- | Turn a 'Nothing' into an error.
note :: e -> Maybe a -> Either e a
note e = maybe (Left e) Right

-- | Read a number that a server sent. Memcached writes value lengths, CAS
-- values, flags and counter values as plain decimal digits, and ElastiCache
-- writes its configuration's version that way, so accept exactly that: at
-- least one digit and nothing else, not even a sign or a space. A number too
-- large for the type is rejected rather than wrapped around.
readDecimal :: (Integral a, Bounded a) => ByteString -> Maybe a
readDecimal input
  | B.null input = Nothing
  | otherwise = go 0 input
  where
    go !n rest = case B.uncons rest of
      Nothing -> Just n
      Just (byte, rest')
        | byte < 0x30 || byte > 0x39 -> Nothing
        | n > limit || (n == limit && digit > lastDigit) -> Nothing
        | otherwise -> go (n * 10 + digit) rest'
        where digit = fromIntegral (byte - 0x30)
    (limit, lastDigit) = maxBound `quotRem` 10

-- | Append a detail, which may hold bytes a server sent, keeping the message
-- on one line of ASCII: characters outside printable ASCII and backslashes are
-- escaped as in a Haskell string literal, and only the first 200 characters
-- are kept.
withDetail :: String -> String -> String
withDetail problem ""     = problem
withDetail problem detail = problem <> ": " <> escape kept <> ellipsis
  where
    (kept, rest) = splitAt 200 detail
    ellipsis = if null rest then "" else "..."
    escape = foldr escapeChar ""
    escapeChar c
        | isAscii c && isPrint c && c /= '\\' = (c :)
        | otherwise                          = showLitChar c

-- | The longest value the client stores or reads: 1 GiB, memcached's
-- @ITEM_SIZE_MAX_UPPER_LIMIT@, the largest item size limit (@-I@) it allows.
-- An item holds its key and a header as well as its value, so no memcached
-- server can store a value this long. The operations in
-- "Database.Memcache.Client" that store a value reject a longer one before
-- anything is sent, and 'Database.Memcache.Socket.recvResponse' rejects a
-- reply that claims a longer one before reading any of it, so that the
-- client can read back any value it can store.
maxValueLength :: Int
maxValueLength = 1024 * 1024 * 1024