Browse Source

allow to create a Crc instance to run progressively (used by hxformat)

Nicolas Cannasse 12 years ago
parent
commit
0373a34a0a
1 changed files with 36 additions and 2 deletions
  1. 36 2
      std/haxe/crypto/Crc32.hx

+ 36 - 2
std/haxe/crypto/Crc32.hx

@@ -23,19 +23,53 @@ package haxe.crypto;
 
 class Crc32 {
 
+	var crc : Int;
+	
+	public function new() {
+		crc = 0xFFFFFFFF;
+	}
+	
+	public function byte( b : Int ) {
+		var tmp = (crc ^ b) & 0xFF;
+		for( j in 0...8 ) {
+			if( tmp & 1 == 1 )
+				tmp = (tmp >>> 1) ^ 0xEDB88320;
+			else
+				tmp >>>= 1;
+		}
+		crc = (crc >>> 8) ^ tmp;
+	}
+	
+	public function update( b : haxe.io.Bytes, pos, len ) {
+		var b = b.getData();
+		for( i in pos...pos+len ) {
+			var tmp = (crc ^ haxe.io.Bytes.fastGet(b,i)) & 0xFF;
+			for( j in 0...8 ) {
+				if( tmp & 1 == 1 )
+					tmp = (tmp >>> 1) ^ 0xEDB88320;
+				else
+					tmp >>>= 1;
+			}
+			crc = (crc >>> 8) ^ tmp;
+		}
+	}
+	
+	public function get() {
+		return crc ^ 0xFFFFFFFF;
+	}
+	
 	/**
 		Calculates the CRC32 of the given data bytes
 	**/
 	public static function make( data : haxe.io.Bytes ) : Int {
 		var init = 0xFFFFFFFF;
-		var polynom = 0xEDB88320;
 		var crc = init;
 		var b = data.getData();
 		for( i in 0...data.length ) {
 			var tmp = (crc ^ haxe.io.Bytes.fastGet(b,i)) & 0xFF;
 			for( j in 0...8 ) {
 				if( tmp & 1 == 1 )
-					tmp = (tmp >>> 1) ^ polynom;
+					tmp = (tmp >>> 1) ^ 0xEDB88320;
 				else
 					tmp >>>= 1;
 			}