1% Copyright (C) 2012-2017,2018 John E. Davis 2% 3% This file is part of the S-Lang Library and may be distributed under the 4% terms of the GNU General Public License. See the file COPYING for 5% more information. 6%--------------------------------------------------------------------------- 7import ("chksum"); 8 9private define chksum_accumulate (c, str) 10{ 11 _chksum_accumulate (c.obj, str); 12} 13 14private define chksum_close (c) 15{ 16 variable chksum = _chksum_close (c.obj); 17 c.obj = NULL; 18 return chksum; 19} 20 21define chksum_new (name) 22{ 23 return struct 24 { 25 obj = _chksum_new (name), 26 accumulate = &chksum_accumulate, 27 close = &chksum_close, 28 name = name, 29 }; 30} 31 32define md5sum_new () 33{ 34 return chksum_new ("md5"); 35} 36 37define sha1sum_new () 38{ 39 return chksum_new ("sha1"); 40} 41 42define md5sum (str) 43{ 44 variable c = _chksum_new ("md5"); 45 _chksum_accumulate (c, str); 46 return _chksum_close (c); 47} 48 49define sha1sum (str) 50{ 51 variable c = _chksum_new ("sha1"); 52 _chksum_accumulate (c, str); 53 return _chksum_close (c); 54} 55 56define chksum_file (fp, type) 57{ 58 variable file = NULL; 59 if (typeof (fp) != File_Type) 60 { 61 file = fp; 62 fp = fopen (file, "rb"); 63 if (fp == NULL) 64 throw OpenError, "Error opening $file"$; 65 } 66 67 variable c = _chksum_new (type); 68 69 variable buf; 70 while (-1 != fread_bytes (&buf, 4096, fp)) 71 { 72 _chksum_accumulate (c, buf); 73 } 74 % Allow the interpreter to close fp when it goes out of scope 75 return _chksum_close (c); 76} 77 78define md5sum_file (file) 79{ 80 return chksum_file (file, "md5"); 81} 82 83define sha1sum_file (file) 84{ 85 return chksum_file (file, "sha1"); 86} 87 88