1/* 2 * Copyright (C) 2005 Junio C Hamano 3 * The delta-parsing part is almost straight copy of patch-delta.c 4 * which is (C) 2005 Nicolas Pitre <nico@cam.org>. 5 */ 6#include <stdlib.h> 7#include <string.h> 8#include <limits.h> 9#include"count-delta.h" 10 11static unsigned longget_hdr_size(const unsigned char**datap) 12{ 13const unsigned char*data = *datap; 14unsigned long size; 15unsigned char cmd; 16int i; 17 size = i =0; 18 cmd = *data++; 19while(cmd) { 20if(cmd &1) 21 size |= *data++ << i; 22 i +=8; 23 cmd >>=1; 24} 25*datap = data; 26return size; 27} 28 29/* 30 * NOTE. We do not _interpret_ delta fully. As an approximation, we 31 * just count the number of bytes that are copied from the source, and 32 * the number of literal data bytes that are inserted. Number of 33 * bytes that are _not_ copied from the source is deletion, and number 34 * of inserted literal bytes are addition, so sum of them is what we 35 * return. xdelta can express an edit that copies data inside of the 36 * destination which originally came from the source. We do not count 37 * that in the following routine, so we are undercounting the source 38 * material that remains in the final output that way. 39 */ 40unsigned longcount_delta(void*delta_buf,unsigned long delta_size) 41{ 42unsigned long copied_from_source, added_literal; 43const unsigned char*data, *top; 44unsigned char cmd; 45unsigned long src_size, dst_size, out; 46 47/* the smallest delta size possible is 6 bytes */ 48if(delta_size <6) 49return UINT_MAX; 50 51 data = delta_buf; 52 top = delta_buf + delta_size; 53 54 src_size =get_hdr_size(&data); 55 dst_size =get_hdr_size(&data); 56 57 added_literal = copied_from_source = out =0; 58while(data < top) { 59 cmd = *data++; 60if(cmd &0x80) { 61unsigned long cp_off =0, cp_size =0; 62if(cmd &0x01) cp_off = *data++; 63if(cmd &0x02) cp_off |= (*data++ <<8); 64if(cmd &0x04) cp_off |= (*data++ <<16); 65if(cmd &0x08) cp_off |= (*data++ <<24); 66if(cmd &0x10) cp_size = *data++; 67if(cmd &0x20) cp_size |= (*data++ <<8); 68if(cp_size ==0) cp_size =0x10000; 69 70if(cmd &0x40) 71/* copy from dst */ 72; 73else 74 copied_from_source += cp_size; 75 out += cp_size; 76}else{ 77/* write literal into dst */ 78 added_literal += cmd; 79 out += cmd; 80 data += cmd; 81} 82} 83 84/* sanity check */ 85if(data != top || out != dst_size) 86return UINT_MAX; 87 88/* delete size is what was _not_ copied from source. 89 * edit size is that and literal additions. 90 */ 91if(src_size + added_literal < copied_from_source) 92/* we ended up overcounting and underflowed */ 93return0; 94return(src_size - copied_from_source) + added_literal; 95}