void PusherClient::getAuthString(const String& channel, String& auth)
{
	Sha256Class sha256;
	
	//Sha init with secret key
	{
		String secret;
		getPusherInfoItem(2, secret);
		sha256.initHmac((uint8_t*)&secret[0], secret.length());
	}
	
	//Set the data to encrypt
	{
		String text;
		text.reserve(_socketid.length() + 1 + channel.length());
		text = _socketid;
		text += ':';
		text += channel;
		sha256.print(text);
	}
	
	uint8_t* result = sha256.resultHmac();
	
	String hexChars;
	getStringTableItem(19, hexChars);
	
	auth.reserve(21 /*key*/ + 1 + 64 /*sha256*/);	
	getPusherInfoItem(1, auth); //key
	auth += ':';	
	for (int i=0; i<32; i++)
	{
		auth += hexChars.charAt(result[i]>>4);
		auth += hexChars.charAt(result[i]&0xf);
	}
}
void Document::loadFileToString( const String& file_name_, String &buffer_ )
{
	FRL_EXCEPT_GUARD();
	if( ! fs::exists( file_name_ ) )
		FRL_THROW_S_CLASS( Document::FileNotFound );
	size_t length = static_cast< size_t >( fs::file_size( file_name_ ) );
	if( length == 0 )
		FRL_THROW_S_CLASS( Document::EmptyFile );
	if( ! buffer_.empty() )
		buffer_.clear();

	static const size_t buffer_size = 4096;
	stream_std::InFile in( file_name_.c_str(), std::ios::binary );
	if( ! in.is_open() )
		FRL_THROW_S_CLASS( Document::UnknownError );
	std::vector< Char > buf( buffer_size );

	buffer_.reserve( length );
	while( in )
	{
		in.read( &buf[ 0 ], buffer_size );
		buffer_.append( &buf[ 0 ], in.gcount() );
	}
	in.close();
}
Example #3
0
    //---------------------------------
    String Utils::checkNCName ( const String &ncName )
    {
        String result;
        result.reserve ( ncName.length() );

        // check if first character is an alpha character
        char firstCharacter = ncName[0];

        if ( isAsciiAlphaChar ( firstCharacter )  )
            result.append ( 1, firstCharacter );
        else
            result.append ( 1, '_' );

        //replace all spaces and colons by underlines
        for ( size_t i = 1; i<ncName.length(); ++i )
        {
            char character = ncName[i];

            if ( isIDChar ( character ) )
                result.append ( 1, character );
            else
                result.append ( 1, '_' );
        }

        return result;
    }
void rx_buffer_to_publish(){
    Particle.publish("spi_rx_len",
        String::format("Received %d bytes", SPI.available())
        );
    String received;
    received.reserve(SPI_BUFFER_SIZE+1);
    for (int i = 0; i < SPI.available(); i++) {
        received += char(rx_buffer[i]);
        // received += String::format("%02x ", rx_buffer[i]);
    }
    Particle.publish("spi_rx_asci", received);
    // Particle.publish("spi_rx_data", received);
}
String io::readTrailingSpaces(ID3_Reader& reader, size_t len)
{
  io::WindowedReader wr(reader, len);
  String str;
  String spaces;
  str.reserve(len);
  spaces.reserve(len);
  while (!wr.atEnd())
  {
    ID3_Reader::char_type ch = wr.readChar();
    if (ch == '\0' || ch == ' ')
    {
      spaces += ch;
    }
    else
    {
      str += spaces + (char) ch;
      spaces.erase();
    }
  }
  return str;
}
Example #6
0
int
hstcpcli::set_error(int code, const char *str)
{
  uint32 str_len = strlen(str);
  DBG(fprintf(stderr, "SET_ERROR: %d\n", code));
  error_code = code;
  error_str.length(0);
  if (error_str.reserve(str_len + 1))
    return 0;
  error_str.q_append(str, str_len);
  error_str.c_ptr_safe();
  return error_code;
}
String io::readText(ID3_Reader& reader, size_t len)
{
  String str;
  str.reserve(len);
  const size_t SIZE = 1024;
  ID3_Reader::char_type buf[SIZE];
  size_t remaining = len;
  while (remaining > 0 && !reader.atEnd())
  {
    size_t numRead = reader.readChars(buf, min(remaining, SIZE));
    remaining -= numRead;
    str.append(reinterpret_cast<String::value_type *>(buf), numRead);
  }
  return str;
}
Example #8
0
	String PSRunner::readAllOutputStream()
	{
		//read default 10*1024 bytes
		DWORD count = 10 * 1024;
		DWORD readed = 0;
		String result;
		result.reserve(count / sizeof(String::traits_type::char_type));
		//read buffer
		BOOL success = ReadFile(
			g_hChildStd_OUT_Rd,
			reinterpret_cast<void*>(
				const_cast<typename String::traits_type::char_type*>(result.c_str())
				),
			count,
			&readed,
			NULL);
		if (!success)
		{
			UC_ERROR << "Read file Error\r\n";
		}
		return result;
	}
Example #9
0
bool
POP3Connection::_ProtocolLIST(const String &sParameter)
{
    if (!_account)
    {
        _SendData("-ERR Message list not loaded");
        return true;
    }

    String sResponse;

    if (sParameter.IsEmpty())
    {
        int iMessageCount = 0;
        __int64 iTotalBytes = 0;
        _GetMailboxContents(iMessageCount, iTotalBytes);

        // preallocate memory to speed up a bit.
        sResponse.reserve(iMessageCount * 10);

        sResponse.Format(_T("+OK %d messages (%I64d octets)"), iMessageCount, iTotalBytes);
        _SendData(sResponse);


        sResponse = "";
        String sRow;

        int index = 0;
        boost_foreach(shared_ptr<Message> pMessage, _messages)
        {
            index++;
            if (!pMessage->GetFlagDeleted())
            {
                sRow.Format(_T("%d %d\r\n"), index, pMessage->GetSize());
                sResponse.append(sRow);
            }
        }
Example #10
0
File: main.cpp Project: ECer23/stl
int main() {
  /*** check 1 ***/
  String a;
  String b("haha");

  cout << "a.size(): " << a.size() << endl;
  cout << "a.capacity(): " << a.capacity() << endl;
  cout << "b.size(): " << b.size() << endl;
  cout << "b.capacity(): " << b.capacity() << endl;

  a.push_back('a');
  a.push_back('b');
  a.reserve(8);

  cout << "a.size(): " << a.size() << endl;
  cout << "a.capacity(): " << a.capacity() << endl;

  b.pop_back();
  cout << "b.size(): " << b.size() << endl;
  cout << "b.capacity(): " << b.capacity() << endl;

  b.resize(8);
  cout << "b.size(): " << b.size() << endl;
  cout << "b.capacity(): " << b.capacity() << endl;

  /*** check 2 ***/
  String c("My name ");
  String d("is ");
  d += "Apple";
  String e = c + d;

  cout << c << endl;
  cout << d << endl;
  cout << e << endl;

  return 0;
}
Example #11
0
	//-----------------------------------------------------------------------
	String CgProgram::resolveCgIncludes(const String& inSource, Resource* resourceBeingLoaded, const String& fileName)
	{
		String outSource;
		// output will be at least this big
		outSource.reserve(inSource.length());

		size_t startMarker = 0;
		size_t i = inSource.find("#include");
		while (i != String::npos)
		{
			size_t includePos = i;
			size_t afterIncludePos = includePos + 8;
			size_t newLineBefore = inSource.rfind("\n", includePos);

			// check we're not in a comment
			size_t lineCommentIt = inSource.rfind("//", includePos);
			if (lineCommentIt != String::npos)
			{
				if (newLineBefore == String::npos || lineCommentIt > newLineBefore)
				{
					// commented
					i = inSource.find("#include", afterIncludePos);
					continue;
				}

			}
			size_t blockCommentIt = inSource.rfind("/*", includePos);
			if (blockCommentIt != String::npos)
			{
				size_t closeCommentIt = inSource.rfind("*/", includePos);
				if (closeCommentIt == String::npos || closeCommentIt < blockCommentIt)
				{
					// commented
					i = inSource.find("#include", afterIncludePos);
					continue;
				}

			}

			// find following newline (or EOF)
			size_t newLineAfter = inSource.find("\n", afterIncludePos);
			// find include file string container
			String endDelimeter = "\"";
			size_t startIt = inSource.find("\"", afterIncludePos);
			if (startIt == String::npos || startIt > newLineAfter)
			{
				// try <>
				startIt = inSource.find("<", afterIncludePos);
				if (startIt == String::npos || startIt > newLineAfter)
				{
					OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
						"Badly formed #include directive (expected \" or <) in file "
						+ fileName + ": " + inSource.substr(includePos, newLineAfter-includePos),
						"CgProgram::preprocessor");
				}
				else
				{
					endDelimeter = ">";
				}
			}
			size_t endIt = inSource.find(endDelimeter, startIt+1);
			if (endIt == String::npos || endIt <= startIt)
			{
				OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
					"Badly formed #include directive (expected " + endDelimeter + ") in file "
					+ fileName + ": " + inSource.substr(includePos, newLineAfter-includePos),
					"CgProgram::preprocessor");
			}

			// extract filename
			String filename(inSource.substr(startIt+1, endIt-startIt-1));

			// open included file
			DataStreamPtr resource = ResourceGroupManager::getSingleton().
				openResource(filename, resourceBeingLoaded->getGroup(), resourceBeingLoaded);

			// replace entire include directive line
			// copy up to just before include
			if (newLineBefore != String::npos && newLineBefore >= startMarker)
				outSource.append(inSource.substr(startMarker, newLineBefore-startMarker+1));

			size_t lineCount = 0;
			size_t lineCountPos = 0;
			
			// Count the line number of #include statement
			lineCountPos = outSource.find('\n');
			while(lineCountPos != String::npos)
			{
				lineCountPos = outSource.find('\n', lineCountPos+1);
				lineCount++;
			}

			// Add #line to the start of the included file to correct the line count
			outSource.append("#line 1 \"" + filename + "\"\n");

			outSource.append(resource->getAsString());

			// Add #line to the end of the included file to correct the line count
			outSource.append("\n#line " + Ogre::StringConverter::toString(lineCount) + 
				"\"" + fileName + "\"\n");

			startMarker = newLineAfter;

			if (startMarker != String::npos)
				i = inSource.find("#include", startMarker);
			else
				i = String::npos;

		}
		// copy any remaining characters
		outSource.append(inSource.substr(startMarker));

		return outSource;
	}
Example #12
0
void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}
Example #13
0
// encode the given text unconditionally, i.e. without checking if it must be
// encoded (this is supposed to be done in the caller) and using the specified
// encodings and charset (which are supposed to be detected by the caller too)
static String
EncodeText(const String& in,
           wxFontEncoding enc,
           MIME::Encoding enc2047,
           const String& csName)
{
   // encode the word splitting it in the chunks such that they will be no
   // longer than 75 characters each
   wxCharBuffer buf(in.mb_str(wxCSConv(enc)));
   if ( !buf )
   {
      // if the header can't be encoded using the given encoding, use UTF-8
      // which always works
      buf = in.utf8_str();
   }

   String out;
   out.reserve(csName.length() + strlen(buf) + 7 /* for =?...?X?...?= */);

   const char *s = buf;
   while ( *s )
   {
      // if we wrapped, insert a line break
      if ( !out.empty() )
         out += "\r\n  ";

      static const size_t RFC2047_MAXWORD_LEN = 75;

      // how many characters may we put in this encoded word?
      size_t len = 0;

      // take into account the length of "=?charset?...?="
      int lenRemaining = RFC2047_MAXWORD_LEN - (5 + csName.length());

      // for QP we need to examine all characters
      if ( enc2047 == MIME::Encoding_QuotedPrintable )
      {
         for ( ; s[len]; len++ )
         {
            const char c = s[len];

            // normal characters stand for themselves in QP, the encoded ones
            // take 3 positions (=XX)
            lenRemaining -= (NeedsEncodingInHeader(c) || strchr(" \t=?", c))
                              ? 3 : 1;

            if ( lenRemaining <= 0 )
            {
               // can't put any more chars into this word
               break;
            }
         }
      }
      else // Base64
      {
         // rfc822_binary() splits lines after 60 characters so don't make
         // chunks longer than this as the base64-encoded headers can't have
         // EOLs in them
         static const int CCLIENT_MAX_BASE64_LEN = 60;

         if ( lenRemaining > CCLIENT_MAX_BASE64_LEN )
            lenRemaining = CCLIENT_MAX_BASE64_LEN;

         // we can calculate how many characters we may put into lenRemaining
         // directly
         len = (lenRemaining / 4) * 3 - 2;

         // but not more than what we have
         size_t lenMax = wxStrlen(s);
         if ( len > lenMax )
         {
            len = lenMax;
         }
      }

      // do encode this word
      unsigned char *text = (unsigned char *)s; // cast for cclient

      // length of the encoded text and the text itself
      unsigned long lenEnc;
      unsigned char *textEnc;

      if ( enc2047 == MIME::Encoding_QuotedPrintable )
      {
            textEnc = rfc822_8bit(text, len, &lenEnc);
      }
      else // Encoding_Base64
      {
            textEnc = rfc822_binary(text, len, &lenEnc);
            while ( textEnc[lenEnc - 2] == '\r' && textEnc[lenEnc - 1] == '\n' )
            {
               // discard eol which we don't need in the header
               lenEnc -= 2;
            }
      }

      // put into string as we might want to do some more replacements...
      String encword(wxString::FromAscii(CHAR_CAST(textEnc), lenEnc));

      // hack: rfc822_8bit() doesn't encode spaces normally but we must
      // do it inside the headers
      //
      // we also have to encode '?'s in the headers which are not encoded by it
      if ( enc2047 == MIME::Encoding_QuotedPrintable )
      {
         String encword2;
         encword2.reserve(encword.length());

         bool replaced = false;
         for ( const wxChar *p = encword.c_str(); *p; p++ )
         {
            switch ( *p )
            {
               case ' ':
                  encword2 += _T("=20");
                  break;

               case '\t':
                  encword2 += _T("=09");
                  break;

               case '?':
                  encword2 += _T("=3F");
                  break;

               default:
                  encword2 += *p;

                  // skip assignment to replaced below
                  continue;
            }

            replaced = true;
         }

         if ( replaced )
         {
            encword = encword2;
         }
      }

      // append this word to the header
      out << _T("=?") << csName << _T('?') << (char)enc2047 << _T('?')
          << encword
          << _T("?=");

      fs_give((void **)&textEnc);

      // skip the already encoded part
      s += len;
   }

   return out;
}
Example #14
0
void setup() {
    // initialize serial:
    Serial.begin(9600);
    // reserve 200 bytes for the inputBuffer:
    inputBuffer.reserve(200);
}
Example #15
0
wxCharBuffer MIME::EncodeHeader(const String& in, wxFontEncoding enc)
{
   if ( !NeedsEncoding(in) )
      return in.ToAscii();

   // decide about the encoding to use if none specified
   if ( enc == wxFONTENCODING_SYSTEM )
   {
      // try to use the user current encoding first
      enc = wxLocale::GetSystemEncoding();
   }

   if ( wxCSConv(enc).FromWChar(NULL, 0, in.wc_str(wxConvLibc)) == wxCONV_FAILED )
   {
      // but if we can't encode with it, fall back to UTF-8 as it never fails
      enc = wxFONTENCODING_UTF8;
   }

   // get the encoding in RFC 2047 sense
   MIME::Encoding enc2047 = MIME::GetEncodingForFontEncoding(enc);

   if ( enc2047 == MIME::Encoding_Unknown )
   {
      FAIL_MSG( _T("should have valid MIME encoding") );

      enc2047 = MIME::Encoding_QuotedPrintable;
   }

   // get the name of the charset to use
   String csName = MIME::GetCharsetForFontEncoding(enc);
   if ( csName.empty() )
   {
      FAIL_MSG( _T("should have a valid charset name!") );

      csName = _T("UNKNOWN");
   }


   String headerEnc;
   headerEnc.reserve(2*in.length());

   // for QP we encode each header word separately as some might not need being
   // encoded at all and the header remains more readable if we don't encode
   // them unnecessarily, but for Base64 it's useless to do this as it's
   // unreadable anyhow so we just encode everything at once
   if ( enc2047 == MIME::Encoding_QuotedPrintable )
   {
      // encode each word of the header if necessary, taking into account one
      // added complication: white space between 2 consecutive encoded words is
      // ignored during decoding, so we must encode 2 consecutive words both of
      // which need encoding as one single encoded word or the space between
      // them would be lost
      bool lastWordEncoded = false;
      const wxArrayString words(wxStringTokenize(in));
      const size_t count = words.size();
      for ( size_t n = 0; n < count; ++n )
      {
         const wxString& word = words[n];
         if ( NeedsEncoding(word) )
         {
            const String wordEnc = EncodeText(word, enc, enc2047, csName);

            if ( lastWordEncoded )
            {
               // we need to merge the 2 consecutive encoded words together: we
               // do it by removing "?=" suffix from the previous word, adding
               // a space and remove the "=?charset?Q?" prefix from this word
               ASSERT_MSG( headerEnc.length() > 7, "bad QP-encoded last word" );
               headerEnc.RemoveLast(2); // "?="

               headerEnc += '_'; // space can be represented like this in QP

               const size_t posText = wordEnc.find("?Q?");
               ASSERT_MSG( posText != String::npos, "bad QP-encoded word" );
               headerEnc += wordEnc.substr(posText + 3);
            }
            else // last word not encoded, just append this one
            {
               if ( !headerEnc.empty() )
                  headerEnc += ' ';

               headerEnc += wordEnc;
            }

            lastWordEncoded = true;
         }
         else // this word doesn't need to be encoded, simply append it
         {
            if ( !headerEnc.empty() )
               headerEnc += ' ';

            headerEnc += word;

            lastWordEncoded = false;
         }
      }
   }
   else // MIME::Encoding_Base64
   {
      headerEnc = EncodeText(in, enc, enc2047, csName);
   }

   return headerEnc.ToAscii();
}
Example #16
0
int
main(size_t argc, const char** argv)
{
  ID3D_INIT_DOUT();
  ID3D_INIT_WARNING();
  ID3D_INIT_NOTICE();

  ID3_IStreamReader isr(cin);
  BString orig = io::readAllBinary(isr);
    
  cout << "input size:    " << orig.size() << endl;
  
  cout << endl;

  cout << "=== Testing Synchronization ===" << endl;
  BString synced;

  {
    io::BStringReader sr(orig);
    io::UnsyncedReader ur(sr);

    synced = io::readAllBinary(ur);
  }

  cout << "synced size:   " << synced.size() << endl;

  BString unsynced;

  {
    io::BStringWriter sw(unsynced);
    io::UnsyncedWriter uw(sw);

    uw.writeChars(synced.data(), synced.size());
  }
  
  cout << "unsynced size: " << unsynced.size() << endl;

  BString resynced;

  {
    io::BStringReader sr(unsynced);
    io::UnsyncedReader ur(sr);

    resynced = io::readAllBinary(ur);
  }

  cout << "resynced size: " << resynced.size() << endl;

  if (unsynced == orig)
  {
    cout << "orig == unsynced" << endl;
  }
  else
  {
    cout << "orig != unsynced" << endl;
  }
  if (synced == resynced)
  {
    cout << "synced == resynced" << endl;
  }
  else
  {
    cout << "synced != resynced" << endl;
  }

  cout << endl;
  cout << "=== Testing Trailing Spaces ===" << endl;

  String text;

  {
    io::StringWriter sw(text);
    io::writeTrailingSpaces (sw, "hello, world", 50);
  }

  cout << "new text  = \"" << text << "\"" << endl;

  String origText;

  {
    io::StringReader sr(text);
    origText = io::readTrailingSpaces(sr, 100);
  }

  cout << "orig text = \"" << origText << "\"" << endl;

  cout << endl;
  cout << "=== Testing Binary Numbers ===" << endl;

  String number;

  {
    io::StringWriter sw(number);
    io::writeBENumber(sw, 1234567890, 4);
  }

  cout << "binary number:";
  for (size_t i = 0; i < number.size(); ++i)
  {
    cout << " 0x" << hex << (size_t) (0xFF & number[i]) << dec;
  }
  cout << endl;

  size_t val;

  {
    io::StringReader sr(number);
    val = io::readBENumber(sr, 4);
  }

  cout << "orig number: " << val << endl;

  cout << endl;
  cout << "=== Testing Compression ===" << endl;

  String compressed;
  size_t origSize = orig.size();
  cout << "origSize = " << origSize << endl;
  

  {
    io::StringWriter sw(compressed);
    io::CompressedWriter cw(sw);
    cw.writeChars(orig.data(), orig.size());
    cw.flush();
    if (origSize != cw.getOrigSize())
    {
      origSize = cw.getOrigSize();
      cout << "cw.getOrigSize() = " << origSize << endl;
    }
  }

  cout << "compressed size = " << compressed.size() << endl;

  BString uncompressed;
  
  if (origSize == 0)
  {
    cout << "no compression" << endl;
  }
  else
  {
    io::StringReader sr(compressed);
    io::CompressedReader cr(sr, origSize);

    uncompressed = io::readAllBinary(cr);
    cout << "uncompressed size = " << uncompressed.size() << endl;
  }

  if (uncompressed.size() == orig.size())
  {
    if (uncompressed == orig)
    {
      cout << "orig == uncompressed" << endl;
    }
    else
    {
      cout << "orig != uncompressed" << endl;
    }
  }

  String ascii;
  ascii.reserve(8192);

  for (size_t i = 0; i < 8192; ++i)
  {
    ascii += 'a' + (i % 26);
  }

  cout << endl;
  cout << "ascii.size() = " << ascii.size() << endl;
  String unicode = dami::convert(ascii, ID3TE_ASCII, ID3TE_UTF16BE);
  cout << "uncicode.size() = " << unicode.size() << endl;
  String ascii_2 = dami::convert(unicode, ID3TE_UTF16BE, ID3TE_ASCII);
  if (ascii != ascii_2)
  {
    cout << "ascii != ascii_2" << endl;
  }
  else
  {
    cout << "ascii == ascii_2" << endl;
  }



  return 0;
}
Example #17
0
int FindFileJob::execute()
{
    std::shared_ptr<Project> proj = project();
    if (!proj) {
        return 1;
    }
    if (!proj->fileManager())
        return 1;
    const Path srcRoot = proj->path();
    assert(srcRoot.endsWith('/'));

    enum Mode {
        All,
        FilePath,
        Regex,
        Pattern,
    } mode = All;

    String::CaseSensitivity cs = String::CaseSensitive;
    if (queryFlags() & QueryMessage::MatchRegex) {
        mode = Regex;
    } else if (!mPattern.isEmpty()) {
        mode = mPattern[0] == '/' ? FilePath : Pattern;
    }
    if (queryFlags() & QueryMessage::MatchCaseInsensitive)
        cs = String::CaseInsensitive;

    String out;
    out.reserve(PATH_MAX);
    const bool absolutePath = queryFlags() & QueryMessage::AbsolutePath;
    if (absolutePath)
        out.append(srcRoot);
    const Files& dirs = proj->files();
    assert(proj->fileManager());
    if (dirs.isEmpty())
        proj->fileManager()->load(FileManager::Synchronous);
    Files::const_iterator dirit = dirs.begin();
    bool foundExact = false;
    const int patternSize = mPattern.size();
    List<String> matches;
    const bool preferExact = queryFlags() & QueryMessage::FindFilePreferExact;
    int ret = 1;
    bool firstElisp = queryFlags() & QueryMessage::Elisp;

    auto writeFile = [this, &firstElisp](const Path &path) {
        if (firstElisp) {
            firstElisp = false;
            if (!write("(list", DontQuote))
                return false;
        }
        return write(path);
    };
    while (dirit != dirs.end()) {
        const Path &dir = dirit->first;
        if (dir.size() < srcRoot.size()) {
            continue;
        } else {
            out.append(dir.constData() + srcRoot.size(), dir.size() - srcRoot.size());
        }

        const Set<String> &files = dirit->second;
        for (Set<String>::const_iterator it = files.begin(); it != files.end(); ++it) {
            const String &key = *it;
            out.append(key);
            bool ok;
            switch (mode) {
            case All:
                ok = true;
                break;
            case Regex:
                ok = Rct::contains(out, mRegex);
                break;
            case FilePath:
            case Pattern:
                if (!preferExact) {
                    ok = out.contains(mPattern, cs);
                } else {
                    const int outSize = out.size();
                    const bool exact = (outSize > patternSize && out.endsWith(mPattern) && out.at(outSize - (patternSize + 1)) == '/');
                    if (exact) {
                        ok = true;
                        if (!foundExact) {
                            matches.clear();
                            foundExact = true;
                        }
                    } else {
                        ok = !foundExact && out.contains(mPattern, cs);
                    }
                }
                if (!ok && mode == FilePath) {
                    Path p(out);
                    if (!absolutePath)
                        p.prepend(srcRoot);
                    p.resolve();
                    if (p == mPattern)
                        ok = true;
                }
                break;
            }
            if (ok) {
                ret = 0;

                Path matched = out;
                if (absolutePath)
                    matched.resolve();
                if (preferExact && !foundExact) {
                    matches.append(matched);
                } else {
                    if (!writeFile(matched))
                        return 1;
                }
            }
            out.chop(key.size());
        }
        out.chop(dir.size() - srcRoot.size());
        ++dirit;
    }
    for (List<String>::const_iterator it = matches.begin(); it != matches.end(); ++it) {
        if (!writeFile(*it)) {
            return 1;
        }
    }
    if (queryFlags() & QueryMessage::Elisp && !firstElisp && !write(")", DontQuote))
        return 1;
    return ret;
}