src/Pure/General/sha1_polyml.ML
changeset 35628 f1456d045151
child 35713 428284ee1465
equal deleted inserted replaced
35627:6cec06ef67a7 35628:f1456d045151
       
     1 (*  Title:      Pure/General/sha1_polyml.ML
       
     2     Author:     Sascha Boehme, TU Muenchen
       
     3 
       
     4 Digesting strings according to SHA-1 (see RFC 3174) -- based on an
       
     5 external implementation in C with a fallback to an internal
       
     6 implementation.
       
     7 *)
       
     8 
       
     9 structure SHA1: SHA1 =
       
    10 struct
       
    11 
       
    12 fun hex_digit i = if i < 10 then chr (ord "0" + i) else chr (ord "a" + i - 10);
       
    13 
       
    14 fun hex_string arr i =
       
    15   let val c = CInterface.fromCchar (CInterface.offset i CInterface.Cchar arr)
       
    16   in (op ^) (pairself hex_digit (Integer.div_mod (Char.ord c) 16)) end
       
    17 
       
    18 fun digest_external str =
       
    19   let
       
    20     val digest = CInterface.alloc 20 CInterface.Cchar;
       
    21     val _ = CInterface.call3 (CInterface.get_sym "sha1" "sha1_buffer")
       
    22       (CInterface.STRING, CInterface.INT, CInterface.POINTER)
       
    23       CInterface.POINTER (str, size str, CInterface.address digest);
       
    24   in fold (suffix o hex_string digest) (0 upto 19) "" end;
       
    25 
       
    26 fun digest str = digest_external str
       
    27   handle CInterface.Foreign _ => SHA1.digest str;
       
    28 
       
    29 end;