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);
70 EXPORT(_strdup); // Takes File/Line too
79 EXPORT(ModUtil_LookupString);
80 EXPORT(ModUtil_SetIdent);
87 * \brief Convert a string into an integer
89 int atoi(const char *string)
94 //Log("atoi: (string='%s')", string);
96 // Clear non-numeric characters
97 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
98 if( *string == '-' ) {
100 while( !('0' <= *string && *string <= '9') ) string++;
112 if('0' <= *string && *string <= '9') {
114 ret += *string - '0';
116 else if('A' <= *string && *string <= 'F') {
118 ret += *string - 'A' + 10;
120 else if('a' <= *string && *string <= 'f') {
122 ret += *string - 'a' + 10;
130 for( ; '0' <= *string && *string <= '7'; string ++ )
133 ret += *string - '0';
139 for( ; '0' <= *string && *string <= '9'; string++)
142 ret += *string - '0';
148 //Log("atoi: RETURN %i", ret);
153 static const char cUCDIGITS[] = "0123456789ABCDEF";
155 * \fn void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
156 * \brief Convert an integer into a character string
158 void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
167 if(base > 16 || base < 2) {
173 while(num > base-1) {
174 tmpBuf[pos] = cUCDIGITS[ num % base ];
175 num /= (Uint)base; // Shift `num` right 1 digit
178 tmpBuf[pos++] = cUCDIGITS[ num % base ]; // Last digit of `num`
183 while(minLength-- > 0) buf[i++] = pad;
184 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
189 * \brief Append a character the the vsnprintf output
191 #define PUTCH(c) do{\
193 if(pos==__maxlen){return pos;}\
194 if(__s){__s[pos++]=ch;}else{pos++;}\
196 #define GETVAL() do {\
197 if(isLongLong) val = va_arg(args, Uint64);\
198 else val = va_arg(args, unsigned int);\
201 * \brief VArg String Number Print Formatted
203 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
206 int minSize = 0, precision = -1, len;
207 char tmpBuf[34]; // For Integers
208 const char *p = NULL;
215 //Log("vsnprintf: (__s=%p, __maxlen=%i, __format='%s', ...)", __s, __maxlen, __format);
217 while((c = *__format++) != 0)
219 // Non control character
220 if(c != '%') { PUTCH(c); continue; }
223 //Log("pos = %i", pos);
226 if(c == '%') { PUTCH('%'); continue; }
228 // Pointer - Done first for debugging
230 Uint ptr = va_arg(args, Uint);
231 PUTCH('*'); PUTCH('0'); PUTCH('x');
232 itoa(tmpBuf, ptr, 16, BITS/4, '0');
237 // - Padding Side Flag
252 if(c == '*') { // Dynamic length
253 minSize = va_arg(args, unsigned int);
256 else if('1' <= c && c <= '9')
259 while('0' <= c && c <= '9')
274 if(c == '*') { // Dynamic length
275 precision = va_arg(args, unsigned int);
278 else if('1' <= c && c <= '9')
281 while('0' <= c && c <= '9')
284 precision += c - '0';
290 // - Default, Long or LongLong?
292 if(c == 'l') // Long is actually the default on x86
301 // - Now get the format code
308 if( isLongLong && val >> 63 ) {
312 else if( !isLongLong && val >> 31 ) {
316 itoa(tmpBuf, val, 10, minSize, pad);
320 itoa(tmpBuf, val, 10, minSize, pad);
324 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
326 itoa(tmpBuf, val, 16, minSize, pad);
331 itoa(tmpBuf, val, 16, minSize, pad);
335 itoa(tmpBuf, val, 8, minSize, pad);
339 itoa(tmpBuf, val, 2, minSize, pad);
343 val = va_arg(args, unsigned int);
348 // String - Null Terminated Array
350 p = va_arg(args, char*); // Get Argument
351 if( !CheckString(p) ) p = "(inval)"; // Avoid #PFs
355 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
356 while(*p && precision--) PUTCH(*p++);
357 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
360 case 'C': // Non-Null Terminated Character Array
361 p = va_arg(args, char*);
362 if( !CheckMem(p, minSize) ) continue; // No #PFs please
363 if(!p) goto printString;
364 while(minSize--) PUTCH(*p++);
376 if(__s && pos != __maxlen)
385 int sprintf(char *__s, const char *__format, ...)
390 va_start(args, __format);
391 ret = vsnprintf(__s, -1, __format, args);
398 * \fn int tolower(int c)
399 * \brief Converts a character to lower case
403 if('A' <= c && c <= 'Z')
404 return c - 'A' + 'a';
409 * \fn int strucmp(const char *Str1, const char *Str2)
410 * \brief Compare \a Str1 and \a Str2 case-insensitively
412 int strucmp(const char *Str1, const char *Str2)
414 while(*Str1 && tolower(*Str1) == tolower(*Str2))
416 return tolower(*Str1) - tolower(*Str2);
420 * \brief Locate a byte in a string
422 char *strchr(const char *__s, int __c)
424 for( ; *__s; __s ++ )
426 if( *__s == __c ) return (char*)__s;
432 * \fn int strpos(const char *Str, char Ch)
433 * \brief Search a string for an ascii character
435 int strpos(const char *Str, char Ch)
438 for(pos=0;Str[pos];pos++)
440 if(Str[pos] == Ch) return pos;
446 * \fn Uint8 ByteSum(void *Ptr, int Size)
447 * \brief Adds the bytes in a memory region and returns the sum
449 Uint8 ByteSum(const void *Ptr, int Size)
452 const Uint8 *data = Ptr;
453 while(Size--) sum += *(data++);
458 * \fn size_t strlen(const char *__str)
459 * \brief Get the length of string
461 size_t strlen(const char *__str)
464 while(*__str++) ret++;
469 * \brief Copy a string to a new location
471 char *strcpy(char *__str1, const char *__str2)
474 *__str1++ = *__str2++;
475 *__str1 = '\0'; // Terminate String
480 * \brief Copy a string to a new location
481 * \note Copies at most `max` chars
483 char *strncpy(char *__str1, const char *__str2, size_t max)
485 while(*__str2 && max-- >= 1)
486 *__str1++ = *__str2++;
488 *__str1 = '\0'; // Terminate String
493 * \brief Append a string to another
495 char *strcat(char *__dest, const char *__src)
500 *__dest++ = *__src++;
506 * \brief Append at most \a n chars to a string from another
507 * \note At most n+1 chars are written (the dest is always zero terminated)
509 char *strncat(char *__dest, const char *__src, size_t n)
512 while(*__src && n-- >= 1)
513 *__dest++ = *__src++;
519 * \fn int strcmp(const char *str1, const char *str2)
520 * \brief Compare two strings return the difference between
521 * the first non-matching characters.
523 int strcmp(const char *str1, const char *str2)
525 while(*str1 && *str1 == *str2)
527 return *str1 - *str2;
531 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
532 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
534 int strncmp(const char *Str1, const char *Str2, size_t num)
536 if(num == 0) return 0; // TODO: Check what should officially happen here
537 while(--num && *Str1 && *Str1 == *Str2)
544 * \fn char *strdup(const char *Str)
545 * \brief Duplicates a string
547 char *strdup(const char *Str)
550 ret = malloc(strlen(Str)+1);
551 if( !ret ) return NULL;
558 * \fn char *_strdup(const char *File, int Line, const char *Str)
559 * \brief Duplicates a string
561 char *_strdup(const char *File, int Line, const char *Str)
564 ret = Heap_Allocate(File, Line, strlen(Str)+1);
565 if( !ret ) return NULL;
572 * \brief Split a string using the passed character
573 * \return NULL terminated array of strings on the heap
574 * \param __str String to split
575 * \param __ch Character to split by
577 char **str_split(const char *__str, char __ch)
584 for( i = 0; __str[i]; i++ )
590 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
591 if( !ret ) return NULL;
594 start = (char *)&ret[len+1];
596 for( i = 0; __str[i]; i++ )
598 if(__str[i] == __ch) {
613 * \fn int DivUp(int num, int dem)
614 * \brief Divide two numbers, rounding up
615 * \param num Numerator
616 * \param dem Denominator
618 int DivUp(int num, int dem)
620 return (num+dem-1)/dem;
624 * \fn int strpos8(const char *str, Uint32 search)
625 * \brief Search a string for a UTF-8 character
627 int strpos8(const char *str, Uint32 Search)
631 for(pos=0;str[pos];pos++)
635 if(str[pos] == Search) return pos;
638 if(*(Uint8*)(str+pos) < 128) continue;
640 pos += ReadUTF8( (Uint8*)&str[pos], &val );
641 if(val == Search) return pos;
647 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
648 * \brief Read a UTF-8 character from a string
650 int ReadUTF8(const Uint8 *str, Uint32 *Val)
652 *Val = 0xFFFD; // Assume invalid character
655 if( !(*str & 0x80) ) {
660 // Middle of a sequence
661 if( (*str & 0xC0) == 0x80 ) {
666 if( (*str & 0xE0) == 0xC0 ) {
667 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
669 if( (*str & 0xC0) != 0x80) return -1; // Validity check
670 *Val |= (*str & 0x3F); // Lower 6 Bits
675 if( (*str & 0xF0) == 0xE0 ) {
676 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
678 if( (*str & 0xC0) != 0x80) return -1; // Validity check
679 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
681 if( (*str & 0xC0) != 0x80) return -1; // Validity check
682 *Val |= (*str & 0x3F); // Lower 6 Bits
687 if( (*str & 0xF1) == 0xF0 ) {
688 *Val = (*str & 0x07) << 18; // Upper 3 Bits
690 if( (*str & 0xC0) != 0x80) return -1; // Validity check
691 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
693 if( (*str & 0xC0) != 0x80) return -1; // Validity check
694 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
696 if( (*str & 0xC0) != 0x80) return -1; // Validity check
697 *Val |= (*str & 0x3F); // Lower 6 Bits
701 // UTF-8 Doesn't support more than four bytes
706 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
707 * \brief Write a UTF-8 character sequence to a string
709 int WriteUTF8(Uint8 *str, Uint32 Val)
719 *str = 0xC0 | (Val >> 6);
721 *str = 0x80 | (Val & 0x3F);
726 if( Val < 0x10000 ) {
727 *str = 0xE0 | (Val >> 12);
729 *str = 0x80 | ((Val >> 6) & 0x3F);
731 *str = 0x80 | (Val & 0x3F);
736 if( Val < 0x110000 ) {
737 *str = 0xF0 | (Val >> 18);
739 *str = 0x80 | ((Val >> 12) & 0x3F);
741 *str = 0x80 | ((Val >> 6) & 0x3F);
743 *str = 0x80 | (Val & 0x3F);
747 // UTF-8 Doesn't support more than four bytes
752 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
753 * \brief Converts a date into an Acess Timestamp
755 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
762 stamp += day*3600*24;
763 stamp += month*DAYS_BEFORE[month]*3600*24;
765 ((year&3) == 0 || year%100 != 0)
766 || (year%100 == 0 && ((year/100)&3) == 0)
767 ) && month > 1) // Leap year and after feb
770 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
771 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
779 * \brief Pseudo random number generator
784 static Uint state = RANDOM_SEED;
786 // Get the next state value
787 giRandomState = (RANDOM_A*state + RANDOM_C);
788 // Check if it has changed, and if it hasn't, change it
789 if(state == old) state += RANDOM_SPRUCE;
792 // http://en.wikipedia.org/wiki/Xorshift
794 static Uint32 x = 123456789;
795 static Uint32 y = 362436069;
796 static Uint32 z = 521288629;
797 static Uint32 w = 88675123;
802 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
807 * \name Memory Validation
811 * \brief Checks if a string resides fully in valid memory
813 int CheckString(const char *String)
815 if( !MM_GetPhysAddr( (tVAddr)String ) )
819 if( MM_IsUser( (tVAddr)String ) )
824 if( !MM_IsUser( (tVAddr)String ) )
826 // Increment string pointer
831 else if( MM_GetPhysAddr( (tVAddr)String ) )
836 if( !MM_GetPhysAddr( (tVAddr)String ) )
838 // Increment string pointer
847 * \brief Check if a sized memory region is valid memory
849 int CheckMem(const void *Mem, int NumBytes)
851 tVAddr addr = (tVAddr)Mem;
853 if( MM_IsUser( addr ) )
857 if( !MM_IsUser( addr ) )
863 else if( MM_GetPhysAddr( addr ) )
867 if( !MM_GetPhysAddr( addr ) )
880 * \brief Search a string array for \a Needle
881 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
883 int ModUtil_LookupString(const char **Array, const char *Needle)
886 if( !CheckString(Needle) ) return -1;
887 for( i = 0; Array[i]; i++ )
889 if(strcmp(Array[i], Needle) == 0) return i;
894 int ModUtil_SetIdent(char *Dest, const char *Value)
896 if( !CheckMem(Dest, 32) ) return -1;
897 strncpy(Dest, Value, 32);
902 * \brief Convert a string of hexadecimal digits into a byte stream
904 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
908 for( i = 0; i < DestSize*2; i += 2 )
912 if(SourceString[i] == '\0') break;
914 if('0' <= SourceString[i] && SourceString[i] <= '9')
915 val |= (SourceString[i]-'0') << 4;
916 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
917 val |= (SourceString[i]-'A'+10) << 4;
918 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
919 val |= (SourceString[i]-'a'+10) << 4;
921 if(SourceString[i+1] == '\0') break;
923 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
924 val |= (SourceString[i+1] - '0');
925 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
926 val |= (SourceString[i+1] - 'A' + 10);
927 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
928 val |= (SourceString[i+1] - 'a' + 10);
935 Uint16 SwapEndian16(Uint16 Val)
937 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
939 Uint32 SwapEndian32(Uint32 Val)
941 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);