当前位置: 首页>>代码示例>>C++>>正文


C++ Substring函数代码示例

本文整理汇总了C++中Substring函数的典型用法代码示例。如果您正苦于以下问题:C++ Substring函数的具体用法?C++ Substring怎么用?C++ Substring使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Substring函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: NS_NAMED_LITERAL_STRING

nsresult nsSceneTracker::SplitHeading (const nsAString& aHeading,
                                       nsAString& aIntExt,
                                       nsAString& aSetting,
                                       nsAString& aDayNight) {
  NS_NAMED_LITERAL_STRING(kSeparatorChars, ". -");
  NS_NAMED_LITERAL_STRING(kPrefixChars, ". -0123456789");

  nsCOMPtr<nsIPrefService> ps = do_GetService(
    "@mozilla.org/preferences-service;1");
  nsCOMPtr<nsIPrefBranch> branch;

  nsresult rv = ps->GetBranch("celtx.scripteditor.", getter_AddRefs(branch));
  if (NS_FAILED(rv))
    return rv;
  nsXPIDLString strdata;

  // Get the int/ext values
  nsCOMPtr<nsISupportsString> intextstr;
  rv = branch->GetComplexValue("intexts",
    NS_GET_IID(nsISupportsString), getter_AddRefs(intextstr));
  if (NS_FAILED(rv))
    return rv;
  intextstr->ToString(getter_Copies(strdata));
  nsTArray<nsString> intexts;
  intexts.AppendElement(NS_LITERAL_STRING("INT"));
  intexts.AppendElement(NS_LITERAL_STRING("EXT"));
  nsXPIDLString::size_type startoffset = 0;
  nsXPIDLString::size_type endoffset = strdata.FindChar(PRUnichar(','));
  while (PRInt32(endoffset) > 0) {
    intexts.AppendElement(Substring(strdata, startoffset,
      endoffset - startoffset));
    startoffset = endoffset + 1;
    endoffset = strdata.FindChar(PRUnichar(','), startoffset);
  }
  if (startoffset < strdata.Length())
    intexts.AppendElement(Substring(strdata, startoffset,
      strdata.Length() - startoffset));

  // Get the day/night values
  nsCOMPtr<nsISupportsString> daynightstr;
  rv = branch->GetComplexValue("daynights",
    NS_GET_IID(nsISupportsString), getter_AddRefs(daynightstr));
  if (NS_FAILED(rv))
    return rv;
  daynightstr->ToString(getter_Copies(strdata));
  nsTArray<nsString> daynights;
  startoffset = 0;
  endoffset = strdata.FindChar(PRUnichar(','));
  while (PRInt32(endoffset) > 0) {
    daynights.AppendElement(Substring(strdata, startoffset,
      endoffset - startoffset));
    startoffset = endoffset + 1;
    endoffset = strdata.FindChar(PRUnichar(','), startoffset);
  }
  if (startoffset < strdata.Length())
    daynights.AppendElement(Substring(strdata, startoffset,
      strdata.Length() - startoffset));

  aIntExt.Truncate();
  aSetting.Truncate();
  aDayNight.Truncate();

  nsAString::const_iterator start, end;
  aHeading.BeginReading(start);
  aHeading.EndReading(end); // This is a one-past-the-end pointer!
  PRUint32 maxfindlen = 0;

  // Skip any prefix characters (e.g., scene numbers)
  while (kPrefixChars.FindChar(*start) >= 0)
    ++start;

  // Find the longest match for an int/ext string
  for (PRUint32 i = 0; i < intexts.Length(); ++i) {
    const nsAString& pattern = intexts[i];
    nsAString::const_iterator aStart = start;
    nsAString::const_iterator aEnd = end;
    if (pattern.Length() <= maxfindlen)
      continue;
    if (CaseInsensitiveFindInReadable(pattern, aStart, aEnd) &&
        aStart == start) {
      maxfindlen = pattern.Length();
      // The odds of assigning more than once should be zero for most locales
      aIntExt = pattern;
    }
  }
  start.advance(maxfindlen);

  // Skip any separator characters
  while (*start && kSeparatorChars.FindChar(*start) >= 0)
    ++start;

  // Find the longest match for a day/night string
  maxfindlen = 0;
  nsCaseInsensitiveStringComparator insensitive;
  for (PRUint32 i = 0; i < daynights.Length(); ++i) {
    const nsAString& pattern = daynights[i];
    nsAString::const_iterator aStart = start;
    nsAString::const_iterator aEnd = end;
    if (pattern.Length() <= maxfindlen)
      continue;
//.........这里部分代码省略.........
开发者ID:VividOperatingSystem,项目名称:celtx,代码行数:101,代码来源:nsSceneTracker.cpp

示例2: NS_ABORT_IF_FALSE

void
nsDOMTokenList::RemoveInternal(const nsAttrValue* aAttr,
                               const nsAString& aToken)
{
  NS_ABORT_IF_FALSE(aAttr, "Need an attribute");

  nsAutoString input;
  aAttr->ToString(input);

  nsAString::const_iterator copyStart, tokenStart, iter, end;
  input.BeginReading(iter);
  input.EndReading(end);
  copyStart = iter;

  nsAutoString output;
  bool lastTokenRemoved = false;

  while (iter != end) {
    // skip whitespace.
    while (iter != end && nsContentUtils::IsHTMLWhitespace(*iter)) {
      ++iter;
    }

    if (iter == end) {
      // At this point we're sure the last seen token (if any) wasn't to be
      // removed. So the trailing spaces will need to be kept.
      NS_ABORT_IF_FALSE(!lastTokenRemoved, "How did this happen?");

      output.Append(Substring(copyStart, end));
      break;
    }

    tokenStart = iter;
    do {
      ++iter;
    } while (iter != end && !nsContentUtils::IsHTMLWhitespace(*iter));

    if (Substring(tokenStart, iter).Equals(aToken)) {

      // Skip whitespace after the token, it will be collapsed.
      while (iter != end && nsContentUtils::IsHTMLWhitespace(*iter)) {
        ++iter;
      }
      copyStart = iter;
      lastTokenRemoved = true;

    } else {

      if (lastTokenRemoved && !output.IsEmpty()) {
        NS_ABORT_IF_FALSE(!nsContentUtils::IsHTMLWhitespace(
          output.CharAt(output.Length() - 1)), "Invalid last output token");
        output.Append(PRUnichar(' '));
      }
      lastTokenRemoved = false;
      output.Append(Substring(copyStart, iter));
      copyStart = iter;
    }
  }

  mElement->SetAttr(kNameSpaceID_None, mAttrAtom, output, true);
}
开发者ID:AntonSilviu,项目名称:v8monkey,代码行数:61,代码来源:nsDOMTokenList.cpp

示例3: GdkErrorHandler

/* See https://bugzilla.gnome.org/show_bug.cgi?id=629608#c8
 *
 * GDK implements X11 error traps to ignore X11 errors.
 * Unfortunatelly We don't know which X11 events can be ignored
 * so we have to utilize the Gdk error handler to avoid
 * false alarms in Gtk3.
 */
static void
GdkErrorHandler(const gchar *log_domain, GLogLevelFlags log_level,
                const gchar *message,  gpointer user_data)
{
  if (strstr(message, "X Window System error")) {
    XErrorEvent event;
    nsDependentCString buffer(message);
    char *endptr;

    /* Parse Gdk X Window error message which has this format:
     * (Details: serial XXXX error_code XXXX request_code XXXX (XXXX) minor_code XXXX)
     */
    NS_NAMED_LITERAL_CSTRING(serialString, "(Details: serial ");
    int32_t start = buffer.Find(serialString);
    if (start == kNotFound)
      NS_RUNTIMEABORT(message);

    start += serialString.Length();
    errno = 0;
    event.serial = strtol(buffer.BeginReading() + start, &endptr, 10);
    if (errno)
      NS_RUNTIMEABORT(message);

    NS_NAMED_LITERAL_CSTRING(errorCodeString, " error_code ");    
    if (!StringBeginsWith(Substring(endptr, buffer.EndReading()), errorCodeString))
      NS_RUNTIMEABORT(message);

    errno = 0;
    event.error_code = strtol(endptr + errorCodeString.Length(), &endptr, 10);
    if (errno)
      NS_RUNTIMEABORT(message);

    NS_NAMED_LITERAL_CSTRING(requestCodeString, " request_code ");
    if (!StringBeginsWith(Substring(endptr, buffer.EndReading()), requestCodeString))
      NS_RUNTIMEABORT(message);

    errno = 0;
    event.request_code = strtol(endptr + requestCodeString.Length(), &endptr, 10);
    if (errno)
      NS_RUNTIMEABORT(message);

    NS_NAMED_LITERAL_CSTRING(minorCodeString, " minor_code ");
    start = buffer.Find(minorCodeString, endptr - buffer.BeginReading());
    if (!start)
      NS_RUNTIMEABORT(message);

    errno = 0;
    event.minor_code = strtol(buffer.BeginReading() + start + minorCodeString.Length(), nullptr, 10);
    if (errno)
      NS_RUNTIMEABORT(message);

    event.display = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
    // Gdk does not provide resource ID
    event.resourceid = 0;

    X11Error(event.display, &event);
  } else {
    g_log_default_handler(log_domain, log_level, message, user_data);
    NS_RUNTIMEABORT(message);
  }
}
开发者ID:Andrel322,项目名称:gecko-dev,代码行数:68,代码来源:nsGDKErrorHandler.cpp

示例4: switch

bool nsPropertiesParser::ParseValueCharacter(
    PRUnichar c, const PRUnichar* cur, const PRUnichar* &tokenStart,
    nsAString& oldValue)
{
  switch (mSpecialState) {

    // the normal state - look for special characters
  case eParserSpecial_None:
    switch (c) {
    case '\\':
      if (mHaveMultiLine)
        // there is nothing to append to mValue yet
        mHaveMultiLine = false;
      else
        mValue += Substring(tokenStart, cur);

      mSpecialState = eParserSpecial_Escaped;
      break;

    case '\n':
      // if we detected multiline and got only "\\\r" ignore next "\n" if any
      if (mHaveMultiLine && mMultiLineCanSkipN) {
        // but don't allow another '\n' to be skipped
        mMultiLineCanSkipN = false;
        // Now there is nothing to append to the mValue since we are skipping
        // whitespaces at the beginning of the new line of the multiline
        // property. Set tokenStart properly to ensure that nothing is appended
        // if we find regular line-end or the end of the buffer.
        tokenStart = cur+1;
        break;
      }
      // no break

    case '\r':
      // we're done! We have a key and value
      mValue += Substring(tokenStart, cur);
      FinishValueState(oldValue);
      mHaveMultiLine = false;
      break;

    default:
      // there is nothing to do with normal characters,
      // but handle multilines correctly
      if (mHaveMultiLine) {
        if (c == ' ' || c == '\t') {
          // don't allow another '\n' to be skipped
          mMultiLineCanSkipN = false;
          // Now there is nothing to append to the mValue since we are skipping
          // whitespaces at the beginning of the new line of the multiline
          // property. Set tokenStart properly to ensure that nothing is appended
          // if we find regular line-end or the end of the buffer.
          tokenStart = cur+1;
          break;
        }
        mHaveMultiLine = false;
        tokenStart = cur;
      }
      break; // from switch on (c)
    }
    break; // from switch on (mSpecialState)

    // saw a \ character, so parse the character after that
  case eParserSpecial_Escaped:
    // probably want to start parsing at the next token
    // other characters, like 'u' might override this
    tokenStart = cur+1;
    mSpecialState = eParserSpecial_None;

    switch (c) {

      // the easy characters - \t, \n, and so forth
    case 't':
      mValue += PRUnichar('\t');
      mMinLength = mValue.Length();
      break;
    case 'n':
      mValue += PRUnichar('\n');
      mMinLength = mValue.Length();
      break;
    case 'r':
      mValue += PRUnichar('\r');
      mMinLength = mValue.Length();
      break;
    case '\\':
      mValue += PRUnichar('\\');
      break;

      // switch to unicode mode!
    case 'u':
    case 'U':
      mSpecialState = eParserSpecial_Unicode;
      mUnicodeValuesRead = 0;
      mUnicodeValue = 0;
      break;

      // a \ immediately followed by a newline means we're going multiline
    case '\r':
    case '\n':
      mHaveMultiLine = true;
      mMultiLineCanSkipN = (c == '\r');
//.........这里部分代码省略.........
开发者ID:Tripleman,项目名称:mozilla-central,代码行数:101,代码来源:nsPersistentProperties.cpp

示例5: MAC8

EXPORT char *   MAC8(char * data,int dataLength, char * ran, char * key8)
{
	char result[17] ;
	char d3[17] ;
	char d4[17];
	unsigned char Ran9[9];
	unsigned char Prtwmp[17];
	unsigned char key8aaa[strlen(key8)/2];Hex2Bin(key8,key8aaa);
	if (dataLength >= 16)
	{
		
		Substring(data,0, 16,d3);
		Prtwmp[16] = 0x00;
		XOR(PadRight( Substring(ran,0,8,Ran9),16,'0',Prtwmp),d3,dataLength,result);
		result[16]=0;
		if (dataLength % 16 == 0)
		{
			unsigned char temp777[8];
			int i;
			for (  i = 1; i < dataLength / 16; i++)
			{
				Hex2Bin(result,temp777);//temp777=Hex2Bin(result);
				enc(key8aaa, temp777);
				Bin2Hex(temp777,8,result);
				Substring(data,i * 16, 16,d3);
				XOR(result, d3,16,result);
				memcpy(d4,(char *)"8000000000000000",16);
				d4[16] = 0x00;
			}
			if (dataLength == 16) 
			{
				memcpy(d4,(char*)"8000000000000000",16);
				d4[16] = 0x00;
			}
			Hex2Bin(result,temp777);
			enc(key8aaa, temp777);
			Bin2Hex(temp777,8,result);
			XOR(result, d4,16,result);
			Hex2Bin(result,temp777);
			enc(key8aaa, temp777);
			Bin2Hex(temp777,8,result);

		}
		else
		{
			int i;
			unsigned char tmp999[8];
			char *tmpx99x;
			unsigned char tmp999keya[strlen(key8)/2];Hex2Bin(key8,tmp999keya);
			for ( i= 1; i < dataLength / 16; i++)
			{
				unsigned char tmp888[8];Hex2Bin(result,tmp888);
				enc(key8aaa, tmp888);
				Substring(data,i * 16, 16,d3);
				Bin2Hex(tmp888,8,result);
				XOR(result, d3,16,result);

			}

			Substring(data,dataLength - dataLength % 16, dataLength % 16,d4);			
			strcat(d4,"8");
			PadRight(d4,16, '0',d4);
			Hex2Bin(result,tmp999);
			enc(tmp999keya, tmp999);
			Bin2Hex(tmp999,8,result);
			XOR(result, d4,16,result);
			Hex2Bin(result,tmp999);
			enc(tmp999keya, tmp999);
			Bin2Hex(tmp999,8,result);
		}
	}
	else
	{
		unsigned char tmp888111[8];
		unsigned char PdTemp[17];
		sprintf(d3,"%s%s", data, "8");
		PadRight(d3,16, '0',d3);
		PdTemp[16] = 0;
		XOR(PadRight( Substring(ran,0, 8,Ran9),16, '0',PdTemp), d3,16,result);
		Hex2Bin(result,tmp888111);
		enc(key8aaa, tmp888111);
		Bin2Hex(tmp888111,8,result);
	}
	memset(___MAC8,0x00,9);
	memcpy(___MAC8,result,8);
	return ___MAC8;
}
开发者ID:moyuanming,项目名称:NWeight,代码行数:87,代码来源:mac.c

示例6: do_QueryInterface

already_AddRefed<Promise>
DataTransfer::GetFilesAndDirectories(ErrorResult& aRv)
{
  nsCOMPtr<nsINode> parentNode = do_QueryInterface(mParent);
  if (!parentNode) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  nsCOMPtr<nsIGlobalObject> global = parentNode->OwnerDoc()->GetScopeObject();
  MOZ_ASSERT(global);
  if (!global) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  RefPtr<Promise> p = Promise::Create(global, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  if (!mFiles) {
    GetFiles(aRv);
    if (NS_WARN_IF(aRv.Failed())) {
      return nullptr;
    }
  }

  Sequence<OwningFileOrDirectory> filesAndDirsSeq;

  if (mFiles && mFiles->Length()) {
    if (!filesAndDirsSeq.SetLength(mFiles->Length(), mozilla::fallible_t())) {
      p->MaybeReject(NS_ERROR_OUT_OF_MEMORY);
      return p.forget();
    }

    nsPIDOMWindow* window = parentNode->OwnerDoc()->GetInnerWindow();

    RefPtr<OSFileSystem> fs;
    for (uint32_t i = 0; i < mFiles->Length(); ++i) {
      if (mFiles->Item(i)->Impl()->IsDirectory()) {
#if defined(ANDROID) || defined(MOZ_B2G)
        MOZ_ASSERT(false,
                   "Directory picking should have been redirected to normal "
                   "file picking for platforms that don't have a directory "
                   "picker");
#endif
        nsAutoString path;
        mFiles->Item(i)->GetMozFullPathInternal(path, aRv);
        if (aRv.Failed()) {
          return nullptr;
        }
        int32_t leafSeparatorIndex = path.RFind(FILE_PATH_SEPARATOR);
        nsDependentSubstring dirname = Substring(path, 0, leafSeparatorIndex);
        nsDependentSubstring basename = Substring(path, leafSeparatorIndex);
        fs = MakeOrReuseFileSystem(dirname, fs, window);
        filesAndDirsSeq[i].SetAsDirectory() = new Directory(fs, basename);
      } else {
        filesAndDirsSeq[i].SetAsFile() = mFiles->Item(i);
      }
    }
  }

  p->MaybeResolve(filesAndDirsSeq);

  return p.forget();
}
开发者ID:tarosuzuki,项目名称:gecko-dev,代码行数:67,代码来源:DataTransfer.cpp

示例7: defined

nsresult
nsXREDirProvider::GetUpdateRootDir(nsIFile* *aResult)
{
  nsCOMPtr<nsIFile> updRoot;
#if defined(MOZ_WIDGET_GONK)

  nsresult rv = NS_NewNativeLocalFile(nsDependentCString("/data/local"),
                                      true,
                                      getter_AddRefs(updRoot));
  NS_ENSURE_SUCCESS(rv, rv);

#else
  nsCOMPtr<nsIFile> appFile;
  bool per = false;
  nsresult rv = GetFile(XRE_EXECUTABLE_FILE, &per, getter_AddRefs(appFile));
  NS_ENSURE_SUCCESS(rv, rv);
  rv = appFile->GetParent(getter_AddRefs(updRoot));
  NS_ENSURE_SUCCESS(rv, rv);

#ifdef XP_WIN

  nsAutoString pathHash;
  bool pathHashResult = false;

  nsAutoString appDirPath;
  if (gAppData->vendor && !getenv("MOZ_UPDATE_NO_HASH_DIR") &&
      SUCCEEDED(updRoot->GetPath(appDirPath))) {

    // Figure out where we should check for a cached hash value
    wchar_t regPath[1024] = { L'\0' };
    swprintf_s(regPath, mozilla::ArrayLength(regPath), L"SOFTWARE\\%S\\%S\\TaskBarIDs",
               gAppData->vendor, MOZ_APP_NAME);

    // If we pre-computed the hash, grab it from the registry.
    pathHashResult = GetCachedHash(HKEY_LOCAL_MACHINE,
                                   nsDependentString(regPath), appDirPath,
                                   pathHash);
    if (!pathHashResult) {
      pathHashResult = GetCachedHash(HKEY_CURRENT_USER,
                                     nsDependentString(regPath), appDirPath,
                                     pathHash);
    }
  }

  // Get the local app data directory and if a vendor name exists append it.
  // If only a product name exists, append it.  If neither exist fallback to
  // old handling.  We don't use the product name on purpose because we want a
  // shared update directory for different apps run from the same path (like
  // Metro & Desktop).
  nsCOMPtr<nsIFile> localDir;
  if (pathHashResult && (gAppData->vendor || gAppData->name) &&
      NS_SUCCEEDED(GetUserDataDirectoryHome(getter_AddRefs(localDir), true)) &&
      NS_SUCCEEDED(localDir->AppendNative(nsDependentCString(gAppData->vendor ?
                                          gAppData->vendor : gAppData->name))) &&
      NS_SUCCEEDED(localDir->Append(NS_LITERAL_STRING("updates"))) &&
      NS_SUCCEEDED(localDir->Append(pathHash))) {
    NS_ADDREF(*aResult = localDir);
    return NS_OK;
  }

  nsAutoString appPath;
  rv = updRoot->GetPath(appPath);
  NS_ENSURE_SUCCESS(rv, rv);

  // AppDir may be a short path. Convert to long path to make sure
  // the consistency of the update folder location
  nsString longPath;
  PRUnichar* buf;

  uint32_t bufLength = longPath.GetMutableData(&buf, MAXPATHLEN);
  NS_ENSURE_TRUE(bufLength >= MAXPATHLEN, NS_ERROR_OUT_OF_MEMORY);

  DWORD len = GetLongPathNameW(appPath.get(), buf, bufLength);

  // Failing GetLongPathName() is not fatal.
  if (len <= 0 || len >= bufLength)
    longPath.Assign(appPath);
  else
    longPath.SetLength(len);

  // Use <UserLocalDataDir>\updates\<relative path to app dir from
  // Program Files> if app dir is under Program Files to avoid the
  // folder virtualization mess on Windows Vista
  nsAutoString programFiles;
  rv = GetShellFolderPath(CSIDL_PROGRAM_FILES, programFiles);
  NS_ENSURE_SUCCESS(rv, rv);

  programFiles.AppendLiteral("\\");
  uint32_t programFilesLen = programFiles.Length();

  nsAutoString programName;
  if (_wcsnicmp(programFiles.get(), longPath.get(), programFilesLen) == 0) {
    programName = Substring(longPath, programFilesLen);
  } else {
    // We need the update root directory to live outside of the installation
    // directory, because otherwise the updater writing the log file can cause
    // the directory to be locked, which prevents it from being replaced after
    // background updates.
    programName.AssignASCII(MOZ_APP_NAME);
  }
//.........这里部分代码省略.........
开发者ID:drexler,项目名称:releases-mozilla-aurora,代码行数:101,代码来源:nsXREDirProvider.cpp

示例8: loadTestEVInfos

static void
loadTestEVInfos()
{
  if (!testEVInfos)
    return;

  testEVInfos->Clear();

  char *env_val = getenv("ENABLE_TEST_EV_ROOTS_FILE");
  if (!env_val)
    return;
    
  int enabled_val = atoi(env_val);
  if (!enabled_val)
    return;

  nsCOMPtr<nsIFile> aFile;
  NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(aFile));
  if (!aFile)
    return;

  aFile->AppendNative(NS_LITERAL_CSTRING(kTestEVRootsFileName));

  nsresult rv;
  nsCOMPtr<nsIInputStream> fileInputStream;
  rv = NS_NewLocalFileInputStream(getter_AddRefs(fileInputStream), aFile);
  if (NS_FAILED(rv))
    return;

  nsCOMPtr<nsILineInputStream> lineInputStream = do_QueryInterface(fileInputStream, &rv);
  if (NS_FAILED(rv))
    return;

  nsCAutoString buffer;
  bool isMore = true;

  /* file format
   *
   * file format must be strictly followed
   * strings in file must be UTF-8
   * each record consists of multiple lines
   * each line consists of a descriptor, a single space, and the data
   * the descriptors are:
   *   1_fingerprint (in format XX:XX:XX:...)
   *   2_readable_oid (treated as a comment)
   * the input file must strictly follow this order
   * the input file may contain 0, 1 or many records
   * completely empty lines are ignored
   * lines that start with the # char are ignored
   */

  int line_counter = 0;
  bool found_error = false;

  enum { 
    pos_fingerprint, pos_readable_oid, pos_issuer, pos_serial
  } reader_position = pos_fingerprint;

  nsCString fingerprint, readable_oid, issuer, serial;

  while (isMore && NS_SUCCEEDED(lineInputStream->ReadLine(buffer, &isMore))) {
    ++line_counter;
    if (buffer.IsEmpty() || buffer.First() == '#') {
      continue;
    }

    int32_t seperatorIndex = buffer.FindChar(' ', 0);
    if (seperatorIndex == 0) {
      found_error = true;
      break;
    }

    const nsASingleFragmentCString &descriptor = Substring(buffer, 0, seperatorIndex);
    const nsASingleFragmentCString &data = 
            Substring(buffer, seperatorIndex + 1, 
                      buffer.Length() - seperatorIndex + 1);

    if (reader_position == pos_fingerprint &&
        descriptor.EqualsLiteral(("1_fingerprint"))) {
      fingerprint = data;
      reader_position = pos_readable_oid;
      continue;
    }
    else if (reader_position == pos_readable_oid &&
        descriptor.EqualsLiteral(("2_readable_oid"))) {
      readable_oid = data;
      reader_position = pos_issuer;
      continue;
    }
    else if (reader_position == pos_issuer &&
        descriptor.EqualsLiteral(("3_issuer"))) {
      issuer = data;
      reader_position = pos_serial;
      continue;
    }
    else if (reader_position == pos_serial &&
        descriptor.EqualsLiteral(("4_serial"))) {
      serial = data;
      reader_position = pos_fingerprint;
    }
//.........这里部分代码省略.........
开发者ID:michaelwu,项目名称:mozilla-central,代码行数:101,代码来源:nsIdentityChecking.cpp

示例9: prefs

PRBool gfxPlatform::ForEachPrefFont(eFontPrefLang aLangArray[], PRUint32 aLangArrayLen, PrefFontCallback aCallback,
                                    void *aClosure)
{
    nsresult rv;

    nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
    if (!prefs)
        return PR_FALSE;

    PRUint32    i;
    
    for (i = 0; i < aLangArrayLen; i++) {
        eFontPrefLang prefLang = aLangArray[i];
        const char *langGroup = GetPrefLangName(prefLang);
        
        nsCAutoString prefName;
        nsXPIDLCString nameValue, nameListValue;
    
        nsCAutoString genericDotLang;
        prefName.AssignLiteral("font.default.");
        prefName.Append(langGroup);
        prefs->GetCharPref(prefName.get(), getter_Copies(genericDotLang));
    
        genericDotLang.AppendLiteral(".");
        genericDotLang.Append(langGroup);
    
        // fetch font.name.xxx value                   
        prefName.AssignLiteral("font.name.");
        prefName.Append(genericDotLang);
        rv = prefs->GetCharPref(prefName.get(), getter_Copies(nameValue));
        if (NS_SUCCEEDED(rv)) {
            if (!aCallback(prefLang, NS_ConvertUTF8toUTF16(nameValue), aClosure))
                return PR_FALSE;
        }
    
        // fetch font.name-list.xxx value                   
        prefName.AssignLiteral("font.name-list.");
        prefName.Append(genericDotLang);
        rv = prefs->GetCharPref(prefName.get(), getter_Copies(nameListValue));
        if (NS_SUCCEEDED(rv) && !nameListValue.Equals(nameValue)) {
            const char kComma = ',';
            const char *p, *p_end;
            nsCAutoString list(nameListValue);
            list.BeginReading(p);
            list.EndReading(p_end);
            while (p < p_end) {
                while (nsCRT::IsAsciiSpace(*p)) {
                    if (++p == p_end)
                        break;
                }
                if (p == p_end)
                    break;
                const char *start = p;
                while (++p != p_end && *p != kComma)
                    /* nothing */ ;
                nsCAutoString fontName(Substring(start, p));
                fontName.CompressWhitespace(PR_FALSE, PR_TRUE);
                if (!aCallback(prefLang, NS_ConvertUTF8toUTF16(fontName), aClosure))
                    return PR_FALSE;
                p++;
            }
        }
    }

    return PR_TRUE;
}
开发者ID:LittleForker,项目名称:mozilla-central,代码行数:66,代码来源:gfxPlatform.cpp

示例10: do_GetService

nsresult
nsIndexedToHTML::FormatInputStream(nsIRequest* aRequest, nsISupports *aContext, const nsAString &aBuffer) 
{
    nsresult rv = NS_OK;

    // set up unicode encoder
    if (!mUnicodeEncoder) {
      nsXPIDLCString encoding;
      rv = mParser->GetEncoding(getter_Copies(encoding));
      if (NS_SUCCEEDED(rv)) {
        nsCOMPtr<nsICharsetConverterManager> charsetConverterManager;
        charsetConverterManager = do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv);
        rv = charsetConverterManager->GetUnicodeEncoder(encoding.get(), 
                                                          getter_AddRefs(mUnicodeEncoder));
        if (NS_SUCCEEDED(rv))
            rv = mUnicodeEncoder->SetOutputErrorBehavior(nsIUnicodeEncoder::kOnError_Replace, 
                                                       nullptr, (PRUnichar)'?');
      }
    }

    // convert the data with unicode encoder
    char *buffer = nullptr;
    int32_t dstLength;
    if (NS_SUCCEEDED(rv)) {
      int32_t unicharLength = aBuffer.Length();
      rv = mUnicodeEncoder->GetMaxLength(PromiseFlatString(aBuffer).get(), 
                                         unicharLength, &dstLength);
      if (NS_SUCCEEDED(rv)) {
        buffer = (char *) nsMemory::Alloc(dstLength);
        NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY);

        rv = mUnicodeEncoder->Convert(PromiseFlatString(aBuffer).get(), &unicharLength, 
                                      buffer, &dstLength);
        if (NS_SUCCEEDED(rv)) {
          int32_t finLen = 0;
          rv = mUnicodeEncoder->Finish(buffer + dstLength, &finLen);
          if (NS_SUCCEEDED(rv))
            dstLength += finLen;
        }
      }
    }

    // if conversion error then fallback to UTF-8
    if (NS_FAILED(rv)) {
      rv = NS_OK;
      if (buffer) {
        nsMemory::Free(buffer);
        buffer = nullptr;
      }
    }

    nsCOMPtr<nsIInputStream> inputData;
    if (buffer) {
      rv = NS_NewCStringInputStream(getter_AddRefs(inputData), Substring(buffer, dstLength));
      nsMemory::Free(buffer);
      NS_ENSURE_SUCCESS(rv, rv);
      rv = mListener->OnDataAvailable(aRequest, aContext,
                                      inputData, 0, dstLength);
    }
    else {
      NS_ConvertUTF16toUTF8 utf8Buffer(aBuffer);
      rv = NS_NewCStringInputStream(getter_AddRefs(inputData), utf8Buffer);
      NS_ENSURE_SUCCESS(rv, rv);
      rv = mListener->OnDataAvailable(aRequest, aContext,
                                      inputData, 0, utf8Buffer.Length());
    }
    return (rv);
}
开发者ID:mdevils,项目名称:services-central-legacy,代码行数:68,代码来源:nsIndexedToHTML.cpp

示例11: PR_LOG


//.........这里部分代码省略.........
    }

    uint32_t consumed;
    ParseBuffer(buffer, length, noMoreBuffers, &consumed);
    if (consumed > 0) {
      nsScannerIterator oldExpatPosition = currentExpatPosition;
      currentExpatPosition.advance(consumed);

      // We consumed some data, we want to store the last line of data that
      // was consumed in case we run into an error (to show the line in which
      // the error occurred).

      // The length of the last line that Expat has parsed.
      XML_Size lastLineLength = XML_GetCurrentColumnNumber(mExpatParser);

      if (lastLineLength <= consumed) {
        // The length of the last line was less than what expat consumed, so
        // there was at least one line break in the consumed data. Store the
        // last line until the point where we stopped parsing.
        nsScannerIterator startLastLine = currentExpatPosition;
        startLastLine.advance(-((ptrdiff_t)lastLineLength));
        CopyUnicodeTo(startLastLine, currentExpatPosition, mLastLine);
      }
      else {
        // There was no line break in the consumed data, append the consumed
        // data.
        AppendUnicodeTo(oldExpatPosition, currentExpatPosition, mLastLine);
      }
    }

    mExpatBuffered += length - consumed;

    if (BlockedOrInterrupted()) {
      PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
             ("Blocked or interrupted parser (probably for loading linked "
              "stylesheets or scripts)."));

      aScanner.SetPosition(currentExpatPosition, true);
      aScanner.Mark();

      return mInternalState;
    }

    if (noMoreBuffers && mExpatBuffered == 0) {
      mMadeFinalCallToExpat = true;
    }

    if (NS_FAILED(mInternalState)) {
      if (XML_GetErrorCode(mExpatParser) != XML_ERROR_NONE) {
        NS_ASSERTION(mInternalState == NS_ERROR_HTMLPARSER_STOPPARSING,
                     "Unexpected error");

        // Look for the next newline after the last one we consumed
        nsScannerIterator lastLine = currentExpatPosition;
        while (lastLine != end) {
          length = uint32_t(lastLine.size_forward());
          uint32_t endOffset = 0;
          const PRUnichar *buffer = lastLine.get();
          while (endOffset < length && buffer[endOffset] != '\n' &&
                 buffer[endOffset] != '\r') {
            ++endOffset;
          }
          mLastLine.Append(Substring(buffer, buffer + endOffset));
          if (endOffset < length) {
            // We found a newline.
            break;
          }

          lastLine.advance(length);
        }

        HandleError();
      }

      return mInternalState;
    }

    // Either we have more buffers, or we were blocked (and we'll flush in the
    // next iteration), or we should have emptied Expat's buffer.
    NS_ASSERTION(!noMoreBuffers || blocked ||
                 (mExpatBuffered == 0 && currentExpatPosition == end),
                 "Unreachable data left in Expat's buffer");

    start.advance(length);

    // It's possible for start to have passed end if we received more data
    // (e.g. if we spun the event loop in an inline script). Reload end now
    // to compensate.
    aScanner.EndReading(end);
  }

  aScanner.SetPosition(currentExpatPosition, true);
  aScanner.Mark();

  PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
         ("Remaining in expat's buffer: %i, remaining in scanner: %i.",
          mExpatBuffered, Distance(currentExpatPosition, end)));

  return NS_SUCCEEDED(mInternalState) ? kEOF : NS_OK;
}
开发者ID:Lynart,项目名称:mozilla-central,代码行数:101,代码来源:nsExpatDriver.cpp

示例12: NS_NewLocalFileInputStream

nsresult
nsDogbertProfileMigrator::FixDogbertCookies()
{
  nsCOMPtr<nsIFile> dogbertCookiesFile;
  mSourceProfile->Clone(getter_AddRefs(dogbertCookiesFile));
  dogbertCookiesFile->Append(COOKIES_FILE_NAME_IN_4x);

  nsCOMPtr<nsIInputStream> fileInputStream;
  NS_NewLocalFileInputStream(getter_AddRefs(fileInputStream), dogbertCookiesFile);
  if (!fileInputStream) return NS_ERROR_OUT_OF_MEMORY;

  nsCOMPtr<nsIFile> firebirdCookiesFile;
  mTargetProfile->Clone(getter_AddRefs(firebirdCookiesFile));
  firebirdCookiesFile->Append(COOKIES_FILE_NAME_IN_5x);

  nsCOMPtr<nsIOutputStream> fileOutputStream;
  NS_NewLocalFileOutputStream(getter_AddRefs(fileOutputStream), firebirdCookiesFile);
  if (!fileOutputStream) return NS_ERROR_OUT_OF_MEMORY;

  nsCOMPtr<nsILineInputStream> lineInputStream(do_QueryInterface(fileInputStream));
  nsCAutoString buffer, outBuffer;
  PRBool moreData = PR_FALSE;
  PRUint32 written = 0;
  do {
    nsresult rv = lineInputStream->ReadLine(buffer, &moreData);
    if (NS_FAILED(rv)) return rv;
    
    if (!moreData)
      break;

    // skip line if it is a comment or null line
    if (buffer.IsEmpty() || buffer.CharAt(0) == '#' ||
        buffer.CharAt(0) == '\r' || buffer.CharAt(0) == '\n') {
      fileOutputStream->Write(buffer.get(), buffer.Length(), &written);
      continue;
    }

    // locate expire field, skip line if it does not contain all its fields
    int hostIndex, isDomainIndex, pathIndex, xxxIndex, expiresIndex, nameIndex, cookieIndex;
    hostIndex = 0;
    if ((isDomainIndex = buffer.FindChar('\t', hostIndex)+1) == 0 ||
        (pathIndex = buffer.FindChar('\t', isDomainIndex)+1) == 0 ||
        (xxxIndex = buffer.FindChar('\t', pathIndex)+1) == 0 ||
        (expiresIndex = buffer.FindChar('\t', xxxIndex)+1) == 0 ||
        (nameIndex = buffer.FindChar('\t', expiresIndex)+1) == 0 ||
        (cookieIndex = buffer.FindChar('\t', nameIndex)+1) == 0 )
      continue;

    // separate the expires field from the rest of the cookie line
    const nsDependentCSubstring prefix = 
      Substring(buffer, hostIndex, expiresIndex-hostIndex-1);
    const nsDependentCSubstring expiresString =
      Substring(buffer, expiresIndex, nameIndex-expiresIndex-1);
    const nsDependentCSubstring suffix =
      Substring(buffer, nameIndex, buffer.Length()-nameIndex);

    // correct the expires field
    char* expiresCString = ToNewCString(expiresString);
    unsigned long expires = strtoul(expiresCString, nsnull, 10);
    NS_Free(expiresCString);

    // if the cookie is supposed to expire at the end of the session
    // expires == 0.  don't adjust those cookies.
    if (expires)
    	expires -= SECONDS_BETWEEN_1900_AND_1970;
    char dateString[36];
    PR_snprintf(dateString, sizeof(dateString), "%lu", expires);

    // generate the output buffer and write it to file
    outBuffer = prefix;
    outBuffer.Append('\t');
    outBuffer.Append(dateString);
    outBuffer.Append('\t');
    outBuffer.Append(suffix);

    fileOutputStream->Write(outBuffer.get(), outBuffer.Length(), &written);
  }
  while (1);
  
  return NS_OK;
}
开发者ID:AllenDou,项目名称:firefox,代码行数:81,代码来源:nsDogbertProfileMigrator.cpp

示例13: do_QueryInterface

void 
ImageDocument::UpdateTitleAndCharset()
{
  nsAutoCString typeStr;
  nsCOMPtr<imgIRequest> imageRequest;
  nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mImageContent);
  if (imageLoader) {
    imageLoader->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
                            getter_AddRefs(imageRequest));
  }
    
  if (imageRequest) {
    nsXPIDLCString mimeType;
    imageRequest->GetMimeType(getter_Copies(mimeType));
    ToUpperCase(mimeType);
    nsXPIDLCString::const_iterator start, end;
    mimeType.BeginReading(start);
    mimeType.EndReading(end);
    nsXPIDLCString::const_iterator iter = end;
    if (FindInReadable(NS_LITERAL_CSTRING("IMAGE/"), start, iter) && 
        iter != end) {
      // strip out "X-" if any
      if (*iter == 'X') {
        ++iter;
        if (iter != end && *iter == '-') {
          ++iter;
          if (iter == end) {
            // looks like "IMAGE/X-" is the type??  Bail out of here.
            mimeType.BeginReading(iter);
          }
        } else {
          --iter;
        }
      }
      typeStr = Substring(iter, end);
    } else {
      typeStr = mimeType;
    }
  }

  nsXPIDLString status;
  if (mImageIsResized) {
    nsAutoString ratioStr;
    ratioStr.AppendInt(NSToCoordFloor(GetRatio() * 100));

    const PRUnichar* formatString[1] = { ratioStr.get() };
    mStringBundle->FormatStringFromName(NS_LITERAL_STRING("ScaledImage").get(),
                                        formatString, 1,
                                        getter_Copies(status));
  }

  static const char* const formatNames[4] = 
  {
    "ImageTitleWithNeitherDimensionsNorFile",
    "ImageTitleWithoutDimensions",
    "ImageTitleWithDimensions",
    "ImageTitleWithDimensionsAndFile",
  };

  MediaDocument::UpdateTitleAndCharset(typeStr, formatNames,
                                       mImageWidth, mImageHeight, status);
}
开发者ID:Jaxo,项目名称:releases-mozilla-central,代码行数:62,代码来源:ImageDocument.cpp

示例14: NS_ENSURE_SUCCESS

nsresult
nsContentBlocker::TestPermission(nsIURI *aCurrentURI,
                                 nsIURI *aFirstURI,
                                 int32_t aContentType,
                                 bool *aPermission,
                                 bool *aFromPrefs)
{
  *aFromPrefs = false;
  // This default will also get used if there is an unknown value in the
  // permission list, or if the permission manager returns unknown values.
  *aPermission = true;

  // check the permission list first; if we find an entry, it overrides
  // default prefs.
  // Don't forget the aContentType ranges from 1..8, while the
  // array is indexed 0..7
  uint32_t permission;
  nsresult rv = mPermissionManager->TestPermission(aCurrentURI, 
                                                   kTypeString[aContentType - 1],
                                                   &permission);
  NS_ENSURE_SUCCESS(rv, rv);

  // If there is nothing on the list, use the default.
  if (!permission) {
    permission = mBehaviorPref[aContentType - 1];
    *aFromPrefs = true;
  }

  // Use the fact that the nsIPermissionManager values map to 
  // the BEHAVIOR_* values above.
  switch (permission) {
  case BEHAVIOR_ACCEPT:
    *aPermission = true;
    break;
  case BEHAVIOR_REJECT:
    *aPermission = false;
    break;

  case BEHAVIOR_NOFOREIGN:
    // Third party checking

    // Need a requesting uri for third party checks to work.
    if (!aFirstURI)
      return NS_OK;

    bool trustedSource = false;
    rv = aFirstURI->SchemeIs("chrome", &trustedSource);
    NS_ENSURE_SUCCESS(rv,rv);
    if (!trustedSource) {
      rv = aFirstURI->SchemeIs("resource", &trustedSource);
      NS_ENSURE_SUCCESS(rv,rv);
    }
    if (trustedSource)
      return NS_OK;

    // compare tails of names checking to see if they have a common domain
    // we do this by comparing the tails of both names where each tail 
    // includes at least one dot
    
    // A more generic method somewhere would be nice

    nsAutoCString currentHost;
    rv = aCurrentURI->GetAsciiHost(currentHost);
    NS_ENSURE_SUCCESS(rv, rv);

    // Search for two dots, starting at the end.
    // If there are no two dots found, ++dot will turn to zero,
    // that will return the entire string.
    int32_t dot = currentHost.RFindChar('.');
    dot = currentHost.RFindChar('.', dot-1);
    ++dot;

    // Get the domain, ie the last part of the host (www.domain.com -> domain.com)
    // This will break on co.uk
    const nsCSubstring &tail =
      Substring(currentHost, dot, currentHost.Length() - dot);

    nsAutoCString firstHost;
    rv = aFirstURI->GetAsciiHost(firstHost);
    NS_ENSURE_SUCCESS(rv, rv);

    // If the tail is longer then the whole firstHost, it will never match
    if (firstHost.Length() < tail.Length()) {
      *aPermission = false;
      return NS_OK;
    }
    
    // Get the last part of the firstUri with the same length as |tail|
    const nsCSubstring &firstTail = 
      Substring(firstHost, firstHost.Length() - tail.Length(), tail.Length());

    // Check that both tails are the same, and that just before the tail in
    // |firstUri| there is a dot. That means both url are in the same domain
    if ((firstHost.Length() > tail.Length() && 
         firstHost.CharAt(firstHost.Length() - tail.Length() - 1) != '.') || 
        !tail.Equals(firstTail)) {
      *aPermission = false;
    }
    break;
  }
//.........这里部分代码省略.........
开发者ID:JuannyWang,项目名称:gecko-dev,代码行数:101,代码来源:nsContentBlocker.cpp

示例15: MAC

char * MAC(char* data,int dataLength, char * ran, char * key16)
{
	int key16Length =32 ;
	char keya[17];
	char keyb[17];
	char d3[17];
	char d4[17];
	char result[17];
	memcpy( keya ,key16, key16Length / 2);
	memcpy( keyb  , (char*)&key16[key16Length / 2],key16Length / 2);
	keya[16]=0;
	keyb[16]=0;
	memset( d3 ,0x00,sizeof(d3));
	memset( d4 ,0x00,sizeof(d3));
	memset( result,0x00,sizeof(16));
	echomac("bb");
	if (dataLength >= 16)
	{
		unsigned char Ran9[9];
		unsigned char PrTemp[17];
		memcpy(d3, data, 16);
		PrTemp[16] = 0x00;
		d3[16]=0;
		XOR(PadRight(Substring(ran,0,8,Ran9), 16, '0',PrTemp),  d3,16,result);
		echomac("bb");
		if (dataLength % 16 == 0)
		{
			int i ;
			for ( i = 1; i <dataLength / 16; i++)
			{
				unsigned char resultBin[8],keyaBin[8] ;				;
				enc(Hex2Bin(keya,keyaBin), Hex2Bin(result,resultBin));
				Bin2Hex(resultBin,8,result);
				printf( result);
				Substring(data,i * 16, 16,d3);
				XOR(result, d3,16,result);
				memcpy(d4 , (char*)&"8000000000000000",16);
				echomac("bb");
			}
			if (dataLength == 16) 
			{
				memcpy(d4 ,"8000000000000000",16);
			}
			echomac("bb");
			unsigned char temp222[8];Hex2Bin(result,temp222);
			unsigned char keyaXXX[8];Hex2Bin(keya,keyaXXX);
			unsigned char keybXXX[8];Hex2Bin(keyb,keybXXX);
			enc(keyaXXX, temp222);
			Bin2Hex(temp222,8,result);			
			XOR(result, d4,16,result);			
			Hex2Bin(result,temp222);
			enc(keyaXXX, temp222);
			Bin2Hex(temp222,8,result);			
			dec(keybXXX, temp222);
			Bin2Hex(temp222,8,result);			
			enc(keyaXXX, temp222);
			Bin2Hex(temp222,8,result);	
			echomac("bb");
		}
		else
		{
			
			int i ;
			unsigned char keyaXXX1[8];Hex2Bin(keya,keyaXXX1);
			unsigned char keybXXX1[8];Hex2Bin(keyb,keybXXX1);
			echomac("bb");
			for ( i = 1; i < dataLength / 16; i++)
			{
				unsigned char temp4441[8];Hex2Bin(result,temp4441);
				unsigned char temp4442keya[8];Hex2Bin(keya,temp4442keya);
				enc(temp4442keya, temp4441);
				Bin2Hex(temp4441,8,result);
				Substring(data, i * 16, 16,d3);
				XOR(result, d3,16,result);
			}
			Substring(data,dataLength - dataLength % 16, dataLength % 16,d4);
			strcat(d4,"8");//可能有问题
			PadRight(d4,16, '0',d4);
			unsigned char temp555[8];Hex2Bin(result,temp555);
			enc(keyaXXX1, temp555);
			Bin2Hex(temp555,8,result);
			XOR(result,  d4,16,result);
			Hex2Bin(result,temp555);//temp555=Hex2Bin(result);
			enc(keyaXXX1, temp555);
			dec(keybXXX1, temp555);
			enc(keyaXXX1, temp555);
			Bin2Hex(temp555,8,result);
			echomac("bb");
		}
	}
	else
	{
		echomac("bb");
		unsigned char Ran9[9];
		unsigned char temp4442keya[8];Hex2Bin(keya,temp4442keya);
		unsigned char temp4442keyb[8];Hex2Bin(keyb,temp4442keyb);
		sprintf(d3,"%s%s",data,"8");
		PadRight(d3,16, '0',d3);
		PadRight(Substring(ran,0,8,Ran9),16,'0',result);
		XOR( result, d3,16,result);
//.........这里部分代码省略.........
开发者ID:moyuanming,项目名称:NWeight,代码行数:101,代码来源:mac.c


注:本文中的Substring函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。