 ! See http://factorcode.org/license.txt for BSD license.
 USING: kernel splitting grouping math sequences namespaces make
 io.binary math.bitwise checksums checksums.common
-sbufs strings combinators.smart math.ranges fry combinators ;
+sbufs strings combinators.smart math.ranges fry combinators
+accessors ;
 IN: checksums.sha2
 
 <PRIVATE
 
-SYMBOLS: vars K H process-M word-size block-size ;
+SYMBOLS: H word-size block-size ;
 
 CONSTANT: a 0
 CONSTANT: b 1


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

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

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

: 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
    block-size get <sliced-groups>
    [
        prepare-message-schedule
        block-size get H get clone process-chunk
    ] each
    H get 4 seq>byte-array ;

PRIVATE>

