string_begins_with.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * @file string_begins_with.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * @section DESCRIPTION
  23. *
  24. * Function for checking if a string begins with a given string.
  25. */
  26. #ifndef BADVPN_MISC_STRING_BEGINS_WITH
  27. #define BADVPN_MISC_STRING_BEGINS_WITH
  28. #include <stddef.h>
  29. #include <string.h>
  30. #include <misc/debug.h>
  31. static size_t data_begins_with (const char *str, size_t str_len, const char *needle)
  32. {
  33. ASSERT(strlen(needle) > 0)
  34. size_t len = 0;
  35. while (str_len > 0 && *needle) {
  36. if (*str != *needle) {
  37. return 0;
  38. }
  39. str++;
  40. str_len--;
  41. needle++;
  42. len++;
  43. }
  44. if (*needle) {
  45. return 0;
  46. }
  47. return len;
  48. }
  49. static size_t string_begins_with (const char *str, const char *needle)
  50. {
  51. ASSERT(strlen(needle) > 0)
  52. return data_begins_with(str, strlen(str), needle);
  53. }
  54. #endif