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, 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')
265 // - Default, Long or LongLong?
267 if(c == 'l') // Long is actually the default on x86
276 // - Now get the format code
283 if( isLongLong && val >> 63 ) {
287 else if( !isLongLong && val >> 31 ) {
291 itoa(tmpBuf, val, 10, minSize, pad);
295 itoa(tmpBuf, val, 10, minSize, pad);
299 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
301 itoa(tmpBuf, val, 16, minSize, pad);
306 itoa(tmpBuf, val, 16, minSize, pad);
310 itoa(tmpBuf, val, 8, minSize, pad);
314 itoa(tmpBuf, val, 2, minSize, pad);
318 val = va_arg(args, unsigned int);
323 // String - Null Terminated Array
325 p = va_arg(args, char*); // Get Argument
326 if( !CheckString(p) ) continue; // Avoid #PFs
330 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
331 while(*p) PUTCH(*p++);
332 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
335 case 'C': // Non-Null Terminated Character Array
336 p = va_arg(args, char*);
337 if( !CheckMem(p, minSize) ) continue; // No #PFs please
338 if(!p) goto printString;
339 while(minSize--) PUTCH(*p++);
351 if(__s && pos != __maxlen)
360 int sprintf(char *__s, const char *__format, ...)
365 va_start(args, __format);
366 ret = vsnprintf(__s, -1, __format, args);
373 * \fn int tolower(int c)
374 * \brief Converts a character to lower case
378 if('A' <= c && c <= 'Z')
379 return c - 'A' + 'a';
384 * \fn int strucmp(const char *Str1, const char *Str2)
385 * \brief Compare \a Str1 and \a Str2 case-insensitively
387 int strucmp(const char *Str1, const char *Str2)
389 while(*Str1 && tolower(*Str1) == tolower(*Str2))
391 return tolower(*Str1) - tolower(*Str2);
395 * \brief Locate a byte in a string
397 char *strchr(const char *__s, int __c)
399 for( ; *__s; __s ++ )
401 if( *__s == __c ) return (char*)__s;
407 * \fn int strpos(const char *Str, char Ch)
408 * \brief Search a string for an ascii character
410 int strpos(const char *Str, char Ch)
413 for(pos=0;Str[pos];pos++)
415 if(Str[pos] == Ch) return pos;
421 * \fn Uint8 ByteSum(void *Ptr, int Size)
422 * \brief Adds the bytes in a memory region and returns the sum
424 Uint8 ByteSum(const void *Ptr, int Size)
427 const Uint8 *data = Ptr;
428 while(Size--) sum += *(data++);
433 * \fn size_t strlen(const char *__str)
434 * \brief Get the length of string
436 size_t strlen(const char *__str)
439 while(*__str++) ret++;
444 * \fn char *strcpy(char *__str1, const char *__str2)
445 * \brief Copy a string to a new location
447 char *strcpy(char *__str1, const char *__str2)
450 *__str1++ = *__str2++;
451 *__str1 = '\0'; // Terminate String
456 * \fn char *strncpy(char *__str1, const char *__str2, size_t max)
457 * \brief Copy a string to a new location
459 char *strncpy(char *__str1, const char *__str2, size_t max)
461 while(*__str2 && max-- >= 1)
462 *__str1++ = *__str2++;
464 *__str1 = '\0'; // Terminate String
469 * \fn int strcmp(const char *str1, const char *str2)
470 * \brief Compare two strings return the difference between
471 * the first non-matching characters.
473 int strcmp(const char *str1, const char *str2)
475 while(*str1 && *str1 == *str2)
477 return *str1 - *str2;
481 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
482 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
484 int strncmp(const char *Str1, const char *Str2, size_t num)
486 if(num == 0) return 0; // TODO: Check what should officially happen here
487 while(--num && *Str1 && *Str1 == *Str2)
494 * \fn char *strdup(const char *Str)
495 * \brief Duplicates a string
497 char *strdup(const char *Str)
500 ret = malloc(strlen(Str)+1);
501 if( !ret ) return NULL;
508 * \fn char *_strdup(const char *File, int Line, const char *Str)
509 * \brief Duplicates a string
511 char *_strdup(const char *File, int Line, const char *Str)
514 ret = Heap_Allocate(File, Line, strlen(Str)+1);
515 if( !ret ) return NULL;
522 * \brief Split a string using the passed character
523 * \return NULL terminated array of strings on the heap
524 * \param __str String to split
525 * \param __ch Character to split by
527 char **str_split(const char *__str, char __ch)
534 for( i = 0; __str[i]; i++ )
540 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
541 if( !ret ) return NULL;
544 start = (char *)&ret[len+1];
546 for( i = 0; __str[i]; i++ )
548 if(__str[i] == __ch) {
563 * \fn int DivUp(int num, int dem)
564 * \brief Divide two numbers, rounding up
565 * \param num Numerator
566 * \param dem Denominator
568 int DivUp(int num, int dem)
570 return (num+dem-1)/dem;
574 * \fn int strpos8(const char *str, Uint32 search)
575 * \brief Search a string for a UTF-8 character
577 int strpos8(const char *str, Uint32 Search)
581 for(pos=0;str[pos];pos++)
585 if(str[pos] == Search) return pos;
588 if(*(Uint8*)(str+pos) < 128) continue;
590 pos += ReadUTF8( (Uint8*)&str[pos], &val );
591 if(val == Search) return pos;
597 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
598 * \brief Read a UTF-8 character from a string
600 int ReadUTF8(const Uint8 *str, Uint32 *Val)
602 *Val = 0xFFFD; // Assume invalid character
605 if( !(*str & 0x80) ) {
610 // Middle of a sequence
611 if( (*str & 0xC0) == 0x80 ) {
616 if( (*str & 0xE0) == 0xC0 ) {
617 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
619 if( (*str & 0xC0) != 0x80) return -1; // Validity check
620 *Val |= (*str & 0x3F); // Lower 6 Bits
625 if( (*str & 0xF0) == 0xE0 ) {
626 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
628 if( (*str & 0xC0) != 0x80) return -1; // Validity check
629 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
631 if( (*str & 0xC0) != 0x80) return -1; // Validity check
632 *Val |= (*str & 0x3F); // Lower 6 Bits
637 if( (*str & 0xF1) == 0xF0 ) {
638 *Val = (*str & 0x07) << 18; // Upper 3 Bits
640 if( (*str & 0xC0) != 0x80) return -1; // Validity check
641 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
643 if( (*str & 0xC0) != 0x80) return -1; // Validity check
644 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
646 if( (*str & 0xC0) != 0x80) return -1; // Validity check
647 *Val |= (*str & 0x3F); // Lower 6 Bits
651 // UTF-8 Doesn't support more than four bytes
656 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
657 * \brief Write a UTF-8 character sequence to a string
659 int WriteUTF8(Uint8 *str, Uint32 Val)
669 *str = 0xC0 | (Val >> 6);
671 *str = 0x80 | (Val & 0x3F);
676 if( Val < 0x10000 ) {
677 *str = 0xE0 | (Val >> 12);
679 *str = 0x80 | ((Val >> 6) & 0x3F);
681 *str = 0x80 | (Val & 0x3F);
686 if( Val < 0x110000 ) {
687 *str = 0xF0 | (Val >> 18);
689 *str = 0x80 | ((Val >> 12) & 0x3F);
691 *str = 0x80 | ((Val >> 6) & 0x3F);
693 *str = 0x80 | (Val & 0x3F);
697 // UTF-8 Doesn't support more than four bytes
702 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
703 * \brief Converts a date into an Acess Timestamp
705 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
712 stamp += day*3600*24;
713 stamp += month*DAYS_BEFORE[month]*3600*24;
715 ((year&3) == 0 || year%100 != 0)
716 || (year%100 == 0 && ((year/100)&3) == 0)
717 ) && month > 1) // Leap year and after feb
720 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
721 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
729 * \brief Pseudo random number generator
734 static Uint state = RANDOM_SEED;
736 // Get the next state value
737 giRandomState = (RANDOM_A*state + RANDOM_C);
738 // Check if it has changed, and if it hasn't, change it
739 if(state == old) state += RANDOM_SPRUCE;
742 // http://en.wikipedia.org/wiki/Xorshift
744 static Uint32 x = 123456789;
745 static Uint32 y = 362436069;
746 static Uint32 z = 521288629;
747 static Uint32 w = 88675123;
752 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
757 * \name Memory Validation
761 * \brief Checks if a string resides fully in valid memory
763 int CheckString(const char *String)
765 if( !MM_GetPhysAddr( (tVAddr)String ) )
769 if( MM_IsUser( (tVAddr)String ) )
774 if( !MM_IsUser( (tVAddr)String ) )
776 // Increment string pointer
781 else if( MM_GetPhysAddr( (tVAddr)String ) )
786 if( !MM_GetPhysAddr( (tVAddr)String ) )
788 // Increment string pointer
797 * \brief Check if a sized memory region is valid memory
799 int CheckMem(const void *Mem, int NumBytes)
801 tVAddr addr = (tVAddr)Mem;
803 if( MM_IsUser( addr ) )
807 if( !MM_IsUser( addr ) )
813 else if( MM_GetPhysAddr( addr ) )
817 if( !MM_GetPhysAddr( addr ) )
830 * \brief Search a string array for \a Needle
831 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
833 int ModUtil_LookupString(const char **Array, const char *Needle)
836 if( !CheckString(Needle) ) return -1;
837 for( i = 0; Array[i]; i++ )
839 if(strcmp(Array[i], Needle) == 0) return i;
844 int ModUtil_SetIdent(char *Dest, const char *Value)
846 if( !CheckMem(Dest, 32) ) return -1;
847 strncpy(Dest, Value, 32);
852 * \brief Convert a string of hexadecimal digits into a byte stream
854 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
858 for( i = 0; i < DestSize*2; i += 2 )
862 if(SourceString[i] == '\0') break;
864 if('0' <= SourceString[i] && SourceString[i] <= '9')
865 val |= (SourceString[i]-'0') << 4;
866 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
867 val |= (SourceString[i]-'A'+10) << 4;
868 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
869 val |= (SourceString[i]-'a'+10) << 4;
871 if(SourceString[i+1] == '\0') break;
873 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
874 val |= (SourceString[i+1] - '0');
875 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
876 val |= (SourceString[i+1] - 'A' + 10);
877 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
878 val |= (SourceString[i+1] - 'a' + 10);