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
18 int atoi(const char *string);
19 void itoa(char *buf, Uint64 num, int base, int minLength, char pad);
20 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args);
21 int sprintf(char *__s, const char *__format, ...);
25 int strucmp(const char *Str1, const char *Str2);
26 char *strchr(const char *__s, int __c);
27 int strpos(const char *Str, char Ch);
28 Uint8 ByteSum(void *Ptr, int Size);
29 size_t strlen(const char *__s);
30 char *strcpy(char *__str1, const char *__str2);
31 char *strncpy(char *__str1, const char *__str2, size_t max);
32 int strcmp(const char *str1, const char *str2);
33 int strncmp(const char *str1, const char *str2, size_t num);
34 char *_strdup(const char *File, int Line, const char *Str);
35 char **str_split(const char *__str, char __ch);
36 int strpos8(const char *str, Uint32 Search);
37 int ReadUTF8(Uint8 *str, Uint32 *Val);
38 int WriteUTF8(Uint8 *str, Uint32 Val);
39 int DivUp(int num, int dem);
40 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year);
43 int CheckString(char *String);
44 int CheckMem(void *Mem, int NumBytes);
46 int ModUtil_LookupString(char **Array, char *Needle);
47 int ModUtil_SetIdent(char *Dest, char *Value);
49 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString);
68 EXPORT(_strdup); // Takes File/Line too
77 EXPORT(ModUtil_LookupString);
78 EXPORT(ModUtil_SetIdent);
83 * \brief Convert a string into an integer
85 int atoi(const char *string)
90 //Log("atoi: (string='%s')", string);
92 // Clear non-numeric characters
93 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
94 if( *string == '-' ) {
96 while( !('0' <= *string && *string <= '9') ) string++;
108 if('0' <= *string && *string <= '9') {
110 ret += *string - '0';
112 else if('A' <= *string && *string <= 'F') {
114 ret += *string - 'A' + 10;
116 else if('a' <= *string && *string <= 'f') {
118 ret += *string - 'a' + 10;
126 for( ; '0' <= *string && *string <= '7'; string ++ )
129 ret += *string - '0';
135 for( ; '0' <= *string && *string <= '9'; string++)
138 ret += *string - '0';
144 //Log("atoi: RETURN %i", ret);
149 static const char cUCDIGITS[] = "0123456789ABCDEF";
151 * \fn void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
152 * \brief Convert an integer into a character string
154 void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
163 if(base > 16 || base < 2) {
169 while(num > base-1) {
170 tmpBuf[pos] = cUCDIGITS[ num % base ];
171 num /= (Uint)base; // Shift `num` right 1 digit
174 tmpBuf[pos++] = cUCDIGITS[ num % base ]; // Last digit of `num`
179 while(minLength-- > 0) buf[i++] = pad;
180 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
185 * \brief Append a character the the vsnprintf output
187 #define PUTCH(c) do{\
189 if(pos==__maxlen){return pos;}\
190 if(__s){__s[pos++]=ch;}else{pos++;}\
192 #define GETVAL() do {\
193 if(isLongLong) val = va_arg(args, Uint64);\
194 else val = va_arg(args, unsigned int);\
197 * \brief VArg String Number Print Formatted
199 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
202 int minSize = 0, precision = -1, len;
203 char tmpBuf[34]; // For Integers
204 const char *p = NULL;
211 //Log("vsnprintf: (__s=%p, __maxlen=%i, __format='%s', ...)", __s, __maxlen, __format);
213 while((c = *__format++) != 0)
215 // Non control character
216 if(c != '%') { PUTCH(c); continue; }
219 //Log("pos = %i", pos);
222 if(c == '%') { PUTCH('%'); continue; }
224 // Pointer - Done first for debugging
226 Uint ptr = va_arg(args, Uint);
227 PUTCH('*'); PUTCH('0'); PUTCH('x');
228 itoa(tmpBuf, ptr, 16, BITS/4, '0');
233 // - Padding Side Flag
248 if(c == '*') { // Dynamic length
249 minSize = va_arg(args, unsigned int);
252 else if('1' <= c && c <= '9')
255 while('0' <= c && c <= '9')
270 if(c == '*') { // Dynamic length
271 precision = va_arg(args, unsigned int);
274 else if('1' <= c && c <= '9')
277 while('0' <= c && c <= '9')
280 precision += c - '0';
286 // - Default, Long or LongLong?
288 if(c == 'l') // Long is actually the default on x86
297 // - Now get the format code
304 if( isLongLong && val >> 63 ) {
308 else if( !isLongLong && val >> 31 ) {
312 itoa(tmpBuf, val, 10, minSize, pad);
316 itoa(tmpBuf, val, 10, minSize, pad);
320 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
322 itoa(tmpBuf, val, 16, minSize, pad);
327 itoa(tmpBuf, val, 16, minSize, pad);
331 itoa(tmpBuf, val, 8, minSize, pad);
335 itoa(tmpBuf, val, 2, minSize, pad);
339 val = va_arg(args, unsigned int);
344 // String - Null Terminated Array
346 p = va_arg(args, char*); // Get Argument
347 if( !CheckString(p) ) p = "(inval)"; // Avoid #PFs
351 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
352 while(*p && precision--) PUTCH(*p++);
353 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
356 case 'C': // Non-Null Terminated Character Array
357 p = va_arg(args, char*);
358 if( !CheckMem(p, minSize) ) continue; // No #PFs please
359 if(!p) goto printString;
360 while(minSize--) PUTCH(*p++);
372 if(__s && pos != __maxlen)
381 int sprintf(char *__s, const char *__format, ...)
386 va_start(args, __format);
387 ret = vsnprintf(__s, -1, __format, args);
394 * \fn int tolower(int c)
395 * \brief Converts a character to lower case
399 if('A' <= c && c <= 'Z')
400 return c - 'A' + 'a';
405 * \fn int strucmp(const char *Str1, const char *Str2)
406 * \brief Compare \a Str1 and \a Str2 case-insensitively
408 int strucmp(const char *Str1, const char *Str2)
410 while(*Str1 && tolower(*Str1) == tolower(*Str2))
412 return tolower(*Str1) - tolower(*Str2);
416 * \brief Locate a byte in a string
418 char *strchr(const char *__s, int __c)
420 for( ; *__s; __s ++ )
422 if( *__s == __c ) return (char*)__s;
428 * \fn int strpos(const char *Str, char Ch)
429 * \brief Search a string for an ascii character
431 int strpos(const char *Str, char Ch)
434 for(pos=0;Str[pos];pos++)
436 if(Str[pos] == Ch) return pos;
442 * \fn Uint8 ByteSum(void *Ptr, int Size)
443 * \brief Adds the bytes in a memory region and returns the sum
445 Uint8 ByteSum(const void *Ptr, int Size)
448 const Uint8 *data = Ptr;
449 while(Size--) sum += *(data++);
454 * \fn size_t strlen(const char *__str)
455 * \brief Get the length of string
457 size_t strlen(const char *__str)
460 while(*__str++) ret++;
465 * \fn char *strcpy(char *__str1, const char *__str2)
466 * \brief Copy a string to a new location
468 char *strcpy(char *__str1, const char *__str2)
471 *__str1++ = *__str2++;
472 *__str1 = '\0'; // Terminate String
477 * \fn char *strncpy(char *__str1, const char *__str2, size_t max)
478 * \brief Copy a string to a new location
480 char *strncpy(char *__str1, const char *__str2, size_t max)
482 while(*__str2 && max-- >= 1)
483 *__str1++ = *__str2++;
485 *__str1 = '\0'; // Terminate String
490 * \fn int strcmp(const char *str1, const char *str2)
491 * \brief Compare two strings return the difference between
492 * the first non-matching characters.
494 int strcmp(const char *str1, const char *str2)
496 while(*str1 && *str1 == *str2)
498 return *str1 - *str2;
502 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
503 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
505 int strncmp(const char *Str1, const char *Str2, size_t num)
507 if(num == 0) return 0; // TODO: Check what should officially happen here
508 while(--num && *Str1 && *Str1 == *Str2)
515 * \fn char *strdup(const char *Str)
516 * \brief Duplicates a string
518 char *strdup(const char *Str)
521 ret = malloc(strlen(Str)+1);
522 if( !ret ) return NULL;
529 * \fn char *_strdup(const char *File, int Line, const char *Str)
530 * \brief Duplicates a string
532 char *_strdup(const char *File, int Line, const char *Str)
535 ret = Heap_Allocate(File, Line, strlen(Str)+1);
536 if( !ret ) return NULL;
543 * \brief Split a string using the passed character
544 * \return NULL terminated array of strings on the heap
545 * \param __str String to split
546 * \param __ch Character to split by
548 char **str_split(const char *__str, char __ch)
555 for( i = 0; __str[i]; i++ )
561 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
562 if( !ret ) return NULL;
565 start = (char *)&ret[len+1];
567 for( i = 0; __str[i]; i++ )
569 if(__str[i] == __ch) {
584 * \fn int DivUp(int num, int dem)
585 * \brief Divide two numbers, rounding up
586 * \param num Numerator
587 * \param dem Denominator
589 int DivUp(int num, int dem)
591 return (num+dem-1)/dem;
595 * \fn int strpos8(const char *str, Uint32 search)
596 * \brief Search a string for a UTF-8 character
598 int strpos8(const char *str, Uint32 Search)
602 for(pos=0;str[pos];pos++)
606 if(str[pos] == Search) return pos;
609 if(*(Uint8*)(str+pos) < 128) continue;
611 pos += ReadUTF8( (Uint8*)&str[pos], &val );
612 if(val == Search) return pos;
618 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
619 * \brief Read a UTF-8 character from a string
621 int ReadUTF8(const Uint8 *str, Uint32 *Val)
623 *Val = 0xFFFD; // Assume invalid character
626 if( !(*str & 0x80) ) {
631 // Middle of a sequence
632 if( (*str & 0xC0) == 0x80 ) {
637 if( (*str & 0xE0) == 0xC0 ) {
638 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
640 if( (*str & 0xC0) != 0x80) return -1; // Validity check
641 *Val |= (*str & 0x3F); // Lower 6 Bits
646 if( (*str & 0xF0) == 0xE0 ) {
647 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
649 if( (*str & 0xC0) != 0x80) return -1; // Validity check
650 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
652 if( (*str & 0xC0) != 0x80) return -1; // Validity check
653 *Val |= (*str & 0x3F); // Lower 6 Bits
658 if( (*str & 0xF1) == 0xF0 ) {
659 *Val = (*str & 0x07) << 18; // Upper 3 Bits
661 if( (*str & 0xC0) != 0x80) return -1; // Validity check
662 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
664 if( (*str & 0xC0) != 0x80) return -1; // Validity check
665 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
667 if( (*str & 0xC0) != 0x80) return -1; // Validity check
668 *Val |= (*str & 0x3F); // Lower 6 Bits
672 // UTF-8 Doesn't support more than four bytes
677 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
678 * \brief Write a UTF-8 character sequence to a string
680 int WriteUTF8(Uint8 *str, Uint32 Val)
690 *str = 0xC0 | (Val >> 6);
692 *str = 0x80 | (Val & 0x3F);
697 if( Val < 0x10000 ) {
698 *str = 0xE0 | (Val >> 12);
700 *str = 0x80 | ((Val >> 6) & 0x3F);
702 *str = 0x80 | (Val & 0x3F);
707 if( Val < 0x110000 ) {
708 *str = 0xF0 | (Val >> 18);
710 *str = 0x80 | ((Val >> 12) & 0x3F);
712 *str = 0x80 | ((Val >> 6) & 0x3F);
714 *str = 0x80 | (Val & 0x3F);
718 // UTF-8 Doesn't support more than four bytes
723 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
724 * \brief Converts a date into an Acess Timestamp
726 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
733 stamp += day*3600*24;
734 stamp += month*DAYS_BEFORE[month]*3600*24;
736 ((year&3) == 0 || year%100 != 0)
737 || (year%100 == 0 && ((year/100)&3) == 0)
738 ) && month > 1) // Leap year and after feb
741 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
742 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
750 * \brief Pseudo random number generator
755 static Uint state = RANDOM_SEED;
757 // Get the next state value
758 giRandomState = (RANDOM_A*state + RANDOM_C);
759 // Check if it has changed, and if it hasn't, change it
760 if(state == old) state += RANDOM_SPRUCE;
763 // http://en.wikipedia.org/wiki/Xorshift
765 static Uint32 x = 123456789;
766 static Uint32 y = 362436069;
767 static Uint32 z = 521288629;
768 static Uint32 w = 88675123;
773 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
778 * \name Memory Validation
782 * \brief Checks if a string resides fully in valid memory
784 int CheckString(const char *String)
786 if( !MM_GetPhysAddr( (tVAddr)String ) )
790 if( MM_IsUser( (tVAddr)String ) )
795 if( !MM_IsUser( (tVAddr)String ) )
797 // Increment string pointer
802 else if( MM_GetPhysAddr( (tVAddr)String ) )
807 if( !MM_GetPhysAddr( (tVAddr)String ) )
809 // Increment string pointer
818 * \brief Check if a sized memory region is valid memory
820 int CheckMem(const void *Mem, int NumBytes)
822 tVAddr addr = (tVAddr)Mem;
824 if( MM_IsUser( addr ) )
828 if( !MM_IsUser( addr ) )
834 else if( MM_GetPhysAddr( addr ) )
838 if( !MM_GetPhysAddr( addr ) )
851 * \brief Search a string array for \a Needle
852 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
854 int ModUtil_LookupString(const char **Array, const char *Needle)
857 if( !CheckString(Needle) ) return -1;
858 for( i = 0; Array[i]; i++ )
860 if(strcmp(Array[i], Needle) == 0) return i;
865 int ModUtil_SetIdent(char *Dest, const char *Value)
867 if( !CheckMem(Dest, 32) ) return -1;
868 strncpy(Dest, Value, 32);
873 * \brief Convert a string of hexadecimal digits into a byte stream
875 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
879 for( i = 0; i < DestSize*2; i += 2 )
883 if(SourceString[i] == '\0') break;
885 if('0' <= SourceString[i] && SourceString[i] <= '9')
886 val |= (SourceString[i]-'0') << 4;
887 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
888 val |= (SourceString[i]-'A'+10) << 4;
889 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
890 val |= (SourceString[i]-'a'+10) << 4;
892 if(SourceString[i+1] == '\0') break;
894 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
895 val |= (SourceString[i+1] - '0');
896 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
897 val |= (SourceString[i+1] - 'A' + 10);
898 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
899 val |= (SourceString[i+1] - 'a' + 10);