Guest User

Untitled

a guest
May 26th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. /*
  2. * Copyright 2018, Valentin Debon
  3. * The following implementation of strlen
  4. * gives reasonable performances built with
  5. * clang and -O3, on both Darwin/XNU and GNU/Linux
  6. * contact me if you have any questions.
  7. */
  8. #include <time.h>
  9. #include <stdio.h>
  10. #include <stdint.h>
  11.  
  12. #include <string.h>
  13.  
  14. #define MAGIC_LOW ((unsigned long)-1 / (unsigned char)-1)
  15. #define MAGIC_HIGH (MAGIC_LOW << 7)
  16. #define HAS_ZERO_BYTE(x) (((x) - MAGIC_LOW) ^ (x) & MAGIC_HIGH)
  17.  
  18. size_t
  19. strlen(const char *string) {
  20. const long *aligned;
  21. const char *iterator = string;
  22.  
  23. while(((uintptr_t)iterator % sizeof(long)) != 0) {
  24. if(*iterator == '\0') {
  25. return iterator - string;
  26. }
  27.  
  28. iterator++;
  29. }
  30.  
  31. aligned = (const long *)iterator;
  32. while(HAS_ZERO_BYTE(*aligned) == 0) {
  33. aligned++;
  34. }
  35.  
  36. iterator = (const char *)aligned;
  37. while(*iterator != '\0') {
  38. iterator++;
  39. }
  40.  
  41. return iterator - string;
  42. }
Add Comment
Please, Sign In to add comment