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)
499 *__dest++ = *__src++;
505 * \brief Append at most \a n chars to a string from another
506 * \note At most n+1 chars are written (the dest is always zero terminated)
508 char *strncat(char *__dest, const char *__src, size_t n)
511 while(*__src && n-- >= 1)
512 *__dest++ = *__src++;
518 * \fn int strcmp(const char *str1, const char *str2)
519 * \brief Compare two strings return the difference between
520 * the first non-matching characters.
522 int strcmp(const char *str1, const char *str2)
524 while(*str1 && *str1 == *str2)
526 return *str1 - *str2;
530 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
531 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
533 int strncmp(const char *Str1, const char *Str2, size_t num)
535 if(num == 0) return 0; // TODO: Check what should officially happen here
536 while(--num && *Str1 && *Str1 == *Str2)
543 * \fn char *strdup(const char *Str)
544 * \brief Duplicates a string
546 char *strdup(const char *Str)
549 ret = malloc(strlen(Str)+1);
550 if( !ret ) return NULL;
557 * \fn char *_strdup(const char *File, int Line, const char *Str)
558 * \brief Duplicates a string
560 char *_strdup(const char *File, int Line, const char *Str)
563 ret = Heap_Allocate(File, Line, strlen(Str)+1);
564 if( !ret ) return NULL;
571 * \brief Split a string using the passed character
572 * \return NULL terminated array of strings on the heap
573 * \param __str String to split
574 * \param __ch Character to split by
576 char **str_split(const char *__str, char __ch)
583 for( i = 0; __str[i]; i++ )
589 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
590 if( !ret ) return NULL;
593 start = (char *)&ret[len+1];
595 for( i = 0; __str[i]; i++ )
597 if(__str[i] == __ch) {
612 * \fn int DivUp(int num, int dem)
613 * \brief Divide two numbers, rounding up
614 * \param num Numerator
615 * \param dem Denominator
617 int DivUp(int num, int dem)
619 return (num+dem-1)/dem;
623 * \fn int strpos8(const char *str, Uint32 search)
624 * \brief Search a string for a UTF-8 character
626 int strpos8(const char *str, Uint32 Search)
630 for(pos=0;str[pos];pos++)
634 if(str[pos] == Search) return pos;
637 if(*(Uint8*)(str+pos) < 128) continue;
639 pos += ReadUTF8( (Uint8*)&str[pos], &val );
640 if(val == Search) return pos;
646 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
647 * \brief Read a UTF-8 character from a string
649 int ReadUTF8(const Uint8 *str, Uint32 *Val)
651 *Val = 0xFFFD; // Assume invalid character
654 if( !(*str & 0x80) ) {
659 // Middle of a sequence
660 if( (*str & 0xC0) == 0x80 ) {
665 if( (*str & 0xE0) == 0xC0 ) {
666 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
668 if( (*str & 0xC0) != 0x80) return -1; // Validity check
669 *Val |= (*str & 0x3F); // Lower 6 Bits
674 if( (*str & 0xF0) == 0xE0 ) {
675 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
677 if( (*str & 0xC0) != 0x80) return -1; // Validity check
678 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
680 if( (*str & 0xC0) != 0x80) return -1; // Validity check
681 *Val |= (*str & 0x3F); // Lower 6 Bits
686 if( (*str & 0xF1) == 0xF0 ) {
687 *Val = (*str & 0x07) << 18; // Upper 3 Bits
689 if( (*str & 0xC0) != 0x80) return -1; // Validity check
690 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
692 if( (*str & 0xC0) != 0x80) return -1; // Validity check
693 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
695 if( (*str & 0xC0) != 0x80) return -1; // Validity check
696 *Val |= (*str & 0x3F); // Lower 6 Bits
700 // UTF-8 Doesn't support more than four bytes
705 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
706 * \brief Write a UTF-8 character sequence to a string
708 int WriteUTF8(Uint8 *str, Uint32 Val)
718 *str = 0xC0 | (Val >> 6);
720 *str = 0x80 | (Val & 0x3F);
725 if( Val < 0x10000 ) {
726 *str = 0xE0 | (Val >> 12);
728 *str = 0x80 | ((Val >> 6) & 0x3F);
730 *str = 0x80 | (Val & 0x3F);
735 if( Val < 0x110000 ) {
736 *str = 0xF0 | (Val >> 18);
738 *str = 0x80 | ((Val >> 12) & 0x3F);
740 *str = 0x80 | ((Val >> 6) & 0x3F);
742 *str = 0x80 | (Val & 0x3F);
746 // UTF-8 Doesn't support more than four bytes
751 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
752 * \brief Converts a date into an Acess Timestamp
754 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
761 stamp += day*3600*24;
762 stamp += month*DAYS_BEFORE[month]*3600*24;
764 ((year&3) == 0 || year%100 != 0)
765 || (year%100 == 0 && ((year/100)&3) == 0)
766 ) && month > 1) // Leap year and after feb
769 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
770 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
778 * \brief Pseudo random number generator
783 static Uint state = RANDOM_SEED;
785 // Get the next state value
786 giRandomState = (RANDOM_A*state + RANDOM_C);
787 // Check if it has changed, and if it hasn't, change it
788 if(state == old) state += RANDOM_SPRUCE;
791 // http://en.wikipedia.org/wiki/Xorshift
793 static Uint32 x = 123456789;
794 static Uint32 y = 362436069;
795 static Uint32 z = 521288629;
796 static Uint32 w = 88675123;
801 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
806 * \name Memory Validation
810 * \brief Checks if a string resides fully in valid memory
812 int CheckString(const char *String)
814 if( !MM_GetPhysAddr( (tVAddr)String ) )
818 if( MM_IsUser( (tVAddr)String ) )
823 if( !MM_IsUser( (tVAddr)String ) )
825 // Increment string pointer
830 else if( MM_GetPhysAddr( (tVAddr)String ) )
835 if( !MM_GetPhysAddr( (tVAddr)String ) )
837 // Increment string pointer
846 * \brief Check if a sized memory region is valid memory
848 int CheckMem(const void *Mem, int NumBytes)
850 tVAddr addr = (tVAddr)Mem;
852 if( MM_IsUser( addr ) )
856 if( !MM_IsUser( addr ) )
862 else if( MM_GetPhysAddr( addr ) )
866 if( !MM_GetPhysAddr( addr ) )
879 * \brief Search a string array for \a Needle
880 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
882 int ModUtil_LookupString(const char **Array, const char *Needle)
885 if( !CheckString(Needle) ) return -1;
886 for( i = 0; Array[i]; i++ )
888 if(strcmp(Array[i], Needle) == 0) return i;
893 int ModUtil_SetIdent(char *Dest, const char *Value)
895 if( !CheckMem(Dest, 32) ) return -1;
896 strncpy(Dest, Value, 32);
901 * \brief Convert a string of hexadecimal digits into a byte stream
903 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
907 for( i = 0; i < DestSize*2; i += 2 )
911 if(SourceString[i] == '\0') break;
913 if('0' <= SourceString[i] && SourceString[i] <= '9')
914 val |= (SourceString[i]-'0') << 4;
915 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
916 val |= (SourceString[i]-'A'+10) << 4;
917 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
918 val |= (SourceString[i]-'a'+10) << 4;
920 if(SourceString[i+1] == '\0') break;
922 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
923 val |= (SourceString[i+1] - '0');
924 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
925 val |= (SourceString[i+1] - 'A' + 10);
926 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
927 val |= (SourceString[i+1] - 'a' + 10);
934 Uint16 SwapEndian16(Uint16 Val)
936 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
938 Uint32 SwapEndian32(Uint32 Val)
940 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);