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);
85 * \brief Convert a string into an integer
87 int atoi(const char *string)
92 //Log("atoi: (string='%s')", string);
94 // Clear non-numeric characters
95 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
96 if( *string == '-' ) {
98 while( !('0' <= *string && *string <= '9') ) string++;
110 if('0' <= *string && *string <= '9') {
112 ret += *string - '0';
114 else if('A' <= *string && *string <= 'F') {
116 ret += *string - 'A' + 10;
118 else if('a' <= *string && *string <= 'f') {
120 ret += *string - 'a' + 10;
128 for( ; '0' <= *string && *string <= '7'; string ++ )
131 ret += *string - '0';
137 for( ; '0' <= *string && *string <= '9'; string++)
140 ret += *string - '0';
146 //Log("atoi: RETURN %i", ret);
151 static const char cUCDIGITS[] = "0123456789ABCDEF";
153 * \fn void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
154 * \brief Convert an integer into a character string
156 void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
165 if(base > 16 || base < 2) {
171 while(num > base-1) {
172 tmpBuf[pos] = cUCDIGITS[ num % base ];
173 num /= (Uint)base; // Shift `num` right 1 digit
176 tmpBuf[pos++] = cUCDIGITS[ num % base ]; // Last digit of `num`
181 while(minLength-- > 0) buf[i++] = pad;
182 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
187 * \brief Append a character the the vsnprintf output
189 #define PUTCH(c) do{\
191 if(pos==__maxlen){return pos;}\
192 if(__s){__s[pos++]=ch;}else{pos++;}\
194 #define GETVAL() do {\
195 if(isLongLong) val = va_arg(args, Uint64);\
196 else val = va_arg(args, unsigned int);\
199 * \brief VArg String Number Print Formatted
201 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
204 int minSize = 0, precision = -1, len;
205 char tmpBuf[34]; // For Integers
206 const char *p = NULL;
213 //Log("vsnprintf: (__s=%p, __maxlen=%i, __format='%s', ...)", __s, __maxlen, __format);
215 while((c = *__format++) != 0)
217 // Non control character
218 if(c != '%') { PUTCH(c); continue; }
221 //Log("pos = %i", pos);
224 if(c == '%') { PUTCH('%'); continue; }
226 // Pointer - Done first for debugging
228 Uint ptr = va_arg(args, Uint);
229 PUTCH('*'); PUTCH('0'); PUTCH('x');
230 itoa(tmpBuf, ptr, 16, BITS/4, '0');
235 // - Padding Side Flag
250 if(c == '*') { // Dynamic length
251 minSize = va_arg(args, unsigned int);
254 else if('1' <= c && c <= '9')
257 while('0' <= c && c <= '9')
272 if(c == '*') { // Dynamic length
273 precision = va_arg(args, unsigned int);
276 else if('1' <= c && c <= '9')
279 while('0' <= c && c <= '9')
282 precision += c - '0';
288 // - Default, Long or LongLong?
290 if(c == 'l') // Long is actually the default on x86
299 // - Now get the format code
306 if( isLongLong && val >> 63 ) {
310 else if( !isLongLong && val >> 31 ) {
314 itoa(tmpBuf, val, 10, minSize, pad);
318 itoa(tmpBuf, val, 10, minSize, pad);
322 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
324 itoa(tmpBuf, val, 16, minSize, pad);
329 itoa(tmpBuf, val, 16, minSize, pad);
333 itoa(tmpBuf, val, 8, minSize, pad);
337 itoa(tmpBuf, val, 2, minSize, pad);
341 val = va_arg(args, unsigned int);
346 // String - Null Terminated Array
348 p = va_arg(args, char*); // Get Argument
349 if( !CheckString(p) ) p = "(inval)"; // Avoid #PFs
353 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
354 while(*p && precision--) PUTCH(*p++);
355 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
358 case 'C': // Non-Null Terminated Character Array
359 p = va_arg(args, char*);
360 if( !CheckMem(p, minSize) ) continue; // No #PFs please
361 if(!p) goto printString;
362 while(minSize--) PUTCH(*p++);
374 if(__s && pos != __maxlen)
383 int sprintf(char *__s, const char *__format, ...)
388 va_start(args, __format);
389 ret = vsnprintf(__s, -1, __format, args);
396 * \fn int tolower(int c)
397 * \brief Converts a character to lower case
401 if('A' <= c && c <= 'Z')
402 return c - 'A' + 'a';
407 * \fn int strucmp(const char *Str1, const char *Str2)
408 * \brief Compare \a Str1 and \a Str2 case-insensitively
410 int strucmp(const char *Str1, const char *Str2)
412 while(*Str1 && tolower(*Str1) == tolower(*Str2))
414 return tolower(*Str1) - tolower(*Str2);
418 * \brief Locate a byte in a string
420 char *strchr(const char *__s, int __c)
422 for( ; *__s; __s ++ )
424 if( *__s == __c ) return (char*)__s;
430 * \fn int strpos(const char *Str, char Ch)
431 * \brief Search a string for an ascii character
433 int strpos(const char *Str, char Ch)
436 for(pos=0;Str[pos];pos++)
438 if(Str[pos] == Ch) return pos;
444 * \fn Uint8 ByteSum(void *Ptr, int Size)
445 * \brief Adds the bytes in a memory region and returns the sum
447 Uint8 ByteSum(const void *Ptr, int Size)
450 const Uint8 *data = Ptr;
451 while(Size--) sum += *(data++);
456 * \fn size_t strlen(const char *__str)
457 * \brief Get the length of string
459 size_t strlen(const char *__str)
462 while(*__str++) ret++;
467 * \fn char *strcpy(char *__str1, const char *__str2)
468 * \brief Copy a string to a new location
470 char *strcpy(char *__str1, const char *__str2)
473 *__str1++ = *__str2++;
474 *__str1 = '\0'; // Terminate String
479 * \fn char *strncpy(char *__str1, const char *__str2, size_t max)
480 * \brief Copy a string to a new location
482 char *strncpy(char *__str1, const char *__str2, size_t max)
484 while(*__str2 && max-- >= 1)
485 *__str1++ = *__str2++;
487 *__str1 = '\0'; // Terminate String
492 * \fn int strcmp(const char *str1, const char *str2)
493 * \brief Compare two strings return the difference between
494 * the first non-matching characters.
496 int strcmp(const char *str1, const char *str2)
498 while(*str1 && *str1 == *str2)
500 return *str1 - *str2;
504 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
505 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
507 int strncmp(const char *Str1, const char *Str2, size_t num)
509 if(num == 0) return 0; // TODO: Check what should officially happen here
510 while(--num && *Str1 && *Str1 == *Str2)
517 * \fn char *strdup(const char *Str)
518 * \brief Duplicates a string
520 char *strdup(const char *Str)
523 ret = malloc(strlen(Str)+1);
524 if( !ret ) return NULL;
531 * \fn char *_strdup(const char *File, int Line, const char *Str)
532 * \brief Duplicates a string
534 char *_strdup(const char *File, int Line, const char *Str)
537 ret = Heap_Allocate(File, Line, strlen(Str)+1);
538 if( !ret ) return NULL;
545 * \brief Split a string using the passed character
546 * \return NULL terminated array of strings on the heap
547 * \param __str String to split
548 * \param __ch Character to split by
550 char **str_split(const char *__str, char __ch)
557 for( i = 0; __str[i]; i++ )
563 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
564 if( !ret ) return NULL;
567 start = (char *)&ret[len+1];
569 for( i = 0; __str[i]; i++ )
571 if(__str[i] == __ch) {
586 * \fn int DivUp(int num, int dem)
587 * \brief Divide two numbers, rounding up
588 * \param num Numerator
589 * \param dem Denominator
591 int DivUp(int num, int dem)
593 return (num+dem-1)/dem;
597 * \fn int strpos8(const char *str, Uint32 search)
598 * \brief Search a string for a UTF-8 character
600 int strpos8(const char *str, Uint32 Search)
604 for(pos=0;str[pos];pos++)
608 if(str[pos] == Search) return pos;
611 if(*(Uint8*)(str+pos) < 128) continue;
613 pos += ReadUTF8( (Uint8*)&str[pos], &val );
614 if(val == Search) return pos;
620 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
621 * \brief Read a UTF-8 character from a string
623 int ReadUTF8(const Uint8 *str, Uint32 *Val)
625 *Val = 0xFFFD; // Assume invalid character
628 if( !(*str & 0x80) ) {
633 // Middle of a sequence
634 if( (*str & 0xC0) == 0x80 ) {
639 if( (*str & 0xE0) == 0xC0 ) {
640 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
642 if( (*str & 0xC0) != 0x80) return -1; // Validity check
643 *Val |= (*str & 0x3F); // Lower 6 Bits
648 if( (*str & 0xF0) == 0xE0 ) {
649 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
651 if( (*str & 0xC0) != 0x80) return -1; // Validity check
652 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
654 if( (*str & 0xC0) != 0x80) return -1; // Validity check
655 *Val |= (*str & 0x3F); // Lower 6 Bits
660 if( (*str & 0xF1) == 0xF0 ) {
661 *Val = (*str & 0x07) << 18; // Upper 3 Bits
663 if( (*str & 0xC0) != 0x80) return -1; // Validity check
664 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
666 if( (*str & 0xC0) != 0x80) return -1; // Validity check
667 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
669 if( (*str & 0xC0) != 0x80) return -1; // Validity check
670 *Val |= (*str & 0x3F); // Lower 6 Bits
674 // UTF-8 Doesn't support more than four bytes
679 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
680 * \brief Write a UTF-8 character sequence to a string
682 int WriteUTF8(Uint8 *str, Uint32 Val)
692 *str = 0xC0 | (Val >> 6);
694 *str = 0x80 | (Val & 0x3F);
699 if( Val < 0x10000 ) {
700 *str = 0xE0 | (Val >> 12);
702 *str = 0x80 | ((Val >> 6) & 0x3F);
704 *str = 0x80 | (Val & 0x3F);
709 if( Val < 0x110000 ) {
710 *str = 0xF0 | (Val >> 18);
712 *str = 0x80 | ((Val >> 12) & 0x3F);
714 *str = 0x80 | ((Val >> 6) & 0x3F);
716 *str = 0x80 | (Val & 0x3F);
720 // UTF-8 Doesn't support more than four bytes
725 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
726 * \brief Converts a date into an Acess Timestamp
728 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
735 stamp += day*3600*24;
736 stamp += month*DAYS_BEFORE[month]*3600*24;
738 ((year&3) == 0 || year%100 != 0)
739 || (year%100 == 0 && ((year/100)&3) == 0)
740 ) && month > 1) // Leap year and after feb
743 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
744 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
752 * \brief Pseudo random number generator
757 static Uint state = RANDOM_SEED;
759 // Get the next state value
760 giRandomState = (RANDOM_A*state + RANDOM_C);
761 // Check if it has changed, and if it hasn't, change it
762 if(state == old) state += RANDOM_SPRUCE;
765 // http://en.wikipedia.org/wiki/Xorshift
767 static Uint32 x = 123456789;
768 static Uint32 y = 362436069;
769 static Uint32 z = 521288629;
770 static Uint32 w = 88675123;
775 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
780 * \name Memory Validation
784 * \brief Checks if a string resides fully in valid memory
786 int CheckString(const char *String)
788 if( !MM_GetPhysAddr( (tVAddr)String ) )
792 if( MM_IsUser( (tVAddr)String ) )
797 if( !MM_IsUser( (tVAddr)String ) )
799 // Increment string pointer
804 else if( MM_GetPhysAddr( (tVAddr)String ) )
809 if( !MM_GetPhysAddr( (tVAddr)String ) )
811 // Increment string pointer
820 * \brief Check if a sized memory region is valid memory
822 int CheckMem(const void *Mem, int NumBytes)
824 tVAddr addr = (tVAddr)Mem;
826 if( MM_IsUser( addr ) )
830 if( !MM_IsUser( addr ) )
836 else if( MM_GetPhysAddr( addr ) )
840 if( !MM_GetPhysAddr( addr ) )
853 * \brief Search a string array for \a Needle
854 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
856 int ModUtil_LookupString(const char **Array, const char *Needle)
859 if( !CheckString(Needle) ) return -1;
860 for( i = 0; Array[i]; i++ )
862 if(strcmp(Array[i], Needle) == 0) return i;
867 int ModUtil_SetIdent(char *Dest, const char *Value)
869 if( !CheckMem(Dest, 32) ) return -1;
870 strncpy(Dest, Value, 32);
875 * \brief Convert a string of hexadecimal digits into a byte stream
877 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
881 for( i = 0; i < DestSize*2; i += 2 )
885 if(SourceString[i] == '\0') break;
887 if('0' <= SourceString[i] && SourceString[i] <= '9')
888 val |= (SourceString[i]-'0') << 4;
889 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
890 val |= (SourceString[i]-'A'+10) << 4;
891 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
892 val |= (SourceString[i]-'a'+10) << 4;
894 if(SourceString[i+1] == '\0') break;
896 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
897 val |= (SourceString[i+1] - '0');
898 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
899 val |= (SourceString[i+1] - 'A' + 10);
900 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
901 val |= (SourceString[i+1] - 'a' + 10);
908 Uint16 SwapEndian16(Uint16 Val)
910 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
912 Uint32 SwapEndian32(Uint32 Val)
914 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);