@@ -4,6 +4,10 @@ module Protobuf.Common
44( FieldNumber
55, WireType(..)
66, Bytes(..)
7+, class Default
8+, default
9+, fromDefault
10+, toDefault
711)
812where
913
@@ -13,11 +17,15 @@ import Data.ArrayBuffer.ArrayBuffer as AB
1317import Data.ArrayBuffer.Typed as TA
1418import Data.ArrayBuffer.Types (ArrayBuffer, Uint8Array)
1519import Data.Enum (class Enum, fromEnum, class BoundedEnum, Cardinality(..))
20+import Data.Float32 (Float32)
21+import Data.Float32 as Float32
1622import Data.Generic.Rep (class Generic)
1723import Data.Generic.Rep.Show (genericShow)
24+import Data.Long.Internal (Long, Signed, Unsigned, fromLowHighBits)
1825import Data.Maybe (Maybe(..))
1926import Data.Newtype (class Newtype)
2027import Data.UInt (UInt)
28+import Data.UInt as UInt
2129import Effect (Effect)
2230import Effect.Unsafe (unsafePerformEffect)
2331
@@ -84,4 +92,33 @@ instance eqBytes :: Eq Bytes
8492 r' <- TA.whole r :: Effect Uint8Array
8593 TA.eq l' r'
8694
87−derive instance newtypeBytes :: Newtype Bytes _
95+derive instance newtypeBytes :: Newtype Bytes _
96+
97+-- | Default values
98+-- |
99+-- | https://developers.google.com/protocol-buffers/docs/proto3#default
100+class Default a
101+ where
102+ default :: a
103+
104+instance defaultString :: Default String where default = ""
105+instance defaultInt :: Default Int where default = 0
106+instance defaultNumber :: Default Number where default = 0.0
107+instance defaultLongSigned :: Default (Long Signed) where default = fromLowHighBits 0 0
108+instance defaultLongUnsigned :: Default (Long Unsigned) where default = fromLowHighBits 0 0
109+instance defaultFloat32 :: Default Float32 where default = Float32.fromNumber' 0.0
110+instance defaultBoolean :: Default Boolean where default = false
111+instance defaultUInt :: Default UInt where default = UInt.fromInt 0
112+instance defaultArray :: Default a => Default (Array a) where default = []
113+instance defaultBytes :: Default Bytes where default = Bytes $ unsafePerformEffect $ AB.empty 0
114+
115+-- Maybe we want to rip off? https://pursuit.purescript.org/packages/purescript-data-default/0.3.2/docs/Data.Default#t:GDefault
116+
117+-- | Turns a `default` value into `Nothing`. Sometimes convenient for decoding.
118+fromDefault :: forall a. Default a => Eq a => a -> Maybe a
119+fromDefault x = if x==default then Nothing else Just x
120+
121+-- | Turns `Nothing` into a `default` value. Sometimes convenient for encoding.
122+toDefault :: forall a. Default a => Maybe a -> a
123+toDefault Nothing = default
124+toDefault (Just x) = x