         K-256 >>K
         initial-H-256 >>H
         4 >>word-size
-        64 >>block-size ; 
+        64 >>block-size ;
 
 M: sha-256 checksum-bytes
-    drop
-    <sha-256-state> sha2 [
-        byte-array>sha2
-    ] with-variable ;
+    drop <sha-256-state> byte-array>sha2 ;

    d c pick exchange
    c b pick exchange
    b a pick exchange
    [ w+ a ] dip set-nth ;

: process-chunk ( M block-size H-cloned -- )
    [
        '[
            _
            [ T1 ]
            [ T2 ]
            [ update-H ] tri 
        ] with each
    ] keep sha2 get H>> [ w+ ] 2map sha2 get (>>H) ;

: pad-initial-bytes ( string -- padded-string )
    dup [
        HEX: 80 ,
        length 
        [ HEX: 3f bitand calculate-pad-length 0 <string> % ]
        [ 3 shift 8 >be % ] bi
    ] "" make append ;

: seq>byte-array ( seq n -- string )
    '[ _ >be ] map B{ } join ;

: byte-array>sha2 ( byte-array -- string )
    pad-initial-bytes
    sha2 get block-size>> <sliced-groups>
    [
        prepare-message-schedule
        sha2 get [ block-size>> ] [ H>> clone ] bi process-chunk
    ] each
    sha2 get H>> 4 seq>byte-array ;

PRIVATE>


USING: kernel splitting grouping math sequences namespaces make
io.binary math.bitwise checksums checksums.common
sbufs strings combinators.smart math.ranges fry combinators
accessors locals ;
IN: checksums.sha2

<PRIVATE
