string.c 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #include "string.h"
  2. size_t strlen(const char *s)
  3. {
  4. register int __res = 0;
  5. while (s[__res] != '\0')
  6. {
  7. ++__res;
  8. }
  9. return __res;
  10. }
  11. int strcmp(const char *FirstPart, const char *SecondPart)
  12. {
  13. register int __res;
  14. __asm__ __volatile__("cld \n\t"
  15. "1: \n\t"
  16. "lodsb \n\t"
  17. "scasb \n\t"
  18. "jne 2f \n\t"
  19. "testb %%al, %%al \n\t"
  20. "jne 1b \n\t"
  21. "xorl %%eax, %%eax \n\t"
  22. "jmp 3f \n\t"
  23. "2: \n\t"
  24. "movl $1, %%eax \n\t"
  25. "jl 3f \n\t"
  26. "negl %%eax \n\t"
  27. "3: \n\t"
  28. : "=a"(__res)
  29. : "D"(FirstPart), "S"(SecondPart)
  30. :);
  31. return __res;
  32. }
  33. void *memset(void *dst, unsigned char C, uint64_t size)
  34. {
  35. int d0, d1;
  36. unsigned long tmp = C * 0x0101010101010101UL;
  37. __asm__ __volatile__("cld \n\t"
  38. "rep \n\t"
  39. "stosq \n\t"
  40. "testb $4, %b3 \n\t"
  41. "je 1f \n\t"
  42. "stosl \n\t"
  43. "1:\ttestb $2, %b3 \n\t"
  44. "je 2f\n\t"
  45. "stosw \n\t"
  46. "2:\ttestb $1, %b3 \n\t"
  47. "je 3f \n\t"
  48. "stosb \n\t"
  49. "3: \n\t"
  50. : "=&c"(d0), "=&D"(d1)
  51. : "a"(tmp), "q"(size), "0"(size / 8), "1"(dst)
  52. : "memory");
  53. return dst;
  54. }
  55. /**
  56. * @brief 拷贝指定字节数的字符串
  57. *
  58. * @param dst 目标地址
  59. * @param src 源字符串
  60. * @param Count 字节数
  61. * @return char*
  62. */
  63. char *strncpy(char *dst, char *src, long Count)
  64. {
  65. __asm__ __volatile__("cld \n\t"
  66. "1: \n\t"
  67. "decq %2 \n\t"
  68. "js 2f \n\t"
  69. "lodsb \n\t"
  70. "stosb \n\t"
  71. "testb %%al, %%al \n\t"
  72. "jne 1b \n\t"
  73. "rep \n\t"
  74. "stosb \n\t"
  75. "2: \n\t"
  76. :
  77. : "S"(src), "D"(dst), "c"(Count)
  78. : "ax", "memory");
  79. return dst;
  80. }
  81. /**
  82. * @brief 拼接两个字符串(将src接到dest末尾)
  83. *
  84. * @param dest 目标串
  85. * @param src 源串
  86. * @return char*
  87. */
  88. char *strcat(char *dest, const char *src)
  89. {
  90. unsigned int dest_size = strlen(dest);
  91. unsigned int src_size = strlen(src);
  92. char *d = dest;
  93. for (size_t i = 0; i < src_size; i++)
  94. {
  95. d[dest_size + i] = src[i];
  96. }
  97. d[dest_size + src_size] = '\0';
  98. return dest;
  99. }