Simple Operating System
string.h
Go to the documentation of this file.
1 
5 #ifndef STRING_H
6 #define STRING_H
7 
8 #include "types.h"
9 
10 #pragma GCC diagnostic push
11 #pragma GCC diagnostic ignored "-Wreturn-type"
20 bool strcmp(int str1, int str2) {
21  asm("L%=:\n"
22  " mov al, [si+bx]\n"
23  " cmp al, [di+bx]\n"
24  " jne neq%=\n"
25  " cmp al,0\n"
26  " je eq%=\n"
27  " inc bx\n"
28  "jmp L%=\n"
29  "eq%=:\n"
30  " mov ax, 1\n"
31  " jmp end%=\n"
32  "neq%=:\n"
33  " mov ax, 0\n"
34  "end%=:"
35  ::"b"(0), "S"(str1), "D"(str2));
36 }
37 
44 size_t strlen(const char *str) {
45  asm("xor eax,eax\n"
46  "L%=:\n"
47  " cmp BYTE ptr [si+bx], 0\n"
48  " je end%=\n"
49  " inc bx\n"
50  " jmp L%=\n"
51  "end%=:\n"
52  " mov eax, ebx"::"b"(0), "S"(str));
53 }
54 
55 #pragma GCC diagnostic pop
56 
64 const char * strchr ( const char * str, int character ) {
65  while(*str != 0) {
66  if(*str == character)
67  return str;
68  str++;
69  }
70  return NULL;
71 }
72 
73 const uint32_t pows[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
80 int stoi(const char *str) {
81  int num = 0;
82  size_t size = strlen(str) - 1;
83  for(size_t i = (str[0] == '-' ? 1 : 0); str[i] != 0; i++)
84  num += pows[size - i] * (str[i] - '0');
85 
86  return (str[0] == '-') ? -num : num;
87 }
88 
97 int memset(int ptr, int value, size_t count) {
98  asm("L%=:\n\
99  mov [bx],dx\n\
100  inc bx\n\
101  loop L%="
102  ::"b"(ptr), "c"(count), "d"(value));
103  return ptr;
104 }
105 
113 char * strcpy ( char * destination, const char * source ) {
114  //copy all characters, including null
115  int i = 0;
116  do {
117  destination[i] = source[i];
118  i++;
119  } while(source[i - 1] != 0);
120  return destination;
121 }
122 
131 int strncpy (int destination, int source, size_t num ) {
132  asm("L%=:\n"
133  " mov al, byte ptr [si+bx]\n"
134  " mov byte ptr [di+bx], al\n"
135  " cmp al,0\n"
136  " je after%=\n"
137  " inc bx\n"
138  "loop L%=\n"
139  "after%=:"
140  ::"D"(destination), "S"(source), "b"(0), "c"(num));
141  return destination;
142 }
143 
144 #endif
size_t strlen(const char *str)
Returns length of string.
Definition: string.h:44
int strncpy(int destination, int source, size_t num)
Copy num Bytes from source to destination until \0 appears.
Definition: string.h:131
bool strcmp(int str1, int str2)
Compares two string until \0 appears.
Definition: string.h:20
int stoi(const char *str)
Convert string to int.
Definition: string.h:80
int memset(int ptr, int value, size_t count)
Set count Bytes of *ptr to value.
Definition: string.h:97
char * strcpy(char *destination, const char *source)
Copy from source to destination until \0 appears.
Definition: string.h:113
const char * strchr(const char *str, int character)
Find first appearance of character.
Definition: string.h:64
useful macros, definitions, enums etc.
#define NULL
pointer to NULL
Definition: types.h:22