Sync with 2.44.1
[git/gitster.git] / hex.c
blobd42262bdca71a8703ce191393f0217f0c589a75e
1 #include "git-compat-util.h"
2 #include "hash.h"
3 #include "hex.h"
5 static int get_hash_hex_algop(const char *hex, unsigned char *hash,
6 const struct git_hash_algo *algop)
8 int i;
9 for (i = 0; i < algop->rawsz; i++) {
10 int val = hex2chr(hex);
11 if (val < 0)
12 return -1;
13 *hash++ = val;
14 hex += 2;
16 return 0;
19 int get_hash_hex(const char *hex, unsigned char *sha1)
21 return get_hash_hex_algop(hex, sha1, the_hash_algo);
24 int get_oid_hex_algop(const char *hex, struct object_id *oid,
25 const struct git_hash_algo *algop)
27 int ret = get_hash_hex_algop(hex, oid->hash, algop);
28 if (!ret)
29 oid_set_algo(oid, algop);
30 return ret;
34 * NOTE: This function relies on hash algorithms being in order from shortest
35 * length to longest length.
37 int get_oid_hex_any(const char *hex, struct object_id *oid)
39 int i;
40 for (i = GIT_HASH_NALGOS - 1; i > 0; i--) {
41 if (!get_oid_hex_algop(hex, oid, &hash_algos[i]))
42 return i;
44 return GIT_HASH_UNKNOWN;
47 int get_oid_hex(const char *hex, struct object_id *oid)
49 return get_oid_hex_algop(hex, oid, the_hash_algo);
52 int parse_oid_hex_algop(const char *hex, struct object_id *oid,
53 const char **end,
54 const struct git_hash_algo *algop)
56 int ret = get_oid_hex_algop(hex, oid, algop);
57 if (!ret)
58 *end = hex + algop->hexsz;
59 return ret;
62 int parse_oid_hex_any(const char *hex, struct object_id *oid, const char **end)
64 int ret = get_oid_hex_any(hex, oid);
65 if (ret)
66 *end = hex + hash_algos[ret].hexsz;
67 return ret;
70 int parse_oid_hex(const char *hex, struct object_id *oid, const char **end)
72 return parse_oid_hex_algop(hex, oid, end, the_hash_algo);
75 char *hash_to_hex_algop_r(char *buffer, const unsigned char *hash,
76 const struct git_hash_algo *algop)
78 static const char hex[] = "0123456789abcdef";
79 char *buf = buffer;
80 int i;
83 * Our struct object_id has been memset to 0, so default to printing
84 * using the default hash.
86 if (algop == &hash_algos[0])
87 algop = the_hash_algo;
89 for (i = 0; i < algop->rawsz; i++) {
90 unsigned int val = *hash++;
91 *buf++ = hex[val >> 4];
92 *buf++ = hex[val & 0xf];
94 *buf = '\0';
96 return buffer;
99 char *oid_to_hex_r(char *buffer, const struct object_id *oid)
101 return hash_to_hex_algop_r(buffer, oid->hash, &hash_algos[oid->algo]);
104 char *hash_to_hex_algop(const unsigned char *hash, const struct git_hash_algo *algop)
106 static int bufno;
107 static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
108 bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
109 return hash_to_hex_algop_r(hexbuffer[bufno], hash, algop);
112 char *hash_to_hex(const unsigned char *hash)
114 return hash_to_hex_algop(hash, the_hash_algo);
117 char *oid_to_hex(const struct object_id *oid)
119 return hash_to_hex_algop(oid->hash, &hash_algos[oid->algo]);