Example #1
0
bool CCCrypto::cbc_encrypt(const char *pBegin, const char *pEnd, block_encrypt_func encrypt_func, int iBlockSize, void *ctx, std::string &sResult)
{
	unsigned char buf[32] = { 0 };
	if (iBlockSize < 8 || iBlockSize > (int)sizeof(buf))
	{
		return false;
	}

	int iDataSize = pEnd - pBegin;
	int rem = iDataSize % iBlockSize;
	if (rem == 0)
	{
		sResult.reserve(sResult.size() + iDataSize);
	}
	else
	{
		sResult.reserve(sResult.size() + iDataSize - rem + iBlockSize + 1);
	}

	for (const char *r = pBegin; r < pEnd; r += iBlockSize)
	{
		int len = std::min(iBlockSize, (int)(pEnd - r));
		for (int i = 0; i < len; ++i)
		{
			buf[i] = *(r + i) ^ buf[i];
		}
		encrypt_func(ctx, buf, buf);
		sResult.append(buf, buf + iBlockSize);
	}
	if (rem != 0)
	{
		sResult.append(1, rem);
	}
	return true;
}
Example #2
0
bool BitmapHandler::loadBmpURL(const std::string &name, std::string &data, bool useCache)
{
	AmigoRest restClient(amigoCoreAgent.c_str());
	restClient.enableCacheWrite(useCache);
	RestClient::response response = restClient.get(name);
	if (!response.isBad())
	{
		data.reserve(response.body.size());
		data.insert(0, response.body.c_str(), response.body.size());
	} else
	{
		if(useCache)
		{
			restClient.enableCacheRead(true);
			response = restClient.get(name);
			if (!response.isBad())
			{
				data.reserve(response.body.size());
				data.insert(0, response.body.c_str(), response.body.size());
				return true;
			}
		}
		AMIGO_LOG_I(TAG, "::loadBmpURL() FILED to load '%s'\n", name.c_str());
		return false;
	}
	return true;
}
int FileToString( const char* filename, std::string& out_contents )
{
	FILE *fp;
	fp = fopen(filename,"r");
	if (!fp) 
	{
		printf("Unable to open file '%s' for read into string (%s, %d)\n",filename, __FILE__, __LINE__);
		return 1;
	}
	const size_t capacity_increment = 512;
	try
	{
		out_contents.clear();
		out_contents.reserve(capacity_increment);
		for (int this_char = fgetc(fp); this_char != EOF; this_char = fgetc(fp))
		{
			//embiggenate the buffer, if needed
			if(out_contents.capacity() == out_contents.size())
			{
				out_contents.reserve(out_contents.capacity() + capacity_increment);
			}
			out_contents.push_back(static_cast<char>(this_char));
		}
	}
	catch (const std::exception& e)
	{
		printf("caught exception '%s' while reading file '%s' into string (%s, %d)\n",e.what(), filename, __FILE__, __LINE__);
		return 1;
	}
	return 0;
}
Example #4
0
bool CCCrypto::cbc_decrypt(const char *pBegin, const char *pEnd, block_decrypt_func decrypt_func, int iBlockSize, void *ctx, std::string &sResult)
{
	unsigned char buf[32] = { 0 };
	if (iBlockSize < 8 || iBlockSize > (int)sizeof(buf))
	{
		return false;
	}

	int iDataSize = pEnd - pBegin;
	int rem = iDataSize % iBlockSize;
	if (rem == 0)
	{
		sResult.reserve(sResult.size() + iDataSize);
	}
	else if (rem == 1)
	{
		if (iDataSize < iBlockSize + 1)
		{
			return false;
		}
		rem = *(pEnd - 1);
		if (rem <= 0 || rem >= iBlockSize)
		{
			return false;
		}
		sResult.reserve(sResult.size() + iDataSize - iBlockSize - 1 + rem);
		--pEnd;
	}
	else
	{
		return false;
	}

	for (const char *r = pBegin; r < pEnd; r += iBlockSize)
	{
		decrypt_func(ctx, r, buf);
		if (r != pBegin)
		{
			for (int i = 0; i < iBlockSize; ++i)
			{
				buf[i] ^= *(r - iBlockSize + i);
			}
		}
		if (rem != 0 && r + iBlockSize >= pEnd)
		{
			sResult.append(buf, buf + rem);
		}
		else
		{
			sResult.append(buf, buf + iBlockSize);
		}
	}
	return true;
}
void load_file(std::string& s, std::istream& is)
{
   s.erase();
   if(is.bad()) return;
   s.reserve(static_cast<std::string::size_type>(is.rdbuf()->in_avail()));
   char c;
   while(is.get(c))
   {
      if(s.capacity() == s.size())
         s.reserve(s.capacity() * 3);
      s.append(1, c);
   }
}
void load_file1(std::string& s, std::istream& is)
{
   s.erase();   //删除字符串
   	//bad() 如果出现错误则返回true 
   if(is.bad()) return;
   s.reserve(is.rdbuf()->in_avail());  //reserve 预留空间 
   char c;
   while(is.get(c))
   { //capacity 在不重新分配内存的情况下,字符串可能的大小  size 得到字符串的大小 
      if(s.capacity() == s.size())
         s.reserve(s.capacity() * 3);
      s.append(1, c);  //append 追加字符 
   }
}
Example #7
0
void WSRequest::MakeMessagePOST(std::string& msg) const
{
  char buf[32];
  size_t content_len = m_contentData.size();

  msg.clear();
  msg.reserve(256);
  msg.append("POST ").append(m_service_url).append(" HTTP/1.1\r\n");
  sprintf(buf, "%u", m_port);
  msg.append("Host: ").append(m_server).append(":").append(buf).append("\r\n");
  msg.append("Connection: keep-alive\r\n");
  if (m_accept != CT_NONE)
    msg.append("Accept: ").append(MimeFromContentType(m_accept)).append("\r\n");
  msg.append("Accept-Charset: ").append(m_charset).append("\r\n");
  if (content_len)
  {
    sprintf(buf, "%lu", (unsigned long)content_len);
    msg.append("Content-Type: ").append(MimeFromContentType(m_contentType));
    msg.append("; charset=" REQUEST_STD_CHARSET "\r\n");
    msg.append("Content-Length: ").append(buf).append("\r\n\r\n");
    msg.append(m_contentData);
  }
  else
    msg.append("\r\n");
}
Example #8
0
void encodequotedstring(std::string& str)
{
  std::string tmp;
  tmp.swap( str );
  const char* s = tmp.c_str();
  str.reserve( tmp.size() + 2 );
  str += "\"";

  while( *s )
  {
    char ch = *s++;
    switch( ch )
    {
    case '\\':
      str += "\\\\";
      break;
    case '\"':
      str += "\\\"";
      break;
    case '\n':
      str += "\\n";
      break;
    default:
      str += ch;
      break;
    }
  }

  str += "\"";
}
Example #9
0
/*
	encryptedPackage = [uint64_t:encData]
*/
inline void MakeEncryptedPackage(std::string& encryptedPackage, const std::string& encData)
{
	encryptedPackage.reserve(encData.size() + 8);
	encryptedPackage.resize(8);
	cybozu::Set64bitAsLE(&encryptedPackage[0], encData.size());
	encryptedPackage += encData;
}
Example #10
0
int string::string_by_replacing_double_curly_braces_from_file(std::string& out,
                                                              std::string& replacement_warnings,
                                                              const char* filename,
                                                              replacement replacement) {
  out.clear();

  // ----------------------------------------
  // Validate parameters.
  if (!filename) {
    return -1;
  }

  // ----------------------------------------
  std::ifstream istream(filename);
  if (!istream) {
    return -1;
  }

  // ----------------------------------------
  // Get length of file and call string.reserve with file length.
  istream.seekg(0, std::ios::end);
  out.reserve(static_cast<size_t>(istream.tellg()));
  istream.seekg(0, std::ios::beg);

  // ----------------------------------------
  return string_by_replacing_double_curly_braces_(out, replacement_warnings, istream, replacement);
}
Example #11
0
inline bool decodeStandardEncryption(std::string& dec, const std::string& encryptedPackage, const EncryptionInfo& info, const std::string& pass, std::string secretKey)
{
	const EncryptionHeader& header = info.seHeader;
	const EncryptionVerifier& verifier = info.seVerifier;

	if (secretKey.empty()) {
		if (!verifyStandardEncryption(secretKey, header, verifier, pass)) {
			return false;
		}
	}
	if (isDebug()) {
		printf("secretKey = "); dump(secretKey, false);
	}

	const char *p = encryptedPackage.data();
	size_t decSize = cybozu::Get32bitAsLE(p);
	p += 8;
	const size_t dataSize = encryptedPackage.size();
	if (decSize > dataSize) {
		throw cybozu::Exception("ms:decodeStandardEncryption:bad decSize") << decSize << dataSize;
	}
	const size_t blockSize = 4096;
	dec.reserve(dataSize);
	const size_t n = (dataSize + blockSize - 1) / blockSize;
	const std::string iv;
	for (size_t i = 0; i < n; i++) {
		const size_t len = (i < n - 1) ? blockSize : (dataSize % blockSize);
		dec.append(cipher(header.cipherName, p + i * blockSize, len, secretKey, iv, cybozu::crypto::Cipher::Decoding));
	}
	dec.resize(decSize);
	return true;
}
Example #12
0
///////////////////////////////////////////////////////////////////////////////
// Descripcion:
// - Lee desde un archivo en binario una cadena de caracteres. Siempre seguiran
//   el formato:
//   * Tamaño de la cadena (word)
//   * Caracteres que forman la cadena (un sbyte por cada uno)
// Parametros:
// - hFile. Handle al fichero.
// - udOffset. Offset de donde comenzar a leer.
// - szDestStr. Referencia al string donde depositar los datos
// Devuelve:
// - Cantidad de datos leidos del archivo.
// Notas:
// - Siempre se liberara el contenido de la cadena recibida
///////////////////////////////////////////////////////////////////////////////
dword 
CFileSystem::ReadStringFromBinary(const FileDefs::FileHandle& hFile,
								  const dword udOffset,
								  std::string& szDestStr)
{
  // Lee el tamaño de la cadena
  word uwStrSize;
  word udDataReaded = Read(hFile, (sbyte *)(&uwStrSize), sizeof(word), udOffset);
  
  // ¿Hay cadena asociada?  
  szDestStr = "";
  if (uwStrSize > 0) {
	// Se reserva espacio y procede a leer byte a byte	
	szDestStr.reserve(uwStrSize);
	word uwIt = 0;
	for (; uwIt < uwStrSize; ++uwIt) {
	  sbyte sbChar;
	  udDataReaded += Read(hFile, &sbChar, sizeof(sbyte), udOffset + udDataReaded);
	  szDestStr += sbChar;
	}
  }

  // Retorna
  return udDataReaded;
}
Example #13
0
  virtual void SetUp()
  {
    const ModelTestParameters& params = GetParam();

    std::ifstream in(params.file.c_str());

    ASSERT_TRUE(!!in);
    in.seekg(0, std::ios::end);
    original_xml.reserve(in.tellg());
    in.seekg(0, std::ios::beg);

    original_xml.assign(std::istreambuf_iterator<char>(in),
                        std::istreambuf_iterator<char>());

    if (std::string("2015") != OME_XML_MODEL_VERSION)
      {
        // Apply upgrade if needed.
        ome::common::xsl::Platform xslplat;
        ome::common::xml::dom::Document upgraded_doc;
        ome::common::xml::dom::Element docroot;

        ome::xml::OMEEntityResolver entity_resolver;
        ome::xml::OMETransformResolver transform_resolver;

        std::string upgraded_xml;
        ome::xml::transform(OME_XML_MODEL_VERSION, original_xml, upgraded_xml,
                            entity_resolver, transform_resolver);

        doc = ome::xml::createDocument(upgraded_xml);
      }
    else
      {
        doc = ome::xml::createDocument(original_xml);
      }
  }
Example #14
0
void
Logs::format (std::string& output, std::string const& message,
    beast::Journal::Severity severity, std::string const& partition)
{
    output.reserve (message.size() + partition.size() + 100);

    output = boost::posix_time::to_simple_string (
        boost::posix_time::second_clock::universal_time ());

    output += boost::str( boost::format(" <%X>") % std::this_thread::get_id());
    
    if (! partition.empty ())
        output += partition + ":";

    switch (severity)
    {
    case beast::Journal::kTrace:    output += "TRC "; break;
    case beast::Journal::kDebug:    output += "DBG "; break;
    case beast::Journal::kInfo:     output += "NFO "; break;
    case beast::Journal::kWarning:  output += "WRN "; break;
    case beast::Journal::kError:    output += "ERR "; break;
    default:
        assert(false);
    case beast::Journal::kFatal:    output += "FTL "; break;
    }

    output += scrub (message);

    if (output.size() > maximumMessageCharacters)
    {
        output.resize (maximumMessageCharacters - 3);
        output += "...";
    }
}
Example #15
0
void NotationClass::xEscapeAndAppend(std::string &strAppendTo, const std::string &strSrc){
	strAppendTo.reserve(strAppendTo.size() + strSrc.size() * 2);
	for(auto iter = strSrc.cbegin(); iter != strSrc.cend(); ++iter){
		const char ch = *iter;
		switch(ch){
		case '\\':
		case '=':
		case '{':
		case '}':
		case ';':
			strAppendTo.push_back('\\');
			strAppendTo.push_back(ch);
			break;
		case '\n':
			strAppendTo.push_back('\\');
			strAppendTo.push_back('n');
			break;
		case '\b':
			strAppendTo.push_back('\\');
			strAppendTo.push_back('b');
			break;
		case '\r':
			strAppendTo.push_back('\\');
			strAppendTo.push_back('r');
			break;
		case '\t':
			strAppendTo.push_back('\\');
			strAppendTo.push_back('t');
			break;
		default:
			strAppendTo.push_back(ch);
			break;
		}
	}
}
Example #16
0
void Logger::formatDump(std::string& message, const void* buffer, std::size_t length)
{
	const int BYTES_PER_LINE = 16;

	message.reserve(message.size() + length*6);
	if (!message.empty()) message.append("\n");
	unsigned char* base = (unsigned char*) buffer;
	int addr = 0;
	while (addr < length)
	{
		if (addr > 0) message.append("\n");
		message.append(NumberFormatter::formatHex(addr, 4));
		message.append("  ");
		int offset = 0;
		while (addr + offset < length && offset < BYTES_PER_LINE)
		{
			message.append(NumberFormatter::formatHex(base[addr + offset], 2));
			message.append(offset == 7 ? "  " : " ");
			++offset;
		}
		if (offset < 7) message.append(" ");
		while (offset < BYTES_PER_LINE) { message.append("   "); ++offset; }
		message.append(" ");
		offset = 0;
		while (addr + offset < length && offset < BYTES_PER_LINE)
		{
			unsigned char c = base[addr + offset];
			message += (c >= 32 && c < 127) ? (char) c : '.';
			++offset;
		}
		addr += BYTES_PER_LINE;
	}
}
Example #17
0
//utf8 = response->GetJsonpCallbackName() + "( \"" + utf8 + "\" )";
void c_RestResponse::CreateJsonpCallbackString(const std::string& CallbackFuncName,const std::string& JsonValue,std::string& JsonP)
{
  //utf8 = response->GetJsonpCallbackName() + "( \"" + utf8 + "\" )"; 

  std::string::const_iterator iter;

  JsonP.reserve(CallbackFuncName.length() + JsonP.length() + 128);
  
  JsonP = CallbackFuncName;
  //JsonP.append("(\'");
  JsonP.append("(");
  for(iter=JsonValue.begin();iter!=JsonValue.end();iter++)
  {
    // replace ' with \' so it will again be evaluated to ' when apperas in html as parameter to fucntion call
    if( *iter == '\'' )
    {
      JsonP.append("\\\'");
    }
    else
    {
      JsonP += *iter;
    }
  }

  //JsonP.append( "\');" );
  JsonP.append( ");" );
}
Example #18
0
void JavaEncodingConverter::convert(std::string &dst, const char *srcStart, const char *srcEnd) {
	JNIEnv *env = AndroidUtil::getEnv();
	const int srcLen = srcEnd - srcStart;
	if (srcLen > myBufferLength) {
		delete[] myCppOutBuffer;
		env->DeleteLocalRef(myOutBuffer);
		env->DeleteLocalRef(myInBuffer);
		myBufferLength = srcLen;
		myInBuffer = env->NewByteArray(myBufferLength);
		myOutBuffer = env->NewCharArray(myBufferLength);
		myCppOutBuffer = new jchar[myBufferLength];
	}

	env->SetByteArrayRegion(myInBuffer, 0, srcLen, (jbyte*)srcStart);
	const jint decodedCount = AndroidUtil::Method_EncodingConverter_convert->call(
		myJavaConverter, myInBuffer, 0, srcLen, myOutBuffer
	);
	dst.reserve(dst.length() + decodedCount * 3);
	env->GetCharArrayRegion(myOutBuffer, 0, decodedCount, myCppOutBuffer);
	const jchar *end = myCppOutBuffer + decodedCount;
	char buffer[3];
	for (const jchar *ptr = myCppOutBuffer; ptr < end; ++ptr) {
		dst.append(buffer, ZLUnicodeUtil::ucs2ToUtf8(buffer, *ptr));
	}
}
bool ReadStream( std::string &strdata, std::string &strpath )
{
struct stat statbuf;
std::ifstream stream;

int res = stat( strpath.data(), &statbuf );

if ( res == -1 )
        {
        strdata.clear();
        return false;
        }

stream.open( strpath.data(), std::ios::in );

strdata.reserve(statbuf.st_size+10);

if ( stream.is_open() )
        {
        ReadStream( stream, strdata, statbuf.st_size );

        stream.close();

        return true;
        }

return(0);
}
void
WorkingBuffer::toString(std::string & result) const
{
  result.clear();
  result.reserve(size());
  result.append(reinterpret_cast<const char *>(buffer_.get()) + startPos_, size());
}
Example #21
0
void SourceFile::getCleanLine(const std::string& line, std::string& cleanedLine)
{
	// Remove single line comments
	cleanedLine.reserve(line.size());
	int lineSize = (int)line.size();
	for (int i = 0; i < (int)line.size(); i++) {
		switch (m_FileType) {
		case FileType::FILETYPE_C:
		case FileType::FILETYPE_CPP:
		case FileType::FILETYPE_CXX:
		case FileType::FILETYPE_H:
		case FileType::FILETYPE_HPP:
		case FileType::FILETYPE_JAVA:
		case FileType::FILETYPE_CS:
			if (i < lineSize - 2 && line[i] == '/' && line[i + 1] == '/') {
				return;
			}
			break;

		case FileType::FILETYPE_VB:
			if (i < lineSize - 1 && line[i] == '\'') {
				return;
			}
			break;
		default:
			return;
		}
		cleanedLine.push_back(line[i]);
	}
}
Example #22
0
File: Reader.cpp Project: LicoC/XML
// Expand the five standard XML entities to their text values.
// &amp; &lt; &gt; &apos; &quot;
// unrecognized entities are preserved.
static void readEntities(const std::string &strValue, std::string &strResult)
{
	bool bEntity = false;
	std::string strEntity;

	strResult.reserve(strValue.size()<<1);
	strEntity.reserve(64);
	const char *strCursor = strValue.c_str();
	const char *strEnd = strValue.c_str() + strValue.size();
	while (strCursor != strEnd)
	{
		char ch = *strCursor++;
		switch (ch)
		{
			case '&':
				bEntity = true;
				break;
			case ';':
				if (bEntity)
				{
					// Content containing brackets collide with tag bracket delimiting 
					// characters. These must be replaced with entity references 
					// &lt; and &gt; when writing XML.
					// The ampersand character collides with the XML entity references 
					// content containing ampersands must be converted to an &amp; 
					// entity reference when writing XML.

					// ampersand
					if (strEntity.compare("amp") == 0)
						strResult += '&';
					// less-than
					else if (strEntity.compare("lt") == 0)
						strResult += '<';
					// greater-than
					else if (strEntity.compare("gt") == 0)
						strResult += '>';
					else if (strEntity.compare("quot") == 0)
						strResult += '"';
					else if (strEntity.compare("apos") == 0)
						strResult += '\'';
					else
					{
						strResult += '&';
						strResult += strEntity;
						strResult += ';';
					}
					strEntity.resize(0);
					bEntity = false;
					break;
				}
				// deliberate fall through
			default:
				if (bEntity)
					append(strEntity, ch);
				else
					append(strResult, ch);
				break;
		}
	}
}
Example #23
0
int LexicalUtils::parseAccessor( const std::string& methodName, int accessorKinds, std::string& fieldName )
{
	assert( accessorKinds > 0 && accessorKinds < 4 );

	int foundKind;
	const char* fieldNamePos = 0;

	if( accessorKinds & Getter && startsWith( methodName, GETTER_PREFIX ) )
	{
		foundKind = Getter;
		fieldNamePos = methodName.c_str() + GETTER_PREFIX.length();
	}

	if( accessorKinds & Setter && startsWith( methodName, SETTER_PREFIX )  )
	{
		foundKind = Setter;
		fieldNamePos = methodName.c_str() + SETTER_PREFIX.length();
	}

	if( fieldNamePos == 0 )
		return -1;

	int firstChar = tolower( fieldNamePos[0] );
	if( firstChar == fieldNamePos[0] )
		return -1;

	fieldName.clear();
	fieldName.reserve( fieldNamePos - methodName.c_str() );
	fieldName += firstChar;
	fieldName += fieldNamePos + 1;

	return foundKind;
}
void InitShaderCombiner()
{
	glActiveTexture(GL_TEXTURE0);
	glEnable(GL_TEXTURE_2D);
	glActiveTexture(GL_TEXTURE1);
	glEnable(GL_TEXTURE_2D);

	g_vertex_shader_object = _createShader(GL_VERTEX_SHADER, vertex_shader);
	g_vertex_shader_object_notex = _createShader(GL_VERTEX_SHADER, vertex_shader_notex);

	strFragmentShader.reserve(1024*5);

#ifndef GLESX
	g_calc_light_shader_object = _createShader(GL_FRAGMENT_SHADER, fragment_shader_calc_light);
	g_calc_mipmap_shader_object = _createShader(GL_FRAGMENT_SHADER, fragment_shader_mipmap);
	g_calc_noise_shader_object = _createShader(GL_FRAGMENT_SHADER, fragment_shader_noise);
	g_readtex_shader_object = _createShader(GL_FRAGMENT_SHADER, config.texture.bilinearMode == BILINEAR_3POINT ? fragment_shader_readtex_3point : fragment_shader_readtex);
	g_readtex_ms_shader_object = _createShader(GL_FRAGMENT_SHADER, fragment_shader_readtex_ms);
	g_dither_shader_object = _createShader(GL_FRAGMENT_SHADER, fragment_shader_dither);
#endif // GLESX

	noiseTex.init();
	g_monochrome_image_program = createShaderProgram(default_vertex_shader, zelda_monochrome_fragment_shader);

#ifdef GL_IMAGE_TEXTURES_SUPPORT
	if (video().getRender().isImageTexturesSupported() && config.frameBufferEmulation.N64DepthCompare != 0)
		g_calc_depth_shader_object = _createShader(GL_FRAGMENT_SHADER, depth_compare_shader_float);

	InitZlutTexture();
	InitShadowMapShader();
#endif // GL_IMAGE_TEXTURES_SUPPORT
}
Example #25
0
	bool getFileText( const std::string& filePath, std::string& outText )
	{

		// Open the file
		//
		std::ifstream sourceFile( filePath.c_str() );


		if(sourceFile.good() )
		{

			// Read the full contents of the file into a string. (may throw.)
			//
			sourceFile.seekg( 0, std::ios::end );
			outText.reserve( static_cast< size_t > ( sourceFile.tellg() ));
			sourceFile.seekg( 0, std::ios::beg );

			outText.assign(( std::istreambuf_iterator<char>(sourceFile )),
				std::istreambuf_iterator<char>() );

			sourceFile.close();
			return true;
		}
		return false;
	}
Example #26
0
/**
 * Check the given string for correct PHP syntax
 *
 * @return bool success or failure?
 */
SyntaxCheckResult php_syntax_check_string(std::string &in) {

  char *buffer;
  in.reserve(in.size() + 1);
  buffer = const_cast<char*>(in.c_str());
  buffer[in.size() + 1] = 0; // need double NULL for scan_buffer

  void* scanner;
  yy_extra_type extra;
  extra.idx_expr = true;//flags.idx_expr;
  extra.include_debug = true;//flags.include_debug;
  extra.insert_token = 0;//flags.eval ? T_OPEN_TAG_FAKE : 0;
  extra.short_tags = false;//flags.short_tags;
  extra.asp_tags = false;//flags.asp_tags;

  xhpast::Node *root = NULL;

  xhpastlex_init(&scanner);
  xhpastset_extra(&extra, scanner);
  xhpast_scan_buffer(buffer, in.size() + 2, scanner);
  xhpastparse(scanner, &root);
  xhpastlex_destroy(scanner);

  if (extra.terminated) {
    return SyntaxCheckResult(false, (int)extra.lineno, extra.error);
  }

  return SyntaxCheckResult(true);
}
void FileReader::ReadRawString(std::string &theStr, int theNumChars)
{
	theStr.erase();
	theStr.reserve(theNumChars);
	for(int i=0; i<theNumChars; i++)
		theStr += (char)ReadByte();
}
Example #28
0
int string::string_from_file(std::string& out, const char* filename) {
  out.clear();

  // ----------------------------------------
  // Validate parameters.
  if (!filename) {
    return -1;
  }

  // ----------------------------------------
  std::ifstream istream(filename);
  if (!istream) {
    return -1;
  }

  // ----------------------------------------
  // Get length of file and call string.reserve with file length.
  istream.seekg(0, std::ios::end);
  out.reserve(static_cast<size_t>(istream.tellg()));
  istream.seekg(0, std::ios::beg);

  for (;;) {
    int c = istream.get();
    if (!istream.good()) break;

    out.push_back(c);
  }

  return 0;
}
Example #29
0
void MIToken::unescapeQuotedStringValue(std::string &Str) const {
    assert(isStringValueQuoted() && "String value isn't quoted");
    StringRef Value = Range.drop_front(StringOffset);
    assert(Value.front() == '"' && Value.back() == '"');
    Cursor C = Cursor(Value.substr(1, Value.size() - 2));

    Str.clear();
    Str.reserve(C.remaining().size());
    while (!C.isEOF()) {
        char Char = C.peek();
        if (Char == '\\') {
            if (C.peek(1) == '\\') {
                // Two '\' become one
                Str += '\\';
                C.advance(2);
                continue;
            }
            if (isxdigit(C.peek(1)) && isxdigit(C.peek(2))) {
                Str += hexDigitValue(C.peek(1)) * 16 + hexDigitValue(C.peek(2));
                C.advance(3);
                continue;
            }
        }
        Str += Char;
        C.advance();
    }
}
Example #30
0
void CodeToHeader(const std::vector<u16> &code, std::string _filename,
				  const char *name, std::string &header)
{
	std::vector<u16> code_padded = code;
	// Pad with nops to 32byte boundary
	while (code_padded.size() & 0x7f)
		code_padded.push_back(0);
	header.clear();
	header.reserve(code_padded.size() * 4);
	header.append("#define NUM_UCODES 1\n\n");
	std::string filename;
	SplitPath(_filename, nullptr, &filename, nullptr);
	header.append(StringFromFormat("const char* UCODE_NAMES[NUM_UCODES] = {\"%s\"};\n\n", filename.c_str()));
	header.append("const unsigned short dsp_code[NUM_UCODES][0x1000] = {\n");

	header.append("\t{\n\t\t");
	for (u32 j = 0; j < code_padded.size(); j++)
	{
		if (j && ((j & 15) == 0))
			header.append("\n\t\t");
		header.append(StringFromFormat("0x%04x, ", code_padded[j]));
	}
	header.append("\n\t},\n");

	header.append("};\n");
}