Ejemplo n.º 1
0
ATF_TC_BODY(wcscspn, tc)
{
	ATF_CHECK_EQ(wcscspn(L"abcdefghijklmnop", L""), 16);
	ATF_CHECK_EQ(wcscspn(L"abcdefghijklmnop", L"a"), 0);
	ATF_CHECK_EQ(wcscspn(L"abcdefghijklmnop", L"b"), 1);
	ATF_CHECK_EQ(wcscspn(L"abcdefghijklmnop", L"cd"), 2);
	ATF_CHECK_EQ(wcscspn(L"abcdefghijklmnop", L"qrstuvwxyz"), 16);
}
Ejemplo n.º 2
0
void runSuccess() {
    wchar_t s1[3]; s1[0] = L's'; s1[1] = L'1'; s1[2] = L'\0';
    wchar_t s2[3]; s2[0] = L's'; s2[1] = L'2'; s2[2] = L'\0';
    //@ assert \valid(s1+(0..2));
    //@ assert \exists integer x; s1[x] == L'\0';
    //@ assert \valid(s2+(0..2));
    //@ assert \exists integer x; s2[x] == L'\0';
    
    wcscspn(s1, s2);
    wcscspn(s1, s1);
}
///
/// Find the next operand, and the delimiter that triggered it. This function returns false if the string is empty, otherwise, it returns true.
///
bool
FindNextOperand( __in PCWSTR pwzOperand, __in PCWSTR pwzDelimiters, __out PCWSTR *ppwzNextOperand, __out size_t * pcchOperand, __out WCHAR * pchDelimiter )
{
	if( *pwzOperand == '\0' )
	{
		*ppwzNextOperand = pwzOperand;
		*pcchOperand = 0;
		*pchDelimiter = *pwzOperand;
		return( false );
	}

	*pcchOperand = wcscspn( pwzOperand, pwzDelimiters );
	*pchDelimiter = *(pwzOperand + *pcchOperand);

	if( *pchDelimiter != '\0' )
	{
		*ppwzNextOperand = pwzOperand + *pcchOperand + 1;
	}
	else
	{
		*ppwzNextOperand = pwzOperand + *pcchOperand;
	}

	return( true );
}
Ejemplo n.º 4
0
int
tst_wcscspn (FILE * fp, int debug_flg)
{
  TST_DECL_VARS (size_t);
  wchar_t *ws1, *ws2;

  TST_DO_TEST (wcscspn)
  {
    TST_HEAD_LOCALE (wcscspn, S_WCSCSPN);
    TST_DO_REC (wcscspn)
    {
      TST_GET_ERRET (wcscspn);
      ws1 = TST_INPUT (wcscspn).ws1;
      ws2 = TST_INPUT (wcscspn).ws2;	/* external value: size WCSSIZE */
      ret = wcscspn (ws1, ws2);

      if (debug_flg)
	{
	  fprintf (stderr, "wcscspn: ret = %d\n", ret);
	}

      TST_IF_RETURN (S_WCSCSPN)
      {
      };
    }
  }

  return err_count;
}
Ejemplo n.º 5
0
int main( void )
{
    TESTCASE( wcscspn( wabcde, L"x" ) == 5 );
    TESTCASE( wcscspn( wabcde, L"xyz" ) == 5 );
    TESTCASE( wcscspn( wabcde, L"zyx" ) == 5 );
    TESTCASE( wcscspn( wabcdx, L"x" ) == 4 );
    TESTCASE( wcscspn( wabcdx, L"xyz" ) == 4 );
    TESTCASE( wcscspn( wabcdx, L"zyx" ) == 4 );
    TESTCASE( wcscspn( wabcde, L"a" ) == 0 );
    TESTCASE( wcscspn( wabcde, L"abc" ) == 0 );
    TESTCASE( wcscspn( wabcde, L"cba" ) == 0 );
    return TEST_RESULTS;
}
Ejemplo n.º 6
0
/*
 * @implemented
 */
CHString CHString::SpanExcluding(LPCWSTR lpszCharSet) const throw (CHeap_Exception)
{
    int Count;

    // Get position and then, extract
    Count = wcscspn(m_pchData, lpszCharSet);
    return Left(Count);
}
Ejemplo n.º 7
0
/**
 * Expand wildcards in the given filepath and store results into vector.
 * If no wildcards are found then just the filepath is stored.
 * Note: only wildcards in the last filename of the path are expanded.
 *
 * @param vect the vector to receive wide-strings with file paths
 * @param filepath the filepath to process
 */
void expand_wildcards(vector_t* vect, wchar_t* filepath)
{
	int added = 0;
	size_t len = wcslen(filepath);
	size_t index = wcscspn(filepath, L"*?");

	/* if a wildcard has been found without a directory separator after it */
	if(index < len && wcscspn(filepath + index, L"/\\") >= (len - index))
	{
		wchar_t* parent;
		WIN32_FIND_DATAW d;
		HANDLE h;

		/* find directory separator */
		for(; index > 0 && !IS_PATH_SEPARATOR(filepath[index]); index--);
		parent = (IS_PATH_SEPARATOR(filepath[index]) ? filepath : 0);

		h = FindFirstFileW(filepath, &d);
		if(INVALID_HANDLE_VALUE != h) {
			do {
				wchar_t* wpath;
				char* cstr;
				int failed;
				if((0 == wcscmp(d.cFileName, L".")) || (0 == wcscmp(d.cFileName, L".."))) continue;
				if(NULL == (wpath = make_pathw(parent, index + 1, d.cFileName))) continue;
				cstr = wchar_to_cstr(wpath, WIN_DEFAULT_ENCODING, &failed);
				/* note: just quietly skip unconvertible file names */
				if(!cstr || failed) {
					free(cstr);
					free(wpath);
					continue;
				}
				rsh_vector_add_ptr(vect, cstr);
				added++;
			} while(FindNextFileW(h, &d));
			FindClose(h);
		}
	}

	if(added == 0) {
		wchar_t* wpath = make_pathw(0, 0, filepath);
		char* cstr = w2c(wpath);
		if(cstr) rsh_vector_add_ptr(vect, cstr);
	}
}
Ejemplo n.º 8
0
CUnicodeString CUnicodeString::SpanExcluding(LPCSTR lpszCharSet)
{
	ASSERT(IsValidString(lpszCharSet));
	WCHAR wc[1024];
	DWORD dwszLen = strlen(lpszCharSet);
	ASSERT(dwszLen < 1024);
	wc[dwszLen] = L'\0';

	MultiByteToWideChar(CP_ACP, 0, lpszCharSet, dwszLen, wc, dwszLen);
	return Left(wcscspn(m_Buffer, wc));
}
Ejemplo n.º 9
0
void testValues() {
    wchar_t s1[3]; s1[0] = L's'; s1[1] = L'1'; s1[2] = L'\0';
    wchar_t s2[3]; s2[0] = L's'; s2[1] = L'2'; s2[2] = L'\0';
    //@ assert \valid(s1+(0..2));
    //@ assert \exists integer x; s1[x] == L'\0';
    //@ assert \valid(s2+(0..2));
    //@ assert \exists integer x; s2[x] == L'\0';
    
    int result = wcscspn(s1, s2);
    //@ assert 0 <= result <= 2;
    
    //@ assert vacuous: \false;
}
int
_wstat(const WCHAR *path, struct _stat *buffer)
{
	WIN32_FIND_DATA data;
	HANDLE handle;
	WCHAR *p;

	/* Fail if wildcard characters are specified */
	if (wcscspn(path, L"?*") != wcslen(path))
		return -1;

	handle = FindFirstFile(path, &data);
	if (handle == INVALID_HANDLE_VALUE) {
		errno = GetLastError();
		return -1;
	}
	FindClose(handle);

	/* Found: Convert the file times */
	buffer->st_mtime = convert_FILETIME_to_time_t(&data.ftLastWriteTime);
	if (data.ftLastAccessTime.dwLowDateTime || data.ftLastAccessTime.dwHighDateTime)
		buffer->st_atime = convert_FILETIME_to_time_t(&data.ftLastAccessTime);
	else
		buffer->st_atime = buffer->st_mtime;
	if (data.ftCreationTime.dwLowDateTime || data.ftCreationTime.dwHighDateTime)
		buffer->st_ctime = convert_FILETIME_to_time_t(&data.ftCreationTime);
	else
		buffer->st_ctime = buffer->st_mtime;

	/* Convert the file modes */
	buffer->st_mode = (unsigned short)((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? (S_IFDIR | S_IEXEC) : S_IFREG);
	buffer->st_mode |= (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? S_IREAD : (S_IREAD | S_IWRITE);
	if((p = wcsrchr(path, L'.')) != NULL) {
		p++;
		if (_wcsicmp(p, L".exe") == 0)
			buffer->st_mode |= S_IEXEC;
	}
	buffer->st_mode |= (buffer->st_mode & 0700) >> 3;
	buffer->st_mode |= (buffer->st_mode & 0700) >> 6;
	/* Set the other information */
	buffer->st_nlink = 1;
	buffer->st_size = (unsigned long int)data.nFileSizeLow;
	buffer->st_uid = 0;
	buffer->st_gid = 0;
	buffer->st_ino = 0 /*data.dwOID ?*/;
	buffer->st_dev = 0;

	return 0;	/* success */
}
Ejemplo n.º 11
0
///////////////////////////////////////////////////////////////////////////////////////////
// common filter
void Filter_c::Set ( const wchar_t * szFilter )
{
	int iLen = wcslen ( szFilter );

	if ( wcscspn ( szFilter, L"?*[]" ) == iLen && iLen + 1 < MAX_FILTER_LEN - 2 )
	{
		wchar_t szTemp [MAX_FILTER_LEN];
		wcscpy ( &(szTemp [1]), szFilter );
		szTemp [0] = L'*';
		szTemp [iLen + 1] = L'*';
		szTemp [iLen + 2] = L'\0';
		BaseFilter_c::Set ( szTemp );
	}
	else
		BaseFilter_c::Set ( szFilter );
}
Ejemplo n.º 12
0
Archivo: Path.c Proyecto: etiago/vbox
/** Identify the type of path pointed to by Path.

    Paths are classified based upon their initial character sequences.
      ^\\       Absolute Path
      ^\.       Relative Path
      ^[^:\\]:  Mapping Path
      .*        Relative Path

    Mapping paths are broken into two parts at the ':'.  The part to the left of the ':'
    is the Map Name, pointed to by Path, and the part to the right of the ':' is pointed
    to by NewPath.

    If Path was not a Mapping Path, then NewPath is set to Path.

    @param[in]    Path      Pointer to the path to be classified.
    @param[out]   NewPath   Pointer to the path portion of a mapping path.
    @param[out]   Length    Length of the Map Name portion of the path.

    @retval PathAbsolute  Path is an absolute path. NewPath points to the first '\'.
    @retval PathRelative  Path is a relative path. NewPath = Path.
    @retval PathMapping   Path is a mapping path.  NewPath points to the character following ':'.
    @retval PathError     Path is NULL.
**/
PATH_CLASS
EFIAPI
ClassifyPath(
  IN  wchar_t    *        Path,
  OUT wchar_t   **        NewPath,
  OUT int        * const  Length
  )
{
  size_t    MapLen;

  if(Path == NULL) {
    return PathError;   // Bad parameter
  }
  if(NewPath != NULL) {
    *NewPath = Path;    // Setup default condition
  }
  if((*Path == L'\\') || (*Path == L'\0')) {
    return PathAbsolute;
  }
  if(*Path == L'.') {
    return PathRelative;
  }
  /* The easy stuff has been done, now see if this is a mapping path.
      See if there is a ':' in Path that isn't the first character and is before
      any '\\' characters.
  */
  MapLen = wcscspn(Path, L"\\:");
  if(Length != NULL) {
    *Length = (int)MapLen;
  }
  /*  MapLen == 0       means that the first character is a ':'
             == PathLen means that there are no '\\' or ':'
      Otherwise, Path[MapLen] == ':'  for a mapping path
                              or '\\' for a relative path.
  */
  if(MapLen == 0) {
    return PathError;
  }
  if(Path[MapLen] == L':') {
    if(NewPath != NULL) {
      *NewPath = &Path[MapLen + 1];   // Point to character after then ':'.  Might be '\0'.
    }
    return PathMapping;
  }
  return PathRelative;
}
Ejemplo n.º 13
0
wchar_t* wcstok(wchar_t* str, const wchar_t* delim, wchar_t** saveptr)
{
	if ( !str && !*saveptr )
		return NULL;
	if ( !str )
		str = *saveptr;
	str += wcsspn(str, delim); // Skip leading
	if ( !*str )
		return *saveptr = NULL;
	size_t amount = wcscspn(str, delim);
	if ( str[amount] )
		*saveptr = str + amount + 1;
	else
		*saveptr = NULL;
	str[amount] = L'\0';
	return str;
}
bool findPackageFromEmbeddedZip(wchar_t* buf, DWORD cbSize) 
{
	bool ret = false;

	CResource zipResource;
	if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) {
		return false;
	}

	DWORD dwSize = zipResource.GetSize();
	if (dwSize < 0x100) {
		return false;
	}

	BYTE* pData = (BYTE*)zipResource.Lock();
	HZIP zipFile = OpenZip(pData, dwSize, NULL);

	ZRESULT zr;
	int index = 0;
	do {
		ZIPENTRY zentry;

		zr = GetZipItem(zipFile, index, &zentry);
		if (zr != ZR_OK && zr != ZR_MORE) {
			break;
		}

		if (wcsstr(zentry.name, L"nupkg")) {
			ZeroMemory(buf, cbSize);

			int idx = wcscspn(zentry.name, L"-");
			memcpy(buf, zentry.name, sizeof(wchar_t) * idx);
			ret = true;
			break;
		}

		index++;
	} while (zr == ZR_MORE || zr == ZR_OK);

	CloseZip(zipFile);
	zipResource.Release();

	return ret;
}
Ejemplo n.º 15
0
/* vi_match():
 *	Vi go to matching () {} or []
 *	[%]
 */
libedit_private el_action_t
/*ARGSUSED*/
vi_match(EditLine *el, wint_t c __attribute__((__unused__)))
{
	const wchar_t match_chars[] = L"()[]{}";
	wchar_t *cp;
	size_t delta, i, count;
	wchar_t o_ch, c_ch;

	*el->el_line.lastchar = '\0';		/* just in case */

	i = wcscspn(el->el_line.cursor, match_chars);
	o_ch = el->el_line.cursor[i];
	if (o_ch == 0)
		return CC_ERROR;
	delta = (size_t)(wcschr(match_chars, o_ch) - match_chars);
	c_ch = match_chars[delta ^ 1];
	count = 1;
	delta = 1 - (delta & 1) * 2;

	for (cp = &el->el_line.cursor[i]; count; ) {
		cp += delta;
		if (cp < el->el_line.buffer || cp >= el->el_line.lastchar)
			return CC_ERROR;
		if (*cp == o_ch)
			count++;
		else if (*cp == c_ch)
			count--;
	}

	el->el_line.cursor = cp;

	if (el->el_chared.c_vcmd.action != NOP) {
		/* NB posix says char under cursor should NOT be deleted
		   for -ve delta - this is different to netbsd vi. */
		if (delta > 0)
			el->el_line.cursor++;
		cv_delfini(el);
		return CC_REFRESH;
	}
	return CC_CURSOR;
}
Ejemplo n.º 16
0
void MakeDir(wchar_t const* dir)
{
	size_t pos = 0;
	size_t len = wcslen(dir);
	while (true)
	{
		//找一段目录名
		size_t dirNameLen = wcscspn(dir + pos, L"/\\");
		if (pos + dirNameLen >= len)
			break;		//最后一段是文件名而非目录名

		if (dirNameLen > 0)
		{
			wchar_t tempBuffer[FILENAME_MAX] = {};
			wcsncpy(tempBuffer, dir,pos + dirNameLen);
			my_wmkdir(tempBuffer);
		}
		pos += (dirNameLen + 1);	//跳过当前段和分隔符
	}
}
Ejemplo n.º 17
0
TimingEvent* TimerEx::GetTimer( LPCWSTR timerId )
{
	if( NULL == timerId )
		return m_Root;

	_ASSERT( "init not called" && (m_pDev != NULL) );

	size_t len = wcslen(timerId);
	size_t seperator = wcscspn( timerId, L"/|\\" );
	if( seperator < len )
	{
		LPWSTR idCopy = new WCHAR[len+1];
		wcscpy_s( idCopy, len+1, timerId );
		idCopy[seperator] = 0;
		TimingEvent* te = m_Root;
		while( te )
		{
			if( !wcscmp(idCopy, te->m_name ) )
			{
				te = te->GetTimerRec( &idCopy[seperator+1] );
				delete[] idCopy;
				return te;
			}
			te = te->m_next;
		}
		delete[] idCopy;
	}
	else
	{
		TimingEvent* te = m_Root;
		while( te )
		{
			if( !wcscmp(timerId, te->m_name ) )
				return te;
			te = te->m_next;
		}
	}
	return NULL;
}
Ejemplo n.º 18
0
// when this function is called we know we're working on a copy of the name, so we can "destruct" it
TimingEvent* TimingEvent::GetTimerRec( LPWSTR timerId ) 
{
	size_t len = wcslen(timerId);
	size_t seperator = wcscspn( timerId, L"/|\\" );
	if( seperator<len )
		timerId[seperator] = 0;

	TimingEvent* te = m_firstChild;
	while( te )
	{
		if( !wcscmp(timerId, te->m_name ) )
		{
			if( seperator<len )
				te = te->GetTimerRec( &timerId[seperator+1] );

			return te;
		}
		te = te->m_next;
	}

	return NULL;
}
Ejemplo n.º 19
0
static TACommandVerdict wcscspn_cmd(TAThread thread,TAInputStream stream)
{
    wchar_t* ws1;
    wchar_t* ws2;
    size_t res;

    // Prepare
    ws1 = (wchar_t*)readPointer(&stream);
    ws2 = (wchar_t*)readPointer(&stream);

    START_TARGET_OPERATION(thread);

    // Execute
    res = wcscspn(ws1, ws2);

    END_TARGET_OPERATION(thread);

    // Response
    writeSize(thread, res);
    sendResponse(thread);

    return taDefaultVerdict;
}
Ejemplo n.º 20
0
TimingEvent* TimingEvent::GetTimer(LPCWSTR timerId)
{
	size_t len = wcslen(timerId);
	size_t seperator = wcscspn( timerId, L"/|\\" );

	if( seperator<len )
	{
		LPWSTR idCopy = new WCHAR[len+1];
		wcscpy_s( idCopy, len+1, timerId );
		idCopy[seperator] = 0;

		TimingEvent* te = m_firstChild;
		while( te )
		{
			if( !wcscmp(idCopy, te->m_name ) )
			{
				te = te->GetTimerRec( &idCopy[seperator+1] );
				delete[] idCopy;
				return te;
			}
			te = te->m_next;
		}

		delete[] idCopy;
	}
	else
	{
		TimingEvent* te = m_firstChild;
		while( te )
		{
			if( !wcscmp(timerId, te->m_name ) )
				return te;
			te = te->m_next;
		}
	}
	return NULL;
}
Ejemplo n.º 21
0
/**
 * Scrobbles a track. Also finds meta data, length and (possibly) album, for
 * the current track.
 */
int Scrobblify::Start(const std::wstring& artist,
                      const std::wstring& track) {
    // Handle currently playing track
    if (current_request_id_ > 0) {
        Stop();
    }

    // Lines are divided into fields terminated by 0x1
    const wchar_t kDelimiterChar = 0x1;
    const wchar_t kDelimiter[] = {kDelimiterChar, _T('\0')};
    const size_t kDelimiterLength = 1;
    const size_t kHashLength = 32;
    const size_t kLongHashLength = 40;

    // Search all the meta-data files available
    for (std::vector<std::wstring>::const_iterator it = metadata_paths_.begin();
            it != metadata_paths_.end();
            ++it) {
        // Go get some meta data
        FILE *metadata_file;

        if (_wfopen_s(&metadata_file, (*it).c_str(), _T("r")) != 0) {
            continue;
        }

        std::wifstream in(metadata_file);
        const size_t kMaxLineLength = 2048;
        wchar_t line[kMaxLineLength];

        // Skip first line (contains "21" for no apparent reason)
        in.getline(line, kMaxLineLength);

        // Skip if file is empty
        if (wcsnlen(line, 1) == 0) {
            in.close();
            continue;
        }

        // Find hash for artist
        wchar_t artist_hash[kHashLength];
        bool artist_hash_found = false;

        for (;
                wcsnlen(line, kMaxLineLength) > 0;
                in.getline(line, kMaxLineLength)) {
            if (wcsncmp(artist.c_str(),
                        &line[kHashLength + kDelimiterLength],
                        artist.size()) == 0) {
                artist_hash_found = true;
                wcsncpy(artist_hash, line, kHashLength);
                break;
            }
        }

        if (!artist_hash_found) {
            in.close();
            continue; // Try next file
        }

        // Skip rest of artist section
        for (in.getline(line, kMaxLineLength);
                wcsnlen(line, kMaxLineLength) > 0;
                in.getline(line, kMaxLineLength)) {}

        in.getline(line, kMaxLineLength); // Skip section separator
        std::wifstream::pos_type album_section_position = in.tellg();

        // Skip albums section -- move to next empty line
        for (;
                wcsnlen(line, kMaxLineLength) > 0;
                in.getline(line, kMaxLineLength)) { }

        // Parse songs section. Each song is formatted like
        //   hash        32 bytes
        //   track
        //   artists     ; split with 0x2
        //   long hash
        //   length
        //   ...
        int length = 0;
        bool track_found = false;
        wchar_t album_hash[kHashLength];

        for (in.getline(line, kMaxLineLength);
                wcsnlen(line, kMaxLineLength) > 0;
                in.getline(line, kMaxLineLength)) {
            if (wcsncmp(track.c_str(),
                        &line[kHashLength + kDelimiterLength],
                        track.size()) == 0) {
                // Skip hash, separator, track, separator.
                wchar_t *p = &line[kHashLength + kDelimiterLength + track.size() +
                                   kDelimiterLength];

                // Match any of the artists
                bool artist_match_found = wcsncmp(artist_hash, p, kHashLength) == 0;

                for (p += kHashLength;
                        *p == 0x2;
                        p += kHashLength + kDelimiterLength) {
                    if (!artist_match_found && // Don't compare if artist has been found
                            wcsncmp(artist_hash, &p[1], kHashLength) == 0) {
                        artist_match_found = true;
                    }
                }

                if (!artist_match_found) {
                    continue;
                }

                p += kDelimiterLength + kLongHashLength + kDelimiterLength;

                // Read track length
                length = _wtoi(p);
                track_found = true;

                // Skip length
                p = wcschr(p, kDelimiterChar);
                p += kDelimiterLength;

                // Skip track number
                p = wcschr(p, kDelimiterChar);
                p += kDelimiterLength;

                // Get album hash
                wcsncpy(album_hash, p, kHashLength);
                break;
            }
        }

        if (!track_found || length <= 0) {
            in.close();
            continue;
        }

        // Get album
        in.seekg(album_section_position); // Seek back to the album section
        std::wstring album;

        for (in.getline(line, kMaxLineLength);
                wcsnlen(line, kMaxLineLength) > 0;
                in.getline(line, kMaxLineLength)) {
            if (wcsncmp(album_hash, line, kHashLength) == 0) {
                size_t album_length = wcscspn(&line[kHashLength + kDelimiterLength],
                                              kDelimiter);
                album.assign(line, kHashLength + kDelimiterLength, album_length);
                break;
            }
        }

        in.close();
        return current_request_id_ = scrob_submitter_.Start(
                                         ToUtf8(artist),
                                         ToUtf8(track),
                                         ToUtf8(album),
                                         "",
                                         length,
                                         scrobble_directory_);
    }

    // No meta-data found; fall back on a five minute track length
    // TODO(liesen): does this violate any AudioScrobbler rules?
    return current_request_id_ = scrob_submitter_.Start(
                                     ToUtf8(artist),
                                     ToUtf8(track),
                                     "",
                                     "",
                                     5 * 60, // five minutes -- more than most songs
                                     scrobble_directory_);
}
Ejemplo n.º 22
0
CUnicodeString CUnicodeString::SpanExcluding(LPCWSTR lpszCharSet)
{
	ASSERT(IsValidString(lpszCharSet));
	return Left(wcscspn(m_Buffer, lpszCharSet));
}
Ejemplo n.º 23
0
Archivo: wcspbrk.c Proyecto: KGG814/AOS
wchar_t *wcspbrk(const wchar_t *s, const wchar_t *b)
{
	s += wcscspn(s, b);
	return *s ? (wchar_t *)s : NULL;
}
Ejemplo n.º 24
0
int scilab_sscanf(wchar_t* _wcsFormat, wchar_t* _wcsData, int _iIterrator, int _iNiter, std::vector<types::InternalType*> *_pITOut)
{
    int i                       = 0;
    int j                       = 0;
    int nbrOfDigit              = 0;
    int dims                    = 2;
    int dimsArray[2]            = {_iNiter, 1};
    BOOL bStar                  = FALSE;
    BOOL bUnsigned              = FALSE;
    BOOL bNegatif               = FALSE;
    BOOL bIgnoredChars          = TRUE;
    int base                    = 0;
    wchar_t wcsLLH              = L' ';
    wchar_t* wcsData            = NULL;
    int sizeOfData              = (int)wcslen(_wcsData);
    int iCountDataRead          = 0;

    wcsData = (wchar_t*)MALLOC((sizeOfData + 1) * sizeof(wchar_t));
    memcpy(wcsData, _wcsData, sizeOfData * sizeof(wchar_t));
    wcsData[sizeOfData] = '\0';

    while (i < (int)wcslen(_wcsFormat))
    {
        while (bIgnoredChars && i < (int)wcslen(_wcsFormat)) // %da%s => 'a' is an ignored char.
        {
            if (wcsData != NULL && wcsData[0] != L'\0' && _wcsFormat[i] == wcsData[0])
            {
                if (_wcsFormat[i] != L' ')
                {
                    i++;
                    wcsData++;
                }
                else
                {
                    while (wcsData[0] == L' ')
                    {
                        wcsData++;
                    }
                    while (_wcsFormat[i] == L' ')
                    {
                        i++;
                    }
                }
            }
            else if ((wcsData == NULL || wcsData[0] == L'\0') && i < (int)wcslen(_wcsFormat) && iCountDataRead == 0 && _pITOut->size() == 0)
            {
                iCountDataRead = -1;
            }
            else
            {
                if (_wcsFormat[i] == L' ')
                {
                    do
                    {
                        i++;
                    }
                    while (i < (int)wcslen(_wcsFormat) && _wcsFormat[i] == L' ');
                }

                if (_wcsFormat[i] != L'%')
                {
                    wcsData = NULL;
                    while (i < (int)wcslen(_wcsFormat) && _wcsFormat[i] != L'%')
                    {
                        i++;
                    }
                }
                break;
            }
        }
        if (i == (int)wcslen(_wcsFormat))
        {
            break;
        }

        if (iswdigit(_wcsFormat[i]))
        {
            nbrOfDigit = wcstol(&_wcsFormat[i], NULL, 10);
            while (iswdigit(_wcsFormat[i]))
            {
                i++;
            }
        }
        else switch (_wcsFormat[i])
            {
                case L' ' :
                case L'\n':
                case L'\t':
                    i++;
                    break;
                case L'%' :
                    i++;
                    bIgnoredChars = FALSE;
                    break;
                case L'*' :
                    bStar = TRUE;
                    i++;
                    break;
                case L'h' :
                case L'l' :
                case L'L' :
                    wcsLLH = _wcsFormat[i];
                    i++;
                    break;
                case L'c' :
                {
                    if (wcsData != NULL && wcsData[0] != L'\0') // If the end of data has not been reached we can get datas.
                    {
                        wchar_t wcSingleData[2];
                        wcSingleData[0] = wcsData[0];
                        wcSingleData[1] = 0;

                        if (!bStar) // If this format is not ignored put the datas found.
                        {
                            if (_iIterrator == 0) // Create and initialize the container only the first time.
                            {
                                types::String* pS = new types::String(dims, dimsArray);
                                for (int k = 0 ; k < pS->getSize(); k++)
                                {
                                    pS->set(k, L"");
                                }
                                _pITOut->push_back(pS);
                            }
                            (*_pITOut)[j]->getAs<types::String>()->set(_iIterrator, wcSingleData);
                            iCountDataRead++;
                        }
                        wcsData++;
                    }
                    else
                    {
                        if (_iIterrator == 0 && !bStar && _iNiter == 1)
                        {
                            _pITOut->push_back(types::Double::Empty());
                        }
                        else
                        {
                            return -10;
                        }
                    }
                    if (!bStar)
                    {
                        j++;
                    }
                    i++;
                    bIgnoredChars = TRUE;
                    bStar = FALSE;
                }
                break;
                case L's' :
                {
                    if (wcsData != NULL && wcsData[0] != L'\0')
                    {
                        wchar_t* wcsSingleData  = NULL;
                        wchar_t* wcsRes         = NULL;
                        wchar_t seps[]          = L" \t\n";
                        int sizeOfCurrentData   = (int)wcslen(wcsData);
                        wchar_t* wcsTemp        = (wchar_t*)MALLOC((sizeOfCurrentData + 1) * sizeof(wchar_t));

                        memcpy(wcsTemp, wcsData, sizeOfCurrentData * sizeof(wchar_t));
                        wcsTemp[sizeOfCurrentData] = L'\0';
                        wcsRes = os_wcstok(wcsTemp, seps, &wcsTemp); // the seps[] found is replaced by the '\0' char.

                        if (wcsTemp == NULL || wcsTemp[0] == L'\0')
                        {
                            wcsData = NULL;
                        }
                        else
                        {
                            wcsData += (wcslen(wcsData) - wcslen(wcsTemp) - 1); // set the pointer on the seps[] and not on the next char.
                        }

                        if (nbrOfDigit) // Get only the numbers of digit indicated in the format. (ex: %2d)
                        {
                            wcsSingleData = (wchar_t*)MALLOC(sizeof(wchar_t) * (nbrOfDigit + 1));
                            memcpy(wcsSingleData, wcsRes, sizeof(wchar_t) * nbrOfDigit);
                            wcsSingleData[nbrOfDigit] = L'\0';
                            nbrOfDigit = 0;
                        }
                        else // Get all data find.
                        {
                            wcsSingleData = wcsRes;
                        }

                        if (!bStar)
                        {
                            if (_iIterrator == 0)
                            {
                                types::String* pS = new types::String(dims, dimsArray);
                                for (int k = 0 ; k < pS->getSize(); k++)
                                {
                                    pS->set(k, L"");
                                }
                                _pITOut->push_back(pS);
                            }
                            (*_pITOut)[j]->getAs<types::String>()->set(_iIterrator, wcsSingleData);
                            iCountDataRead++;
                        }

                        if (nbrOfDigit)
                        {
                            FREE(wcsSingleData);
                        }
                    }
                    else
                    {
                        if (_iIterrator == 0 && !bStar && _iNiter == 1)
                        {
                            _pITOut->push_back(types::Double::Empty());
                        }
                        else
                        {
                            return -10;
                        }
                    }
                    if (!bStar)
                    {
                        j++;
                    }
                    i++;
                    bIgnoredChars = TRUE;
                    bStar = FALSE;
                }
                break;
                case L'[' :
                {
                    if (wcsData != NULL && wcsData[0] != L'\0')
                    {
                        wchar_t* wcsInside          = NULL;
                        wchar_t* wcsCpyFormat       = NULL;
                        unsigned int iPos           = 0;
                        wchar_t* wcsSingleData      = NULL;
                        wchar_t* wcsRes             = NULL;
                        wchar_t* wscToFind          = NULL;
                        BOOL bInv                   = FALSE;

                        i++;
                        wcsCpyFormat = (wchar_t*)MALLOC((wcslen(_wcsFormat) - i + 1) * sizeof(wchar_t));
                        memcpy(wcsCpyFormat, &_wcsFormat[i], (wcslen(_wcsFormat) - i) * sizeof(wchar_t));
                        wcsCpyFormat[wcslen(_wcsFormat) - i] = L'\0';

                        wcsInside = os_wcstok(wcsCpyFormat, L"]", &wcsCpyFormat);
                        i += (int)wcslen(wcsInside) + 1; // +1 => ]

                        wscToFind = findChars(wcsInside, &bInv);
                        if (wscToFind == NULL)
                        {
                            // MALLOC error
                            return -10;
                        }

                        if (bInv)
                        {
                            iPos = (int)wcscspn(wcsData, wscToFind);
                        }
                        else
                        {
                            iPos = (int)wcsspn(wcsData, wscToFind);
                        }

                        if (iPos == 0)
                        {
                            // The string begins with a character which is not in wscToFind
                            if (_iIterrator == 0 && !bStar && _iNiter == 1)
                            {
                                _pITOut->push_back(types::Double::Empty());
                            }
                            else
                            {
                                return -10;
                            }
                        }
                        else
                        {
                            wcsRes = (wchar_t*)MALLOC((iPos + 1) * sizeof(wchar_t));
                            memcpy(wcsRes, wcsData, iPos * sizeof(wchar_t));
                            wcsRes[iPos] = '\0';

                            FREE(wcsInside);

                            if (nbrOfDigit)
                            {
                                wcsSingleData = (wchar_t*)MALLOC(sizeof(wchar_t) * (nbrOfDigit + 1));
                                memcpy(wcsSingleData, wcsRes, sizeof(wchar_t) * nbrOfDigit);
                                wcsSingleData[nbrOfDigit] = L'\0';
                                wcsData += nbrOfDigit;
                            }
                            else
                            {
                                wcsSingleData = wcsRes;
                                wcsData += iPos;
                            }
                        }

                        if (!bStar)
                        {
                            if (_iIterrator == 0)
                            {
                                types::String* pS = new types::String(dims, dimsArray);
                                for (int k = 0 ; k < pS->getSize(); k++)
                                {
                                    pS->set(k, L"");
                                }
                                _pITOut->push_back(pS);
                            }
                            if (wcsSingleData != NULL)
                            {
                                (*_pITOut)[j]->getAs<types::String>()->set(_iIterrator, wcsSingleData);
                                iCountDataRead++;
                            }
                        }

                        if (nbrOfDigit)
                        {
                            FREE(wcsSingleData);
                        }
                    }
                    else
                    {
                        if (_iIterrator == 0 && !bStar && _iNiter == 1)
                        {
                            _pITOut->push_back(types::Double::Empty());
                        }
                        else
                        {
                            return -10;
                        }
                    }
                    if (!bStar)
                    {
                        j++;
                    }
                    bIgnoredChars   = TRUE;
                    nbrOfDigit      = 0;
                    bStar           = FALSE;
                }
                break;
                case L'x' :
                case L'X' :
                    base += 6; // 6 + 2 + 8 = 16 // Compute the base of data to get.
                case L'u' :
                    if (base == 0)
                    {
                        bUnsigned = TRUE;    // unsigned int
                    }
                case L'i' :
                case L'd' :
                    base += 2; // 2 + 8 = 10
                case L'o' :
                    base += 8; // 8 = 8 :D
                    {
                        if (wcsData != NULL && wcsData[0] != L'\0')
                        {
                            long int iSingleData = 0;
                            while (wcsData[0] == L' ')
                            {
                                wcsData++;
                            }
                            if (nbrOfDigit)
                            {
                                wchar_t* number = NULL;
                                if (wcslen(wcsData) < nbrOfDigit)
                                {
                                    nbrOfDigit = (int)wcslen(wcsData);
                                }

                                number = (wchar_t*)MALLOC((nbrOfDigit + 1) * sizeof(wchar_t));
                                memcpy(number, wcsData, nbrOfDigit * sizeof(wchar_t));
                                number[nbrOfDigit] = L'\0';
                                iSingleData = wcstoul(number, &number, base);
                                if ((iSingleData == 0) && (number[0] == wcsData[0]))
                                {
                                    if (_iIterrator == 0 && !bStar && _iNiter == 1)
                                    {
                                        wcsData = NULL;
                                        _pITOut->push_back(types::Double::Empty());
                                        bStar = TRUE;
                                    }
                                    else
                                    {
                                        return -10;
                                    }
                                }
                                if (number == NULL)
                                {
                                    wcsData += nbrOfDigit;
                                }
                                else
                                {
                                    wcsData += (nbrOfDigit - wcslen(number));
                                }
                                nbrOfDigit = 0;
                            }
                            else
                            {
                                wchar_t temp = wcsData[0];
                                iSingleData = wcstoul(wcsData, &wcsData, base);
                                if ((iSingleData == 0) && (temp == wcsData[0]))
                                {
                                    if (_iIterrator == 0 && !bStar && _iNiter == 1)
                                    {
                                        wcsData = NULL;
                                        _pITOut->push_back(types::Double::Empty());
                                        bStar = TRUE;
                                    }
                                    else
                                    {
                                        return -10;
                                    }
                                }
                            }

                            if (!bStar)
                            {
                                if (_iIterrator == 0)
                                {
                                    switch (wcsLLH)
                                    {
                                        case L'h' :
                                        {
                                            if (bUnsigned)
                                            {
                                                types::UInt16* pUInt16 = new types::UInt16(dims, dimsArray);
                                                for (int k = 0; k < pUInt16->getSize(); k++)
                                                {
                                                    pUInt16->set(k, 0);
                                                }
                                                _pITOut->push_back(pUInt16);
                                            }
                                            else
                                            {
                                                types::Int16* pInt16 = new types::Int16(dims, dimsArray);
                                                for (int k = 0; k < pInt16->getSize(); k++)
                                                {
                                                    pInt16->set(k, 0);
                                                }
                                                _pITOut->push_back(pInt16);
                                            }
                                        }
                                        break;
                                        case L'l' :
                                        case L'L' :
                                        {
                                            if (bUnsigned)
                                            {
                                                types::UInt64* pUInt64 = new types::UInt64(dims, dimsArray);
                                                for (int k = 0; k < pUInt64->getSize(); k++)
                                                {
                                                    pUInt64->set(k, 0);
                                                }
                                                _pITOut->push_back(pUInt64);
                                            }
                                            else
                                            {
                                                types::Int64* pInt64 = new types::Int64(dims, dimsArray);
                                                for (int k = 0; k < pInt64->getSize(); k++)
                                                {
                                                    pInt64->set(k, 0);
                                                }
                                                _pITOut->push_back(pInt64);
                                            }
                                        }
                                        break;
                                        default :
                                        {
                                            if (bUnsigned)
                                            {
                                                types::UInt32* pUInt32 = new types::UInt32(dims, dimsArray);
                                                for (int k = 0; k < pUInt32->getSize(); k++)
                                                {
                                                    pUInt32->set(k, 0);
                                                }
                                                _pITOut->push_back(pUInt32);
                                            }
                                            else
                                            {
                                                types::Int32* pInt32 = new types::Int32(dims, dimsArray);
                                                for (int k = 0; k < pInt32->getSize(); k++)
                                                {
                                                    pInt32->set(k, 0);
                                                }
                                                _pITOut->push_back(pInt32);
                                            }
                                        }
                                    }
                                }
                                switch (wcsLLH)
                                {
                                    case L'h' :
                                        if (bUnsigned)
                                        {
                                            (*_pITOut)[j]->getAs<types::UInt16>()->set(_iIterrator, static_cast<unsigned short int>(iSingleData));
                                            iCountDataRead++;
                                        }
                                        else
                                        {
                                            (*_pITOut)[j]->getAs<types::Int16>()->set(_iIterrator, static_cast<short int>(iSingleData));
                                            iCountDataRead++;
                                        }
                                        break;
                                    case L'l' :
                                    case L'L' :
                                        if (bUnsigned)
                                        {
                                            (*_pITOut)[j]->getAs<types::UInt64>()->set(_iIterrator, iSingleData);
                                            iCountDataRead++;
                                        }
                                        else
                                        {
                                            (*_pITOut)[j]->getAs<types::Int64>()->set(_iIterrator, static_cast<long int>(iSingleData));
                                            iCountDataRead++;
                                        }
                                        break;
                                    default :
                                        if (bUnsigned)
                                        {
                                            (*_pITOut)[j]->getAs<types::UInt32>()->set(_iIterrator, static_cast<unsigned int>(iSingleData));
                                            iCountDataRead++;
                                        }
                                        else
                                        {
                                            (*_pITOut)[j]->getAs<types::Int32>()->set(_iIterrator, static_cast<int>(iSingleData));
                                            iCountDataRead++;
                                        }
                                }
                            }
                        }
                        else
                        {
                            if (_iIterrator == 0 && !bStar && _iNiter == 1)
                            {
                                _pITOut->push_back(types::Double::Empty());
                            }
                            else
                            {
                                return -10;
                            }
                        }
                        if (!bStar)
                        {
                            j++;
                        }
                        wcsLLH          = L' ';
                        bIgnoredChars   = TRUE;
                        bUnsigned       = FALSE;
                        bNegatif        = FALSE;
                        bStar           = FALSE;
                        base            = 0;
                        i++;
                    }
                    break;
                case L'e' :
                case L'E' :
                case L'g' :
                case L'G' :
                case L'f' :
                {
                    if (wcsData != NULL && wcsData[0] != L'\0')
                    {
                        double dSingleData  = 0;
                        BOOL bSigne         = FALSE;
                        while (wcsData[0] == L' ')
                        {
                            wcsData++;
                        }
                        if (nbrOfDigit)
                        {
                            int iSizeRead   = 0;
                            wchar_t* number = NULL;
                            wchar_t* next   = NULL;
                            if (wcslen(wcsData) < nbrOfDigit)
                            {
                                nbrOfDigit = (int)wcslen(wcsData);
                            }
                            number = (wchar_t*)MALLOC((nbrOfDigit + 1) * sizeof(wchar_t));
                            memcpy(number, wcsData, nbrOfDigit * sizeof(wchar_t));
                            number[nbrOfDigit] = L'\0';
                            dSingleData = wcstod(number, &next);
                            if (next)
                            {
                                iSizeRead = nbrOfDigit - (int)wcslen(next);
                            }
                            else
                            {
                                iSizeRead = nbrOfDigit;
                            }
                            if ((dSingleData == 0) && (number[0] == next[0]))
                            {
                                if (_iIterrator == 0 && !bStar && _iNiter == 1)
                                {
                                    wcsData = NULL;
                                    _pITOut->push_back(types::Double::Empty());
                                    bStar = TRUE;
                                }
                                else
                                {
                                    return -10;
                                }
                            }
                            wcsData += iSizeRead;
                            FREE(number);
                            nbrOfDigit = 0;
                        }
                        else
                        {
                            int iLenData = (int)wcslen(wcsData);
                            dSingleData = wcstod(wcsData, &wcsData);
                            if ((dSingleData == 0) && (iLenData == wcslen(wcsData)))
                            {
                                if (_iIterrator == 0 && !bStar && _iNiter == 1)
                                {
                                    wcsData = NULL;
                                    _pITOut->push_back(types::Double::Empty());
                                    bStar = TRUE;
                                }
                                else
                                {
                                    return -10;
                                }
                            }
                        }

                        if (!bStar)
                        {
                            if (_iIterrator == 0)
                            {
                                types::Double* pD = new types::Double(dims, dimsArray);
                                for (int k = 0 ; k < pD->getSize(); k++)
                                {
                                    pD->set(k, 0);
                                }
                                _pITOut->push_back(pD);
                            }
                            (*_pITOut)[j]->getAs<types::Double>()->set(_iIterrator, dSingleData);
                            iCountDataRead++;
                        }
                    }
                    else
                    {
                        if (_iIterrator == 0 && !bStar && _iNiter == 1)
                        {
                            _pITOut->push_back(types::Double::Empty());
                        }
                        else
                        {
                            return -10;
                        }
                    }
                    if (!bStar)
                    {
                        j++;
                    }
                    i++;
                    bIgnoredChars = TRUE;
                    bStar = FALSE;
                }
                break;
                case L'n' :
                {
                    double dSingleData = -1;
                    if (_iIterrator == 0 && !bStar)
                    {
                        types::Double* pD = new types::Double(dims, dimsArray);
                        for (int k = 0 ; k < pD->getSize(); k++)
                        {
                            pD->set(k, 0);
                        }
                        _pITOut->push_back(pD);
                    }

                    if (wcsData == NULL || wcsData[0] == L'\0')
                    {
                        dSingleData = (double)sizeOfData;
                    }
                    else
                    {
                        dSingleData = (double)sizeOfData - (double)wcslen(wcsData);
                    }

                    if (!bStar)
                    {
                        (*_pITOut)[j]->getAs<types::Double>()->set(_iIterrator, dSingleData);
                        j++;
                    }

                    i++;
                    bIgnoredChars = TRUE;
                    bStar = FALSE;
                }
                break;
                default :
                    printf("format read : %c\n", _wcsFormat[i]);
                    return -10;
            }
    }

    return iCountDataRead;
}
Ejemplo n.º 25
0
int main()
{
    mbstate_t mb = {0};
    size_t s = 0;
    tm tm = {0};
    wint_t w = 0;
    ::FILE* fp = 0;
    __darwin_va_list va;
    char* ns = 0;
    wchar_t* ws = 0;
    static_assert((std::is_same<decltype(fwprintf(fp, L"")), int>::value), "");
    static_assert((std::is_same<decltype(fwscanf(fp, L"")), int>::value), "");
    static_assert((std::is_same<decltype(swprintf(ws, s, L"")), int>::value), "");
    static_assert((std::is_same<decltype(swscanf(L"", L"")), int>::value), "");
    static_assert((std::is_same<decltype(vfwprintf(fp, L"", va)), int>::value), "");
    static_assert((std::is_same<decltype(vfwscanf(fp, L"", va)), int>::value), "");
    static_assert((std::is_same<decltype(vswprintf(ws, s, L"", va)), int>::value), "");
    static_assert((std::is_same<decltype(vswscanf(L"", L"", va)), int>::value), "");
    static_assert((std::is_same<decltype(vwprintf(L"", va)), int>::value), "");
    static_assert((std::is_same<decltype(vwscanf(L"", va)), int>::value), "");
    static_assert((std::is_same<decltype(wprintf(L"")), int>::value), "");
    static_assert((std::is_same<decltype(wscanf(L"")), int>::value), "");
    static_assert((std::is_same<decltype(fgetwc(fp)), wint_t>::value), "");
    static_assert((std::is_same<decltype(fgetws(ws, 0, fp)), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(fputwc(L' ', fp)), wint_t>::value), "");
    static_assert((std::is_same<decltype(fputws(L"", fp)), int>::value), "");
    static_assert((std::is_same<decltype(fwide(fp, 0)), int>::value), "");
    static_assert((std::is_same<decltype(getwc(fp)), wint_t>::value), "");
    static_assert((std::is_same<decltype(getwchar()), wint_t>::value), "");
    static_assert((std::is_same<decltype(putwc(L' ', fp)), wint_t>::value), "");
    static_assert((std::is_same<decltype(putwchar(L' ')), wint_t>::value), "");
    static_assert((std::is_same<decltype(ungetwc(L' ', fp)), wint_t>::value), "");
    static_assert((std::is_same<decltype(wcstod(L"", (wchar_t**)0)), double>::value), "");
    static_assert((std::is_same<decltype(wcstof(L"", (wchar_t**)0)), float>::value), "");
    static_assert((std::is_same<decltype(wcstold(L"", (wchar_t**)0)), long double>::value), "");
    static_assert((std::is_same<decltype(wcstol(L"", (wchar_t**)0, 0)), long>::value), "");
    static_assert((std::is_same<decltype(wcstoll(L"", (wchar_t**)0, 0)), long long>::value), "");
    static_assert((std::is_same<decltype(wcstoul(L"", (wchar_t**)0, 0)), unsigned long>::value), "");
    static_assert((std::is_same<decltype(wcstoull(L"", (wchar_t**)0, 0)), unsigned long long>::value), "");
    static_assert((std::is_same<decltype(wcscpy(ws, L"")), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wcsncpy(ws, L"", s)), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wcscat(ws, L"")), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wcsncat(ws, L"", s)), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wcscmp(L"", L"")), int>::value), "");
    static_assert((std::is_same<decltype(wcscoll(L"", L"")), int>::value), "");
    static_assert((std::is_same<decltype(wcsncmp(L"", L"", s)), int>::value), "");
    static_assert((std::is_same<decltype(wcsxfrm(ws, L"", s)), size_t>::value), "");
    static_assert((std::is_same<decltype(wcschr((wchar_t*)0, L' ')), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wcscspn(L"", L"")), size_t>::value), "");
    static_assert((std::is_same<decltype(wcslen(L"")), size_t>::value), "");
    static_assert((std::is_same<decltype(wcspbrk((wchar_t*)0, L"")), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wcsrchr((wchar_t*)0, L' ')), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wcsspn(L"", L"")), size_t>::value), "");
    static_assert((std::is_same<decltype(wcsstr((wchar_t*)0, L"")), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wcstok(ws, L"", (wchar_t**)0)), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wmemchr((wchar_t*)0, L' ', s)), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wmemcmp(L"", L"", s)), int>::value), "");
    static_assert((std::is_same<decltype(wmemcpy(ws, L"", s)), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wmemmove(ws, L"", s)), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wmemset(ws, L' ', s)), wchar_t*>::value), "");
    static_assert((std::is_same<decltype(wcsftime(ws, s, L"", &tm)), size_t>::value), "");
    static_assert((std::is_same<decltype(btowc(0)), wint_t>::value), "");
    static_assert((std::is_same<decltype(wctob(w)), int>::value), "");
    static_assert((std::is_same<decltype(mbsinit(&mb)), int>::value), "");
    static_assert((std::is_same<decltype(mbrlen("", s, &mb)), size_t>::value), "");
    static_assert((std::is_same<decltype(mbrtowc(ws, "", s, &mb)), size_t>::value), "");
    static_assert((std::is_same<decltype(wcrtomb(ns, L' ', &mb)), size_t>::value), "");
    static_assert((std::is_same<decltype(mbsrtowcs(ws, (const char**)0, s, &mb)), size_t>::value), "");
    static_assert((std::is_same<decltype(wcsrtombs(ns, (const wchar_t**)0, s, &mb)), size_t>::value), "");
}
Ejemplo n.º 26
0
/* Implementation based on [1].

[1] http://www.kernel.org/doc/man-pages/online/pages/man3/getopt.3.html
*/
int getopt_long(int argc, wchar_t* const argv[], const wchar_t* optstring,
  const struct option* longopts, int* longindex) {
  const struct option* o = longopts;
  const struct option* match = NULL;
  int num_matches = 0;
  size_t argument_name_length = 0;
  const wchar_t* current_argument = NULL;
  int retval = -1;

  optarg = NULL;
  optopt = 0;

  if (optind >= argc)
    return -1;

  if (wcslen(argv[optind]) < 3 || wcsncmp(argv[optind], L"--", 2) != 0)
    return getopt(argc, argv, optstring);

  /* It's an option; starts with -- and is longer than two chars. */
  current_argument = argv[optind] + 2;
  argument_name_length = wcscspn(current_argument, L"=");
  for (; o->name; ++o) {
    if (wcsncmp(o->name, current_argument, argument_name_length) == 0) {
      match = o;
      ++num_matches;
      /* if it's an exact match, i.e. there was no '=' in it, this is the one */
      if (wcscmp(o->name, current_argument) == 0)
          break;
    }
  }

  if (num_matches == 1) {
    /* If longindex is not NULL, it points to a variable which is set to the
index of the long option relative to longopts. */
    if (longindex)
      *longindex = (match - longopts);

    /* If flag is NULL, then getopt_long() shall return val.
Otherwise, getopt_long() returns 0, and flag shall point to a variable
which shall be set to val if the option is found, but left unchanged if
the option is not found. */
    if (match->flag)
      *(match->flag) = match->val;

    retval = match->flag ? 0 : match->val;

    if (match->has_arg != no_argument) {
      optarg = wcschr(argv[optind], '=');
      if (optarg != NULL)
        ++optarg;

      if (match->has_arg == required_argument) {
        /* Only scan the next argv for required arguments. Behavior is not
specified, but has been observed with Ubuntu and Mac OSX. */
        if (optarg == NULL && ++optind < argc) {
          optarg = argv[optind];
        }

        if (optarg == NULL)
          retval = ':';
      }
    } else if (wcschr(argv[optind], '=')) {
      /* An argument was provided to a non-argument option.
I haven't seen this specified explicitly, but both GNU and BSD-based
implementations show this behavior.
*/
      retval = '?';
    }
  } else {
    /* Unknown option or ambiguous match. */
    retval = '?';
  }

  ++optind;
  return retval;
}
///
/// Find the operands for the instruction for x86 and x64
///
void
Findx86_x64Operands( INSTRUCTION *pInstruction, const INSTRUCTION_INFO& objInstructionInfo, PCWSTR *ppwzRegisters )
{
	// Set the implicit operands
	const OPERAND *pOperands = (const OPERAND *) objInstructionInfo.arrImplicitSourceRegisters;

	while( (pOperands != NULL) && pOperands->pwzOperand != NULL )
	{
		pInstruction->setSourceRegisters.insert( *pOperands );
		pOperands++;
	}

	pOperands = (const OPERAND *) objInstructionInfo.arrImplicitDestinationRegisters;

	while( (pOperands != NULL) && pOperands->pwzOperand != NULL )
	{
		pInstruction->setDestinationRegisters.insert( *pOperands );
		pOperands++;
	}

	pOperands = (const OPERAND *) objInstructionInfo.arrImplicitDestinationPointerRegisters;

	while( (pOperands != NULL) && pOperands->pwzOperand != NULL )
	{
		pInstruction->setDestinationPointerRegisters.insert( *pOperands );
		pOperands++;
	}

	pOperands = (const OPERAND *) objInstructionInfo.arrImplicitPassedOrReturnedRegisters;

	while( (pOperands != NULL) && pOperands->pwzOperand != NULL )
	{
		pInstruction->setPassedOrReturnedRegisters.insert( *pOperands );
		pOperands++;
	}

	if( objInstructionInfo.eOperandClassification == NO_OPERANDS )
	{
		return;
	}

	// Set our search rules. Note that we have some special case code to handle EBP and ESP references, because we 
	// want to be able to track those. To do that, we end up with special monitoring flags and an extra backwards looking
	// operand pointer.
	bool fInSource = !HAS_DEST_OPERANDS( objInstructionInfo.eOperandClassification ) || HAS_OPERAND_ORDER_REVERSED( objInstructionInfo.eOperandClassification );
	bool fInIndirectReference = false;
	bool fInMonitoredPointerReference = false;
	PCWSTR pwzMonitoredPointerOperand = NULL;

	PCWSTR pwzOperand = pInstruction->pwzArguments;
	PCWSTR pwzNextOperand = NULL;
	size_t cchOperand;
	WCHAR chDelimiter;

	while( FindNextOperand( pwzOperand, L"[], :+-*", &pwzNextOperand, &cchOperand, &chDelimiter ) )
	{
		// Prepare for the next iteration
		PCWSTR pwzCurrentOperand = pwzOperand;
		pwzOperand = pwzNextOperand;

		// Cache state information for this iteration
		bool fWasInIndirectReference = fInIndirectReference;
		bool fWasInSource = fInSource;

		// Check the delimiter we found, because it can change things
		switch( chDelimiter )
		{
			case ',':
				{
					if( HAS_OPERAND_ORDER_REVERSED( objInstructionInfo.eOperandClassification ) )
					{
						fInSource = !HAS_DEST_OPERANDS( objInstructionInfo.eOperandClassification );
					}
					else
					{
						fInSource = HAS_SOURCE_OPERANDS( objInstructionInfo.eOperandClassification );
					}
				}
				break;

			case '[':
				fInIndirectReference = true;
				break;

			case ']':
				fInIndirectReference = false;

				if( fInMonitoredPointerReference )
				{
					OPERAND objOperand;
					
					objOperand.pwzOperand = pwzMonitoredPointerOperand;
					objOperand.cchOperand = (pwzCurrentOperand - pwzMonitoredPointerOperand) + cchOperand;
					
					if( fWasInSource )
					{
						pInstruction->setSourceRegisters.insert( objOperand );
					}
					else
					{
						// If the destination operand is flagged as being unaffected by the instruction, don't add it
						// to the destination register set
						if( !HAS_DEST_OPERAND_AS_UNAFFECTED( objInstructionInfo.eOperandClassification ) )
						{
							pInstruction->setDestinationRegisters.insert( objOperand );
						}

						// If the destination is flagged as being an implied source register, we add it to the 
						// implied source registers as well
						if( HAS_DEST_OPERAND_AS_IMPLIED_SOURCE( objInstructionInfo.eOperandClassification ) )
						{
							pInstruction->setSourceRegisters.insert( objOperand );
						}
					}

					// We additionally tag registers that were explicitly defined, rather than implicitly defined
					pInstruction->setExplicitRegisters.insert( objOperand );

					// And we tag compound registers because we want to be able to invalidate them 
					// if the indexing registers are changed
					if( wcscspn( objOperand.pwzOperand, L", :+-*" ) < objOperand.cchOperand )
					{
						pInstruction->setCompoundRegisters.insert( objOperand );
					}

					fInMonitoredPointerReference = false;
					pwzMonitoredPointerOperand = NULL;

					// And we're done, since we've added the pointer reference as a logical register
					continue;
				}
				break;

			case ':':
				continue;
		}

		// Continue if we don't have any actual operand
		if( cchOperand == 0 )
		{
			continue;
		}

		// Otherwise, we have to check the operand found to see if we are going to add it to the list
		if( IsStringInSet( pwzCurrentOperand, cchOperand, X64_X86_EXCLUDED_OPERANDS ) )
		{
			fInMonitoredPointerReference = false;
			pwzMonitoredPointerOperand = NULL;
			continue;
		}

		/// Skip the numbers
		if( iswdigit( *pwzCurrentOperand ) )
		{
			continue;
		}

		// Skip items in parentheses 
		if( *pwzCurrentOperand == '(' )
		{
			fInMonitoredPointerReference = false;
			pwzMonitoredPointerOperand = NULL;
			continue;
		}

		// Skip anything that isn't a register
		if( !IsStringInSet( pwzCurrentOperand, cchOperand, ppwzRegisters ) )
		{
			continue;
		}

		// Check to see if this is a monitored register (for local variable references)
		if( fInIndirectReference &&
			(pwzCurrentOperand[cchOperand-1] == 'p') && (pwzMonitoredPointerOperand == NULL) &&
			((chDelimiter == '+') || (chDelimiter == '-')) )
		{
			fInMonitoredPointerReference = true;
			pwzMonitoredPointerOperand = pwzCurrentOperand;
		}
		else
		{
			fInMonitoredPointerReference = false;
			pwzMonitoredPointerOperand = NULL;
		}

		// Add the register
		OPERAND objOperand;
		
		objOperand.pwzOperand = pwzCurrentOperand;
		objOperand.cchOperand = cchOperand;

		if( fWasInSource )
		{
			pInstruction->setSourceRegisters.insert( objOperand );
		}
		else
		{
			// If the destination operand is flagged as being unaffected by the instruction, don't add it
			// to the destination register set
			if( !HAS_DEST_OPERAND_AS_UNAFFECTED( objInstructionInfo.eOperandClassification ) )
			{
				if( fWasInIndirectReference || !HAS_DEST_REGISTERS( objInstructionInfo.eOperandClassification) )
				{
					pInstruction->setDestinationPointerRegisters.insert( objOperand );
				}
				else
				{
					pInstruction->setDestinationRegisters.insert( objOperand );
				}
			}

			// If the destination is flagged as being an implied source register, we add it to the 
			// implied source registers as well
			if( HAS_DEST_OPERAND_AS_IMPLIED_SOURCE( objInstructionInfo.eOperandClassification ) )
			{
				pInstruction->setSourceRegisters.insert( objOperand );
			}
		}

		// We additionally tag registers that were explicitly defined, rather than implicitly defined
		pInstruction->setExplicitRegisters.insert( objOperand );
	}
}
Ejemplo n.º 28
0
/* allocate and fill the file_search_data */
file_search_data* create_file_search_data(rsh_tchar** paths, size_t count, int max_depth)
{
	size_t i;

	file_search_data* data = (file_search_data*)rsh_malloc(sizeof(file_search_data));
	memset(data, 0, sizeof(file_search_data));
	rsh_blocks_vector_init(&data->root_files);
	data->max_depth = max_depth;

#ifdef _WIN32
	/* expand wildcards and fill the root_files */
	for (i = 0; i < count; i++)
	{
		int added = 0;
		size_t length, index;
		wchar_t* path = paths[i];
		wchar_t* p = wcschr(path, L'\0') - 1;

		/* strip trailing '\','/' symbols (if not preceded by ':') */
		for (; p > path && IS_PATH_SEPARATOR_W(*p) && p[-1] != L':'; p--) *p = 0;

		/* Expand a wildcard in the current file path and store results into data->root_files.
		 * If a wildcard is not found then just the file path is stored.
		 * NB, only wildcards in the last filename of the path are expanded. */

		length = p - path + 1;
		index = wcscspn(path, L"*?");

		if (index < length && wcscspn(path + index, L"/\\") >= (length - index))
		{
			/* a wildcard is found without a directory separator after it */
			wchar_t* parent;
			WIN32_FIND_DATAW d;
			HANDLE handle;

			/* find a directory separator before the file name */
			for (; index > 0 && !IS_PATH_SEPARATOR(path[index]); index--);
			parent = (IS_PATH_SEPARATOR(path[index]) ? path : 0);

			handle = FindFirstFileW(path, &d);
			if (INVALID_HANDLE_VALUE != handle)
			{
				do {
					file_t file;
					int failed;
					if (IS_CURRENT_OR_PARENT_DIRW(d.cFileName)) continue;

					memset(&file, 0, sizeof(file));
					file.wpath = make_pathw(parent, index + 1, d.cFileName);
					if (!file.wpath) continue;

					/* skip directories if not in recursive mode */
					if (data->max_depth == 0 && (d.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;

					/* convert file name */
					file.path = wchar_to_cstr(file.wpath, WIN_DEFAULT_ENCODING, &failed);
					if (!failed) {
						failed = (file_statw(&file) < 0);
					}

					/* quietly skip unconvertible file names */
					if (!file.path || failed) {
						if (failed) {
							data->errors_count++;
						}
						free(file.path);
						free(file.wpath);
						continue;
					}

					/* fill the file information */
					file.mode |= FILE_IFROOT;
					add_root_file(data, &file);
					added++;
				} while (FindNextFileW(handle, &d));
				FindClose(handle);
			} else {
				/* report error on the specified wildcard */
				char * cpath = wchar_to_cstr(path, WIN_DEFAULT_ENCODING, NULL);
				set_errno_from_last_file_error();
				log_file_error(cpath);
				free(cpath);
				data->errors_count++;
			}
		}
		else
		{
			int failed;
			file_t file;
			memset(&file, 0, sizeof(file));

			/* if filepath is a dash string "-" */
			if ((path[0] == L'-' && path[1] == L'\0'))
			{
				file.mode = FILE_IFSTDIN;
				file.path = rsh_strdup("(stdin)");
			} else {
				file.path = wchar_to_cstr(path, WIN_DEFAULT_ENCODING, &failed);
				if (failed) {
					log_error(_("Can't convert the path to local encoding: %s\n"), file.path);
					free(file.path);
					data->errors_count++;
					continue;
				}
				file.wpath = path;
				if (file_statw(&file) < 0) {
					log_file_error(file.path);
					free(file.path);
					data->errors_count++;
					continue;
				}
			}

			/* mark the file as obtained from the command line */
			file.mode |= FILE_IFROOT;
			file.wpath = rsh_wcsdup(path);
			add_root_file(data, &file);
		}
	} /* for */
#else
	/* copy file paths */
	for (i = 0; i < count; i++)
	{
		file_t file;
		file_init(&file, paths[i], 0);

		if (IS_DASH_STR(file.path))
		{
			file.mode = FILE_IFSTDIN;
		}
		else if (file_stat2(&file, USE_LSTAT) < 0) {
			log_file_error(file.path);
			file_cleanup(&file);
			data->errors_count++;
			continue;
		}

		file.mode |= FILE_IFROOT;
		add_root_file(data, &file);
	}
#endif
	return data;
}
Ejemplo n.º 29
0
CCOMStringW CCOMStringW::SpanExcluding(const WCHAR*  lpszCharSet) 
{
	ATLASSERT(lpszCharSet != NULL);
	ATLASSERT(::IsBadStringPtrW(lpszCharSet, -1) == 0);
	return Left(wcscspn(m_pszString, lpszCharSet));
}
Ejemplo n.º 30
0
static int
wrap(wchar_t *prefix, wchar_t *suffix, int indent_len, wchar_t *str)
{
	int	len, n, col;
	int	maxlen, tmpcol;
	wchar_t	*p, *pw, *ppw;
	static const wchar_t	eol[] = {L'\r', L'\n', L'\0'};

	/*
	 * Display the initial stuff followed by a colon.
	 */
	if ((len = wscol(suffix)))
		n = fprintf(stderr, gettext("%*ws: %ws: "),
			indent_len - len - 2, prefix, suffix);
	else
		n = fprintf(stderr, gettext("%*ws: "), indent_len, prefix);
	if (n <= 0)
		return (-1);

	maxlen = LINE_LEN - indent_len - 1;

	/* Check for bogus indent_len */
	if (maxlen < 1) {
		return (-1);
	}

	/*
	 * Loop once for each line of the string to display.
	 */
	for (p = str; *p; ) {

		/*
		 * Display the next "len" bytes of the string, where
		 * "len" is the smallest of:
		 *
		 *	- LINE_LEN
		 *	- # bytes before control character
		 *	- # bytes left in string
		 *
		 */

		len = wcscspn(p, eol);
		/* calc how many columns the string will take */
		col = wcswidth(p, len);
		if (col > maxlen) {
			/*
			 * How many characters fit into our desired line length
			 */
			pw = p;
			tmpcol = 0;
			while (*pw) {
				if (iswprint(*pw))
					tmpcol += wcwidth(*pw);
				if (tmpcol > maxlen)
					break;
				else
					pw++;
			}
			/*
			 * At this point, pw may point to:
			 * A null character:  EOL found (should never happen, though)
			 * The character that just overruns the maxlen.
			 */
			if (!*pw) {
				/*
				 * Found a EOL.
				 * This should never happen.
				 */
				len = pw - p;
				goto printline;
			}
			ppw = pw;
			/*
			 * Don't split words
			 *
			 * Bugid 4202307 - liblpoam in lp internal library doesn't
			 * handle multibyte character.
			 */
			while (pw > p) {
				if (iswspace(*pw) ||
				    (wdbindf(*(pw - 1), *pw, 1) < 5)) {
					break;
				} else {
					pw--;
				}
			}
			if (pw != p) {
				len = pw - p;
			} else {
				/*
				 * Failed to find the best place to fold.
				 * So, prints as much characters as maxlen allows
				 */
				len = ppw - p;
			}
		}

printline:
		for (n = 0; n < len; n++, p++) {
			if (iswprint(*p)) {
				if (fputwc(*p, stderr) == WEOF) {
					return (-1);
				}
			}
		}

		/*
		 * If we displayed up to a control character,
		 * put out the control character now; otherwise,
		 * put out a newline unless we've put out all
		 * the text.
		 */

		if (*p == L'\r' || *p == L'\n') {
			while (*p == L'\r' || *p == L'\n') {
				if (fputwc(*p, stderr) == WEOF)
					return (-1);
				p++;
			}
		} else if (*p) {
			if (fputwc(L'\n', stderr) == WEOF)
				return (-1);
		}

		while (iswspace(*p))
			p++;

		/*
		 * If the loop won't end this time (because we
		 * have more stuff to display) put out leading
		 * blanks to align the next line with the previous
		 * lines.
		 */
		if (*p) {
			for (n = 0; n < indent_len + 2; n++)
				(void) fputwc(L' ', stderr);
		}
	}

	return (1);
}