[PATCH] fix git-checkout-cache segfault on parisc
[git/spearce.git] / patch-delta.c
blob26281ea1230f730931442bc0ed59966a6f4031be
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;
24 if (delta_size < DELTA_SIZE_MIN)
25 return NULL;
27 data = delta_buf;
28 top = delta_buf + delta_size;
30 /* make sure the orig file size matches what we expect */
31 size = get_delta_hdr_size(&data);
32 if (size != src_size)
33 return NULL;
35 /* now the result size */
36 size = get_delta_hdr_size(&data);
37 dst_buf = malloc(size);
38 if (!dst_buf)
39 return NULL;
41 out = dst_buf;
42 while (data < top) {
43 cmd = *data++;
44 if (cmd & 0x80) {
45 unsigned long cp_off = 0, cp_size = 0;
46 const unsigned char *buf;
47 if (cmd & 0x01) cp_off = *data++;
48 if (cmd & 0x02) cp_off |= (*data++ << 8);
49 if (cmd & 0x04) cp_off |= (*data++ << 16);
50 if (cmd & 0x08) cp_off |= (*data++ << 24);
51 if (cmd & 0x10) cp_size = *data++;
52 if (cmd & 0x20) cp_size |= (*data++ << 8);
53 if (cp_size == 0) cp_size = 0x10000;
54 buf = (cmd & 0x40) ? dst_buf : src_buf;
55 memcpy(out, buf + cp_off, cp_size);
56 out += cp_size;
57 } else {
58 memcpy(out, data, cmd);
59 out += cmd;
60 data += cmd;
64 /* sanity check */
65 if (data != top || out - dst_buf != size) {
66 free(dst_buf);
67 return NULL;
70 *dst_size = size;
71 return dst_buf;