TSOS/src/kernel/util.c

122 lines
2.7 KiB
C

/*
Copyright 2022 Mattia Giambirtone & Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "kernel/types.h"
#include "kernel/util.h"
void copystr(const char* restrict source, char* restrict dest, i32 n) {
/*
Copies n bytes from source to dest. The two memory locations may
not overlap: if they do, the behavior is undefined. This function's
behavior is also undefined if:
- n is larger than source's or dest's actual size
- dest is smaller than source
The caller should make sure these conditions are checked for before
calling this function
*/
int i;
for (i = 0; i < n; i++) {
*(dest + i) = *(source + i);
}
}
void memset(byte* dest, byte val, u32 len) {
/*
Fills the first len bytes of the memory area pointed to by dest
with the constant byte val
*/
u8* temp = (u8*)dest;
while (len) {
*temp++ = val;
len--;
}
}
u8 countDigits(i32 n) {
/*
Returns the number of digits
of n
*/
i8 result = 0;
while (n) {
n /= 10;
result++;
}
return result;
}
i32 uCountDigits(u32 n) {
/*
Returns the number of digits
of n
*/
i32 result = 0;
while (n) {
n /= 10;
result++;
}
return result;
}
void itoa(i32 n, char* a) {
/*
Converts the integer n to
a string. The result is written
to a, which is assumed to be large
enough to accomodate an optional
negative sign, the number itself
and a null byte at the end (if the
buffer is not large enough, the
behavior is undefined)
*/
bool sign = n >= 0;
if (!sign) n = -n;
i32 i = countDigits(n);
do {
a[--i] = n % 10 + '0';
} while (n /= 10);
if (!sign) a[--i] = '-';
a[--i] = '\0';
}
void utoa(u32 n, char* a) {
/*
Converts the unsigned integer n to
a string. The result is written
to a, which is assumed to be large
enough to accomodate the number
itself and a null byte at the end
(if the buffer is not large enough,
the behavior is undefined)
*/
i32 i = uCountDigits(n);
do {
a[--i] = n % 10 + '0';
} while (n /= 10);
a[--i] = '\0';
}