// SPDX-License-Identifier: MPL-2.0
#include "std/string.h"
sh_uint64 sh_string_len(char *str) {
  sh_uint64 i=0;
  if (!str) return 0;
  while (str[i]) i++;
  return i;
}
sh_bool sh_string_compare(char *str1,char *str2,sh_uint64 length) {
  sh_uint64 i=0;
  if (!str1 || !str2) return SH_FALSE;
  while (i<length) {
    if (str1[i]!=str2[i]) return SH_FALSE;
    if (str1[i]=='\0' && str2[i]=='\0') return SH_TRUE;
    i++;
  }
  return 1;
}
sh_uint64 sh_string_find_char(char *str,char character) {
  sh_uint64 i=0;
  if (!str) return SH_UINT64_MAX;
  while (str[i]) {
    if (str[i]==character) return i;
    i++;
  }
  return SH_UINT64_MAX;
}
sh_uint64 sh_string_find(char *str,char *substr) {
  sh_uint64 i=0;
  sh_uint64 j=0;
  if (!str || !substr) return SH_UINT64_MAX;
  if (!substr[0]) return 0;
  while (str[i]) {
    j=0;
    while (str[i+j] && substr[j] && str[i+j]==substr[j]) j++;
    if (!substr[j]) return i;
    i++;
  }
  return SH_UINT64_MAX;
}
char *sh_string_substring(char *source_str,sh_uint64 start_index,sh_uint64 length,char *output) {
  sh_uint64 i=0;
  if (!source_str || !output) return SH_NULLPTR;
  while (i<length && source_str[start_index+i]) {
    output[i]=source_str[start_index+i];
    i++;
  }
  output[i]='\0';
  return output;
}
sh_uint64 sh_string_to_uint64(char *str) {
  sh_uint64 result=0;
  if (!str) return SH_UINT64_MAX;
  while(*str) {
    if (*str<'0' || *str>'9') break;
    sh_uint64 digit=(sh_uint64)(*str-'0');
    if (result>(SH_UINT64_MAX-digit)/10) return SH_UINT64_MAX;
    result=result*10+digit;
    str++;
  }
  return result;
}
