(.require [library [lux (.except nat) [abstract [equivalence (.only Equivalence)] [order (.only Order)]] [control ["[0]" try (.only Try)] ["[0]" exception (.only exception)]] [data [text ["%" \\format (.only format)]] [binary ["[0]" \\format (.only Format)]]] [math [number ["n" nat] ["[0]" i64]]] [meta [macro ["[0]" template]] [type [primitive (.except)]]]]]) (primitive .public (Unsigned brand) Nat (def .public value (-> (Unsigned Any) Nat) (|>> representation)) (def .public equivalence (All (_ brand) (Equivalence (Unsigned brand))) (implementation (def (= reference sample) (n.= (representation reference) (representation sample))))) (def .public order (All (_ brand) (Order (Unsigned brand))) (implementation (def equivalence ..equivalence) (def (< reference sample) (n.< (representation reference) (representation sample))))) (exception .public (value_exceeds_the_maximum [type Symbol value Nat maximum (Unsigned Any)]) (exception.report "Type" (%.symbol type) "Value" (%.nat value) "Maximum" (%.nat (representation maximum)))) (exception .public [brand] (subtraction_cannot_yield_negative_value [type Symbol parameter (Unsigned brand) subject (Unsigned brand)]) (exception.report "Type" (%.symbol type) "Parameter" (%.nat (representation parameter)) "Subject" (%.nat (representation subject)))) (with_template [ <+> <-> ] [(with_expansions [ (template.symbol [ "'"])] (primitive .public Any) (type .public (Unsigned ))) (def .public ) (def .public (|> (n.* i64.bits_per_byte) i64.mask abstraction)) (def .public ( value) (-> Nat (Try )) (if (n.> (representation ) value) (exception.except ..value_exceeds_the_maximum [(symbol ) value ]) {try.#Success (abstraction value)})) (def .public (<+> parameter subject) (-> (Try )) ( (n.+ (representation parameter) (representation subject)))) (def .public (<-> parameter subject) (-> (Try )) (let [parameter' (representation parameter) subject' (representation subject)] (if (n.> subject' parameter') (exception.except ..subtraction_cannot_yield_negative_value [(symbol ) parameter subject]) {try.#Success (abstraction (n.- parameter' subject'))}))) (def .public ( left right) (-> ) (abstraction (n.max (representation left) (representation right))))] [1 U1 bytes/1 u1 maximum/1 +/1 -/1 max/1] [2 U2 bytes/2 u2 maximum/2 +/2 -/2 max/2] [4 U4 bytes/4 u4 maximum/4 +/4 -/4 max/4] ) (with_template [ ] [(def .public (-> ) (|>> transmutation))] [lifted/2 U1 U2] [lifted/4 U2 U4] ) (with_template [ ] [(def .public (Format ) (|>> representation ))] [format/1 U1 \\format.bits_8] [format/2 U2 \\format.bits_16] [format/4 U4 \\format.bits_32] ) )