[PATCH 4/8] Add a utility function to make parsing hex values easier.
From: brian m. carlson <hidden>
Date: 2016-06-15 23:05:13
Subsystem:
the rest · Maintainer:
Linus Torvalds
get_oid_hex is already available for parsing hex object IDs into struct object_id, but parsing code still must hard-code the number of bytes read. Introduce parse_oid_hex, which accepts an optional length, and also returns the number of bytes parsed on success, or 0 on failure. This makes it easier for code not to assume fixed values when parsing, and to move to larger hash functions in the future. Signed-off-by: brian m. carlson <redacted> --- cache.h | 9 +++++++++ hex.c | 7 +++++++ 2 files changed, 16 insertions(+)
diff --git a/cache.h b/cache.h
index fa1f067..f3b829f 100644
--- a/cache.h
+++ b/cache.h@@ -1012,6 +1012,15 @@ extern int for_each_abbrev(const char *prefix, each_abbrev_fn, void *); extern int get_sha1_hex(const char *hex, unsigned char *sha1); extern int get_oid_hex(const char *hex, struct object_id *sha1); +/* + * Like get_oid_hex, but accepts an optional length argument, which may be -1 + * if the string is terminated by a non-hex character. As with get_oid_hex, + * reading stops if a NUL is encountered. Returns the number of characters + * read (40) on success and 0 on failure. This is designed to be easier to + * use for parsing data than get_oid_hex. + */ +extern int parse_oid_hex(const char *hex, int len, struct object_id *oid); + extern char *sha1_to_hex(const unsigned char *sha1); /* static buffer result! */ extern char *oid_to_hex(const struct object_id *oid); /* same static buffer as sha1_to_hex */ extern int read_ref_full(const char *refname, int resolve_flags,
diff --git a/hex.c b/hex.c
index 899b74a..ba196d7 100644
--- a/hex.c
+++ b/hex.c@@ -61,6 +61,13 @@ int get_oid_hex(const char *hex, struct object_id *oid) return get_sha1_hex(hex, oid->hash); } +int parse_oid_hex(const char *hex, int len, struct object_id *oid) +{ + if (len != -1 && len < GIT_SHA1_HEXSZ) + return 0; + return get_sha1_hex(hex, oid->hash) ? GIT_SHA1_HEXSZ : 0; +} + char *sha1_to_hex(const unsigned char *sha1) { static int bufno;
--
2.4.0