3 * Common Library Functions
8 #define RANDOM_SEED 0xACE55052
9 #define RANDOM_A 0x00731ADE
10 #define RANDOM_C 12345
11 #define RANDOM_SPRUCE 0xf12b039
12 // Jan Feb Mar Apr May Jun Jul Aug Sept Oct Nov Dec
13 const short DAYS_BEFORE[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
14 #define UNIX_TO_2K ((30*365*3600*24) + (7*3600*24)) //Normal years + leap years
17 int atoi(const char *string);
18 void itoa(char *buf, Uint num, int base, int minLength, char pad);
19 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args);
20 int sprintf(char *__s, const char *__format, ...);
22 int strucmp(const char *Str1, const char *Str2);
23 int strpos(const char *Str, char Ch);
24 Uint8 ByteSum(void *Ptr, int Size);
25 size_t strlen(const char *__s);
26 char *strcpy(char *__str1, const char *__str2);
27 char *strncpy(char *__str1, const char *__str2, size_t max);
28 int strcmp(const char *str1, const char *str2);
29 int strncmp(const char *str1, const char *str2, size_t num);
30 char *_strdup(const char *File, int Line, const char *Str);
31 char **str_split(const char *__str, char __ch);
32 int strpos8(const char *str, Uint32 Search);
33 int ReadUTF8(Uint8 *str, Uint32 *Val);
34 int WriteUTF8(Uint8 *str, Uint32 Val);
35 int DivUp(int num, int dem);
36 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year);
38 int CheckString(char *String);
39 int CheckMem(void *Mem, int NumBytes);
40 int ModUtil_LookupString(char **Array, char *Needle);
41 int ModUtil_SetIdent(char *Dest, char *Value);
58 EXPORT(_strdup); // Takes File/Line too
67 EXPORT(ModUtil_LookupString);
68 EXPORT(ModUtil_SetIdent);
72 * \brief Convert a string into an integer
74 int atoi(const char *string)
79 //Log("atoi: (string='%s')", string);
81 // Clear non-numeric characters
82 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
83 if( *string == '-' ) {
85 while( !('0' <= *string && *string <= '9') ) string++;
97 if('0' <= *string && *string <= '9') {
101 else if('A' <= *string && *string <= 'F') {
103 ret += *string - 'A' + 10;
105 else if('a' <= *string && *string <= 'f') {
107 ret += *string - 'a' + 10;
115 for( ; '0' <= *string && *string <= '7'; string ++ )
118 ret += *string - '0';
124 for( ; '0' <= *string && *string <= '9'; string++)
127 ret += *string - '0';
133 //Log("atoi: RETURN %i", ret);
138 static const char cUCDIGITS[] = "0123456789ABCDEF";
140 * \fn void itoa(char *buf, Uint num, int base, int minLength, char pad)
141 * \brief Convert an integer into a character string
143 void itoa(char *buf, Uint num, int base, int minLength, char pad)
152 if(base > 16 || base < 2) {
158 while(num > base-1) {
159 tmpBuf[pos] = cUCDIGITS[ num % base ];
160 num /= (Uint)base; // Shift `num` right 1 digit
163 tmpBuf[pos++] = cUCDIGITS[ num % base ]; // Last digit of `num`
168 while(minLength-- > 0) buf[i++] = pad;
169 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
174 * \brief Append a character the the vsnprintf output
176 #define PUTCH(c) do{\
178 if(pos==__maxlen){return pos;}\
179 if(__s){__s[pos++]=ch;}else{pos++;}\
181 #define GETVAL() do {\
182 if(isLongLong) val = va_arg(args, Uint64);\
183 else val = va_arg(args, unsigned int);\
186 * \brief VArg String Number Print Formatted
188 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
191 int minSize = 0, len;
192 char tmpBuf[34]; // For Integers
200 //Log("vsnprintf: (__s=%p, __maxlen=%i, __format='%s', ...)", __s, __maxlen, __format);
202 while((c = *__format++) != 0)
204 // Non control character
205 if(c != '%') { PUTCH(c); continue; }
208 //Log("pos = %i", pos);
211 if(c == '%') { PUTCH('%'); continue; }
213 // Pointer - Done first for debugging
215 Uint ptr = va_arg(args, Uint);
216 PUTCH('*'); PUTCH('0'); PUTCH('x');
218 itoa(p, ptr, 16, BITS/4, '0');
222 // - Padding Side Flag
237 if(c == '*') { // Dynamic length
238 minSize = va_arg(args, unsigned int);
241 else if('1' <= c && c <= '9')
244 while('0' <= c && c <= '9')
254 // - Default, Long or LongLong?
256 if(c == 'l') // Long is actually the default on x86
265 // - Now get the format code
272 if( isLongLong && val >> 63 ) {
276 else if( !isLongLong && val >> 31 ) {
280 itoa(p, val, 10, minSize, pad);
284 itoa(p, val, 10, minSize, pad);
288 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
291 itoa(p, val, 16, minSize, pad);
296 itoa(p, val, 16, minSize, pad);
300 itoa(p, val, 8, minSize, pad);
304 itoa(p, val, 2, minSize, pad);
308 val = va_arg(args, unsigned int);
313 // String - Null Terminated Array
315 p = va_arg(args, char*); // Get Argument
319 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
320 while(*p) PUTCH(*p++);
321 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
324 case 'C': // Non-Null Terminated Character Array
325 p = va_arg(args, char*);
326 if(!p) goto printString;
327 while(minSize--) PUTCH(*p++);
339 if(__s && pos != __maxlen)
348 int sprintf(char *__s, const char *__format, ...)
353 va_start(args, __format);
354 ret = vsnprintf(__s, -1, __format, args);
361 * \fn int tolower(int c)
362 * \brief Converts a character to lower case
366 if('A' <= c && c <= 'Z')
367 return c - 'A' + 'a';
372 * \fn int strucmp(const char *Str1, const char *Str2)
373 * \brief Compare \a Str1 and \a Str2 case-insensitively
375 int strucmp(const char *Str1, const char *Str2)
377 while(*Str1 && tolower(*Str1) == tolower(*Str2))
379 return tolower(*Str1) - tolower(*Str2);
383 * \fn int strpos(const char *Str, char Ch)
384 * \brief Search a string for an ascii character
386 int strpos(const char *Str, char Ch)
389 for(pos=0;Str[pos];pos++)
391 if(Str[pos] == Ch) return pos;
397 * \fn Uint8 ByteSum(void *Ptr, int Size)
398 * \brief Adds the bytes in a memory region and returns the sum
400 Uint8 ByteSum(void *Ptr, int Size)
403 while(Size--) sum += *(Uint8*)Ptr++;
408 * \fn Uint strlen(const char *__str)
409 * \brief Get the length of string
411 Uint strlen(const char *__str)
414 while(*__str++) ret++;
419 * \fn char *strcpy(char *__str1, const char *__str2)
420 * \brief Copy a string to a new location
422 char *strcpy(char *__str1, const char *__str2)
425 *__str1++ = *__str2++;
426 *__str1 = '\0'; // Terminate String
431 * \fn char *strncpy(char *__str1, const char *__str2, size_t max)
432 * \brief Copy a string to a new location
434 char *strncpy(char *__str1, const char *__str2, size_t max)
436 while(*__str2 && max-- >= 1)
437 *__str1++ = *__str2++;
439 *__str1 = '\0'; // Terminate String
444 * \fn int strcmp(const char *str1, const char *str2)
445 * \brief Compare two strings return the difference between
446 * the first non-matching characters.
448 int strcmp(const char *str1, const char *str2)
450 while(*str1 && *str1 == *str2)
452 return *str1 - *str2;
456 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
457 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
459 int strncmp(const char *Str1, const char *Str2, size_t num)
461 if(num == 0) return 0; // TODO: Check what should officially happen here
462 while(--num && *Str1 && *Str1 == *Str2)
469 * \fn char *strdup(const char *Str)
470 * \brief Duplicates a string
472 char *strdup(const char *Str)
475 ret = malloc(strlen(Str)+1);
476 if( !ret ) return NULL;
483 * \fn char *_strdup(const char *File, int Line, const char *Str)
484 * \brief Duplicates a string
486 char *_strdup(const char *File, int Line, const char *Str)
489 ret = Heap_Allocate(File, Line, strlen(Str)+1);
490 if( !ret ) return NULL;
497 * \brief Split a string using the passed character
498 * \return NULL terminated array of strings on the heap
499 * \param __str String to split
500 * \param __ch Character to split by
502 char **str_split(const char *__str, char __ch)
509 for( i = 0; __str[i]; i++ )
515 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
516 if( !ret ) return NULL;
519 start = (char *)&ret[len+1];
521 for( i = 0; __str[i]; i++ )
523 if(__str[i] == __ch) {
538 * \fn int DivUp(int num, int dem)
539 * \brief Divide two numbers, rounding up
540 * \param num Numerator
541 * \param dem Denominator
543 int DivUp(int num, int dem)
545 return (num+dem-1)/dem;
549 * \fn int strpos8(const char *str, Uint32 search)
550 * \brief Search a string for a UTF-8 character
552 int strpos8(const char *str, Uint32 Search)
556 for(pos=0;str[pos];pos++)
560 if(str[pos] == Search) return pos;
563 if(*(Uint8*)(str+pos) < 128) continue;
565 pos += ReadUTF8( (Uint8*)&str[pos], &val );
566 if(val == Search) return pos;
572 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
573 * \brief Read a UTF-8 character from a string
575 int ReadUTF8(Uint8 *str, Uint32 *Val)
577 *Val = 0xFFFD; // Assume invalid character
580 if( !(*str & 0x80) ) {
585 // Middle of a sequence
586 if( (*str & 0xC0) == 0x80 ) {
591 if( (*str & 0xE0) == 0xC0 ) {
592 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
594 if( (*str & 0xC0) != 0x80) return -1; // Validity check
595 *Val |= (*str & 0x3F); // Lower 6 Bits
600 if( (*str & 0xF0) == 0xE0 ) {
601 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
603 if( (*str & 0xC0) != 0x80) return -1; // Validity check
604 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
606 if( (*str & 0xC0) != 0x80) return -1; // Validity check
607 *Val |= (*str & 0x3F); // Lower 6 Bits
612 if( (*str & 0xF1) == 0xF0 ) {
613 *Val = (*str & 0x07) << 18; // Upper 3 Bits
615 if( (*str & 0xC0) != 0x80) return -1; // Validity check
616 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
618 if( (*str & 0xC0) != 0x80) return -1; // Validity check
619 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
621 if( (*str & 0xC0) != 0x80) return -1; // Validity check
622 *Val |= (*str & 0x3F); // Lower 6 Bits
626 // UTF-8 Doesn't support more than four bytes
631 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
632 * \brief Write a UTF-8 character sequence to a string
634 int WriteUTF8(Uint8 *str, Uint32 Val)
644 *str = 0xC0 | (Val >> 6);
646 *str = 0x80 | (Val & 0x3F);
651 if( Val < 0x10000 ) {
652 *str = 0xE0 | (Val >> 12);
654 *str = 0x80 | ((Val >> 6) & 0x3F);
656 *str = 0x80 | (Val & 0x3F);
661 if( Val < 0x110000 ) {
662 *str = 0xF0 | (Val >> 18);
664 *str = 0x80 | ((Val >> 12) & 0x3F);
666 *str = 0x80 | ((Val >> 6) & 0x3F);
668 *str = 0x80 | (Val & 0x3F);
672 // UTF-8 Doesn't support more than four bytes
677 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
678 * \brief Converts a date into an Acess Timestamp
680 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
687 stamp += day*3600*24;
688 stamp += month*DAYS_BEFORE[month]*3600*24;
690 ((year&3) == 0 || year%100 != 0)
691 || (year%100 == 0 && ((year/100)&3) == 0)
692 ) && month > 1) // Leap year and after feb
695 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
696 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
704 * \brief Pseudo random number generator
705 * \note Unknown effectiveness (made up on the spot)
710 static Uint state = RANDOM_SEED;
712 // Get the next state value
713 giRandomState = (RANDOM_A*state + RANDOM_C);
714 // Check if it has changed, and if it hasn't, change it
715 if(state == old) state += RANDOM_SPRUCE;
718 // http://en.wikipedia.org/wiki/Xorshift
720 static Uint32 x = 123456789;
721 static Uint32 y = 362436069;
722 static Uint32 z = 521288629;
723 static Uint32 w = 88675123;
728 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
733 * \name Memory Validation
737 * \brief Checks if a string resides fully in valid memory
739 int CheckString(char *String)
741 if( !MM_GetPhysAddr( (tVAddr)String ) )
745 if( MM_IsUser( (tVAddr)String ) )
750 if( !MM_IsUser( (tVAddr)String ) )
752 // Increment string pointer
757 else if( MM_GetPhysAddr( (tVAddr)String ) )
762 if( !MM_GetPhysAddr( (tVAddr)String ) )
764 // Increment string pointer
773 * \brief Check if a sized memory region is valid memory
775 int CheckMem(void *Mem, int NumBytes)
777 tVAddr addr = (tVAddr)Mem;
779 if( MM_IsUser( addr ) )
783 if( !MM_IsUser( addr ) )
789 else if( MM_GetPhysAddr( addr ) )
793 if( !MM_GetPhysAddr( addr ) )
806 * \brief Search a string array for \a Needle
807 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
809 int ModUtil_LookupString(char **Array, char *Needle)
812 if( !CheckString(Needle) ) return -1;
813 for( i = 0; Array[i]; i++ )
815 if(strcmp(Array[i], Needle) == 0) return i;
820 int ModUtil_SetIdent(char *Dest, char *Value)
822 if( !CheckMem(Dest, 32) ) return -1;
823 strncpy(Dest, Value, 32);