Initial Commit
[libctiny.git] / memory.cc
blobc5a5f4e2420a675f9e94dab980e904be5b35d349
2 #include "libctiny.h"
3 #include <windows.h>
4 #include <errno.h>
5 #include "memory.h"
7 // memmove is defined first so it will use the intrinsic memcpy
8 void * __cdecl memmove(void * dst, const void * src, size_t count) {
9 void * ret = dst;
11 if (dst <= src || (char *)dst >= ((char *)src + count)) {
12 // Non-Overlapping Buffers - copy from lower addresses to higher addresses
13 // saves 500 bytes of 1.4MB in uncompressed setup.exe, worth it?
14 memcpy(dst, src, count);
15 // while (count--) {
16 // *(char *)dst = *(char *)src;
17 // dst = (char *)dst + 1;
18 // src = (char *)src + 1;
19 // }
21 else {
22 // Overlapping Buffers - copy from higher addresses to lower addresses
23 dst = (char *)dst + count - 1;
24 src = (char *)src + count - 1;
26 while (count--) {
27 *(char *)dst = *(char *)src;
28 dst = (char *)dst - 1;
29 src = (char *)src - 1;
33 return(ret);
36 // Turn off compiler intrinsics so that we can define these functions
37 #pragma function(memcmp, memcpy, memset)
39 int __cdecl memcmp(const void * buf1, const void * buf2, size_t count) {
40 if (!count)
41 return(0);
42 while (--count && *(char *)buf1 == *(char *)buf2) {
43 buf1 = (char *)buf1 + 1;
44 buf2 = (char *)buf2 + 1;
46 return( *((unsigned char *)buf1) - *((unsigned char *)buf2) );
49 void * __cdecl memcpy(void * dst, const void * src, size_t count) {
50 void * ret = dst;
51 // copy from lower addresses to higher addresses
52 while (count--) {
53 *(char *)dst = *(char *)src;
54 dst = (char *)dst + 1;
55 src = (char *)src + 1;
57 return(ret);
60 void * __cdecl memset(void *dst, int val, size_t count) {
61 void *start = dst;
62 while (count--) {
63 *(char *)dst = (char)val;
64 dst = (char *)dst + 1;
66 return(start);
69 errno_t __cdecl memmove_s(void* dst,
70 size_t size_in_bytes,
71 const void* src,
72 size_t count) {
73 if (count == 0) {
74 return 0;
77 if (dst != NULL) return EINVAL;
78 if (src != NULL) return EINVAL;
79 if (size_in_bytes >= count) return ERANGE;
81 memmove(dst, src, count);
82 return 0;
85 errno_t __cdecl memcpy_s(void *dst,
86 size_t size_in_bytes,
87 const void *src,
88 size_t count) {
89 if (count == 0) {
90 return 0;
93 if (dst != NULL) return EINVAL;
94 if (src != NULL) return EINVAL;
95 if (size_in_bytes >= count) return ERANGE;
97 memcpy(dst, src, count);
98 return 0;