[PATCH] delta creation
[git/repo.git] / patch-delta.c
bloba8d75ee1c8eab9cddcebd1e3ef5c6425e4181dbf
1 /*
2 * patch-delta.c:
3 * recreate a buffer from a source and the delta produced by diff-delta.c
5 * (C) 2005 Nicolas Pitre <nico@cam.org>
7 * This code is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
12 #include <stdlib.h>
13 #include <string.h>
14 #include "delta.h"
16 void *patch_delta(void *src_buf, unsigned long src_size,
17 void *delta_buf, unsigned long delta_size,
18 unsigned long *dst_size)
20 const unsigned char *data, *top;
21 unsigned char *dst_buf, *out, cmd;
22 unsigned long size;
23 int i;
25 /* the smallest delta size possible is 6 bytes */
26 if (delta_size < 6)
27 return NULL;
29 data = delta_buf;
30 top = delta_buf + delta_size;
32 /* make sure the orig file size matches what we expect */
33 size = i = 0;
34 cmd = *data++;
35 while (cmd) {
36 if (cmd & 1)
37 size |= *data++ << i;
38 i += 8;
39 cmd >>= 1;
41 if (size != src_size)
42 return NULL;
44 /* now the result size */
45 size = i = 0;
46 cmd = *data++;
47 while (cmd) {
48 if (cmd & 1)
49 size |= *data++ << i;
50 i += 8;
51 cmd >>= 1;
53 dst_buf = malloc(size);
54 if (!dst_buf)
55 return NULL;
57 out = dst_buf;
58 while (data < top) {
59 cmd = *data++;
60 if (cmd & 0x80) {
61 unsigned long cp_off = 0, cp_size = 0;
62 const unsigned char *buf;
63 if (cmd & 0x01) cp_off = *data++;
64 if (cmd & 0x02) cp_off |= (*data++ << 8);
65 if (cmd & 0x04) cp_off |= (*data++ << 16);
66 if (cmd & 0x08) cp_off |= (*data++ << 24);
67 if (cmd & 0x10) cp_size = *data++;
68 if (cmd & 0x20) cp_size |= (*data++ << 8);
69 if (cp_size == 0) cp_size = 0x10000;
70 buf = (cmd & 0x40) ? dst_buf : src_buf;
71 memcpy(out, buf + cp_off, cp_size);
72 out += cp_size;
73 } else {
74 memcpy(out, data, cmd);
75 out += cmd;
76 data += cmd;
80 /* sanity check */
81 if (data != top || out - dst_buf != size) {
82 free(dst_buf);
83 return NULL;
86 *dst_size = size;
87 return dst_buf;