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
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(!p) goto printString;
335 while(minSize--) PUTCH(*p++);
347 if(__s && pos != __maxlen)
356 int sprintf(char *__s, const char *__format, ...)
361 va_start(args, __format);
362 ret = vsnprintf(__s, -1, __format, args);
369 * \fn int tolower(int c)
370 * \brief Converts a character to lower case
374 if('A' <= c && c <= 'Z')
375 return c - 'A' + 'a';
380 * \fn int strucmp(const char *Str1, const char *Str2)
381 * \brief Compare \a Str1 and \a Str2 case-insensitively
383 int strucmp(const char *Str1, const char *Str2)
385 while(*Str1 && tolower(*Str1) == tolower(*Str2))
387 return tolower(*Str1) - tolower(*Str2);
391 * \brief Locate a byte in a string
393 char *strchr(const char *__s, int __c)
395 for( ; *__s; __s ++ )
397 if( *__s == __c ) return (char*)__s;
403 * \fn int strpos(const char *Str, char Ch)
404 * \brief Search a string for an ascii character
406 int strpos(const char *Str, char Ch)
409 for(pos=0;Str[pos];pos++)
411 if(Str[pos] == Ch) return pos;
417 * \fn Uint8 ByteSum(void *Ptr, int Size)
418 * \brief Adds the bytes in a memory region and returns the sum
420 Uint8 ByteSum(void *Ptr, int Size)
423 while(Size--) sum += *(Uint8*)Ptr++;
428 * \fn Uint strlen(const char *__str)
429 * \brief Get the length of string
431 Uint strlen(const char *__str)
434 while(*__str++) ret++;
439 * \fn char *strcpy(char *__str1, const char *__str2)
440 * \brief Copy a string to a new location
442 char *strcpy(char *__str1, const char *__str2)
445 *__str1++ = *__str2++;
446 *__str1 = '\0'; // Terminate String
451 * \fn char *strncpy(char *__str1, const char *__str2, size_t max)
452 * \brief Copy a string to a new location
454 char *strncpy(char *__str1, const char *__str2, size_t max)
456 while(*__str2 && max-- >= 1)
457 *__str1++ = *__str2++;
459 *__str1 = '\0'; // Terminate String
464 * \fn int strcmp(const char *str1, const char *str2)
465 * \brief Compare two strings return the difference between
466 * the first non-matching characters.
468 int strcmp(const char *str1, const char *str2)
470 while(*str1 && *str1 == *str2)
472 return *str1 - *str2;
476 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
477 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
479 int strncmp(const char *Str1, const char *Str2, size_t num)
481 if(num == 0) return 0; // TODO: Check what should officially happen here
482 while(--num && *Str1 && *Str1 == *Str2)
489 * \fn char *strdup(const char *Str)
490 * \brief Duplicates a string
492 char *strdup(const char *Str)
495 ret = malloc(strlen(Str)+1);
496 if( !ret ) return NULL;
503 * \fn char *_strdup(const char *File, int Line, const char *Str)
504 * \brief Duplicates a string
506 char *_strdup(const char *File, int Line, const char *Str)
509 ret = Heap_Allocate(File, Line, strlen(Str)+1);
510 if( !ret ) return NULL;
517 * \brief Split a string using the passed character
518 * \return NULL terminated array of strings on the heap
519 * \param __str String to split
520 * \param __ch Character to split by
522 char **str_split(const char *__str, char __ch)
529 for( i = 0; __str[i]; i++ )
535 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
536 if( !ret ) return NULL;
539 start = (char *)&ret[len+1];
541 for( i = 0; __str[i]; i++ )
543 if(__str[i] == __ch) {
558 * \fn int DivUp(int num, int dem)
559 * \brief Divide two numbers, rounding up
560 * \param num Numerator
561 * \param dem Denominator
563 int DivUp(int num, int dem)
565 return (num+dem-1)/dem;
569 * \fn int strpos8(const char *str, Uint32 search)
570 * \brief Search a string for a UTF-8 character
572 int strpos8(const char *str, Uint32 Search)
576 for(pos=0;str[pos];pos++)
580 if(str[pos] == Search) return pos;
583 if(*(Uint8*)(str+pos) < 128) continue;
585 pos += ReadUTF8( (Uint8*)&str[pos], &val );
586 if(val == Search) return pos;
592 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
593 * \brief Read a UTF-8 character from a string
595 int ReadUTF8(Uint8 *str, Uint32 *Val)
597 *Val = 0xFFFD; // Assume invalid character
600 if( !(*str & 0x80) ) {
605 // Middle of a sequence
606 if( (*str & 0xC0) == 0x80 ) {
611 if( (*str & 0xE0) == 0xC0 ) {
612 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
614 if( (*str & 0xC0) != 0x80) return -1; // Validity check
615 *Val |= (*str & 0x3F); // Lower 6 Bits
620 if( (*str & 0xF0) == 0xE0 ) {
621 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
623 if( (*str & 0xC0) != 0x80) return -1; // Validity check
624 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
626 if( (*str & 0xC0) != 0x80) return -1; // Validity check
627 *Val |= (*str & 0x3F); // Lower 6 Bits
632 if( (*str & 0xF1) == 0xF0 ) {
633 *Val = (*str & 0x07) << 18; // Upper 3 Bits
635 if( (*str & 0xC0) != 0x80) return -1; // Validity check
636 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
638 if( (*str & 0xC0) != 0x80) return -1; // Validity check
639 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
641 if( (*str & 0xC0) != 0x80) return -1; // Validity check
642 *Val |= (*str & 0x3F); // Lower 6 Bits
646 // UTF-8 Doesn't support more than four bytes
651 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
652 * \brief Write a UTF-8 character sequence to a string
654 int WriteUTF8(Uint8 *str, Uint32 Val)
664 *str = 0xC0 | (Val >> 6);
666 *str = 0x80 | (Val & 0x3F);
671 if( Val < 0x10000 ) {
672 *str = 0xE0 | (Val >> 12);
674 *str = 0x80 | ((Val >> 6) & 0x3F);
676 *str = 0x80 | (Val & 0x3F);
681 if( Val < 0x110000 ) {
682 *str = 0xF0 | (Val >> 18);
684 *str = 0x80 | ((Val >> 12) & 0x3F);
686 *str = 0x80 | ((Val >> 6) & 0x3F);
688 *str = 0x80 | (Val & 0x3F);
692 // UTF-8 Doesn't support more than four bytes
697 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
698 * \brief Converts a date into an Acess Timestamp
700 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
707 stamp += day*3600*24;
708 stamp += month*DAYS_BEFORE[month]*3600*24;
710 ((year&3) == 0 || year%100 != 0)
711 || (year%100 == 0 && ((year/100)&3) == 0)
712 ) && month > 1) // Leap year and after feb
715 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
716 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
724 * \brief Pseudo random number generator
725 * \note Unknown effectiveness (made up on the spot)
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);