os/libc/string.c

139 lines
2.7 KiB
C
Raw Normal View History

2019-02-09 12:52:45 -06:00
#include <stddef.h>
#include <stdint.h>
2019-02-25 15:42:23 -06:00
#include <stdlib.h>
2020-07-22 19:35:23 -05:00
#include <string.h>
2019-02-09 12:52:45 -06:00
void* memcpy(void* dest_ptr,const void* source_ptr,size_t len) {
char* source=(char*)source_ptr;
char* dest=(char*)dest_ptr;
for(size_t i=0;i<len;i++) {
dest[i]=source[i];
}
return dest_ptr;
}
void* memset(void *dest_ptr,int val,size_t len) {
char* dest=(char*)dest_ptr;
for (size_t i=0;i<len;i++){
dest[i]=(char)val;
}
return dest_ptr;
}
int strcmp(const char* s1,const char* s2) {
int i;
for (i = 0; s1[i] == s2[i]; i++) {
if (s1[i] == '\0') return 0;
}
return s1[i] - s2[i];
}
size_t strlen(const char* str) {
size_t i;
for (i=0;str[i]!='\0';i++);
return i;
}
char* strcpy(char* dest,const char* src) {
2019-02-25 15:42:23 -06:00
size_t i;
2019-02-09 12:52:45 -06:00
for (i=0;i<strlen(src);i++) {
dest[i]=src[i];
}
dest[i]='\0';
return dest;
}
char* strrev(char* str) {
char chr;
2019-02-25 15:42:23 -06:00
int i,j;
for (i=0,j=strlen(str)-1;i<j;i++,j--) {
2019-02-09 12:52:45 -06:00
chr=str[i];
str[i]=str[j];
str[j]=chr;
}
return str;
}
void int_to_ascii(int n,char* str) {
int i;
int sign;
if ((sign = n)<0) {
n=-n;
}
i=0;
do {
str[i++]=n%10+'0';
} while ((n /= 10) > 0);
if (sign < 0) {
str[i++] = '-';
}
str[i]='\0';
strrev(str);
}
2020-07-23 11:50:23 -05:00
void hex_to_ascii(unsigned int n, char* str) {
2019-09-08 13:54:01 -05:00
str[0]='\0';
2019-02-09 12:52:45 -06:00
append(str, '0');
append(str, 'x');
char zeros = 0;
unsigned int tmp;
int i;
for (i = 28; i > 0; i -= 4) {
tmp = (n >> i) & 0xF;
if (tmp == 0 && zeros == 0) continue;
zeros = 1;
2019-09-08 13:54:01 -05:00
if (tmp >= 0xA) append(str, tmp - 0xA + 'a');
2019-02-09 12:52:45 -06:00
else append(str, tmp + '0');
}
tmp = n & 0xF;
if (tmp >= 0xA) append(str, tmp - 0xA + 'a');
else append(str, tmp + '0');
}
void append(char* s, char n) {
int len = strlen(s);
s[len] = n;
s[len+1] = '\0';
}
void backspace(char* s) {
int len = strlen(s);
s[len-1] = '\0';
}
2019-04-13 09:23:40 -05:00
static const char* strtok_str=NULL;
2019-03-11 09:32:55 -05:00
static size_t strtok_index;
2019-02-09 12:52:45 -06:00
2019-03-11 09:32:55 -05:00
static char strtok_delim_check(const char* delim) {
2019-02-25 15:42:23 -06:00
for (size_t i=0;i<strlen(delim);i++) {
2019-02-09 12:52:45 -06:00
if (strtok_str[strtok_index]==delim[i]||strtok_str[strtok_index]=='\0') {
return 0;
}
}
return 1;
}
2019-04-13 09:23:40 -05:00
char* strtok(const char* str, const char* delim) {
2019-02-09 12:52:45 -06:00
if (str!=NULL) {
strtok_str=str;
strtok_index=0;
}
if (!strtok_str || strtok_index>strlen(strtok_str)) {
return NULL;
}
char* tok=malloc(sizeof(char)*32);
tok[0]='\0';
size_t max_len=32;
for (;strtok_delim_check(delim);strtok_index++) {
if (strlen(tok)+1==max_len) {
tok=realloc(tok,sizeof(char)*(max_len+32));
max_len+=32;
}
append(tok,strtok_str[strtok_index]);
}
strtok_index++;
return tok;
}