metaforce/hecl/lib/winsupport.cpp

47 lines
1.2 KiB
C++
Raw Normal View History

2017-12-29 07:56:31 +00:00
#include <cstdlib>
#include <cstdint>
#include <cstring>
2015-08-31 03:36:24 +00:00
#include <string>
2016-03-04 23:02:44 +00:00
#include "hecl/winsupport.hpp"
2015-08-31 03:36:24 +00:00
/*
2018-12-08 05:18:42 +00:00
* The memmem() function finds the start of the first occurrence of the
* substring 'needle' of length 'nlen' in the memory area 'haystack' of
* length 'hlen'.
*
* The return value is a pointer to the beginning of the sub-string, or
* NULL if the substring is not found.
*/
void* memmem(const void* haystack, size_t hlen, const void* needle, size_t nlen) {
int needle_first;
const uint8_t* p = static_cast<const uint8_t*>(haystack);
size_t plen = hlen;
2015-08-31 03:36:24 +00:00
2018-12-08 05:18:42 +00:00
if (!nlen)
return NULL;
2015-08-31 03:36:24 +00:00
2018-12-08 05:18:42 +00:00
needle_first = *(unsigned char*)needle;
2015-08-31 03:36:24 +00:00
2018-12-08 05:18:42 +00:00
while (plen >= nlen && (p = static_cast<const uint8_t*>(memchr(p, needle_first, plen - nlen + 1)))) {
if (!memcmp(p, needle, nlen))
return (void*)p;
2015-08-31 03:36:24 +00:00
2018-12-08 05:18:42 +00:00
p++;
plen = hlen - (p - static_cast<const uint8_t*>(haystack));
}
2015-08-31 03:36:24 +00:00
2018-12-08 05:18:42 +00:00
return NULL;
2015-08-31 03:36:24 +00:00
}
2017-11-25 02:49:50 +00:00
2018-12-08 05:18:42 +00:00
int asprintf(char** buf, const char* format, ...) {
va_list ap;
va_start(ap, format);
int len = vsnprintf(nullptr, 0, format, ap);
va_end(ap);
*buf = (char*)malloc(len + 1);
va_start(ap, format);
vsnprintf(*buf, len + 1, format, ap);
va_end(ap);
return len;
2017-11-25 02:49:50 +00:00
}