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
298 itoa(p, val, 16, minSize, pad);
303 itoa(p, val, 16, minSize, pad);
307 itoa(p, val, 8, minSize, pad);
311 itoa(p, val, 2, minSize, pad);
315 val = va_arg(args, unsigned int);
320 // String - Null Terminated Array
322 p = va_arg(args, char*); // Get Argument
323 if( !CheckString(p) ) continue; // Avoid #PFs
327 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
328 while(*p) PUTCH(*p++);
329 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
332 case 'C': // Non-Null Terminated Character Array
333 p = va_arg(args, char*);
334 if( !CheckMem(p, minSize) ) continue; // No #PFs please
335 if(!p) goto printString;
336 while(minSize--) PUTCH(*p++);
348 if(__s && pos != __maxlen)
357 int sprintf(char *__s, const char *__format, ...)
362 va_start(args, __format);
363 ret = vsnprintf(__s, -1, __format, args);
370 * \fn int tolower(int c)
371 * \brief Converts a character to lower case
375 if('A' <= c && c <= 'Z')
376 return c - 'A' + 'a';
381 * \fn int strucmp(const char *Str1, const char *Str2)
382 * \brief Compare \a Str1 and \a Str2 case-insensitively
384 int strucmp(const char *Str1, const char *Str2)
386 while(*Str1 && tolower(*Str1) == tolower(*Str2))
388 return tolower(*Str1) - tolower(*Str2);
392 * \brief Locate a byte in a string
394 char *strchr(const char *__s, int __c)
396 for( ; *__s; __s ++ )
398 if( *__s == __c ) return (char*)__s;
404 * \fn int strpos(const char *Str, char Ch)
405 * \brief Search a string for an ascii character
407 int strpos(const char *Str, char Ch)
410 for(pos=0;Str[pos];pos++)
412 if(Str[pos] == Ch) return pos;
418 * \fn Uint8 ByteSum(void *Ptr, int Size)
419 * \brief Adds the bytes in a memory region and returns the sum
421 Uint8 ByteSum(void *Ptr, int Size)
424 while(Size--) sum += *(Uint8*)Ptr++;
429 * \fn size_t strlen(const char *__str)
430 * \brief Get the length of string
432 size_t strlen(const char *__str)
435 while(*__str++) ret++;
440 * \fn char *strcpy(char *__str1, const char *__str2)
441 * \brief Copy a string to a new location
443 char *strcpy(char *__str1, const char *__str2)
446 *__str1++ = *__str2++;
447 *__str1 = '\0'; // Terminate String
452 * \fn char *strncpy(char *__str1, const char *__str2, size_t max)
453 * \brief Copy a string to a new location
455 char *strncpy(char *__str1, const char *__str2, size_t max)
457 while(*__str2 && max-- >= 1)
458 *__str1++ = *__str2++;
460 *__str1 = '\0'; // Terminate String
465 * \fn int strcmp(const char *str1, const char *str2)
466 * \brief Compare two strings return the difference between
467 * the first non-matching characters.
469 int strcmp(const char *str1, const char *str2)
471 while(*str1 && *str1 == *str2)
473 return *str1 - *str2;
477 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
478 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
480 int strncmp(const char *Str1, const char *Str2, size_t num)
482 if(num == 0) return 0; // TODO: Check what should officially happen here
483 while(--num && *Str1 && *Str1 == *Str2)
490 * \fn char *strdup(const char *Str)
491 * \brief Duplicates a string
493 char *strdup(const char *Str)
496 ret = malloc(strlen(Str)+1);
497 if( !ret ) return NULL;
504 * \fn char *_strdup(const char *File, int Line, const char *Str)
505 * \brief Duplicates a string
507 char *_strdup(const char *File, int Line, const char *Str)
510 ret = Heap_Allocate(File, Line, strlen(Str)+1);
511 if( !ret ) return NULL;
518 * \brief Split a string using the passed character
519 * \return NULL terminated array of strings on the heap
520 * \param __str String to split
521 * \param __ch Character to split by
523 char **str_split(const char *__str, char __ch)
530 for( i = 0; __str[i]; i++ )
536 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
537 if( !ret ) return NULL;
540 start = (char *)&ret[len+1];
542 for( i = 0; __str[i]; i++ )
544 if(__str[i] == __ch) {
559 * \fn int DivUp(int num, int dem)
560 * \brief Divide two numbers, rounding up
561 * \param num Numerator
562 * \param dem Denominator
564 int DivUp(int num, int dem)
566 return (num+dem-1)/dem;
570 * \fn int strpos8(const char *str, Uint32 search)
571 * \brief Search a string for a UTF-8 character
573 int strpos8(const char *str, Uint32 Search)
577 for(pos=0;str[pos];pos++)
581 if(str[pos] == Search) return pos;
584 if(*(Uint8*)(str+pos) < 128) continue;
586 pos += ReadUTF8( (Uint8*)&str[pos], &val );
587 if(val == Search) return pos;
593 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
594 * \brief Read a UTF-8 character from a string
596 int ReadUTF8(Uint8 *str, Uint32 *Val)
598 *Val = 0xFFFD; // Assume invalid character
601 if( !(*str & 0x80) ) {
606 // Middle of a sequence
607 if( (*str & 0xC0) == 0x80 ) {
612 if( (*str & 0xE0) == 0xC0 ) {
613 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
615 if( (*str & 0xC0) != 0x80) return -1; // Validity check
616 *Val |= (*str & 0x3F); // Lower 6 Bits
621 if( (*str & 0xF0) == 0xE0 ) {
622 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
624 if( (*str & 0xC0) != 0x80) return -1; // Validity check
625 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
627 if( (*str & 0xC0) != 0x80) return -1; // Validity check
628 *Val |= (*str & 0x3F); // Lower 6 Bits
633 if( (*str & 0xF1) == 0xF0 ) {
634 *Val = (*str & 0x07) << 18; // Upper 3 Bits
636 if( (*str & 0xC0) != 0x80) return -1; // Validity check
637 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
639 if( (*str & 0xC0) != 0x80) return -1; // Validity check
640 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
642 if( (*str & 0xC0) != 0x80) return -1; // Validity check
643 *Val |= (*str & 0x3F); // Lower 6 Bits
647 // UTF-8 Doesn't support more than four bytes
652 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
653 * \brief Write a UTF-8 character sequence to a string
655 int WriteUTF8(Uint8 *str, Uint32 Val)
665 *str = 0xC0 | (Val >> 6);
667 *str = 0x80 | (Val & 0x3F);
672 if( Val < 0x10000 ) {
673 *str = 0xE0 | (Val >> 12);
675 *str = 0x80 | ((Val >> 6) & 0x3F);
677 *str = 0x80 | (Val & 0x3F);
682 if( Val < 0x110000 ) {
683 *str = 0xF0 | (Val >> 18);
685 *str = 0x80 | ((Val >> 12) & 0x3F);
687 *str = 0x80 | ((Val >> 6) & 0x3F);
689 *str = 0x80 | (Val & 0x3F);
693 // UTF-8 Doesn't support more than four bytes
698 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
699 * \brief Converts a date into an Acess Timestamp
701 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
708 stamp += day*3600*24;
709 stamp += month*DAYS_BEFORE[month]*3600*24;
711 ((year&3) == 0 || year%100 != 0)
712 || (year%100 == 0 && ((year/100)&3) == 0)
713 ) && month > 1) // Leap year and after feb
716 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
717 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
725 * \brief Pseudo random number generator
730 static Uint state = RANDOM_SEED;
732 // Get the next state value
733 giRandomState = (RANDOM_A*state + RANDOM_C);
734 // Check if it has changed, and if it hasn't, change it
735 if(state == old) state += RANDOM_SPRUCE;
738 // http://en.wikipedia.org/wiki/Xorshift
740 static Uint32 x = 123456789;
741 static Uint32 y = 362436069;
742 static Uint32 z = 521288629;
743 static Uint32 w = 88675123;
748 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
753 * \name Memory Validation
757 * \brief Checks if a string resides fully in valid memory
759 int CheckString(char *String)
761 if( !MM_GetPhysAddr( (tVAddr)String ) )
765 if( MM_IsUser( (tVAddr)String ) )
770 if( !MM_IsUser( (tVAddr)String ) )
772 // Increment string pointer
777 else if( MM_GetPhysAddr( (tVAddr)String ) )
782 if( !MM_GetPhysAddr( (tVAddr)String ) )
784 // Increment string pointer
793 * \brief Check if a sized memory region is valid memory
795 int CheckMem(void *Mem, int NumBytes)
797 tVAddr addr = (tVAddr)Mem;
799 if( MM_IsUser( addr ) )
803 if( !MM_IsUser( addr ) )
809 else if( MM_GetPhysAddr( addr ) )
813 if( !MM_GetPhysAddr( addr ) )
826 * \brief Search a string array for \a Needle
827 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
829 int ModUtil_LookupString(char **Array, char *Needle)
832 if( !CheckString(Needle) ) return -1;
833 for( i = 0; Array[i]; i++ )
835 if(strcmp(Array[i], Needle) == 0) return i;
840 int ModUtil_SetIdent(char *Dest, char *Value)
842 if( !CheckMem(Dest, 32) ) return -1;
843 strncpy(Dest, Value, 32);
848 * \brief Convert a string of hexadecimal digits into a byte stream
850 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
854 for( i = 0; i < DestSize*2; i += 2 )
858 if(SourceString[i] == '\0') break;
860 if('0' <= SourceString[i] && SourceString[i] <= '9')
861 val |= (SourceString[i]-'0') << 4;
862 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
863 val |= (SourceString[i]-'A'+10) << 4;
864 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
865 val |= (SourceString[i]-'a'+10) << 4;
867 if(SourceString[i+1] == '\0') break;
869 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
870 val |= (SourceString[i+1] - '0');
871 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
872 val |= (SourceString[i+1] - 'A' + 10);
873 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
874 val |= (SourceString[i+1] - 'a' + 10);