module Binrep.Type.Text.Encoding.Utf16 where

import Binrep.Type.Text.Internal
import Binrep.Type.Common ( Endianness(..) )

import Refined
import Data.Typeable ( Typeable )

import Data.Text.Encoding qualified as Text
import Data.Text ( Text )

data Utf16 (end :: Endianness)

instance Encode (Utf16 'BE) where encode' :: Text -> Bytes
encode' = Text -> Bytes
Text.encodeUtf16BE
instance Encode (Utf16 'LE) where encode' :: Text -> Bytes
encode' = Text -> Bytes
Text.encodeUtf16LE

instance Decode (Utf16 'BE) where decode :: Bytes -> Either String (AsText (Utf16 'BE))
decode = (UnicodeException -> String)
-> (Bytes -> Either UnicodeException Text)
-> Bytes
-> Either String (AsText (Utf16 'BE))
forall {k} (enc :: k) e.
(e -> String)
-> (Bytes -> Either e Text) -> Bytes -> Either String (AsText enc)
decodeText UnicodeException -> String
forall a. Show a => a -> String
show ((Bytes -> Either UnicodeException Text)
 -> Bytes -> Either String (AsText (Utf16 'BE)))
-> (Bytes -> Either UnicodeException Text)
-> Bytes
-> Either String (AsText (Utf16 'BE))
forall a b. (a -> b) -> a -> b
$ (Bytes -> Text) -> Bytes -> Either UnicodeException Text
wrapUnsafeDecoder Bytes -> Text
Text.decodeUtf16BE
instance Decode (Utf16 'LE) where decode :: Bytes -> Either String (AsText (Utf16 'LE))
decode = (UnicodeException -> String)
-> (Bytes -> Either UnicodeException Text)
-> Bytes
-> Either String (AsText (Utf16 'LE))
forall {k} (enc :: k) e.
(e -> String)
-> (Bytes -> Either e Text) -> Bytes -> Either String (AsText enc)
decodeText UnicodeException -> String
forall a. Show a => a -> String
show ((Bytes -> Either UnicodeException Text)
 -> Bytes -> Either String (AsText (Utf16 'LE)))
-> (Bytes -> Either UnicodeException Text)
-> Bytes
-> Either String (AsText (Utf16 'LE))
forall a b. (a -> b) -> a -> b
$ (Bytes -> Text) -> Bytes -> Either UnicodeException Text
wrapUnsafeDecoder Bytes -> Text
Text.decodeUtf16LE

-- | Any 'Text' value is always valid UTF-16.
instance Typeable end => Predicate (Utf16 end) Text where validate :: Proxy (Utf16 end) -> Text -> Maybe RefineException
validate Proxy (Utf16 end)
_ Text
_ = Maybe RefineException
success