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 char *strchr(const char *__s, int __c);
24 int strpos(const char *Str, char Ch);
25 Uint8 ByteSum(void *Ptr, int Size);
26 size_t strlen(const char *__s);
27 char *strcpy(char *__str1, const char *__str2);
28 char *strncpy(char *__str1, const char *__str2, size_t max);
29 int strcmp(const char *str1, const char *str2);
30 int strncmp(const char *str1, const char *str2, size_t num);
31 char *_strdup(const char *File, int Line, const char *Str);
32 char **str_split(const char *__str, char __ch);
33 int strpos8(const char *str, Uint32 Search);
34 int ReadUTF8(Uint8 *str, Uint32 *Val);
35 int WriteUTF8(Uint8 *str, Uint32 Val);
37 int DivUp(int num, int dem);
38 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year);
41 int CheckString(char *String);
42 int CheckMem(void *Mem, int NumBytes);
44 int ModUtil_LookupString(char **Array, char *Needle);
45 int ModUtil_SetIdent(char *Dest, char *Value);
47 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString);
65 EXPORT(_strdup); // Takes File/Line too
74 EXPORT(ModUtil_LookupString);
75 EXPORT(ModUtil_SetIdent);
80 * \brief Convert a string into an integer
82 int atoi(const char *string)
87 //Log("atoi: (string='%s')", string);
89 // Clear non-numeric characters
90 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
91 if( *string == '-' ) {
93 while( !('0' <= *string && *string <= '9') ) string++;
105 if('0' <= *string && *string <= '9') {
107 ret += *string - '0';
109 else if('A' <= *string && *string <= 'F') {
111 ret += *string - 'A' + 10;
113 else if('a' <= *string && *string <= 'f') {
115 ret += *string - 'a' + 10;
123 for( ; '0' <= *string && *string <= '7'; string ++ )
126 ret += *string - '0';
132 for( ; '0' <= *string && *string <= '9'; string++)
135 ret += *string - '0';
141 //Log("atoi: RETURN %i", ret);
146 static const char cUCDIGITS[] = "0123456789ABCDEF";
148 * \fn void itoa(char *buf, Uint num, int base, int minLength, char pad)
149 * \brief Convert an integer into a character string
151 void itoa(char *buf, Uint num, int base, int minLength, char pad)
160 if(base > 16 || base < 2) {
166 while(num > base-1) {
167 tmpBuf[pos] = cUCDIGITS[ num % base ];
168 num /= (Uint)base; // Shift `num` right 1 digit
171 tmpBuf[pos++] = cUCDIGITS[ num % base ]; // Last digit of `num`
176 while(minLength-- > 0) buf[i++] = pad;
177 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
182 * \brief Append a character the the vsnprintf output
184 #define PUTCH(c) do{\
186 if(pos==__maxlen){return pos;}\
187 if(__s){__s[pos++]=ch;}else{pos++;}\
189 #define GETVAL() do {\
190 if(isLongLong) val = va_arg(args, Uint64);\
191 else val = va_arg(args, unsigned int);\
194 * \brief VArg String Number Print Formatted
196 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
199 int minSize = 0, len;
200 char tmpBuf[34]; // For Integers
208 //Log("vsnprintf: (__s=%p, __maxlen=%i, __format='%s', ...)", __s, __maxlen, __format);
210 while((c = *__format++) != 0)
212 // Non control character
213 if(c != '%') { PUTCH(c); continue; }
216 //Log("pos = %i", pos);
219 if(c == '%') { PUTCH('%'); continue; }
221 // Pointer - Done first for debugging
223 Uint ptr = va_arg(args, Uint);
224 PUTCH('*'); PUTCH('0'); PUTCH('x');
226 itoa(p, ptr, 16, BITS/4, '0');
230 // - Padding Side Flag
245 if(c == '*') { // Dynamic length
246 minSize = va_arg(args, unsigned int);
249 else if('1' <= c && c <= '9')
252 while('0' <= c && c <= '9')
262 // - Default, Long or LongLong?
264 if(c == 'l') // Long is actually the default on x86
273 // - Now get the format code
280 if( isLongLong && val >> 63 ) {
284 else if( !isLongLong && val >> 31 ) {
288 itoa(p, val, 10, minSize, pad);
292 itoa(p, val, 10, minSize, pad);
296 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
299 itoa(p, val, 16, minSize, pad);
304 itoa(p, val, 16, minSize, pad);
308 itoa(p, val, 8, minSize, pad);
312 itoa(p, val, 2, minSize, pad);
316 val = va_arg(args, unsigned int);
321 // String - Null Terminated Array
323 p = va_arg(args, char*); // Get Argument
324 if( !CheckString(p) ) continue; // Avoid #PFs
328 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
329 while(*p) PUTCH(*p++);
330 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
333 case 'C': // Non-Null Terminated Character Array
334 p = va_arg(args, char*);
335 if( !CheckMem(p, minSize) ) continue; // No #PFs please
336 if(!p) goto printString;
337 while(minSize--) PUTCH(*p++);
349 if(__s && pos != __maxlen)
358 int sprintf(char *__s, const char *__format, ...)
363 va_start(args, __format);
364 ret = vsnprintf(__s, -1, __format, args);
371 * \fn int tolower(int c)
372 * \brief Converts a character to lower case
376 if('A' <= c && c <= 'Z')
377 return c - 'A' + 'a';
382 * \fn int strucmp(const char *Str1, const char *Str2)
383 * \brief Compare \a Str1 and \a Str2 case-insensitively
385 int strucmp(const char *Str1, const char *Str2)
387 while(*Str1 && tolower(*Str1) == tolower(*Str2))
389 return tolower(*Str1) - tolower(*Str2);
393 * \brief Locate a byte in a string
395 char *strchr(const char *__s, int __c)
397 for( ; *__s; __s ++ )
399 if( *__s == __c ) return (char*)__s;
405 * \fn int strpos(const char *Str, char Ch)
406 * \brief Search a string for an ascii character
408 int strpos(const char *Str, char Ch)
411 for(pos=0;Str[pos];pos++)
413 if(Str[pos] == Ch) return pos;
419 * \fn Uint8 ByteSum(void *Ptr, int Size)
420 * \brief Adds the bytes in a memory region and returns the sum
422 Uint8 ByteSum(void *Ptr, int Size)
425 while(Size--) sum += *(Uint8*)Ptr++;
430 * \fn Uint strlen(const char *__str)
431 * \brief Get the length of string
433 Uint strlen(const char *__str)
436 while(*__str++) ret++;
441 * \fn char *strcpy(char *__str1, const char *__str2)
442 * \brief Copy a string to a new location
444 char *strcpy(char *__str1, const char *__str2)
447 *__str1++ = *__str2++;
448 *__str1 = '\0'; // Terminate String
453 * \fn char *strncpy(char *__str1, const char *__str2, size_t max)
454 * \brief Copy a string to a new location
456 char *strncpy(char *__str1, const char *__str2, size_t max)
458 while(*__str2 && max-- >= 1)
459 *__str1++ = *__str2++;
461 *__str1 = '\0'; // Terminate String
466 * \fn int strcmp(const char *str1, const char *str2)
467 * \brief Compare two strings return the difference between
468 * the first non-matching characters.
470 int strcmp(const char *str1, const char *str2)
472 while(*str1 && *str1 == *str2)
474 return *str1 - *str2;
478 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
479 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
481 int strncmp(const char *Str1, const char *Str2, size_t num)
483 if(num == 0) return 0; // TODO: Check what should officially happen here
484 while(--num && *Str1 && *Str1 == *Str2)
491 * \fn char *strdup(const char *Str)
492 * \brief Duplicates a string
494 char *strdup(const char *Str)
497 ret = malloc(strlen(Str)+1);
498 if( !ret ) return NULL;
505 * \fn char *_strdup(const char *File, int Line, const char *Str)
506 * \brief Duplicates a string
508 char *_strdup(const char *File, int Line, const char *Str)
511 ret = Heap_Allocate(File, Line, strlen(Str)+1);
512 if( !ret ) return NULL;
519 * \brief Split a string using the passed character
520 * \return NULL terminated array of strings on the heap
521 * \param __str String to split
522 * \param __ch Character to split by
524 char **str_split(const char *__str, char __ch)
531 for( i = 0; __str[i]; i++ )
537 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
538 if( !ret ) return NULL;
541 start = (char *)&ret[len+1];
543 for( i = 0; __str[i]; i++ )
545 if(__str[i] == __ch) {
560 * \fn int DivUp(int num, int dem)
561 * \brief Divide two numbers, rounding up
562 * \param num Numerator
563 * \param dem Denominator
565 int DivUp(int num, int dem)
567 return (num+dem-1)/dem;
571 * \fn int strpos8(const char *str, Uint32 search)
572 * \brief Search a string for a UTF-8 character
574 int strpos8(const char *str, Uint32 Search)
578 for(pos=0;str[pos];pos++)
582 if(str[pos] == Search) return pos;
585 if(*(Uint8*)(str+pos) < 128) continue;
587 pos += ReadUTF8( (Uint8*)&str[pos], &val );
588 if(val == Search) return pos;
594 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
595 * \brief Read a UTF-8 character from a string
597 int ReadUTF8(Uint8 *str, Uint32 *Val)
599 *Val = 0xFFFD; // Assume invalid character
602 if( !(*str & 0x80) ) {
607 // Middle of a sequence
608 if( (*str & 0xC0) == 0x80 ) {
613 if( (*str & 0xE0) == 0xC0 ) {
614 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
616 if( (*str & 0xC0) != 0x80) return -1; // Validity check
617 *Val |= (*str & 0x3F); // Lower 6 Bits
622 if( (*str & 0xF0) == 0xE0 ) {
623 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
625 if( (*str & 0xC0) != 0x80) return -1; // Validity check
626 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
628 if( (*str & 0xC0) != 0x80) return -1; // Validity check
629 *Val |= (*str & 0x3F); // Lower 6 Bits
634 if( (*str & 0xF1) == 0xF0 ) {
635 *Val = (*str & 0x07) << 18; // Upper 3 Bits
637 if( (*str & 0xC0) != 0x80) return -1; // Validity check
638 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
640 if( (*str & 0xC0) != 0x80) return -1; // Validity check
641 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
643 if( (*str & 0xC0) != 0x80) return -1; // Validity check
644 *Val |= (*str & 0x3F); // Lower 6 Bits
648 // UTF-8 Doesn't support more than four bytes
653 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
654 * \brief Write a UTF-8 character sequence to a string
656 int WriteUTF8(Uint8 *str, Uint32 Val)
666 *str = 0xC0 | (Val >> 6);
668 *str = 0x80 | (Val & 0x3F);
673 if( Val < 0x10000 ) {
674 *str = 0xE0 | (Val >> 12);
676 *str = 0x80 | ((Val >> 6) & 0x3F);
678 *str = 0x80 | (Val & 0x3F);
683 if( Val < 0x110000 ) {
684 *str = 0xF0 | (Val >> 18);
686 *str = 0x80 | ((Val >> 12) & 0x3F);
688 *str = 0x80 | ((Val >> 6) & 0x3F);
690 *str = 0x80 | (Val & 0x3F);
694 // UTF-8 Doesn't support more than four bytes
699 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
700 * \brief Converts a date into an Acess Timestamp
702 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
709 stamp += day*3600*24;
710 stamp += month*DAYS_BEFORE[month]*3600*24;
712 ((year&3) == 0 || year%100 != 0)
713 || (year%100 == 0 && ((year/100)&3) == 0)
714 ) && month > 1) // Leap year and after feb
717 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
718 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
726 * \brief Pseudo random number generator
727 * \note Unknown effectiveness (made up on the spot)
732 static Uint state = RANDOM_SEED;
734 // Get the next state value
735 giRandomState = (RANDOM_A*state + RANDOM_C);
736 // Check if it has changed, and if it hasn't, change it
737 if(state == old) state += RANDOM_SPRUCE;
740 // http://en.wikipedia.org/wiki/Xorshift
742 static Uint32 x = 123456789;
743 static Uint32 y = 362436069;
744 static Uint32 z = 521288629;
745 static Uint32 w = 88675123;
750 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
755 * \name Memory Validation
759 * \brief Checks if a string resides fully in valid memory
761 int CheckString(char *String)
763 if( !MM_GetPhysAddr( (tVAddr)String ) )
767 if( MM_IsUser( (tVAddr)String ) )
772 if( !MM_IsUser( (tVAddr)String ) )
774 // Increment string pointer
779 else if( MM_GetPhysAddr( (tVAddr)String ) )
784 if( !MM_GetPhysAddr( (tVAddr)String ) )
786 // Increment string pointer
795 * \brief Check if a sized memory region is valid memory
797 int CheckMem(void *Mem, int NumBytes)
799 tVAddr addr = (tVAddr)Mem;
801 if( MM_IsUser( addr ) )
805 if( !MM_IsUser( addr ) )
811 else if( MM_GetPhysAddr( addr ) )
815 if( !MM_GetPhysAddr( addr ) )
828 * \brief Search a string array for \a Needle
829 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
831 int ModUtil_LookupString(char **Array, char *Needle)
834 if( !CheckString(Needle) ) return -1;
835 for( i = 0; Array[i]; i++ )
837 if(strcmp(Array[i], Needle) == 0) return i;
842 int ModUtil_SetIdent(char *Dest, char *Value)
844 if( !CheckMem(Dest, 32) ) return -1;
845 strncpy(Dest, Value, 32);
850 * \brief Convert a string of hexadecimal digits into a byte stream
852 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
856 for( i = 0; i < DestSize*2; i += 2 )
860 if(SourceString[i] == '\0') break;
862 if('0' <= SourceString[i] && SourceString[i] <= '9')
863 val |= (SourceString[i]-'0') << 4;
864 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
865 val |= (SourceString[i]-'A'+10) << 4;
866 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
867 val |= (SourceString[i]-'a'+10) << 4;
869 if(SourceString[i+1] == '\0') break;
871 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
872 val |= (SourceString[i+1] - '0');
873 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
874 val |= (SourceString[i+1] - 'A' + 10);
875 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
876 val |= (SourceString[i+1] - 'a' + 10);