소스 검색

string: add strnlen_s()

Alex Lyon 5 년 전
부모
커밋
5bbce37789
4개의 변경된 파일91개의 추가작업 그리고 0개의 파일을 삭제
  1. 9 0
      src/header/string/mod.rs
  2. 0 0
      tests/expected/string/strlen.stderr
  3. 9 0
      tests/expected/string/strlen.stdout
  4. 73 0
      tests/string/strlen.c

+ 9 - 0
src/header/string/mod.rs

@@ -263,6 +263,15 @@ pub unsafe extern "C" fn strnlen(s: *const c_char, size: size_t) -> size_t {
     i as size_t
 }
 
+#[no_mangle]
+pub unsafe extern "C" fn strnlen_s(s: *const c_char, size: size_t) -> size_t {
+    if s.is_null() {
+        0
+    } else {
+        strnlen(s, size)
+    }
+}
+
 #[no_mangle]
 pub unsafe extern "C" fn strcat(s1: *mut c_char, s2: *const c_char) -> *mut c_char {
     strncat(s1, s2, usize::MAX)

+ 0 - 0
tests/expected/string/strlen.stderr


+ 9 - 0
tests/expected/string/strlen.stdout

@@ -0,0 +1,9 @@
+12
+0
+12
+12
+0
+12
+6
+12
+0

+ 73 - 0
tests/string/strlen.c

@@ -0,0 +1,73 @@
+#include <string.h>
+#include <stdio.h>
+
+#include "test_helpers.h"
+
+int main(void) {
+    char dest1[13] = "hello world!";
+    int dest1_len = strlen(dest1);
+    printf("%d\n", dest1_len);
+    if(dest1_len != 12) {
+        puts("strlen(\"hello world!\") failed");
+	exit(EXIT_FAILURE);
+    }
+
+    char empty[1] = { 0 };
+    int empty_len = strlen(empty);
+    printf("%d\n", empty_len);
+    if(empty_len != 0) {
+        puts("strlen(\"\") failed");
+        exit(EXIT_FAILURE);
+    }
+
+    dest1_len = strnlen(dest1, sizeof(dest1));
+    printf("%d\n", dest1_len);
+    if(dest1_len != 12) {
+        puts("strnlen(\"hello world!\", 13) failed");
+        exit(EXIT_FAILURE);
+    }
+
+    dest1_len = strnlen(dest1, sizeof(dest1) - 1);
+    printf("%d\n", dest1_len);
+    if(dest1_len != 12) {
+        puts("strnlen(\"hello world!\", 12) failed");
+        exit(EXIT_FAILURE);
+    }
+
+    dest1_len = strnlen(dest1, 0);
+    printf("%d\n", dest1_len);
+    if(dest1_len != 0) {
+        puts("strnlen(\"hello world!\", 0) failed");
+        exit(EXIT_FAILURE);
+    }
+
+    dest1_len = strnlen(dest1, 300);
+    printf("%d\n", dest1_len);
+    if(dest1_len != 12) {
+        puts("strnlen(\"hello world!\", 300) failed");
+        exit(EXIT_FAILURE);
+    }
+
+    dest1_len = strnlen_s(dest1, 6);
+    printf("%d\n", dest1_len);
+    if(dest1_len != 6) {
+        puts("strnlen_s(\"hello world!\", 6) failed");
+        exit(EXIT_FAILURE);
+    }
+
+    dest1_len = strnlen_s(dest1, 20);
+    printf("%d\n", dest1_len);
+    if(dest1_len != 12) {
+        puts("strnlen_s(\"hello world!\", 20) failed");
+        exit(EXIT_FAILURE);
+    }
+
+    int null_len = strnlen_s(NULL, 100);
+    printf("%d\n", null_len);
+    if(null_len != 0) {
+        puts("strnlen_s(NULL, 100) failed");
+        exit(EXIT_FAILURE);
+    }
+
+    return 0;
+}