Browse Source

new: memcmp函数

longjin 2 years ago
parent
commit
c2fa7bf46d
1 changed files with 25 additions and 0 deletions
  1. 25 0
      kernel/common/string.h

+ 25 - 0
kernel/common/string.h

@@ -51,3 +51,28 @@ long strncpy_from_user(char *dst, const char *src, unsigned long size);
  * @return long
  */
 long strnlen_user(const char *src, unsigned long maxlen);
+
+/**
+ * @brief 逐字节比较指定内存区域的值,并返回s1、s2的第一个不相等的字节i处的差值(s1[i]-s2[i])。
+ * 若两块内存区域的内容相同,则返回0
+ *
+ * @param s1 内存区域1
+ * @param s2 内存区域2
+ * @param len 要比较的内存区域长度
+ * @return int s1、s2的第一个不相等的字节i处的差值(s1[i]-s2[i])。若两块内存区域的内容相同,则返回0
+ */
+static inline int memcmp(const void *s1, const void *s2, size_t len)
+{
+    int diff;
+
+    asm("cld \n\t"  // 复位DF,确保s1、s2指针是自增的
+        "repz; cmpsb\n\t" CC_SET(nz)
+        : CC_OUT(nz)(diff), "+D"(s1), "+S"(s2)
+        : "c"(len)
+        : "memory");
+
+    if (diff)
+        diff = *(const unsigned char *)(s1 - 1) - *(const unsigned char *)(s2 - 1);
+
+    return diff;
+}