git: deb9bfbd5bce - main - LinuxKPI: add hex2bin()

From: Bjoern A. Zeeb <bz_at_FreeBSD.org>
Date: Sun, 09 Jan 2022 14:38:21 UTC
The branch main has been updated by bz:

URL: https://cgit.FreeBSD.org/src/commit/?id=deb9bfbd5bcea70c79f70c7091c35d399b40fb0a

commit deb9bfbd5bcea70c79f70c7091c35d399b40fb0a
Author:     Bjoern A. Zeeb <bz@FreeBSD.org>
AuthorDate: 2022-01-09 01:09:17 +0000
Commit:     Bjoern A. Zeeb <bz@FreeBSD.org>
CommitDate: 2022-01-09 14:36:28 +0000

    LinuxKPI: add hex2bin()
    
    Add a hex2bin() implementation needed by a driver's debugfs code.
    
    MFC after:      3 days
    Reviewed by:    hselasky
    Differential Revision: https://reviews.freebsd.org/D33798
---
 sys/compat/linuxkpi/common/include/linux/kernel.h | 31 +++++++++++++++++++++++
 1 file changed, 31 insertions(+)

diff --git a/sys/compat/linuxkpi/common/include/linux/kernel.h b/sys/compat/linuxkpi/common/include/linux/kernel.h
index 94af8f29c4d7..80b684745175 100644
--- a/sys/compat/linuxkpi/common/include/linux/kernel.h
+++ b/sys/compat/linuxkpi/common/include/linux/kernel.h
@@ -649,6 +649,37 @@ linux_ratelimited(linux_ratelimit_t *rl)
 #define	TAINT_WARN	0
 #define	test_taint(x)	(0)
 
+static inline int
+_h2b(const char c)
+{
+
+	if (c >= '0' && c <= '9')
+		return (c - '0');
+	if (c >= 'a' && c <= 'f')
+		return (10 + c - 'a');
+	if (c >= 'A' && c <= 'F')
+		return (10 + c - 'A');
+	return (-EINVAL);
+}
+
+static inline int
+hex2bin(uint8_t *bindst, const char *hexsrc, size_t binlen)
+{
+	int hi4, lo4;
+
+	while (binlen > 0) {
+		hi4 = _h2b(*hexsrc++);
+		lo4 = _h2b(*hexsrc++);
+		if (hi4 < 0 || lo4 < 0)
+			return (-EINVAL);
+
+		*bindst++ = (hi4 << 4) | lo4;
+		binlen--;
+	}
+
+	return (0);
+}
+
 /*
  * Checking if an option is defined would be easy if we could do CPP inside CPP.
  * The defined case whether -Dxxx or -Dxxx=1 are easy to deal with.  In either