Bug 995730 - Change xpcom/io/ to use 2 space indentation

This also removes trailing whitespace in reindented files.
This commit is contained in:
Birunthan Mohanathas
2014-05-05 20:30:43 +03:00
parent 34a78370e0
commit b7e2587f32
45 changed files with 10298 additions and 10263 deletions

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -19,67 +20,67 @@ template <typename T>
static void
Encode3to4(const unsigned char *src, T *dest)
{
uint32_t b32 = (uint32_t)0;
int i, j = 18;
uint32_t b32 = (uint32_t)0;
int i, j = 18;
for( i = 0; i < 3; i++ )
{
b32 <<= 8;
b32 |= (uint32_t)src[i];
}
for( i = 0; i < 3; i++ )
{
b32 <<= 8;
b32 |= (uint32_t)src[i];
}
for( i = 0; i < 4; i++ )
{
dest[i] = base[ (uint32_t)((b32>>j) & 0x3F) ];
j -= 6;
}
for( i = 0; i < 4; i++ )
{
dest[i] = base[ (uint32_t)((b32>>j) & 0x3F) ];
j -= 6;
}
}
template <typename T>
static void
Encode2to4(const unsigned char *src, T *dest)
{
dest[0] = base[ (uint32_t)((src[0]>>2) & 0x3F) ];
dest[1] = base[ (uint32_t)(((src[0] & 0x03) << 4) | ((src[1] >> 4) & 0x0F)) ];
dest[2] = base[ (uint32_t)((src[1] & 0x0F) << 2) ];
dest[3] = (unsigned char)'=';
dest[0] = base[ (uint32_t)((src[0]>>2) & 0x3F) ];
dest[1] = base[ (uint32_t)(((src[0] & 0x03) << 4) | ((src[1] >> 4) & 0x0F)) ];
dest[2] = base[ (uint32_t)((src[1] & 0x0F) << 2) ];
dest[3] = (unsigned char)'=';
}
template <typename T>
static void
Encode1to4(const unsigned char *src, T *dest)
{
dest[0] = base[ (uint32_t)((src[0]>>2) & 0x3F) ];
dest[1] = base[ (uint32_t)((src[0] & 0x03) << 4) ];
dest[2] = (unsigned char)'=';
dest[3] = (unsigned char)'=';
dest[0] = base[ (uint32_t)((src[0]>>2) & 0x3F) ];
dest[1] = base[ (uint32_t)((src[0] & 0x03) << 4) ];
dest[2] = (unsigned char)'=';
dest[3] = (unsigned char)'=';
}
template <typename T>
static void
Encode(const unsigned char *src, uint32_t srclen, T *dest)
{
while( srclen >= 3 )
{
Encode3to4(src, dest);
src += 3;
dest += 4;
srclen -= 3;
}
while( srclen >= 3 )
{
Encode3to4(src, dest);
src += 3;
dest += 4;
srclen -= 3;
}
switch( srclen )
{
case 2:
Encode2to4(src, dest);
break;
case 1:
Encode1to4(src, dest);
break;
case 0:
break;
default:
NS_NOTREACHED("coding error");
}
switch( srclen )
{
case 2:
Encode2to4(src, dest);
break;
case 1:
Encode1to4(src, dest);
break;
case 0:
break;
default:
NS_NOTREACHED("coding error");
}
}
// END base64 encode code copied and modified from NSPR.
@@ -128,7 +129,7 @@ EncodeInputStream_Encoder(nsIInputStream *aStream,
state->charsOnStack = 0;
}
// Encode the bulk of the
// Encode the bulk of the
uint32_t encodeLength = countRemaining - countRemaining % 3;
NS_ABORT_IF_FALSE(encodeLength % 3 == 0,
"Should have an exact number of triplets!");
@@ -153,7 +154,7 @@ EncodeInputStream_Encoder(nsIInputStream *aStream,
template <typename T>
nsresult
EncodeInputStream(nsIInputStream *aInputStream,
EncodeInputStream(nsIInputStream *aInputStream,
T &aDest,
uint32_t aCount,
uint32_t aOffset)
@@ -222,7 +223,7 @@ EncodeInputStream(nsIInputStream *aInputStream,
namespace mozilla {
nsresult
Base64EncodeInputStream(nsIInputStream *aInputStream,
Base64EncodeInputStream(nsIInputStream *aInputStream,
nsACString &aDest,
uint32_t aCount,
uint32_t aOffset)
@@ -231,7 +232,7 @@ Base64EncodeInputStream(nsIInputStream *aInputStream,
}
nsresult
Base64EncodeInputStream(nsIInputStream *aInputStream,
Base64EncodeInputStream(nsIInputStream *aInputStream,
nsAString &aDest,
uint32_t aCount,
uint32_t aOffset)
@@ -259,8 +260,8 @@ Base64Encode(const nsACString &aBinaryData, nsACString &aString)
// Add one byte for null termination.
if (aString.SetCapacity(stringLen + 1, fallible_t()) &&
(buffer = aString.BeginWriting()) &&
PL_Base64Encode(aBinaryData.BeginReading(), aBinaryData.Length(), buffer)) {
(buffer = aString.BeginWriting()) &&
PL_Base64Encode(aBinaryData.BeginReading(), aBinaryData.Length(), buffer)) {
// PL_Base64Encode doesn't null terminate the buffer for us when we pass
// the buffer in. Do that manually.
buffer[stringLen] = '\0';
@@ -309,8 +310,8 @@ Base64Decode(const nsACString &aString, nsACString &aBinaryData)
// Add one byte for null termination.
if (aBinaryData.SetCapacity(binaryDataLen + 1, fallible_t()) &&
(buffer = aBinaryData.BeginWriting()) &&
PL_Base64Decode(aString.BeginReading(), aString.Length(), buffer)) {
(buffer = aBinaryData.BeginWriting()) &&
PL_Base64Decode(aString.BeginReading(), aString.Length(), buffer)) {
// PL_Base64Decode doesn't null terminate the buffer for us when we pass
// the buffer in. Do that manually, taking into account the number of '='
// characters we were passed.

View File

@@ -13,12 +13,12 @@ class nsIInputStream;
namespace mozilla {
nsresult
Base64EncodeInputStream(nsIInputStream *aInputStream,
Base64EncodeInputStream(nsIInputStream *aInputStream,
nsACString &aDest,
uint32_t aCount,
uint32_t aOffset = 0);
nsresult
Base64EncodeInputStream(nsIInputStream *aInputStream,
Base64EncodeInputStream(nsIInputStream *aInputStream,
nsAString &aDest,
uint32_t aCount,
uint32_t aOffset = 0);

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -19,57 +20,57 @@ extern void StartupSpecialSystemDirectory();
enum SystemDirectories {
OS_DriveDirectory = 1,
OS_TemporaryDirectory = 2,
OS_CurrentProcessDirectory= 3,
OS_DriveDirectory = 1,
OS_TemporaryDirectory = 2,
OS_CurrentProcessDirectory= 3,
OS_CurrentWorkingDirectory= 4,
XPCOM_CurrentProcessComponentDirectory= 5,
XPCOM_CurrentProcessComponentRegistry= 6,
XPCOM_CurrentProcessComponentDirectory= 5,
XPCOM_CurrentProcessComponentRegistry= 6,
Moz_BinDirectory = 100 ,
Mac_SystemDirectory = 101,
Mac_DesktopDirectory = 102,
Mac_TrashDirectory = 103,
Mac_StartupDirectory = 104,
Mac_ShutdownDirectory = 105,
Mac_AppleMenuDirectory = 106,
Mac_ControlPanelDirectory = 107,
Mac_ExtensionDirectory = 108,
Mac_FontsDirectory = 109,
Mac_ClassicPreferencesDirectory = 110,
Mac_DocumentsDirectory = 111,
Mac_InternetSearchDirectory = 112,
Mac_DefaultDownloadDirectory = 113,
Mac_UserLibDirectory = 114,
Mac_SystemDirectory = 101,
Mac_DesktopDirectory = 102,
Mac_TrashDirectory = 103,
Mac_StartupDirectory = 104,
Mac_ShutdownDirectory = 105,
Mac_AppleMenuDirectory = 106,
Mac_ControlPanelDirectory = 107,
Mac_ExtensionDirectory = 108,
Mac_FontsDirectory = 109,
Mac_ClassicPreferencesDirectory = 110,
Mac_DocumentsDirectory = 111,
Mac_InternetSearchDirectory = 112,
Mac_DefaultDownloadDirectory = 113,
Mac_UserLibDirectory = 114,
Mac_PreferencesDirectory = 115,
Win_SystemDirectory = 201,
Win_SystemDirectory = 201,
Win_WindowsDirectory = 202,
Win_HomeDirectory = 203,
Win_Desktop = 204,
Win_Programs = 205,
Win_Controls = 206,
Win_Printers = 207,
Win_Personal = 208,
Win_Favorites = 209,
Win_Startup = 210,
Win_Recent = 211,
Win_Sendto = 212,
Win_Bitbucket = 213,
Win_Startmenu = 214,
Win_Desktopdirectory = 215,
Win_Drives = 216,
Win_Network = 217,
Win_Nethood = 218,
Win_Fonts = 219,
Win_Templates = 220,
Win_Common_Startmenu = 221,
Win_Common_Programs = 222,
Win_Common_Startup = 223,
Win_Common_Desktopdirectory = 224,
Win_Appdata = 225,
Win_Printhood = 226,
Win_Cookies = 227,
Win_HomeDirectory = 203,
Win_Desktop = 204,
Win_Programs = 205,
Win_Controls = 206,
Win_Printers = 207,
Win_Personal = 208,
Win_Favorites = 209,
Win_Startup = 210,
Win_Recent = 211,
Win_Sendto = 212,
Win_Bitbucket = 213,
Win_Startmenu = 214,
Win_Desktopdirectory = 215,
Win_Drives = 216,
Win_Network = 217,
Win_Nethood = 218,
Win_Fonts = 219,
Win_Templates = 220,
Win_Common_Startmenu = 221,
Win_Common_Programs = 222,
Win_Common_Startup = 223,
Win_Common_Desktopdirectory = 224,
Win_Appdata = 225,
Win_Printhood = 226,
Win_Cookies = 227,
Win_LocalAppdata = 228,
Win_ProgramFiles = 229,
Win_Downloads = 230,
@@ -79,8 +80,8 @@ enum SystemDirectories {
Win_Music = 234,
Win_Videos = 235,
Unix_LocalDirectory = 301,
Unix_LibDirectory = 302,
Unix_LocalDirectory = 301,
Unix_LibDirectory = 302,
Unix_HomeDirectory = 303,
Unix_XDG_Desktop = 304,
Unix_XDG_Documents = 305,

View File

@@ -68,7 +68,7 @@ GetTempDir(nsIFile** aTempDir)
if (rv != NS_ERROR_FILE_ALREADY_EXISTS && NS_WARN_IF(NS_FAILED(rv)))
return rv;
#endif
tmpFile.forget(aTempDir);
return NS_OK;
@@ -106,7 +106,7 @@ NS_OpenAnonymousTemporaryFile(PRFileDesc** aOutFileDesc)
rv = tmpFile->OpenNSPRFileDesc(PR_RDWR | nsIFile::DELETE_ON_CLOSE,
PR_IRWXU, aOutFileDesc);
return rv;
return rv;
}
#ifdef XP_WIN
@@ -157,8 +157,8 @@ public:
if (NS_WARN_IF(!mTimer))
return NS_ERROR_FAILURE;
nsresult rv = mTimer->Init(this,
SCHEDULE_TIMEOUT_MS,
nsITimer::TYPE_ONE_SHOT);
SCHEDULE_TIMEOUT_MS,
nsITimer::TYPE_ONE_SHOT);
if (NS_WARN_IF(NS_FAILED(rv)))
return rv;
@@ -175,12 +175,12 @@ public:
if (mTimer) {
mTimer->Cancel();
mTimer = nullptr;
}
}
// Remove idle service observer.
nsCOMPtr<nsIIdleService> idleSvc =
do_GetService("@mozilla.org/widget/idleservice;1");
if (idleSvc) {
idleSvc->RemoveIdleObserver(this, TEMP_FILE_IDLE_TIME_S);
idleSvc->RemoveIdleObserver(this, TEMP_FILE_IDLE_TIME_S);
}
// Remove shutdown observer.
nsCOMPtr<nsIObserverService> obsSrv = services::GetObserverService();
@@ -188,7 +188,7 @@ public:
obsSrv->RemoveObserver(this, XPCOM_SHUTDOWN_TOPIC);
}
}
NS_IMETHODIMP Observe(nsISupports *aSubject,
const char *aTopic,
const char16_t *aData)
@@ -209,7 +209,7 @@ public:
}
nsresult RegisterIdleObserver() {
// Add this as an idle observer. When we've been idle for
// Add this as an idle observer. When we've been idle for
// TEMP_FILE_IDLE_TIME_S seconds, we'll get a notification, and we'll then
// try to delete any stray temp files.
nsCOMPtr<nsIIdleService> idleSvc =

View File

@@ -25,7 +25,7 @@
* crashes or the computer power cycles unexpectedly, so unopened temporary
* files are purged at some time after application startup.
*
*/
*/
nsresult
NS_OpenAnonymousTemporaryFile(PRFileDesc** aOutFileDesc);

View File

@@ -2,7 +2,7 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef nsAppDirectoryServiceDefs_h___
#define nsAppDirectoryServiceDefs_h___
@@ -57,7 +57,7 @@
// key with NS_SHARED returns a location that is shared by
// other users of the profile. Without this prefix, the consumer
// has exclusive access to this location.
#define NS_SHARED "SHARED"
#define NS_APP_PREFS_50_DIR "PrefD" // Directory which contains user prefs
@@ -66,13 +66,13 @@
#define NS_APP_PREFS_DEFAULTS_DIR_LIST "PrefDL"
#define NS_EXT_PREFS_DEFAULTS_DIR_LIST "ExtPrefDL"
#define NS_APP_PREFS_OVERRIDE_DIR "PrefDOverride" // Directory for per-profile defaults
#define NS_APP_USER_PROFILE_50_DIR "ProfD"
#define NS_APP_USER_PROFILE_LOCAL_50_DIR "ProfLD"
#define NS_APP_USER_CHROME_DIR "UChrm"
#define NS_APP_USER_SEARCH_DIR "UsrSrchPlugns"
#define NS_APP_LOCALSTORE_50_FILE "LclSt"
#define NS_APP_USER_PANELS_50_FILE "UPnls"
#define NS_APP_USER_MIMETYPES_50_FILE "UMimTyp"
@@ -81,9 +81,9 @@
#define NS_APP_BOOKMARKS_50_FILE "BMarks"
#define NS_APP_DOWNLOADS_50_FILE "DLoads"
#define NS_APP_SEARCH_50_FILE "SrchF"
#define NS_APP_INSTALL_CLEANUP_DIR "XPIClnupD" //location of xpicleanup.dat xpicleanup.exe
#define NS_APP_INDEXEDDB_PARENT_DIR "indexedDBPDir"

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -83,201 +84,201 @@ NS_IMPL_ISUPPORTS(nsAppFileLocationProvider, nsIDirectoryServiceProvider, nsIDir
NS_IMETHODIMP
nsAppFileLocationProvider::GetFile(const char *prop, bool *persistent, nsIFile **_retval)
{
if (NS_WARN_IF(!prop))
return NS_ERROR_INVALID_ARG;
if (NS_WARN_IF(!prop))
return NS_ERROR_INVALID_ARG;
nsCOMPtr<nsIFile> localFile;
nsresult rv = NS_ERROR_FAILURE;
nsCOMPtr<nsIFile> localFile;
nsresult rv = NS_ERROR_FAILURE;
*_retval = nullptr;
*persistent = true;
*_retval = nullptr;
*persistent = true;
#ifdef MOZ_WIDGET_COCOA
FSRef fileRef;
nsCOMPtr<nsILocalFileMac> macFile;
FSRef fileRef;
nsCOMPtr<nsILocalFileMac> macFile;
#endif
if (nsCRT::strcmp(prop, NS_APP_APPLICATION_REGISTRY_DIR) == 0)
{
rv = GetProductDirectory(getter_AddRefs(localFile));
if (nsCRT::strcmp(prop, NS_APP_APPLICATION_REGISTRY_DIR) == 0)
{
rv = GetProductDirectory(getter_AddRefs(localFile));
}
else if (nsCRT::strcmp(prop, NS_APP_APPLICATION_REGISTRY_FILE) == 0)
{
rv = GetProductDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendNative(APP_REGISTRY_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_DEFAULTS_50_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(DEFAULTS_DIR_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_PREF_DEFAULTS_50_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv)) {
rv = localFile->AppendRelativeNativePath(DEFAULTS_DIR_NAME);
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(DEFAULTS_PREF_DIR_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_APPLICATION_REGISTRY_FILE) == 0)
{
rv = GetProductDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendNative(APP_REGISTRY_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_DEFAULTS_50_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(DEFAULTS_DIR_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_PREF_DEFAULTS_50_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv)) {
rv = localFile->AppendRelativeNativePath(DEFAULTS_DIR_NAME);
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(DEFAULTS_PREF_DIR_NAME);
}
}
else if (nsCRT::strcmp(prop, NS_APP_PROFILE_DEFAULTS_50_DIR) == 0 ||
nsCRT::strcmp(prop, NS_APP_PROFILE_DEFAULTS_NLOC_50_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv)) {
rv = localFile->AppendRelativeNativePath(DEFAULTS_DIR_NAME);
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(DEFAULTS_PROFILE_DIR_NAME);
}
}
else if (nsCRT::strcmp(prop, NS_APP_USER_PROFILES_ROOT_DIR) == 0)
{
rv = GetDefaultUserProfileRoot(getter_AddRefs(localFile));
}
else if (nsCRT::strcmp(prop, NS_APP_USER_PROFILES_LOCAL_ROOT_DIR) == 0)
{
rv = GetDefaultUserProfileRoot(getter_AddRefs(localFile), true);
}
else if (nsCRT::strcmp(prop, NS_APP_RES_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(RES_DIR_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_CHROME_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(CHROME_DIR_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_PLUGINS_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(PLUGINS_DIR_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_PROFILE_DEFAULTS_50_DIR) == 0 ||
nsCRT::strcmp(prop, NS_APP_PROFILE_DEFAULTS_NLOC_50_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv)) {
rv = localFile->AppendRelativeNativePath(DEFAULTS_DIR_NAME);
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(DEFAULTS_PROFILE_DIR_NAME);
}
}
else if (nsCRT::strcmp(prop, NS_APP_USER_PROFILES_ROOT_DIR) == 0)
{
rv = GetDefaultUserProfileRoot(getter_AddRefs(localFile));
}
else if (nsCRT::strcmp(prop, NS_APP_USER_PROFILES_LOCAL_ROOT_DIR) == 0)
{
rv = GetDefaultUserProfileRoot(getter_AddRefs(localFile), true);
}
else if (nsCRT::strcmp(prop, NS_APP_RES_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(RES_DIR_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_CHROME_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(CHROME_DIR_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_PLUGINS_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(PLUGINS_DIR_NAME);
}
#ifdef MOZ_WIDGET_COCOA
else if (nsCRT::strcmp(prop, NS_MACOSX_USER_PLUGIN_DIR) == 0)
{
if (::FSFindFolder(kUserDomain, kInternetPlugInFolderType, false, &fileRef) == noErr) {
rv = NS_NewLocalFileWithFSRef(&fileRef, true, getter_AddRefs(macFile));
if (NS_SUCCEEDED(rv))
localFile = macFile;
}
else if (nsCRT::strcmp(prop, NS_MACOSX_USER_PLUGIN_DIR) == 0)
{
if (::FSFindFolder(kUserDomain, kInternetPlugInFolderType, false, &fileRef) == noErr) {
rv = NS_NewLocalFileWithFSRef(&fileRef, true, getter_AddRefs(macFile));
if (NS_SUCCEEDED(rv))
localFile = macFile;
}
else if (nsCRT::strcmp(prop, NS_MACOSX_LOCAL_PLUGIN_DIR) == 0)
{
if (::FSFindFolder(kLocalDomain, kInternetPlugInFolderType, false, &fileRef) == noErr) {
rv = NS_NewLocalFileWithFSRef(&fileRef, true, getter_AddRefs(macFile));
if (NS_SUCCEEDED(rv))
localFile = macFile;
}
}
else if (nsCRT::strcmp(prop, NS_MACOSX_JAVA2_PLUGIN_DIR) == 0)
{
static const char *const java2PluginDirPath =
"/System/Library/Java/Support/Deploy.bundle/Contents/Resources/";
rv = NS_NewNativeLocalFile(nsDependentCString(java2PluginDirPath), true, getter_AddRefs(localFile));
}
else if (nsCRT::strcmp(prop, NS_MACOSX_LOCAL_PLUGIN_DIR) == 0)
{
if (::FSFindFolder(kLocalDomain, kInternetPlugInFolderType, false, &fileRef) == noErr) {
rv = NS_NewLocalFileWithFSRef(&fileRef, true, getter_AddRefs(macFile));
if (NS_SUCCEEDED(rv))
localFile = macFile;
}
}
else if (nsCRT::strcmp(prop, NS_MACOSX_JAVA2_PLUGIN_DIR) == 0)
{
static const char *const java2PluginDirPath =
"/System/Library/Java/Support/Deploy.bundle/Contents/Resources/";
rv = NS_NewNativeLocalFile(nsDependentCString(java2PluginDirPath), true, getter_AddRefs(localFile));
}
#else
else if (nsCRT::strcmp(prop, NS_ENV_PLUGINS_DIR) == 0)
{
NS_ERROR("Don't use nsAppFileLocationProvider::GetFile(NS_ENV_PLUGINS_DIR, ...). "
"Use nsAppFileLocationProvider::GetFiles(...).");
const char *pathVar = PR_GetEnv("MOZ_PLUGIN_PATH");
if (pathVar && *pathVar)
rv = NS_NewNativeLocalFile(nsDependentCString(pathVar), true,
getter_AddRefs(localFile));
}
else if (nsCRT::strcmp(prop, NS_USER_PLUGINS_DIR) == 0)
{
else if (nsCRT::strcmp(prop, NS_ENV_PLUGINS_DIR) == 0)
{
NS_ERROR("Don't use nsAppFileLocationProvider::GetFile(NS_ENV_PLUGINS_DIR, ...). "
"Use nsAppFileLocationProvider::GetFiles(...).");
const char *pathVar = PR_GetEnv("MOZ_PLUGIN_PATH");
if (pathVar && *pathVar)
rv = NS_NewNativeLocalFile(nsDependentCString(pathVar), true,
getter_AddRefs(localFile));
}
else if (nsCRT::strcmp(prop, NS_USER_PLUGINS_DIR) == 0)
{
#ifdef ENABLE_SYSTEM_EXTENSION_DIRS
rv = GetProductDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(PLUGINS_DIR_NAME);
rv = GetProductDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(PLUGINS_DIR_NAME);
#else
rv = NS_ERROR_FAILURE;
rv = NS_ERROR_FAILURE;
#endif
}
}
#ifdef XP_UNIX
else if (nsCRT::strcmp(prop, NS_SYSTEM_PLUGINS_DIR) == 0) {
else if (nsCRT::strcmp(prop, NS_SYSTEM_PLUGINS_DIR) == 0) {
#ifdef ENABLE_SYSTEM_EXTENSION_DIRS
static const char *const sysLPlgDir =
static const char *const sysLPlgDir =
#if defined(HAVE_USR_LIB64_DIR) && defined(__LP64__)
"/usr/lib64/mozilla/plugins";
"/usr/lib64/mozilla/plugins";
#elif defined(__OpenBSD__) || defined (__FreeBSD__)
"/usr/local/lib/mozilla/plugins";
"/usr/local/lib/mozilla/plugins";
#else
"/usr/lib/mozilla/plugins";
"/usr/lib/mozilla/plugins";
#endif
rv = NS_NewNativeLocalFile(nsDependentCString(sysLPlgDir),
false, getter_AddRefs(localFile));
rv = NS_NewNativeLocalFile(nsDependentCString(sysLPlgDir),
false, getter_AddRefs(localFile));
#else
rv = NS_ERROR_FAILURE;
rv = NS_ERROR_FAILURE;
#endif
}
}
#endif
#endif
else if (nsCRT::strcmp(prop, NS_APP_SEARCH_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(SEARCH_DIR_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_USER_SEARCH_DIR) == 0)
{
rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, _retval);
if (NS_SUCCEEDED(rv))
rv = (*_retval)->AppendNative(SEARCH_DIR_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_INSTALL_CLEANUP_DIR) == 0)
{
// This is cloned so that embeddors will have a hook to override
// with their own cleanup dir. See bugzilla bug #105087
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
}
else if (nsCRT::strcmp(prop, NS_APP_SEARCH_DIR) == 0)
{
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendRelativeNativePath(SEARCH_DIR_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_USER_SEARCH_DIR) == 0)
{
rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, _retval);
if (NS_SUCCEEDED(rv))
rv = (*_retval)->AppendNative(SEARCH_DIR_NAME);
}
else if (nsCRT::strcmp(prop, NS_APP_INSTALL_CLEANUP_DIR) == 0)
{
// This is cloned so that embeddors will have a hook to override
// with their own cleanup dir. See bugzilla bug #105087
rv = CloneMozBinDirectory(getter_AddRefs(localFile));
}
if (localFile && NS_SUCCEEDED(rv))
return localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)_retval);
return rv;
if (localFile && NS_SUCCEEDED(rv))
return localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)_retval);
return rv;
}
NS_METHOD nsAppFileLocationProvider::CloneMozBinDirectory(nsIFile **aLocalFile)
{
if (NS_WARN_IF(!aLocalFile))
return NS_ERROR_INVALID_ARG;
nsresult rv;
if (NS_WARN_IF(!aLocalFile))
return NS_ERROR_INVALID_ARG;
nsresult rv;
if (!mMozBinDirectory)
{
// Get the mozilla bin directory
// 1. Check the directory service first for NS_XPCOM_CURRENT_PROCESS_DIR
// This will be set if a directory was passed to NS_InitXPCOM
// 2. If that doesn't work, set it to be the current process directory
nsCOMPtr<nsIProperties>
directoryService(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv));
if (NS_FAILED(rv))
return rv;
rv = directoryService->Get(NS_XPCOM_CURRENT_PROCESS_DIR, NS_GET_IID(nsIFile), getter_AddRefs(mMozBinDirectory));
if (NS_FAILED(rv)) {
rv = directoryService->Get(NS_OS_CURRENT_PROCESS_DIR, NS_GET_IID(nsIFile), getter_AddRefs(mMozBinDirectory));
if (NS_FAILED(rv))
return rv;
}
}
nsCOMPtr<nsIFile> aFile;
rv = mMozBinDirectory->Clone(getter_AddRefs(aFile));
if (!mMozBinDirectory)
{
// Get the mozilla bin directory
// 1. Check the directory service first for NS_XPCOM_CURRENT_PROCESS_DIR
// This will be set if a directory was passed to NS_InitXPCOM
// 2. If that doesn't work, set it to be the current process directory
nsCOMPtr<nsIProperties>
directoryService(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv));
if (NS_FAILED(rv))
return rv;
return rv;
NS_IF_ADDREF(*aLocalFile = aFile);
return NS_OK;
rv = directoryService->Get(NS_XPCOM_CURRENT_PROCESS_DIR, NS_GET_IID(nsIFile), getter_AddRefs(mMozBinDirectory));
if (NS_FAILED(rv)) {
rv = directoryService->Get(NS_OS_CURRENT_PROCESS_DIR, NS_GET_IID(nsIFile), getter_AddRefs(mMozBinDirectory));
if (NS_FAILED(rv))
return rv;
}
}
nsCOMPtr<nsIFile> aFile;
rv = mMozBinDirectory->Clone(getter_AddRefs(aFile));
if (NS_FAILED(rv))
return rv;
NS_IF_ADDREF(*aLocalFile = aFile);
return NS_OK;
}
@@ -290,50 +291,50 @@ NS_METHOD nsAppFileLocationProvider::CloneMozBinDirectory(nsIFile **aLocalFile)
//----------------------------------------------------------------------------------------
NS_METHOD nsAppFileLocationProvider::GetProductDirectory(nsIFile **aLocalFile, bool aLocal)
{
if (NS_WARN_IF(!aLocalFile))
return NS_ERROR_INVALID_ARG;
if (NS_WARN_IF(!aLocalFile))
return NS_ERROR_INVALID_ARG;
nsresult rv;
bool exists;
nsCOMPtr<nsIFile> localDir;
nsresult rv;
bool exists;
nsCOMPtr<nsIFile> localDir;
#if defined(MOZ_WIDGET_COCOA)
FSRef fsRef;
OSType folderType = aLocal ? (OSType) kCachedDataFolderType : (OSType) kDomainLibraryFolderType;
OSErr err = ::FSFindFolder(kUserDomain, folderType, kCreateFolder, &fsRef);
if (err) return NS_ERROR_FAILURE;
NS_NewLocalFile(EmptyString(), true, getter_AddRefs(localDir));
if (!localDir) return NS_ERROR_FAILURE;
nsCOMPtr<nsILocalFileMac> localDirMac(do_QueryInterface(localDir));
rv = localDirMac->InitWithFSRef(&fsRef);
if (NS_FAILED(rv)) return rv;
FSRef fsRef;
OSType folderType = aLocal ? (OSType) kCachedDataFolderType : (OSType) kDomainLibraryFolderType;
OSErr err = ::FSFindFolder(kUserDomain, folderType, kCreateFolder, &fsRef);
if (err) return NS_ERROR_FAILURE;
NS_NewLocalFile(EmptyString(), true, getter_AddRefs(localDir));
if (!localDir) return NS_ERROR_FAILURE;
nsCOMPtr<nsILocalFileMac> localDirMac(do_QueryInterface(localDir));
rv = localDirMac->InitWithFSRef(&fsRef);
if (NS_FAILED(rv)) return rv;
#elif defined(XP_WIN)
nsCOMPtr<nsIProperties> directoryService =
do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
const char* prop = aLocal ? NS_WIN_LOCAL_APPDATA_DIR : NS_WIN_APPDATA_DIR;
rv = directoryService->Get(prop, NS_GET_IID(nsIFile), getter_AddRefs(localDir));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIProperties> directoryService =
do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
const char* prop = aLocal ? NS_WIN_LOCAL_APPDATA_DIR : NS_WIN_APPDATA_DIR;
rv = directoryService->Get(prop, NS_GET_IID(nsIFile), getter_AddRefs(localDir));
if (NS_FAILED(rv)) return rv;
#elif defined(XP_UNIX)
rv = NS_NewNativeLocalFile(nsDependentCString(PR_GetEnv("HOME")), true, getter_AddRefs(localDir));
if (NS_FAILED(rv)) return rv;
rv = NS_NewNativeLocalFile(nsDependentCString(PR_GetEnv("HOME")), true, getter_AddRefs(localDir));
if (NS_FAILED(rv)) return rv;
#else
#error dont_know_how_to_get_product_dir_on_your_platform
#endif
rv = localDir->AppendRelativeNativePath(DEFAULT_PRODUCT_DIR);
if (NS_FAILED(rv)) return rv;
rv = localDir->Exists(&exists);
rv = localDir->AppendRelativeNativePath(DEFAULT_PRODUCT_DIR);
if (NS_FAILED(rv)) return rv;
rv = localDir->Exists(&exists);
if (NS_SUCCEEDED(rv) && !exists)
rv = localDir->Create(nsIFile::DIRECTORY_TYPE, 0700);
if (NS_SUCCEEDED(rv) && !exists)
rv = localDir->Create(nsIFile::DIRECTORY_TYPE, 0700);
if (NS_FAILED(rv)) return rv;
if (NS_FAILED(rv)) return rv;
*aLocalFile = localDir;
NS_ADDREF(*aLocalFile);
*aLocalFile = localDir;
NS_ADDREF(*aLocalFile);
return rv;
return rv;
}
@@ -346,31 +347,31 @@ NS_METHOD nsAppFileLocationProvider::GetProductDirectory(nsIFile **aLocalFile, b
//----------------------------------------------------------------------------------------
NS_METHOD nsAppFileLocationProvider::GetDefaultUserProfileRoot(nsIFile **aLocalFile, bool aLocal)
{
if (NS_WARN_IF(!aLocalFile))
return NS_ERROR_INVALID_ARG;
if (NS_WARN_IF(!aLocalFile))
return NS_ERROR_INVALID_ARG;
nsresult rv;
nsCOMPtr<nsIFile> localDir;
nsresult rv;
nsCOMPtr<nsIFile> localDir;
rv = GetProductDirectory(getter_AddRefs(localDir), aLocal);
if (NS_FAILED(rv)) return rv;
rv = GetProductDirectory(getter_AddRefs(localDir), aLocal);
if (NS_FAILED(rv)) return rv;
#if defined(MOZ_WIDGET_COCOA) || defined(XP_WIN)
// These 3 platforms share this part of the path - do them as one
rv = localDir->AppendRelativeNativePath(NS_LITERAL_CSTRING("Profiles"));
if (NS_FAILED(rv)) return rv;
// These 3 platforms share this part of the path - do them as one
rv = localDir->AppendRelativeNativePath(NS_LITERAL_CSTRING("Profiles"));
if (NS_FAILED(rv)) return rv;
bool exists;
rv = localDir->Exists(&exists);
if (NS_SUCCEEDED(rv) && !exists)
rv = localDir->Create(nsIFile::DIRECTORY_TYPE, 0775);
if (NS_FAILED(rv)) return rv;
bool exists;
rv = localDir->Exists(&exists);
if (NS_SUCCEEDED(rv) && !exists)
rv = localDir->Create(nsIFile::DIRECTORY_TYPE, 0775);
if (NS_FAILED(rv)) return rv;
#endif
*aLocalFile = localDir;
NS_ADDREF(*aLocalFile);
*aLocalFile = localDir;
NS_ADDREF(*aLocalFile);
return rv;
return rv;
}
//*****************************************************************************
@@ -379,65 +380,65 @@ NS_METHOD nsAppFileLocationProvider::GetDefaultUserProfileRoot(nsIFile **aLocalF
class nsAppDirectoryEnumerator : public nsISimpleEnumerator
{
public:
NS_DECL_ISUPPORTS
public:
NS_DECL_ISUPPORTS
/**
* aKeyList is a null-terminated list of properties which are provided by aProvider
* They do not need to be publicly defined keys.
*/
nsAppDirectoryEnumerator(nsIDirectoryServiceProvider *aProvider,
const char* aKeyList[]) :
mProvider(aProvider),
mCurrentKey(aKeyList)
/**
* aKeyList is a null-terminated list of properties which are provided by aProvider
* They do not need to be publicly defined keys.
*/
nsAppDirectoryEnumerator(nsIDirectoryServiceProvider *aProvider,
const char* aKeyList[]) :
mProvider(aProvider),
mCurrentKey(aKeyList)
{
}
NS_IMETHOD HasMoreElements(bool *result)
{
while (!mNext && *mCurrentKey)
{
bool dontCare;
nsCOMPtr<nsIFile> testFile;
(void)mProvider->GetFile(*mCurrentKey++, &dontCare, getter_AddRefs(testFile));
// Don't return a file which does not exist.
bool exists;
if (testFile && NS_SUCCEEDED(testFile->Exists(&exists)) && exists)
mNext = testFile;
}
*result = mNext != nullptr;
return NS_OK;
}
NS_IMETHOD HasMoreElements(bool *result)
{
while (!mNext && *mCurrentKey)
{
bool dontCare;
nsCOMPtr<nsIFile> testFile;
(void)mProvider->GetFile(*mCurrentKey++, &dontCare, getter_AddRefs(testFile));
// Don't return a file which does not exist.
bool exists;
if (testFile && NS_SUCCEEDED(testFile->Exists(&exists)) && exists)
mNext = testFile;
}
*result = mNext != nullptr;
return NS_OK;
}
NS_IMETHOD GetNext(nsISupports **result)
{
if (NS_WARN_IF(!result))
return NS_ERROR_INVALID_ARG;
*result = nullptr;
NS_IMETHOD GetNext(nsISupports **result)
{
if (NS_WARN_IF(!result))
return NS_ERROR_INVALID_ARG;
*result = nullptr;
bool hasMore;
HasMoreElements(&hasMore);
if (!hasMore)
return NS_ERROR_FAILURE;
bool hasMore;
HasMoreElements(&hasMore);
if (!hasMore)
return NS_ERROR_FAILURE;
*result = mNext;
NS_IF_ADDREF(*result);
mNext = nullptr;
return *result ? NS_OK : NS_ERROR_FAILURE;
}
*result = mNext;
NS_IF_ADDREF(*result);
mNext = nullptr;
// Virtual destructor since subclass nsPathsDirectoryEnumerator
// does not re-implement Release()
return *result ? NS_OK : NS_ERROR_FAILURE;
}
virtual ~nsAppDirectoryEnumerator()
{
}
// Virtual destructor since subclass nsPathsDirectoryEnumerator
// does not re-implement Release()
protected:
nsIDirectoryServiceProvider *mProvider;
const char** mCurrentKey;
nsCOMPtr<nsIFile> mNext;
virtual ~nsAppDirectoryEnumerator()
{
}
protected:
nsIDirectoryServiceProvider *mProvider;
const char** mCurrentKey;
nsCOMPtr<nsIFile> mNext;
};
NS_IMPL_ISUPPORTS(nsAppDirectoryEnumerator, nsISimpleEnumerator)
@@ -453,123 +454,123 @@ NS_IMPL_ISUPPORTS(nsAppDirectoryEnumerator, nsISimpleEnumerator)
class nsPathsDirectoryEnumerator : public nsAppDirectoryEnumerator
{
public:
/**
* aKeyList is a null-terminated list.
* The first element is a path list.
* The remainder are properties provided by aProvider.
* They do not need to be publicly defined keys.
*/
nsPathsDirectoryEnumerator(nsIDirectoryServiceProvider *aProvider,
const char* aKeyList[]) :
public:
/**
* aKeyList is a null-terminated list.
* The first element is a path list.
* The remainder are properties provided by aProvider.
* They do not need to be publicly defined keys.
*/
nsPathsDirectoryEnumerator(nsIDirectoryServiceProvider *aProvider,
const char* aKeyList[]) :
nsAppDirectoryEnumerator(aProvider, aKeyList+1),
mEndPath(aKeyList[0])
{
}
{
}
NS_IMETHOD HasMoreElements(bool *result)
{
if (mEndPath)
while (!mNext && *mEndPath)
{
const char *pathVar = mEndPath;
// skip PATH_SEPARATORs at the begining of the mEndPath
while (*pathVar == PATH_SEPARATOR) pathVar++;
NS_IMETHOD HasMoreElements(bool *result)
{
if (mEndPath)
while (!mNext && *mEndPath)
{
const char *pathVar = mEndPath;
do { ++mEndPath; } while (*mEndPath && *mEndPath != PATH_SEPARATOR);
// skip PATH_SEPARATORs at the begining of the mEndPath
while (*pathVar == PATH_SEPARATOR) pathVar++;
nsCOMPtr<nsIFile> localFile;
NS_NewNativeLocalFile(Substring(pathVar, mEndPath),
true,
getter_AddRefs(localFile));
if (*mEndPath == PATH_SEPARATOR)
++mEndPath;
// Don't return a "file" (directory) which does not exist.
bool exists;
if (localFile &&
NS_SUCCEEDED(localFile->Exists(&exists)) &&
exists)
mNext = localFile;
}
if (mNext)
*result = true;
else
nsAppDirectoryEnumerator::HasMoreElements(result);
do { ++mEndPath; } while (*mEndPath && *mEndPath != PATH_SEPARATOR);
return NS_OK;
}
nsCOMPtr<nsIFile> localFile;
NS_NewNativeLocalFile(Substring(pathVar, mEndPath),
true,
getter_AddRefs(localFile));
if (*mEndPath == PATH_SEPARATOR)
++mEndPath;
// Don't return a "file" (directory) which does not exist.
bool exists;
if (localFile &&
NS_SUCCEEDED(localFile->Exists(&exists)) &&
exists)
mNext = localFile;
}
if (mNext)
*result = true;
else
nsAppDirectoryEnumerator::HasMoreElements(result);
protected:
const char *mEndPath;
return NS_OK;
}
protected:
const char *mEndPath;
};
NS_IMETHODIMP
nsAppFileLocationProvider::GetFiles(const char *prop, nsISimpleEnumerator **_retval)
{
if (NS_WARN_IF(!_retval))
return NS_ERROR_INVALID_ARG;
*_retval = nullptr;
nsresult rv = NS_ERROR_FAILURE;
if (!nsCRT::strcmp(prop, NS_APP_PLUGINS_DIR_LIST))
{
if (NS_WARN_IF(!_retval))
return NS_ERROR_INVALID_ARG;
*_retval = nullptr;
nsresult rv = NS_ERROR_FAILURE;
if (!nsCRT::strcmp(prop, NS_APP_PLUGINS_DIR_LIST))
{
#ifdef MOZ_WIDGET_COCOA
// As of Java for Mac OS X 10.5 Update 10, Apple has (in effect) deprecated Java Plugin2 on
// on OS X 10.5, and removed the soft link to it from /Library/Internet Plug-Ins/. Java
// Plugin2 is still present and usable, but there are no longer any links to it in the
// "normal" locations. So we won't be able to find it unless we look in the "non-normal"
// location where it actually is. Safari can use the WebKit-specific JavaPluginCocoa.bundle,
// which (of course) is still fully supported on OS X 10.5. But we have no alternative to
// using Java Plugin2. For more information see bug 668639.
static const char* keys[] = { NS_APP_PLUGINS_DIR, NS_MACOSX_USER_PLUGIN_DIR,
NS_MACOSX_LOCAL_PLUGIN_DIR,
IsOSXLeopard() ? NS_MACOSX_JAVA2_PLUGIN_DIR : nullptr, nullptr };
*_retval = new nsAppDirectoryEnumerator(this, keys);
// As of Java for Mac OS X 10.5 Update 10, Apple has (in effect) deprecated Java Plugin2 on
// on OS X 10.5, and removed the soft link to it from /Library/Internet Plug-Ins/. Java
// Plugin2 is still present and usable, but there are no longer any links to it in the
// "normal" locations. So we won't be able to find it unless we look in the "non-normal"
// location where it actually is. Safari can use the WebKit-specific JavaPluginCocoa.bundle,
// which (of course) is still fully supported on OS X 10.5. But we have no alternative to
// using Java Plugin2. For more information see bug 668639.
static const char* keys[] = { NS_APP_PLUGINS_DIR, NS_MACOSX_USER_PLUGIN_DIR,
NS_MACOSX_LOCAL_PLUGIN_DIR,
IsOSXLeopard() ? NS_MACOSX_JAVA2_PLUGIN_DIR : nullptr, nullptr };
*_retval = new nsAppDirectoryEnumerator(this, keys);
#else
#ifdef XP_UNIX
static const char* keys[] = { nullptr, NS_USER_PLUGINS_DIR, NS_APP_PLUGINS_DIR, NS_SYSTEM_PLUGINS_DIR, nullptr };
static const char* keys[] = { nullptr, NS_USER_PLUGINS_DIR, NS_APP_PLUGINS_DIR, NS_SYSTEM_PLUGINS_DIR, nullptr };
#else
static const char* keys[] = { nullptr, NS_USER_PLUGINS_DIR, NS_APP_PLUGINS_DIR, nullptr };
static const char* keys[] = { nullptr, NS_USER_PLUGINS_DIR, NS_APP_PLUGINS_DIR, nullptr };
#endif
if (!keys[0] && !(keys[0] = PR_GetEnv("MOZ_PLUGIN_PATH"))) {
static const char nullstr = 0;
keys[0] = &nullstr;
}
*_retval = new nsPathsDirectoryEnumerator(this, keys);
if (!keys[0] && !(keys[0] = PR_GetEnv("MOZ_PLUGIN_PATH"))) {
static const char nullstr = 0;
keys[0] = &nullstr;
}
*_retval = new nsPathsDirectoryEnumerator(this, keys);
#endif
NS_IF_ADDREF(*_retval);
rv = *_retval ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
NS_IF_ADDREF(*_retval);
rv = *_retval ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
if (!nsCRT::strcmp(prop, NS_APP_SEARCH_DIR_LIST))
{
static const char* keys[] = { nullptr, NS_APP_SEARCH_DIR, NS_APP_USER_SEARCH_DIR, nullptr };
if (!keys[0] && !(keys[0] = PR_GetEnv("MOZ_SEARCH_ENGINE_PATH"))) {
static const char nullstr = 0;
keys[0] = &nullstr;
}
if (!nsCRT::strcmp(prop, NS_APP_SEARCH_DIR_LIST))
{
static const char* keys[] = { nullptr, NS_APP_SEARCH_DIR, NS_APP_USER_SEARCH_DIR, nullptr };
if (!keys[0] && !(keys[0] = PR_GetEnv("MOZ_SEARCH_ENGINE_PATH"))) {
static const char nullstr = 0;
keys[0] = &nullstr;
}
*_retval = new nsPathsDirectoryEnumerator(this, keys);
NS_IF_ADDREF(*_retval);
rv = *_retval ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
return rv;
*_retval = new nsPathsDirectoryEnumerator(this, keys);
NS_IF_ADDREF(*_retval);
rv = *_retval ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
return rv;
}
#if defined(MOZ_WIDGET_COCOA)
bool
nsAppFileLocationProvider::IsOSXLeopard()
{
static SInt32 version = 0;
static SInt32 version = 0;
if (!version) {
OSErr err = ::Gestalt(gestaltSystemVersion, &version);
if (err != noErr) {
version = 0;
} else {
version &= 0xFFFF; // The system version is in the low order word
}
if (!version) {
OSErr err = ::Gestalt(gestaltSystemVersion, &version);
if (err != noErr) {
version = 0;
} else {
version &= 0xFFFF; // The system version is in the low order word
}
}
return ((version >= 0x1050) && (version < 0x1060));
return ((version >= 0x1050) && (version < 0x1060));
}
#endif

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -14,39 +15,39 @@ class nsIFile;
//*****************************************************************************
// class nsAppFileLocationProvider
//*****************************************************************************
//*****************************************************************************
class nsAppFileLocationProvider MOZ_FINAL : public nsIDirectoryServiceProvider2
{
public:
nsAppFileLocationProvider();
nsAppFileLocationProvider();
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIDIRECTORYSERVICEPROVIDER
NS_DECL_NSIDIRECTORYSERVICEPROVIDER2
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIDIRECTORYSERVICEPROVIDER
NS_DECL_NSIDIRECTORYSERVICEPROVIDER2
private:
~nsAppFileLocationProvider() {}
~nsAppFileLocationProvider() {}
protected:
NS_METHOD CloneMozBinDirectory(nsIFile **aLocalFile);
/**
* Get the product directory. This is a user-specific directory for storing
* application settings (e.g. the Application Data directory on windows
* systems).
* @param aLocal If true, should try to get a directory that is only stored
* locally (ie not transferred with roaming profiles)
*/
NS_METHOD GetProductDirectory(nsIFile **aLocalFile,
bool aLocal = false);
NS_METHOD GetDefaultUserProfileRoot(nsIFile **aLocalFile,
bool aLocal = false);
NS_METHOD CloneMozBinDirectory(nsIFile **aLocalFile);
/**
* Get the product directory. This is a user-specific directory for storing
* application settings (e.g. the Application Data directory on windows
* systems).
* @param aLocal If true, should try to get a directory that is only stored
* locally (ie not transferred with roaming profiles)
*/
NS_METHOD GetProductDirectory(nsIFile **aLocalFile,
bool aLocal = false);
NS_METHOD GetDefaultUserProfileRoot(nsIFile **aLocalFile,
bool aLocal = false);
#if defined(MOZ_WIDGET_COCOA)
static bool IsOSXLeopard();
static bool IsOSXLeopard();
#endif
nsCOMPtr<nsIFile> mMozBinDirectory;
nsCOMPtr<nsIFile> mMozBinDirectory;
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,6 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -27,36 +28,36 @@
class nsBinaryOutputStream : public nsIObjectOutputStream
{
public:
nsBinaryOutputStream() {}
// virtual dtor since subclasses call our Release()
virtual ~nsBinaryOutputStream() {}
nsBinaryOutputStream() {}
// virtual dtor since subclasses call our Release()
virtual ~nsBinaryOutputStream() {}
protected:
// nsISupports methods
NS_DECL_ISUPPORTS
// nsISupports methods
NS_DECL_ISUPPORTS
// nsIOutputStream methods
NS_DECL_NSIOUTPUTSTREAM
// nsIOutputStream methods
NS_DECL_NSIOUTPUTSTREAM
// nsIBinaryOutputStream methods
NS_DECL_NSIBINARYOUTPUTSTREAM
// nsIBinaryOutputStream methods
NS_DECL_NSIBINARYOUTPUTSTREAM
// nsIObjectOutputStream methods
NS_DECL_NSIOBJECTOUTPUTSTREAM
// nsIObjectOutputStream methods
NS_DECL_NSIOBJECTOUTPUTSTREAM
// Call Write(), ensuring that all proffered data is written
nsresult WriteFully(const char *aBuf, uint32_t aCount);
// Call Write(), ensuring that all proffered data is written
nsresult WriteFully(const char *aBuf, uint32_t aCount);
nsCOMPtr<nsIOutputStream> mOutputStream;
nsCOMPtr<nsIStreamBufferAccess> mBufferAccess;
nsCOMPtr<nsIOutputStream> mOutputStream;
nsCOMPtr<nsIStreamBufferAccess> mBufferAccess;
};
#define NS_BINARYINPUTSTREAM_CID \
{ /* c521a612-2aad-46db-b6ab-3b821fb150b1 */ \
0xc521a612, \
0x2aad, \
0x46db, \
{0xb6, 0xab, 0x3b, 0x82, 0x1f, 0xb1, 0x50, 0xb1} \
{ /* c521a612-2aad-46db-b6ab-3b821fb150b1 */ \
0xc521a612, \
0x2aad, \
0x46db, \
{0xb6, 0xab, 0x3b, 0x82, 0x1f, 0xb1, 0x50, 0xb1} \
}
#define NS_BINARYINPUTSTREAM_CONTRACTID "@mozilla.org/binaryinputstream;1"
@@ -66,25 +67,25 @@ protected:
class nsBinaryInputStream : public nsIObjectInputStream
{
public:
nsBinaryInputStream() {}
// virtual dtor since subclasses call our Release()
virtual ~nsBinaryInputStream() {}
nsBinaryInputStream() {}
// virtual dtor since subclasses call our Release()
virtual ~nsBinaryInputStream() {}
protected:
// nsISupports methods
NS_DECL_ISUPPORTS
// nsISupports methods
NS_DECL_ISUPPORTS
// nsIInputStream methods
NS_DECL_NSIINPUTSTREAM
// nsIInputStream methods
NS_DECL_NSIINPUTSTREAM
// nsIBinaryInputStream methods
NS_DECL_NSIBINARYINPUTSTREAM
// nsIBinaryInputStream methods
NS_DECL_NSIBINARYINPUTSTREAM
// nsIObjectInputStream methods
NS_DECL_NSIOBJECTINPUTSTREAM
// nsIObjectInputStream methods
NS_DECL_NSIOBJECTINPUTSTREAM
nsCOMPtr<nsIInputStream> mInputStream;
nsCOMPtr<nsIStreamBufferAccess> mBufferAccess;
nsCOMPtr<nsIInputStream> mInputStream;
nsCOMPtr<nsIStreamBufferAccess> mBufferAccess;
};
#endif // nsBinaryStream_h___

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -21,21 +22,21 @@ class nsDirectoryService MOZ_FINAL : public nsIDirectoryService,
public nsIProperties,
public nsIDirectoryServiceProvider2
{
public:
public:
// nsISupports interface
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIPROPERTIES
NS_DECL_NSIPROPERTIES
NS_DECL_NSIDIRECTORYSERVICE
NS_DECL_NSIDIRECTORYSERVICEPROVIDER
NS_DECL_NSIDIRECTORYSERVICEPROVIDER2
nsDirectoryService();
~nsDirectoryService();
~nsDirectoryService();
static void RealInit();
void RegisterCategoryProviders();
@@ -46,10 +47,10 @@ class nsDirectoryService MOZ_FINAL : public nsIDirectoryService,
static nsDirectoryService* gService;
private:
nsresult GetCurrentProcessDirectory(nsIFile** aFile);
nsInterfaceHashtable<nsCStringHashKey, nsIFile> mHashtable;
nsTArray<nsCOMPtr<nsIDirectoryServiceProvider> > mProviders;
nsresult GetCurrentProcessDirectory(nsIFile** aFile);
nsInterfaceHashtable<nsCStringHashKey, nsIFile> mHashtable;
nsTArray<nsCOMPtr<nsIDirectoryServiceProvider> > mProviders;
public:

View File

@@ -42,7 +42,7 @@ DIR_ATOM(sPictureDocumentsDirectory, NS_OSX_PICTURE_DOCUMENTS_DIR)
DIR_ATOM(sMovieDocumentsDirectory, NS_OSX_MOVIE_DOCUMENTS_DIR)
DIR_ATOM(sMusicDocumentsDirectory, NS_OSX_MUSIC_DOCUMENTS_DIR)
DIR_ATOM(sInternetSitesDirectory, NS_OSX_INTERNET_SITES_DIR)
#elif defined (XP_WIN)
#elif defined (XP_WIN)
DIR_ATOM(sSystemDirectory, NS_OS_SYSTEM_DIR)
DIR_ATOM(sWindowsDirectory, NS_WIN_WINDOWS_DIR)
DIR_ATOM(sWindowsProgramFiles, NS_WIN_PROGRAM_FILES_DIR)

View File

@@ -1,15 +1,16 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* Defines the property names for directories available from
* nsIDirectoryService. These dirs are always available even if no
* nsIDirectoryServiceProviders have been registered with the service.
* Defines the property names for directories available from
* nsIDirectoryService. These dirs are always available even if no
* nsIDirectoryServiceProviders have been registered with the service.
* Application level keys are defined in nsAppDirectoryServiceDefs.h.
*
* Keys whose definition ends in "DIR" or "FILE" return a single nsIFile (or
* Keys whose definition ends in "DIR" or "FILE" return a single nsIFile (or
* subclass). Keys whose definition ends in "LIST" return an nsISimpleEnumerator
* which enumerates a list of file objects.
*
@@ -29,15 +30,15 @@
*/
#define NS_OS_DESKTOP_DIR "Desk"
/* Property returns the directory in which the procces was started from.
* On Unix this will be the path in the MOZILLA_FIVE_HOME env var and if
* unset will be the current working directory.
/* Property returns the directory in which the procces was started from.
* On Unix this will be the path in the MOZILLA_FIVE_HOME env var and if
* unset will be the current working directory.
*/
#define NS_OS_CURRENT_PROCESS_DIR "CurProcD"
/* This location is similar to NS_OS_CURRENT_PROCESS_DIR, however,
/* This location is similar to NS_OS_CURRENT_PROCESS_DIR, however,
* NS_XPCOM_CURRENT_PROCESS_DIR can be overriden by passing a "bin
* directory" to NS_InitXPCOM2().
* directory" to NS_InitXPCOM2().
*/
#define NS_XPCOM_CURRENT_PROCESS_DIR "XCurProcD"
@@ -45,8 +46,8 @@
*/
#define NS_XPCOM_LIBRARY_FILE "XpcomLib"
/* Property will return the current location of the the GRE directory.
* If no GRE is used, this propery will behave like
/* Property will return the current location of the the GRE directory.
* If no GRE is used, this propery will behave like
* NS_XPCOM_CURRENT_PROCESS_DIR.
*/
#define NS_GRE_DIR "GreD"
@@ -58,91 +59,91 @@
#endif
#if defined (MOZ_WIDGET_COCOA)
#define NS_MAC_DESKTOP_DIR NS_OS_DESKTOP_DIR
#define NS_MAC_TRASH_DIR "Trsh"
#define NS_MAC_STARTUP_DIR "Strt"
#define NS_MAC_SHUTDOWN_DIR "Shdwn"
#define NS_MAC_APPLE_MENU_DIR "ApplMenu"
#define NS_MAC_CONTROL_PANELS_DIR "CntlPnl"
#define NS_MAC_EXTENSIONS_DIR "Exts"
#define NS_MAC_FONTS_DIR "Fnts"
#define NS_MAC_PREFS_DIR "Prfs"
#define NS_MAC_DOCUMENTS_DIR "Docs"
#define NS_MAC_INTERNET_SEARCH_DIR "ISrch"
#define NS_OSX_HOME_DIR NS_OS_HOME_DIR
#define NS_MAC_HOME_DIR NS_OS_HOME_DIR
#define NS_MAC_DEFAULT_DOWNLOAD_DIR "DfltDwnld"
#define NS_MAC_USER_LIB_DIR "ULibDir" // Only available under OS X
#define NS_OSX_DEFAULT_DOWNLOAD_DIR NS_MAC_DEFAULT_DOWNLOAD_DIR
#define NS_OSX_USER_DESKTOP_DIR "UsrDsk"
#define NS_OSX_LOCAL_DESKTOP_DIR "LocDsk"
#define NS_OSX_USER_APPLICATIONS_DIR "UsrApp"
#define NS_OSX_LOCAL_APPLICATIONS_DIR "LocApp"
#define NS_OSX_USER_DOCUMENTS_DIR "UsrDocs"
#define NS_OSX_LOCAL_DOCUMENTS_DIR "LocDocs"
#define NS_OSX_USER_INTERNET_PLUGIN_DIR "UsrIntrntPlgn"
#define NS_OSX_LOCAL_INTERNET_PLUGIN_DIR "LoclIntrntPlgn"
#define NS_OSX_USER_FRAMEWORKS_DIR "UsrFrmwrks"
#define NS_OSX_LOCAL_FRAMEWORKS_DIR "LocFrmwrks"
#define NS_OSX_USER_PREFERENCES_DIR "UsrPrfs"
#define NS_OSX_LOCAL_PREFERENCES_DIR "LocPrfs"
#define NS_OSX_PICTURE_DOCUMENTS_DIR "Pct"
#define NS_OSX_MOVIE_DOCUMENTS_DIR "Mov"
#define NS_OSX_MUSIC_DOCUMENTS_DIR "Music"
#define NS_OSX_INTERNET_SITES_DIR "IntrntSts"
#define NS_MAC_DESKTOP_DIR NS_OS_DESKTOP_DIR
#define NS_MAC_TRASH_DIR "Trsh"
#define NS_MAC_STARTUP_DIR "Strt"
#define NS_MAC_SHUTDOWN_DIR "Shdwn"
#define NS_MAC_APPLE_MENU_DIR "ApplMenu"
#define NS_MAC_CONTROL_PANELS_DIR "CntlPnl"
#define NS_MAC_EXTENSIONS_DIR "Exts"
#define NS_MAC_FONTS_DIR "Fnts"
#define NS_MAC_PREFS_DIR "Prfs"
#define NS_MAC_DOCUMENTS_DIR "Docs"
#define NS_MAC_INTERNET_SEARCH_DIR "ISrch"
#define NS_OSX_HOME_DIR NS_OS_HOME_DIR
#define NS_MAC_HOME_DIR NS_OS_HOME_DIR
#define NS_MAC_DEFAULT_DOWNLOAD_DIR "DfltDwnld"
#define NS_MAC_USER_LIB_DIR "ULibDir" // Only available under OS X
#define NS_OSX_DEFAULT_DOWNLOAD_DIR NS_MAC_DEFAULT_DOWNLOAD_DIR
#define NS_OSX_USER_DESKTOP_DIR "UsrDsk"
#define NS_OSX_LOCAL_DESKTOP_DIR "LocDsk"
#define NS_OSX_USER_APPLICATIONS_DIR "UsrApp"
#define NS_OSX_LOCAL_APPLICATIONS_DIR "LocApp"
#define NS_OSX_USER_DOCUMENTS_DIR "UsrDocs"
#define NS_OSX_LOCAL_DOCUMENTS_DIR "LocDocs"
#define NS_OSX_USER_INTERNET_PLUGIN_DIR "UsrIntrntPlgn"
#define NS_OSX_LOCAL_INTERNET_PLUGIN_DIR "LoclIntrntPlgn"
#define NS_OSX_USER_FRAMEWORKS_DIR "UsrFrmwrks"
#define NS_OSX_LOCAL_FRAMEWORKS_DIR "LocFrmwrks"
#define NS_OSX_USER_PREFERENCES_DIR "UsrPrfs"
#define NS_OSX_LOCAL_PREFERENCES_DIR "LocPrfs"
#define NS_OSX_PICTURE_DOCUMENTS_DIR "Pct"
#define NS_OSX_MOVIE_DOCUMENTS_DIR "Mov"
#define NS_OSX_MUSIC_DOCUMENTS_DIR "Music"
#define NS_OSX_INTERNET_SITES_DIR "IntrntSts"
#elif defined (XP_WIN)
#define NS_WIN_WINDOWS_DIR "WinD"
#define NS_WIN_PROGRAM_FILES_DIR "ProgF"
#define NS_WIN_HOME_DIR NS_OS_HOME_DIR
#define NS_WIN_DESKTOP_DIR "DeskV" // virtual folder at the root of the namespace
#define NS_WIN_PROGRAMS_DIR "Progs" // User start menu programs directory!
#define NS_WIN_CONTROLS_DIR "Cntls"
#define NS_WIN_PRINTERS_DIR "Prnts"
#define NS_WIN_PERSONAL_DIR "Pers"
#define NS_WIN_FAVORITES_DIR "Favs"
#define NS_WIN_STARTUP_DIR "Strt"
#define NS_WIN_RECENT_DIR "Rcnt"
#define NS_WIN_SEND_TO_DIR "SndTo"
#define NS_WIN_BITBUCKET_DIR "Buckt"
#define NS_WIN_STARTMENU_DIR "Strt"
#define NS_WIN_WINDOWS_DIR "WinD"
#define NS_WIN_PROGRAM_FILES_DIR "ProgF"
#define NS_WIN_HOME_DIR NS_OS_HOME_DIR
#define NS_WIN_DESKTOP_DIR "DeskV" // virtual folder at the root of the namespace
#define NS_WIN_PROGRAMS_DIR "Progs" // User start menu programs directory!
#define NS_WIN_CONTROLS_DIR "Cntls"
#define NS_WIN_PRINTERS_DIR "Prnts"
#define NS_WIN_PERSONAL_DIR "Pers"
#define NS_WIN_FAVORITES_DIR "Favs"
#define NS_WIN_STARTUP_DIR "Strt"
#define NS_WIN_RECENT_DIR "Rcnt"
#define NS_WIN_SEND_TO_DIR "SndTo"
#define NS_WIN_BITBUCKET_DIR "Buckt"
#define NS_WIN_STARTMENU_DIR "Strt"
// This gives the same thing as NS_OS_DESKTOP_DIR
#define NS_WIN_DESKTOP_DIRECTORY "DeskP" // file sys dir which physically stores objects on desktop
#define NS_WIN_DRIVES_DIR "Drivs"
#define NS_WIN_NETWORK_DIR "NetW"
#define NS_WIN_NETHOOD_DIR "netH"
#define NS_WIN_FONTS_DIR "Fnts"
#define NS_WIN_TEMPLATES_DIR "Tmpls"
#define NS_WIN_COMMON_STARTMENU_DIR "CmStrt"
#define NS_WIN_COMMON_PROGRAMS_DIR "CmPrgs"
#define NS_WIN_COMMON_STARTUP_DIR "CmStrt"
#define NS_WIN_COMMON_DESKTOP_DIRECTORY "CmDeskP"
#define NS_WIN_COMMON_APPDATA_DIR "CmAppData"
#define NS_WIN_APPDATA_DIR "AppData"
#define NS_WIN_LOCAL_APPDATA_DIR "LocalAppData"
#define NS_WIN_PRINTHOOD "PrntHd"
#define NS_WIN_COOKIES_DIR "CookD"
#define NS_WIN_DEFAULT_DOWNLOAD_DIR "DfltDwnld"
// On Win7 and up these ids will return the default save-to location for
// Windows Libraries associated with the specific content type. For other
// os they return the local user folder. Note these can return network file
// paths which can jank the ui thread so be careful how you access them.
#define NS_WIN_DOCUMENTS_DIR "Docs"
#define NS_WIN_PICTURES_DIR "Pict"
#define NS_WIN_MUSIC_DIR "Music"
#define NS_WIN_VIDEOS_DIR "Vids"
#define NS_WIN_DESKTOP_DIRECTORY "DeskP" // file sys dir which physically stores objects on desktop
#define NS_WIN_DRIVES_DIR "Drivs"
#define NS_WIN_NETWORK_DIR "NetW"
#define NS_WIN_NETHOOD_DIR "netH"
#define NS_WIN_FONTS_DIR "Fnts"
#define NS_WIN_TEMPLATES_DIR "Tmpls"
#define NS_WIN_COMMON_STARTMENU_DIR "CmStrt"
#define NS_WIN_COMMON_PROGRAMS_DIR "CmPrgs"
#define NS_WIN_COMMON_STARTUP_DIR "CmStrt"
#define NS_WIN_COMMON_DESKTOP_DIRECTORY "CmDeskP"
#define NS_WIN_COMMON_APPDATA_DIR "CmAppData"
#define NS_WIN_APPDATA_DIR "AppData"
#define NS_WIN_LOCAL_APPDATA_DIR "LocalAppData"
#define NS_WIN_PRINTHOOD "PrntHd"
#define NS_WIN_COOKIES_DIR "CookD"
#define NS_WIN_DEFAULT_DOWNLOAD_DIR "DfltDwnld"
// On Win7 and up these ids will return the default save-to location for
// Windows Libraries associated with the specific content type. For other
// os they return the local user folder. Note these can return network file
// paths which can jank the ui thread so be careful how you access them.
#define NS_WIN_DOCUMENTS_DIR "Docs"
#define NS_WIN_PICTURES_DIR "Pict"
#define NS_WIN_MUSIC_DIR "Music"
#define NS_WIN_VIDEOS_DIR "Vids"
#elif defined (XP_UNIX)
#define NS_UNIX_LOCAL_DIR "Locl"
#define NS_UNIX_LIB_DIR "LibD"
#define NS_UNIX_HOME_DIR NS_OS_HOME_DIR
#define NS_UNIX_XDG_DESKTOP_DIR "XDGDesk"
#define NS_UNIX_XDG_DOCUMENTS_DIR "XDGDocs"
#define NS_UNIX_XDG_DOWNLOAD_DIR "XDGDwnld"
#define NS_UNIX_XDG_MUSIC_DIR "XDGMusic"
#define NS_UNIX_XDG_PICTURES_DIR "XDGPict"
#define NS_UNIX_XDG_PUBLIC_SHARE_DIR "XDGPubSh"
#define NS_UNIX_XDG_TEMPLATES_DIR "XDGTempl"
#define NS_UNIX_XDG_VIDEOS_DIR "XDGVids"
#define NS_UNIX_DEFAULT_DOWNLOAD_DIR "DfltDwnld"
#define NS_UNIX_LOCAL_DIR "Locl"
#define NS_UNIX_LIB_DIR "LibD"
#define NS_UNIX_HOME_DIR NS_OS_HOME_DIR
#define NS_UNIX_XDG_DESKTOP_DIR "XDGDesk"
#define NS_UNIX_XDG_DOCUMENTS_DIR "XDGDocs"
#define NS_UNIX_XDG_DOWNLOAD_DIR "XDGDwnld"
#define NS_UNIX_XDG_MUSIC_DIR "XDGMusic"
#define NS_UNIX_XDG_PICTURES_DIR "XDGPict"
#define NS_UNIX_XDG_PUBLIC_SHARE_DIR "XDGPubSh"
#define NS_UNIX_XDG_TEMPLATES_DIR "XDGTempl"
#define NS_UNIX_XDG_VIDEOS_DIR "XDGVids"
#define NS_UNIX_DEFAULT_DOWNLOAD_DIR "DfltDwnld"
#endif
/* Deprecated */

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -16,13 +17,13 @@
inline nsresult
NS_GetSpecialDirectory(const char* specialDirName, nsIFile* *result)
{
nsresult rv;
nsCOMPtr<nsIProperties> serv(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv));
if (NS_FAILED(rv))
return rv;
nsresult rv;
nsCOMPtr<nsIProperties> serv(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv));
if (NS_FAILED(rv))
return rv;
return serv->Get(specialDirName, NS_GET_IID(nsIFile),
reinterpret_cast<void**>(result));
return serv->Get(specialDirName, NS_GET_IID(nsIFile),
reinterpret_cast<void**>(result));
}
#endif

View File

@@ -1,9 +1,10 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// First checked in on 98/12/03 by John R. McMullen, derived from net.h/mkparse.c.
// First checked in on 98/12/03 by John R. McMullen, derived from net.h/mkparse.c.
#include "nsEscape.h"
#include "nsMemory.h"
@@ -11,23 +12,23 @@
#include "nsReadableUtils.h"
const int netCharType[256] =
/* Bit 0 xalpha -- the alphas
** Bit 1 xpalpha -- as xalpha but
/* Bit 0 xalpha -- the alphas
** Bit 1 xpalpha -- as xalpha but
** converts spaces to plus and plus to %2B
** Bit 3 ... path -- as xalphas but doesn't escape '/'
** Bit 3 ... path -- as xalphas but doesn't escape '/'
*/
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
{ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x */
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 1x */
0,0,0,0,0,0,0,0,0,0,7,4,0,7,7,4, /* 2x !"#$%&'()*+,-./ */
7,7,7,7,7,7,7,7,7,7,0,0,0,0,0,0, /* 3x 0123456789:;<=>? */
0,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, /* 4x @ABCDEFGHIJKLMNO */
/* bits for '@' changed from 7 to 0 so '@' can be escaped */
/* in usernames and passwords in publishing. */
7,7,7,7,7,7,7,7,7,7,7,0,0,0,0,7, /* 5X PQRSTUVWXYZ[\]^_ */
0,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, /* 6x `abcdefghijklmno */
7,7,7,7,7,7,7,7,7,7,7,0,0,0,0,0, /* 7X pqrstuvwxyz{\}~ DEL */
0, };
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
{ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x */
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 1x */
0,0,0,0,0,0,0,0,0,0,7,4,0,7,7,4, /* 2x !"#$%&'()*+,-./ */
7,7,7,7,7,7,7,7,7,7,0,0,0,0,0,0, /* 3x 0123456789:;<=>? */
0,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, /* 4x @ABCDEFGHIJKLMNO */
/* bits for '@' changed from 7 to 0 so '@' can be escaped */
/* in usernames and passwords in publishing. */
7,7,7,7,7,7,7,7,7,7,7,0,0,0,0,7, /* 5X PQRSTUVWXYZ[\]^_ */
0,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, /* 6x `abcdefghijklmno */
7,7,7,7,7,7,7,7,7,7,7,0,0,0,0,0, /* 7X pqrstuvwxyz{\}~ DEL */
0, };
/* decode % escaped hex codes into character values
*/
@@ -42,154 +43,154 @@ const int netCharType[256] =
//----------------------------------------------------------------------------------------
static char* nsEscapeCount(
const char * str,
nsEscapeMask flags,
size_t* out_len)
const char * str,
nsEscapeMask flags,
size_t* out_len)
//----------------------------------------------------------------------------------------
{
if (!str)
return 0;
if (!str)
return 0;
size_t i, len = 0, charsToEscape = 0;
static const char hexChars[] = "0123456789ABCDEF";
size_t i, len = 0, charsToEscape = 0;
static const char hexChars[] = "0123456789ABCDEF";
const unsigned char* src = (const unsigned char *) str;
while (*src)
{
len++;
if (!IS_OK(*src++))
charsToEscape++;
}
const unsigned char* src = (const unsigned char *) str;
while (*src)
{
len++;
if (!IS_OK(*src++))
charsToEscape++;
}
// calculate how much memory should be allocated
// original length + 2 bytes for each escaped character + terminating '\0'
// do the sum in steps to check for overflow
size_t dstSize = len + 1 + charsToEscape;
if (dstSize <= len)
return 0;
dstSize += charsToEscape;
if (dstSize < len)
return 0;
// calculate how much memory should be allocated
// original length + 2 bytes for each escaped character + terminating '\0'
// do the sum in steps to check for overflow
size_t dstSize = len + 1 + charsToEscape;
if (dstSize <= len)
return 0;
dstSize += charsToEscape;
if (dstSize < len)
return 0;
// fail if we need more than 4GB
// size_t is likely to be long unsigned int but nsMemory::Alloc(size_t)
// calls NS_Alloc_P(size_t) which calls PR_Malloc(uint32_t), so there is
// no chance to allocate more than 4GB using nsMemory::Alloc()
if (dstSize > UINT32_MAX)
return 0;
// fail if we need more than 4GB
// size_t is likely to be long unsigned int but nsMemory::Alloc(size_t)
// calls NS_Alloc_P(size_t) which calls PR_Malloc(uint32_t), so there is
// no chance to allocate more than 4GB using nsMemory::Alloc()
if (dstSize > UINT32_MAX)
return 0;
char* result = (char *)nsMemory::Alloc(dstSize);
if (!result)
return 0;
char* result = (char *)nsMemory::Alloc(dstSize);
if (!result)
return 0;
unsigned char* dst = (unsigned char *) result;
src = (const unsigned char *) str;
if (flags == url_XPAlphas)
{
for (i = 0; i < len; i++)
{
unsigned char c = *src++;
if (IS_OK(c))
*dst++ = c;
else if (c == ' ')
*dst++ = '+'; /* convert spaces to pluses */
else
{
*dst++ = HEX_ESCAPE;
*dst++ = hexChars[c >> 4]; /* high nibble */
*dst++ = hexChars[c & 0x0f]; /* low nibble */
}
}
}
else
{
for (i = 0; i < len; i++)
{
unsigned char c = *src++;
if (IS_OK(c))
*dst++ = c;
else
{
*dst++ = HEX_ESCAPE;
*dst++ = hexChars[c >> 4]; /* high nibble */
*dst++ = hexChars[c & 0x0f]; /* low nibble */
}
}
}
unsigned char* dst = (unsigned char *) result;
src = (const unsigned char *) str;
if (flags == url_XPAlphas)
{
for (i = 0; i < len; i++)
{
unsigned char c = *src++;
if (IS_OK(c))
*dst++ = c;
else if (c == ' ')
*dst++ = '+'; /* convert spaces to pluses */
else
{
*dst++ = HEX_ESCAPE;
*dst++ = hexChars[c >> 4]; /* high nibble */
*dst++ = hexChars[c & 0x0f]; /* low nibble */
}
}
}
else
{
for (i = 0; i < len; i++)
{
unsigned char c = *src++;
if (IS_OK(c))
*dst++ = c;
else
{
*dst++ = HEX_ESCAPE;
*dst++ = hexChars[c >> 4]; /* high nibble */
*dst++ = hexChars[c & 0x0f]; /* low nibble */
}
}
}
*dst = '\0'; /* tack on eos */
if(out_len)
*out_len = dst - (unsigned char *) result;
return result;
*dst = '\0'; /* tack on eos */
if(out_len)
*out_len = dst - (unsigned char *) result;
return result;
}
//----------------------------------------------------------------------------------------
char* nsEscape(const char * str, nsEscapeMask flags)
//----------------------------------------------------------------------------------------
{
if(!str)
return nullptr;
return nsEscapeCount(str, flags, nullptr);
if(!str)
return nullptr;
return nsEscapeCount(str, flags, nullptr);
}
//----------------------------------------------------------------------------------------
char* nsUnescape(char * str)
//----------------------------------------------------------------------------------------
{
nsUnescapeCount(str);
return str;
nsUnescapeCount(str);
return str;
}
//----------------------------------------------------------------------------------------
int32_t nsUnescapeCount(char * str)
//----------------------------------------------------------------------------------------
{
char *src = str;
char *dst = str;
static const char hexChars[] = "0123456789ABCDEFabcdef";
char *src = str;
char *dst = str;
static const char hexChars[] = "0123456789ABCDEFabcdef";
char c1[] = " ";
char c2[] = " ";
char* const pc1 = c1;
char* const pc2 = c2;
char c1[] = " ";
char c2[] = " ";
char* const pc1 = c1;
char* const pc2 = c2;
if (!*src) {
// A null string was passed in. Nothing to escape.
// Returns early as the string might not actually be mutable with
// length 0.
return 0;
}
if (!*src) {
// A null string was passed in. Nothing to escape.
// Returns early as the string might not actually be mutable with
// length 0.
return 0;
}
while (*src)
while (*src)
{
c1[0] = *(src+1);
if (*(src+1) == '\0')
c2[0] = '\0';
else
c2[0] = *(src+2);
if (*src != HEX_ESCAPE || PL_strpbrk(pc1, hexChars) == 0 ||
PL_strpbrk(pc2, hexChars) == 0 )
*dst++ = *src++;
else
{
c1[0] = *(src+1);
if (*(src+1) == '\0')
c2[0] = '\0';
else
c2[0] = *(src+2);
if (*src != HEX_ESCAPE || PL_strpbrk(pc1, hexChars) == 0 ||
PL_strpbrk(pc2, hexChars) == 0 )
*dst++ = *src++;
else
{
src++; /* walk over escape */
if (*src)
{
*dst = UNHEX(*src) << 4;
src++;
}
if (*src)
{
*dst = (*dst + UNHEX(*src));
src++;
}
dst++;
}
src++; /* walk over escape */
if (*src)
{
*dst = UNHEX(*src) << 4;
src++;
}
if (*src)
{
*dst = (*dst + UNHEX(*src));
src++;
}
dst++;
}
}
*dst = 0;
return (int)(dst - str);
*dst = 0;
return (int)(dst - str);
} /* NET_UnEscapeCnt */
@@ -197,67 +198,67 @@ int32_t nsUnescapeCount(char * str)
char *
nsEscapeHTML(const char * string)
{
char *rv = nullptr;
/* XXX Hardcoded max entity len. The +1 is for the trailing null. */
uint32_t len = strlen(string);
if (len >= (UINT32_MAX / 6))
return nullptr;
char *rv = nullptr;
/* XXX Hardcoded max entity len. The +1 is for the trailing null. */
uint32_t len = strlen(string);
if (len >= (UINT32_MAX / 6))
return nullptr;
rv = (char *)NS_Alloc( (6 * len) + 1 );
char *ptr = rv;
rv = (char *)NS_Alloc( (6 * len) + 1 );
char *ptr = rv;
if(rv)
if(rv)
{
for(; *string != '\0'; string++)
{
if(*string == '<')
{
for(; *string != '\0'; string++)
{
if(*string == '<')
{
*ptr++ = '&';
*ptr++ = 'l';
*ptr++ = 't';
*ptr++ = ';';
}
else if(*string == '>')
{
*ptr++ = '&';
*ptr++ = 'g';
*ptr++ = 't';
*ptr++ = ';';
}
else if(*string == '&')
{
*ptr++ = '&';
*ptr++ = 'a';
*ptr++ = 'm';
*ptr++ = 'p';
*ptr++ = ';';
}
else if (*string == '"')
{
*ptr++ = '&';
*ptr++ = 'q';
*ptr++ = 'u';
*ptr++ = 'o';
*ptr++ = 't';
*ptr++ = ';';
}
else if (*string == '\'')
{
*ptr++ = '&';
*ptr++ = '#';
*ptr++ = '3';
*ptr++ = '9';
*ptr++ = ';';
}
else
{
*ptr++ = *string;
}
}
*ptr = '\0';
*ptr++ = '&';
*ptr++ = 'l';
*ptr++ = 't';
*ptr++ = ';';
}
else if(*string == '>')
{
*ptr++ = '&';
*ptr++ = 'g';
*ptr++ = 't';
*ptr++ = ';';
}
else if(*string == '&')
{
*ptr++ = '&';
*ptr++ = 'a';
*ptr++ = 'm';
*ptr++ = 'p';
*ptr++ = ';';
}
else if (*string == '"')
{
*ptr++ = '&';
*ptr++ = 'q';
*ptr++ = 'u';
*ptr++ = 'o';
*ptr++ = 't';
*ptr++ = ';';
}
else if (*string == '\'')
{
*ptr++ = '&';
*ptr++ = '#';
*ptr++ = '3';
*ptr++ = '9';
*ptr++ = ';';
}
else
{
*ptr++ = *string;
}
}
*ptr = '\0';
}
return(rv);
return(rv);
}
char16_t *
@@ -274,7 +275,7 @@ nsEscapeHTML2(const char16_t *aSourceBuffer, int32_t aSourceBufferLen)
return nullptr;
char16_t *resultBuffer = (char16_t *)nsMemory::Alloc(aSourceBufferLen *
6 * sizeof(char16_t) + sizeof(char16_t('\0')));
6 * sizeof(char16_t) + sizeof(char16_t('\0')));
char16_t *ptr = resultBuffer;
if (resultBuffer) {
@@ -323,17 +324,17 @@ nsEscapeHTML2(const char16_t *aSourceBuffer, int32_t aSourceBufferLen)
//----------------------------------------------------------------------------------------
const int EscapeChars[256] =
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
0,1023, 0, 512,1023, 0,1023, 0,1023,1023,1023,1023,1023,1023, 953, 784, /* 2x !"#$%&'()*+,-./ */
1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1008,1008, 0,1008, 0, 768, /* 3x 0123456789:;<=>? */
1008,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023, /* 4x @ABCDEFGHIJKLMNO */
1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023, 896, 896, 896, 896,1023, /* 5x PQRSTUVWXYZ[\]^_ */
0,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023, /* 6x `abcdefghijklmno */
1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023, 896,1012, 896,1023, 0, /* 7x pqrstuvwxyz{|}~ */
0 /* 8x DEL */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
0,1023, 0, 512,1023, 0,1023, 0,1023,1023,1023,1023,1023,1023, 953, 784, /* 2x !"#$%&'()*+,-./ */
1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1008,1008, 0,1008, 0, 768, /* 3x 0123456789:;<=>? */
1008,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023, /* 4x @ABCDEFGHIJKLMNO */
1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023, 896, 896, 896, 896,1023, /* 5x PQRSTUVWXYZ[\]^_ */
0,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023, /* 6x `abcdefghijklmno */
1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023, 896,1012, 896,1023, 0, /* 7x pqrstuvwxyz{|}~ */
0 /* 8x DEL */
};
#define NO_NEED_ESC(C) (EscapeChars[((unsigned int) (C))] & (flags))
@@ -342,8 +343,8 @@ const int EscapeChars[256] =
/* returns an escaped string */
/* use the following flags to specify which
part of an URL you want to escape:
/* use the following flags to specify which
part of an URL you want to escape:
esc_Scheme = 1
esc_Username = 2
@@ -358,147 +359,147 @@ const int EscapeChars[256] =
*/
/* by default this function will not escape parts of a string
that already look escaped, which means it already includes
that already look escaped, which means it already includes
a valid hexcode. This is done to avoid multiple escapes of
a string. Use the following flags to force escaping of a
a string. Use the following flags to force escaping of a
string:
esc_Forced = 1024
*/
bool NS_EscapeURL(const char *part,
int32_t partLen,
uint32_t flags,
nsACString &result)
int32_t partLen,
uint32_t flags,
nsACString &result)
{
if (!part) {
NS_NOTREACHED("null pointer");
return false;
}
if (!part) {
NS_NOTREACHED("null pointer");
return false;
}
int i = 0;
static const char hexChars[] = "0123456789ABCDEF";
if (partLen < 0)
partLen = strlen(part);
bool forced = !!(flags & esc_Forced);
bool ignoreNonAscii = !!(flags & esc_OnlyASCII);
bool ignoreAscii = !!(flags & esc_OnlyNonASCII);
bool writing = !!(flags & esc_AlwaysCopy);
bool colon = !!(flags & esc_Colon);
int i = 0;
static const char hexChars[] = "0123456789ABCDEF";
if (partLen < 0)
partLen = strlen(part);
bool forced = !!(flags & esc_Forced);
bool ignoreNonAscii = !!(flags & esc_OnlyASCII);
bool ignoreAscii = !!(flags & esc_OnlyNonASCII);
bool writing = !!(flags & esc_AlwaysCopy);
bool colon = !!(flags & esc_Colon);
const unsigned char* src = (const unsigned char *) part;
const unsigned char* src = (const unsigned char *) part;
char tempBuffer[100];
unsigned int tempBufferPos = 0;
char tempBuffer[100];
unsigned int tempBufferPos = 0;
bool previousIsNonASCII = false;
for (i = 0; i < partLen; i++)
bool previousIsNonASCII = false;
for (i = 0; i < partLen; i++)
{
unsigned char c = *src++;
// if the char has not to be escaped or whatever follows % is
// a valid escaped string, just copy the char.
//
// Also the % will not be escaped until forced
// See bugzilla bug 61269 for details why we changed this
//
// And, we will not escape non-ascii characters if requested.
// On special request we will also escape the colon even when
// not covered by the matrix.
// ignoreAscii is not honored for control characters (C0 and DEL)
//
// And, we should escape the '|' character when it occurs after any
// non-ASCII character as it may be part of a multi-byte character.
//
// 0x20..0x7e are the valid ASCII characters. We also escape spaces
// (0x20) since they are not legal in URLs.
if ((NO_NEED_ESC(c) || (c == HEX_ESCAPE && !forced)
|| (c > 0x7f && ignoreNonAscii)
|| (c > 0x20 && c < 0x7f && ignoreAscii))
&& !(c == ':' && colon)
&& !(previousIsNonASCII && c == '|' && !ignoreNonAscii))
{
unsigned char c = *src++;
// if the char has not to be escaped or whatever follows % is
// a valid escaped string, just copy the char.
//
// Also the % will not be escaped until forced
// See bugzilla bug 61269 for details why we changed this
//
// And, we will not escape non-ascii characters if requested.
// On special request we will also escape the colon even when
// not covered by the matrix.
// ignoreAscii is not honored for control characters (C0 and DEL)
//
// And, we should escape the '|' character when it occurs after any
// non-ASCII character as it may be part of a multi-byte character.
//
// 0x20..0x7e are the valid ASCII characters. We also escape spaces
// (0x20) since they are not legal in URLs.
if ((NO_NEED_ESC(c) || (c == HEX_ESCAPE && !forced)
|| (c > 0x7f && ignoreNonAscii)
|| (c > 0x20 && c < 0x7f && ignoreAscii))
&& !(c == ':' && colon)
&& !(previousIsNonASCII && c == '|' && !ignoreNonAscii))
{
if (writing)
tempBuffer[tempBufferPos++] = c;
}
else /* do the escape magic */
{
if (!writing)
{
result.Append(part, i);
writing = true;
}
tempBuffer[tempBufferPos++] = HEX_ESCAPE;
tempBuffer[tempBufferPos++] = hexChars[c >> 4]; /* high nibble */
tempBuffer[tempBufferPos++] = hexChars[c & 0x0f]; /* low nibble */
}
if (tempBufferPos >= sizeof(tempBuffer) - 4)
{
NS_ASSERTION(writing, "should be writing");
tempBuffer[tempBufferPos] = '\0';
result += tempBuffer;
tempBufferPos = 0;
}
previousIsNonASCII = (c > 0x7f);
if (writing)
tempBuffer[tempBufferPos++] = c;
}
if (writing) {
else /* do the escape magic */
{
if (!writing)
{
result.Append(part, i);
writing = true;
}
tempBuffer[tempBufferPos++] = HEX_ESCAPE;
tempBuffer[tempBufferPos++] = hexChars[c >> 4]; /* high nibble */
tempBuffer[tempBufferPos++] = hexChars[c & 0x0f]; /* low nibble */
}
if (tempBufferPos >= sizeof(tempBuffer) - 4)
{
NS_ASSERTION(writing, "should be writing");
tempBuffer[tempBufferPos] = '\0';
result += tempBuffer;
tempBufferPos = 0;
}
return writing;
previousIsNonASCII = (c > 0x7f);
}
if (writing) {
tempBuffer[tempBufferPos] = '\0';
result += tempBuffer;
}
return writing;
}
#define ISHEX(c) memchr(hexChars, c, sizeof(hexChars)-1)
bool NS_UnescapeURL(const char *str, int32_t len, uint32_t flags, nsACString &result)
{
if (!str) {
NS_NOTREACHED("null pointer");
return false;
}
if (!str) {
NS_NOTREACHED("null pointer");
return false;
}
if (len < 0)
len = strlen(str);
if (len < 0)
len = strlen(str);
bool ignoreNonAscii = !!(flags & esc_OnlyASCII);
bool ignoreAscii = !!(flags & esc_OnlyNonASCII);
bool writing = !!(flags & esc_AlwaysCopy);
bool skipControl = !!(flags & esc_SkipControl);
bool ignoreNonAscii = !!(flags & esc_OnlyASCII);
bool ignoreAscii = !!(flags & esc_OnlyNonASCII);
bool writing = !!(flags & esc_AlwaysCopy);
bool skipControl = !!(flags & esc_SkipControl);
static const char hexChars[] = "0123456789ABCDEFabcdef";
static const char hexChars[] = "0123456789ABCDEFabcdef";
const char *last = str;
const char *p = str;
const char *last = str;
const char *p = str;
for (int i=0; i<len; ++i, ++p) {
//printf("%c [i=%d of len=%d]\n", *p, i, len);
if (*p == HEX_ESCAPE && i < len-2) {
unsigned char *p1 = ((unsigned char *) p) + 1;
unsigned char *p2 = ((unsigned char *) p) + 2;
if (ISHEX(*p1) && ISHEX(*p2) &&
((*p1 < '8' && !ignoreAscii) || (*p1 >= '8' && !ignoreNonAscii)) &&
!(skipControl &&
(*p1 < '2' || (*p1 == '7' && (*p2 == 'f' || *p2 == 'F'))))) {
//printf("- p1=%c p2=%c\n", *p1, *p2);
writing = true;
if (p > last) {
//printf("- p=%p, last=%p\n", p, last);
result.Append(last, p - last);
last = p;
}
char u = (UNHEX(*p1) << 4) + UNHEX(*p2);
//printf("- u=%c\n", u);
result.Append(u);
i += 2;
p += 2;
last += 3;
}
for (int i=0; i<len; ++i, ++p) {
//printf("%c [i=%d of len=%d]\n", *p, i, len);
if (*p == HEX_ESCAPE && i < len-2) {
unsigned char *p1 = ((unsigned char *) p) + 1;
unsigned char *p2 = ((unsigned char *) p) + 2;
if (ISHEX(*p1) && ISHEX(*p2) &&
((*p1 < '8' && !ignoreAscii) || (*p1 >= '8' && !ignoreNonAscii)) &&
!(skipControl &&
(*p1 < '2' || (*p1 == '7' && (*p2 == 'f' || *p2 == 'F'))))) {
//printf("- p1=%c p2=%c\n", *p1, *p2);
writing = true;
if (p > last) {
//printf("- p=%p, last=%p\n", p, last);
result.Append(last, p - last);
last = p;
}
char u = (UNHEX(*p1) << 4) + UNHEX(*p2);
//printf("- u=%c\n", u);
result.Append(u);
i += 2;
p += 2;
last += 3;
}
}
if (writing && last < str + len)
result.Append(last, str + len - last);
}
if (writing && last < str + len)
result.Append(last, str + len - last);
return writing;
return writing;
}

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -18,10 +19,10 @@
* in sync.
*/
typedef enum {
url_All = 0 /**< %-escape every byte unconditionally */
, url_XAlphas = 1u << 0 /**< Normal escape - leave alphas intact, escape the rest */
, url_XPAlphas = 1u << 1 /**< As url_XAlphas, but convert spaces (0x20) to '+' and plus to %2B */
, url_Path = 1u << 2 /**< As url_XAlphas, but don't escape slash ('/') */
url_All = 0 /**< %-escape every byte unconditionally */
, url_XAlphas = 1u << 0 /**< Normal escape - leave alphas intact, escape the rest */
, url_XPAlphas = 1u << 1 /**< As url_XAlphas, but convert spaces (0x20) to '+' and plus to %2B */
, url_Path = 1u << 2 /**< As url_XAlphas, but don't escape slash ('/') */
} nsEscapeMask;
#ifdef __cplusplus
@@ -38,15 +39,15 @@ extern "C" {
char * nsEscape(const char * str, nsEscapeMask mask);
char * nsUnescape(char * str);
/* decode % escaped hex codes into character values,
* modifies the parameter, returns the same buffer
*/
/* decode % escaped hex codes into character values,
* modifies the parameter, returns the same buffer
*/
int32_t nsUnescapeCount (char * str);
/* decode % escaped hex codes into character values,
* modifies the parameter buffer, returns the length of the result
* (result may contain \0's).
*/
/* decode % escaped hex codes into character values,
* modifies the parameter buffer, returns the length of the result
* (result may contain \0's).
*/
char *
nsEscapeHTML(const char * string);
@@ -54,9 +55,9 @@ nsEscapeHTML(const char * string);
char16_t *
nsEscapeHTML2(const char16_t *aSourceBuffer,
int32_t aSourceBufferLen = -1);
/*
* Escape problem char's for HTML display
*/
/*
* Escape problem char's for HTML display
*/
#ifdef __cplusplus
@@ -84,10 +85,10 @@ enum EscapeMask {
esc_Query = 1u << 8,
esc_Ref = 1u << 9,
/** special flags **/
esc_Minimal = esc_Scheme | esc_Username | esc_Password | esc_Host | esc_FilePath | esc_Param | esc_Query | esc_Ref,
esc_Minimal = esc_Scheme | esc_Username | esc_Password | esc_Host | esc_FilePath | esc_Param | esc_Query | esc_Ref,
esc_Forced = 1u << 10, /* forces escaping of existing escape sequences */
esc_OnlyASCII = 1u << 11, /* causes non-ascii octets to be skipped */
esc_OnlyNonASCII = 1u << 12, /* causes _graphic_ ascii octets (0x20-0x7E)
esc_OnlyNonASCII = 1u << 12, /* causes _graphic_ ascii octets (0x20-0x7E)
* to be skipped when escaping. causes all
* ascii octets (<= 0x7F) to be skipped when unescaping */
esc_AlwaysCopy = 1u << 13, /* copy input to result buf even if escaping is unnecessary */
@@ -110,29 +111,29 @@ enum EscapeMask {
* @return TRUE if escaping was performed, FALSE otherwise.
*/
bool NS_EscapeURL(const char *str,
int32_t len,
uint32_t flags,
nsACString &result);
int32_t len,
uint32_t flags,
nsACString &result);
/**
* Expands URL escape sequences... beware embedded null bytes!
*
* @param str url string to unescape
* @param len length of |str|
* @param flags only esc_OnlyNonASCII, esc_SkipControl and esc_AlwaysCopy
* @param flags only esc_OnlyNonASCII, esc_SkipControl and esc_AlwaysCopy
* are recognized
* @param result result buffer, untouched if |str| is already unescaped
*
* @return TRUE if unescaping was performed, FALSE otherwise.
*/
bool NS_UnescapeURL(const char *str,
int32_t len,
uint32_t flags,
nsACString &result);
int32_t len,
uint32_t flags,
nsACString &result);
/** returns resultant string length **/
inline int32_t NS_UnescapeURL(char *str) {
return nsUnescapeCount(str);
return nsUnescapeCount(str);
}
/**
@@ -140,15 +141,15 @@ inline int32_t NS_UnescapeURL(char *str) {
*/
inline const nsCSubstring &
NS_EscapeURL(const nsCSubstring &str, uint32_t flags, nsCSubstring &result) {
if (NS_EscapeURL(str.Data(), str.Length(), flags, result))
return result;
return str;
if (NS_EscapeURL(str.Data(), str.Length(), flags, result))
return result;
return str;
}
inline const nsCSubstring &
NS_UnescapeURL(const nsCSubstring &str, uint32_t flags, nsCSubstring &result) {
if (NS_UnescapeURL(str.Data(), str.Length(), flags, result))
return result;
return str;
if (NS_UnescapeURL(str.Data(), str.Length(), flags, result))
return result;
return str;
}
/**
@@ -172,8 +173,8 @@ NS_Escape(const nsCString& aOriginal, nsCString& aEscaped,
inline nsCString &
NS_UnescapeURL(nsCString &str)
{
str.SetLength(nsUnescapeCount(str.BeginWriting()));
return str;
str.SetLength(nsUnescapeCount(str.BeginWriting()));
return str;
}
#endif // _ESCAPE_H_

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -25,10 +26,10 @@ using namespace mozilla;
static PRLogModuleInfo*
GetTeeLog()
{
static PRLogModuleInfo *sLog;
if (!sLog)
sLog = PR_NewLogModule("nsInputStreamTee");
return sLog;
static PRLogModuleInfo *sLog;
if (!sLog)
sLog = PR_NewLogModule("nsInputStreamTee");
return sLog;
}
#define LOG(args) PR_LOG(GetTeeLog(), PR_LOG_DEBUG, args)
#else
@@ -38,100 +39,100 @@ GetTeeLog()
class nsInputStreamTee MOZ_FINAL : public nsIInputStreamTee
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIINPUTSTREAM
NS_DECL_NSIINPUTSTREAMTEE
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIINPUTSTREAM
NS_DECL_NSIINPUTSTREAMTEE
nsInputStreamTee();
bool SinkIsValid();
void InvalidateSink();
nsInputStreamTee();
bool SinkIsValid();
void InvalidateSink();
private:
~nsInputStreamTee() {}
~nsInputStreamTee() {}
nsresult TeeSegment(const char *buf, uint32_t count);
static NS_METHOD WriteSegmentFun(nsIInputStream *, void *, const char *,
uint32_t, uint32_t, uint32_t *);
nsresult TeeSegment(const char *buf, uint32_t count);
static NS_METHOD WriteSegmentFun(nsIInputStream *, void *, const char *,
uint32_t, uint32_t, uint32_t *);
private:
nsCOMPtr<nsIInputStream> mSource;
nsCOMPtr<nsIOutputStream> mSink;
nsCOMPtr<nsIEventTarget> mEventTarget;
nsWriteSegmentFun mWriter; // for implementing ReadSegments
void *mClosure; // for implementing ReadSegments
nsAutoPtr<Mutex> mLock; // synchronize access to mSinkIsValid
bool mSinkIsValid; // False if TeeWriteEvent fails
nsCOMPtr<nsIInputStream> mSource;
nsCOMPtr<nsIOutputStream> mSink;
nsCOMPtr<nsIEventTarget> mEventTarget;
nsWriteSegmentFun mWriter; // for implementing ReadSegments
void *mClosure; // for implementing ReadSegments
nsAutoPtr<Mutex> mLock; // synchronize access to mSinkIsValid
bool mSinkIsValid; // False if TeeWriteEvent fails
};
class nsInputStreamTeeWriteEvent : public nsRunnable {
public:
// aTee's lock is held across construction of this object
nsInputStreamTeeWriteEvent(const char *aBuf, uint32_t aCount,
nsIOutputStream *aSink,
nsInputStreamTee *aTee)
{
// copy the buffer - will be free'd by dtor
mBuf = (char *)malloc(aCount);
if (mBuf) memcpy(mBuf, (char *)aBuf, aCount);
mCount = aCount;
mSink = aSink;
bool isNonBlocking;
mSink->IsNonBlocking(&isNonBlocking);
NS_ASSERTION(isNonBlocking == false, "mSink is nonblocking");
mTee = aTee;
// aTee's lock is held across construction of this object
nsInputStreamTeeWriteEvent(const char *aBuf, uint32_t aCount,
nsIOutputStream *aSink,
nsInputStreamTee *aTee)
{
// copy the buffer - will be free'd by dtor
mBuf = (char *)malloc(aCount);
if (mBuf) memcpy(mBuf, (char *)aBuf, aCount);
mCount = aCount;
mSink = aSink;
bool isNonBlocking;
mSink->IsNonBlocking(&isNonBlocking);
NS_ASSERTION(isNonBlocking == false, "mSink is nonblocking");
mTee = aTee;
}
NS_IMETHOD Run()
{
if (!mBuf) {
NS_WARNING("nsInputStreamTeeWriteEvent::Run() "
"memory not allocated\n");
return NS_OK;
}
NS_ABORT_IF_FALSE(mSink, "mSink is null!");
// The output stream could have been invalidated between when
// this event was dispatched and now, so check before writing.
if (!mTee->SinkIsValid()) {
return NS_OK;
}
NS_IMETHOD Run()
{
if (!mBuf) {
NS_WARNING("nsInputStreamTeeWriteEvent::Run() "
"memory not allocated\n");
return NS_OK;
}
NS_ABORT_IF_FALSE(mSink, "mSink is null!");
LOG(("nsInputStreamTeeWriteEvent::Run() [%p]"
"will write %u bytes to %p\n",
this, mCount, mSink.get()));
// The output stream could have been invalidated between when
// this event was dispatched and now, so check before writing.
if (!mTee->SinkIsValid()) {
return NS_OK;
}
LOG(("nsInputStreamTeeWriteEvent::Run() [%p]"
"will write %u bytes to %p\n",
this, mCount, mSink.get()));
uint32_t totalBytesWritten = 0;
while (mCount) {
nsresult rv;
uint32_t bytesWritten = 0;
rv = mSink->Write(mBuf + totalBytesWritten, mCount, &bytesWritten);
if (NS_FAILED(rv)) {
LOG(("nsInputStreamTeeWriteEvent::Run[%p] error %x in writing",
this,rv));
mTee->InvalidateSink();
break;
}
totalBytesWritten += bytesWritten;
NS_ASSERTION(bytesWritten <= mCount, "wrote too much");
mCount -= bytesWritten;
}
return NS_OK;
uint32_t totalBytesWritten = 0;
while (mCount) {
nsresult rv;
uint32_t bytesWritten = 0;
rv = mSink->Write(mBuf + totalBytesWritten, mCount, &bytesWritten);
if (NS_FAILED(rv)) {
LOG(("nsInputStreamTeeWriteEvent::Run[%p] error %x in writing",
this,rv));
mTee->InvalidateSink();
break;
}
totalBytesWritten += bytesWritten;
NS_ASSERTION(bytesWritten <= mCount, "wrote too much");
mCount -= bytesWritten;
}
return NS_OK;
}
protected:
virtual ~nsInputStreamTeeWriteEvent()
{
if (mBuf) free(mBuf);
mBuf = nullptr;
}
virtual ~nsInputStreamTeeWriteEvent()
{
if (mBuf) free(mBuf);
mBuf = nullptr;
}
private:
char *mBuf;
uint32_t mCount;
nsCOMPtr<nsIOutputStream> mSink;
// back pointer to the tee that created this runnable
nsRefPtr<nsInputStreamTee> mTee;
char *mBuf;
uint32_t mCount;
nsCOMPtr<nsIOutputStream> mSink;
// back pointer to the tee that created this runnable
nsRefPtr<nsInputStreamTee> mTee;
};
nsInputStreamTee::nsInputStreamTee(): mLock(nullptr)
@@ -142,69 +143,69 @@ nsInputStreamTee::nsInputStreamTee(): mLock(nullptr)
bool
nsInputStreamTee::SinkIsValid()
{
MutexAutoLock lock(*mLock);
return mSinkIsValid;
MutexAutoLock lock(*mLock);
return mSinkIsValid;
}
void
nsInputStreamTee::InvalidateSink()
{
MutexAutoLock lock(*mLock);
mSinkIsValid = false;
MutexAutoLock lock(*mLock);
mSinkIsValid = false;
}
nsresult
nsInputStreamTee::TeeSegment(const char *buf, uint32_t count)
{
if (!mSink) return NS_OK; // nothing to do
if (mLock) { // asynchronous case
NS_ASSERTION(mEventTarget, "mEventTarget is null, mLock is not null.");
if (!SinkIsValid()) {
return NS_OK; // nothing to do
}
nsRefPtr<nsIRunnable> event =
new nsInputStreamTeeWriteEvent(buf, count, mSink, this);
LOG(("nsInputStreamTee::TeeSegment [%p] dispatching write %u bytes\n",
this, count));
return mEventTarget->Dispatch(event, NS_DISPATCH_NORMAL);
} else { // synchronous case
NS_ASSERTION(!mEventTarget, "mEventTarget is not null, mLock is null.");
nsresult rv;
uint32_t totalBytesWritten = 0;
while (count) {
uint32_t bytesWritten = 0;
rv = mSink->Write(buf + totalBytesWritten, count, &bytesWritten);
if (NS_FAILED(rv)) {
// ok, this is not a fatal error... just drop our reference to mSink
// and continue on as if nothing happened.
NS_WARNING("Write failed (non-fatal)");
// catch possible misuse of the input stream tee
NS_ASSERTION(rv != NS_BASE_STREAM_WOULD_BLOCK, "sink must be a blocking stream");
mSink = 0;
break;
}
totalBytesWritten += bytesWritten;
NS_ASSERTION(bytesWritten <= count, "wrote too much");
count -= bytesWritten;
}
return NS_OK;
if (!mSink) return NS_OK; // nothing to do
if (mLock) { // asynchronous case
NS_ASSERTION(mEventTarget, "mEventTarget is null, mLock is not null.");
if (!SinkIsValid()) {
return NS_OK; // nothing to do
}
nsRefPtr<nsIRunnable> event =
new nsInputStreamTeeWriteEvent(buf, count, mSink, this);
LOG(("nsInputStreamTee::TeeSegment [%p] dispatching write %u bytes\n",
this, count));
return mEventTarget->Dispatch(event, NS_DISPATCH_NORMAL);
} else { // synchronous case
NS_ASSERTION(!mEventTarget, "mEventTarget is not null, mLock is null.");
nsresult rv;
uint32_t totalBytesWritten = 0;
while (count) {
uint32_t bytesWritten = 0;
rv = mSink->Write(buf + totalBytesWritten, count, &bytesWritten);
if (NS_FAILED(rv)) {
// ok, this is not a fatal error... just drop our reference to mSink
// and continue on as if nothing happened.
NS_WARNING("Write failed (non-fatal)");
// catch possible misuse of the input stream tee
NS_ASSERTION(rv != NS_BASE_STREAM_WOULD_BLOCK, "sink must be a blocking stream");
mSink = 0;
break;
}
totalBytesWritten += bytesWritten;
NS_ASSERTION(bytesWritten <= count, "wrote too much");
count -= bytesWritten;
}
return NS_OK;
}
}
NS_METHOD
nsInputStreamTee::WriteSegmentFun(nsIInputStream *in, void *closure, const char *fromSegment,
uint32_t offset, uint32_t count, uint32_t *writeCount)
{
nsInputStreamTee *tee = reinterpret_cast<nsInputStreamTee *>(closure);
nsInputStreamTee *tee = reinterpret_cast<nsInputStreamTee *>(closure);
nsresult rv = tee->mWriter(in, tee->mClosure, fromSegment, offset, count, writeCount);
if (NS_FAILED(rv) || (*writeCount == 0)) {
NS_ASSERTION((NS_FAILED(rv) ? (*writeCount == 0) : true),
"writer returned an error with non-zero writeCount");
return rv;
}
nsresult rv = tee->mWriter(in, tee->mClosure, fromSegment, offset, count, writeCount);
if (NS_FAILED(rv) || (*writeCount == 0)) {
NS_ASSERTION((NS_FAILED(rv) ? (*writeCount == 0) : true),
"writer returned an error with non-zero writeCount");
return rv;
}
return tee->TeeSegment(fromSegment, *writeCount);
return tee->TeeSegment(fromSegment, *writeCount);
}
NS_IMPL_ISUPPORTS(nsInputStreamTee,
@@ -213,110 +214,110 @@ NS_IMPL_ISUPPORTS(nsInputStreamTee,
NS_IMETHODIMP
nsInputStreamTee::Close()
{
if (NS_WARN_IF(!mSource))
return NS_ERROR_NOT_INITIALIZED;
nsresult rv = mSource->Close();
mSource = 0;
mSink = 0;
return rv;
if (NS_WARN_IF(!mSource))
return NS_ERROR_NOT_INITIALIZED;
nsresult rv = mSource->Close();
mSource = 0;
mSink = 0;
return rv;
}
NS_IMETHODIMP
nsInputStreamTee::Available(uint64_t *avail)
{
if (NS_WARN_IF(!mSource))
return NS_ERROR_NOT_INITIALIZED;
return mSource->Available(avail);
if (NS_WARN_IF(!mSource))
return NS_ERROR_NOT_INITIALIZED;
return mSource->Available(avail);
}
NS_IMETHODIMP
nsInputStreamTee::Read(char *buf, uint32_t count, uint32_t *bytesRead)
{
if (NS_WARN_IF(!mSource))
return NS_ERROR_NOT_INITIALIZED;
if (NS_WARN_IF(!mSource))
return NS_ERROR_NOT_INITIALIZED;
nsresult rv = mSource->Read(buf, count, bytesRead);
if (NS_FAILED(rv) || (*bytesRead == 0))
return rv;
nsresult rv = mSource->Read(buf, count, bytesRead);
if (NS_FAILED(rv) || (*bytesRead == 0))
return rv;
return TeeSegment(buf, *bytesRead);
return TeeSegment(buf, *bytesRead);
}
NS_IMETHODIMP
nsInputStreamTee::ReadSegments(nsWriteSegmentFun writer,
nsInputStreamTee::ReadSegments(nsWriteSegmentFun writer,
void *closure,
uint32_t count,
uint32_t *bytesRead)
{
if (NS_WARN_IF(!mSource))
return NS_ERROR_NOT_INITIALIZED;
if (NS_WARN_IF(!mSource))
return NS_ERROR_NOT_INITIALIZED;
mWriter = writer;
mClosure = closure;
mWriter = writer;
mClosure = closure;
return mSource->ReadSegments(WriteSegmentFun, this, count, bytesRead);
return mSource->ReadSegments(WriteSegmentFun, this, count, bytesRead);
}
NS_IMETHODIMP
nsInputStreamTee::IsNonBlocking(bool *result)
{
if (NS_WARN_IF(!mSource))
return NS_ERROR_NOT_INITIALIZED;
return mSource->IsNonBlocking(result);
if (NS_WARN_IF(!mSource))
return NS_ERROR_NOT_INITIALIZED;
return mSource->IsNonBlocking(result);
}
NS_IMETHODIMP
nsInputStreamTee::SetSource(nsIInputStream *source)
{
mSource = source;
return NS_OK;
mSource = source;
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamTee::GetSource(nsIInputStream **source)
{
NS_IF_ADDREF(*source = mSource);
return NS_OK;
NS_IF_ADDREF(*source = mSource);
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamTee::SetSink(nsIOutputStream *sink)
{
#ifdef DEBUG
if (sink) {
bool nonBlocking;
nsresult rv = sink->IsNonBlocking(&nonBlocking);
if (NS_FAILED(rv) || nonBlocking)
NS_ERROR("sink should be a blocking stream");
}
if (sink) {
bool nonBlocking;
nsresult rv = sink->IsNonBlocking(&nonBlocking);
if (NS_FAILED(rv) || nonBlocking)
NS_ERROR("sink should be a blocking stream");
}
#endif
mSink = sink;
return NS_OK;
mSink = sink;
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamTee::GetSink(nsIOutputStream **sink)
{
NS_IF_ADDREF(*sink = mSink);
return NS_OK;
NS_IF_ADDREF(*sink = mSink);
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamTee::SetEventTarget(nsIEventTarget *anEventTarget)
{
mEventTarget = anEventTarget;
if (mEventTarget) {
// Only need synchronization if this is an async tee
mLock = new Mutex("nsInputStreamTee.mLock");
}
return NS_OK;
mEventTarget = anEventTarget;
if (mEventTarget) {
// Only need synchronization if this is an async tee
mLock = new Mutex("nsInputStreamTee.mLock");
}
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamTee::GetEventTarget(nsIEventTarget **anEventTarget)
{
NS_IF_ADDREF(*anEventTarget = mEventTarget);
return NS_OK;
NS_IF_ADDREF(*anEventTarget = mEventTarget);
return NS_OK;
}
@@ -326,23 +327,23 @@ NS_NewInputStreamTeeAsync(nsIInputStream **result,
nsIOutputStream *sink,
nsIEventTarget *anEventTarget)
{
nsresult rv;
nsCOMPtr<nsIInputStreamTee> tee = new nsInputStreamTee();
if (!tee)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv;
rv = tee->SetSource(source);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIInputStreamTee> tee = new nsInputStreamTee();
if (!tee)
return NS_ERROR_OUT_OF_MEMORY;
rv = tee->SetSink(sink);
if (NS_FAILED(rv)) return rv;
rv = tee->SetSource(source);
if (NS_FAILED(rv)) return rv;
rv = tee->SetEventTarget(anEventTarget);
if (NS_FAILED(rv)) return rv;
rv = tee->SetSink(sink);
if (NS_FAILED(rv)) return rv;
NS_ADDREF(*result = tee);
return rv;
rv = tee->SetEventTarget(anEventTarget);
if (NS_FAILED(rv)) return rv;
NS_ADDREF(*result = tee);
return rv;
}
nsresult
@@ -350,7 +351,7 @@ NS_NewInputStreamTee(nsIInputStream **result,
nsIInputStream *source,
nsIOutputStream *sink)
{
return NS_NewInputStreamTeeAsync(result, source, sink, nullptr);
return NS_NewInputStreamTeeAsync(result, source, sink, nullptr);
}
#undef LOG

View File

@@ -10,8 +10,8 @@
/*----------------------------------------------------------------------------
GetLinebreakString
GetLinebreakString
Could make this inline
----------------------------------------------------------------------------*/
static const char* GetLinebreakString(nsLinebreakConverter::ELinebreakType aBreakType)
@@ -25,16 +25,16 @@ static const char* GetLinebreakString(nsLinebreakConverter::ELinebreakType aBrea
LFSTR, // Unix
CRLF, // Windows
" ", // space
nullptr
nullptr
};
return sLinebreaks[aBreakType];
}
/*----------------------------------------------------------------------------
AppendLinebreak
AppendLinebreak
Wee inline method to append a line break. Modifies ioDest.
----------------------------------------------------------------------------*/
template<class T>
@@ -47,8 +47,8 @@ void AppendLinebreak(T*& ioDest, const char* lineBreakStr)
}
/*----------------------------------------------------------------------------
CountChars
CountChars
Counts occurrences of breakStr in aSrc
----------------------------------------------------------------------------*/
template<class T>
@@ -82,23 +82,23 @@ int32_t CountLinebreaks(const T* aSrc, int32_t inLen, const char* breakStr)
src++;
}
}
return theCount;
}
/*----------------------------------------------------------------------------
ConvertBreaks
ConvertBreaks
ioLen *includes* a terminating null, if any
----------------------------------------------------------------------------*/
template<class T>
static T* ConvertBreaks(const T* inSrc, int32_t& ioLen, const char* srcBreak, const char* destBreak)
{
NS_ASSERTION(inSrc && srcBreak && destBreak, "Got a null string");
T* resultString = nullptr;
// handle the no conversion case
if (nsCRT::strcmp(srcBreak, destBreak) == 0)
{
@@ -107,7 +107,7 @@ static T* ConvertBreaks(const T* inSrc, int32_t& ioLen, const char* srcBreak, co
memcpy(resultString, inSrc, sizeof(T) * ioLen); // includes the null, if any
return resultString;
}
int32_t srcBreakLen = strlen(srcBreak);
int32_t destBreakLen = strlen(destBreak);
@@ -117,14 +117,14 @@ static T* ConvertBreaks(const T* inSrc, int32_t& ioLen, const char* srcBreak, co
{
resultString = (T *)nsMemory::Alloc(sizeof(T) * ioLen);
if (!resultString) return nullptr;
const T* src = inSrc;
const T* srcEnd = inSrc + ioLen; // includes null, if any
T* dst = resultString;
char srcBreakChar = *srcBreak; // we know it's one char long already
char dstBreakChar = *destBreak;
while (src < srcEnd)
{
if (*src == srcBreakChar)
@@ -143,18 +143,18 @@ static T* ConvertBreaks(const T* inSrc, int32_t& ioLen, const char* srcBreak, co
else
{
// src and dest termination is different length. Do it a slower way.
// count linebreaks in src. Assumes that chars in 2-char linebreaks are unique.
int32_t numLinebreaks = CountLinebreaks(inSrc, ioLen, srcBreak);
int32_t newBufLen = ioLen - (numLinebreaks * srcBreakLen) + (numLinebreaks * destBreakLen);
resultString = (T *)nsMemory::Alloc(sizeof(T) * newBufLen);
if (!resultString) return nullptr;
const T* src = inSrc;
const T* srcEnd = inSrc + ioLen; // includes null, if any
T* dst = resultString;
while (src < srcEnd)
{
if (*src == *srcBreak)
@@ -162,7 +162,7 @@ static T* ConvertBreaks(const T* inSrc, int32_t& ioLen, const char* srcBreak, co
*dst++ = *destBreak;
if (destBreak[1])
*dst++ = destBreak[1];
src++;
if (src < srcEnd && srcBreak[1] && *src == srcBreak[1])
src++;
@@ -172,17 +172,17 @@ static T* ConvertBreaks(const T* inSrc, int32_t& ioLen, const char* srcBreak, co
*dst++ = *src++;
}
}
ioLen = newBufLen;
}
return resultString;
}
/*----------------------------------------------------------------------------
ConvertBreaksInSitu
ConvertBreaksInSitu
Convert breaks in situ. Can only do this if the linebreak length
does not change.
----------------------------------------------------------------------------*/
@@ -196,17 +196,17 @@ static void ConvertBreaksInSitu(T* inSrc, int32_t inLen, char srcBreak, char des
{
if (*src == srcBreak)
*src = destBreak;
src++;
}
}
/*----------------------------------------------------------------------------
ConvertUnknownBreaks
ConvertUnknownBreaks
Convert unknown line breaks to the specified break.
This will convert CRLF pairs to one break, and single CR or LF to a break.
----------------------------------------------------------------------------*/
template<class T>
@@ -214,7 +214,7 @@ static T* ConvertUnknownBreaks(const T* inSrc, int32_t& ioLen, const char* destB
{
const T* src = inSrc;
const T* srcEnd = inSrc + ioLen; // includes null, if any
int32_t destBreakLen = strlen(destBreak);
int32_t finalLen = 0;
@@ -245,7 +245,7 @@ static T* ConvertUnknownBreaks(const T* inSrc, int32_t& ioLen, const char* destB
}
src++;
}
T* resultString = (T *)nsMemory::Alloc(sizeof(T) * finalLen);
if (!resultString) return nullptr;
@@ -253,7 +253,7 @@ static T* ConvertUnknownBreaks(const T* inSrc, int32_t& ioLen, const char* destB
srcEnd = inSrc + ioLen; // includes null, if any
T* dst = resultString;
while (src < srcEnd)
{
if (*src == nsCRT::CR)
@@ -288,16 +288,16 @@ static T* ConvertUnknownBreaks(const T* inSrc, int32_t& ioLen, const char* destB
/*----------------------------------------------------------------------------
ConvertLineBreaks
ConvertLineBreaks
----------------------------------------------------------------------------*/
char* nsLinebreakConverter::ConvertLineBreaks(const char* aSrc,
ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks, int32_t aSrcLen, int32_t* outLen)
ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks, int32_t aSrcLen, int32_t* outLen)
{
NS_ASSERTION(aDestBreaks != eLinebreakAny &&
aSrcBreaks != eLinebreakSpace, "Invalid parameter");
if (!aSrc) return nullptr;
int32_t sourceLen = (aSrcLen == kIgnoreLen) ? strlen(aSrc) + 1 : aSrcLen;
char* resultString;
@@ -305,7 +305,7 @@ char* nsLinebreakConverter::ConvertLineBreaks(const char* aSrc,
resultString = ConvertUnknownBreaks(aSrc, sourceLen, GetLinebreakString(aDestBreaks));
else
resultString = ConvertBreaks(aSrc, sourceLen, GetLinebreakString(aSrcBreaks), GetLinebreakString(aDestBreaks));
if (outLen)
*outLen = sourceLen;
return resultString;
@@ -313,24 +313,24 @@ char* nsLinebreakConverter::ConvertLineBreaks(const char* aSrc,
/*----------------------------------------------------------------------------
ConvertLineBreaksInSitu
ConvertLineBreaksInSitu
----------------------------------------------------------------------------*/
nsresult nsLinebreakConverter::ConvertLineBreaksInSitu(char **ioBuffer, ELinebreakType aSrcBreaks,
ELinebreakType aDestBreaks, int32_t aSrcLen, int32_t* outLen)
ELinebreakType aDestBreaks, int32_t aSrcLen, int32_t* outLen)
{
NS_ASSERTION(ioBuffer && *ioBuffer, "Null pointer passed");
if (!ioBuffer || !*ioBuffer) return NS_ERROR_NULL_POINTER;
NS_ASSERTION(aDestBreaks != eLinebreakAny &&
aSrcBreaks != eLinebreakSpace, "Invalid parameter");
int32_t sourceLen = (aSrcLen == kIgnoreLen) ? strlen(*ioBuffer) + 1 : aSrcLen;
// can we convert in-place?
const char* srcBreaks = GetLinebreakString(aSrcBreaks);
const char* dstBreaks = GetLinebreakString(aDestBreaks);
if ( (aSrcBreaks != eLinebreakAny) &&
(strlen(srcBreaks) == 1) &&
(strlen(dstBreaks) == 1) )
@@ -342,7 +342,7 @@ nsresult nsLinebreakConverter::ConvertLineBreaksInSitu(char **ioBuffer, ELinebre
else
{
char* destBuffer;
if (aSrcBreaks == eLinebreakAny)
destBuffer = ConvertUnknownBreaks(*ioBuffer, sourceLen, dstBreaks);
else
@@ -353,22 +353,22 @@ nsresult nsLinebreakConverter::ConvertLineBreaksInSitu(char **ioBuffer, ELinebre
if (outLen)
*outLen = sourceLen;
}
return NS_OK;
}
/*----------------------------------------------------------------------------
ConvertUnicharLineBreaks
ConvertUnicharLineBreaks
----------------------------------------------------------------------------*/
char16_t* nsLinebreakConverter::ConvertUnicharLineBreaks(const char16_t* aSrc,
ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks, int32_t aSrcLen, int32_t* outLen)
ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks, int32_t aSrcLen, int32_t* outLen)
{
NS_ASSERTION(aDestBreaks != eLinebreakAny &&
aSrcBreaks != eLinebreakSpace, "Invalid parameter");
if (!aSrc) return nullptr;
int32_t bufLen = (aSrcLen == kIgnoreLen) ? NS_strlen(aSrc) + 1 : aSrcLen;
char16_t* resultString;
@@ -376,7 +376,7 @@ char16_t* nsLinebreakConverter::ConvertUnicharLineBreaks(const char16_t* aSrc,
resultString = ConvertUnknownBreaks(aSrc, bufLen, GetLinebreakString(aDestBreaks));
else
resultString = ConvertBreaks(aSrc, bufLen, GetLinebreakString(aSrcBreaks), GetLinebreakString(aDestBreaks));
if (outLen)
*outLen = bufLen;
return resultString;
@@ -384,11 +384,11 @@ char16_t* nsLinebreakConverter::ConvertUnicharLineBreaks(const char16_t* aSrc,
/*----------------------------------------------------------------------------
ConvertStringLineBreaks
ConvertStringLineBreaks
----------------------------------------------------------------------------*/
nsresult nsLinebreakConverter::ConvertUnicharLineBreaksInSitu(char16_t **ioBuffer,
ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks, int32_t aSrcLen, int32_t* outLen)
ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks, int32_t aSrcLen, int32_t* outLen)
{
NS_ASSERTION(ioBuffer && *ioBuffer, "Null pointer passed");
if (!ioBuffer || !*ioBuffer) return NS_ERROR_NULL_POINTER;
@@ -400,7 +400,7 @@ nsresult nsLinebreakConverter::ConvertUnicharLineBreaksInSitu(char16_t **ioBuffe
// can we convert in-place?
const char* srcBreaks = GetLinebreakString(aSrcBreaks);
const char* dstBreaks = GetLinebreakString(aDestBreaks);
if ( (aSrcBreaks != eLinebreakAny) &&
(strlen(srcBreaks) == 1) &&
(strlen(dstBreaks) == 1) )
@@ -412,7 +412,7 @@ nsresult nsLinebreakConverter::ConvertUnicharLineBreaksInSitu(char16_t **ioBuffe
else
{
char16_t* destBuffer;
if (aSrcBreaks == eLinebreakAny)
destBuffer = ConvertUnknownBreaks(*ioBuffer, sourceLen, dstBreaks);
else
@@ -423,16 +423,16 @@ nsresult nsLinebreakConverter::ConvertUnicharLineBreaksInSitu(char16_t **ioBuffe
if (outLen)
*outLen = sourceLen;
}
return NS_OK;
}
/*----------------------------------------------------------------------------
ConvertStringLineBreaks
ConvertStringLineBreaks
----------------------------------------------------------------------------*/
nsresult nsLinebreakConverter::ConvertStringLineBreaks(nsString& ioString,
ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks)
ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks)
{
NS_ASSERTION(aDestBreaks != eLinebreakAny &&
@@ -440,16 +440,16 @@ nsresult nsLinebreakConverter::ConvertStringLineBreaks(nsString& ioString,
// nothing to do
if (ioString.IsEmpty()) return NS_OK;
nsresult rv;
// remember the old buffer in case
// we blow it away later
nsString::char_iterator stringBuf;
ioString.BeginWriting(stringBuf);
int32_t newLen;
rv = ConvertUnicharLineBreaksInSitu(&stringBuf,
aSrcBreaks, aDestBreaks,
ioString.Length() + 1, &newLen);
@@ -457,7 +457,7 @@ nsresult nsLinebreakConverter::ConvertStringLineBreaks(nsString& ioString,
if (stringBuf != ioString.get())
ioString.Adopt(stringBuf);
return NS_OK;
}

View File

@@ -18,23 +18,23 @@ public:
// Note: enum must match char* array in GetLinebreakString
typedef enum {
eLinebreakAny, // any kind of linebreak (i.e. "don't care" source)
eLinebreakPlatform, // platform linebreak
eLinebreakContent, // Content model linebreak (LF)
eLinebreakNet, // Form submission linebreak (CRLF)
eLinebreakMac, // CR
eLinebreakUnix, // LF
eLinebreakWindows, // CRLF
eLinebreakSpace // space characters. Only valid as destination type
} ELinebreakType;
enum {
kIgnoreLen = -1
};
/* ConvertLineBreaks
* Convert line breaks in the supplied string, allocating and returning
* a new buffer. Returns nullptr on failure.
@@ -48,9 +48,9 @@ public:
* @param aOutLen: used to return character length of returned buffer, if not null.
*/
static char* ConvertLineBreaks(const char* aSrc,
ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks,
int32_t aSrcLen = kIgnoreLen, int32_t* aOutLen = nullptr);
ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks,
int32_t aSrcLen = kIgnoreLen, int32_t* aOutLen = nullptr);
/* ConvertUnicharLineBreaks
* Convert line breaks in the supplied string, allocating and returning
@@ -65,9 +65,9 @@ public:
* @param aOutLen: used to return character length of returned buffer, if not null.
*/
static char16_t* ConvertUnicharLineBreaks(const char16_t* aSrc,
ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks,
int32_t aSrcLen = kIgnoreLen, int32_t* aOutLen = nullptr);
ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks,
int32_t aSrcLen = kIgnoreLen, int32_t* aOutLen = nullptr);
/* ConvertStringLineBreaks
* Convert line breaks in the supplied string, changing the string buffer (i.e. in-place conversion)
@@ -86,7 +86,7 @@ public:
* BUT IT WON'T FREE THE OLD BUFFER (because it doesn't know how). So be prepared
* to keep a copy of the old pointer, and free it if this passes back a new pointer.
* ALSO NOTE: DON'T PASS A STATIC STRING POINTER TO THIS FUNCTION.
*
*
* @param ioBuffer: the source buffer. if aSrcLen == kIgnoreLen this string is assumed
* to be null terminated, otherwise it must be at least aSrcLen long.
* @param aSrcBreaks: the line breaks in the source. If unknown, pass eLinebreakAny.
@@ -97,14 +97,14 @@ public:
* @param aOutLen: used to return character length of returned buffer, if not null.
*/
static nsresult ConvertLineBreaksInSitu(char **ioBuffer, ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks,
int32_t aSrcLen = kIgnoreLen, int32_t* aOutLen = nullptr);
int32_t aSrcLen = kIgnoreLen, int32_t* aOutLen = nullptr);
/* ConvertUnicharLineBreaksInSitu
* Convert line breaks in place if possible. NOTE: THIS MAY REALLOCATE THE BUFFER,
* BUT IT WON'T FREE THE OLD BUFFER (because it doesn't know how). So be prepared
* to keep a copy of the old pointer, and free it if this passes back a new pointer.
*
*
* @param ioBuffer: the source buffer. if aSrcLen == kIgnoreLen this string is assumed
* to be null terminated, otherwise it must be at least aSrcLen long.
* @param aSrcBreaks: the line breaks in the source. If unknown, pass eLinebreakAny.
@@ -115,8 +115,8 @@ public:
* @param aOutLen: used to return character length of returned buffer, if not null.
*/
static nsresult ConvertUnicharLineBreaksInSitu(char16_t **ioBuffer, ELinebreakType aSrcBreaks, ELinebreakType aDestBreaks,
int32_t aSrcLen = kIgnoreLen, int32_t* aOutLen = nullptr);
int32_t aSrcLen = kIgnoreLen, int32_t* aOutLen = nullptr);
};
#endif // nsLinebreakConverter_h_

View File

@@ -1,9 +1,10 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Original Code has been modified by IBM Corporation. Modifications made by IBM
* This Original Code has been modified by IBM Corporation. Modifications made by IBM
* described herein are Copyright (c) International Business Machines Corporation, 2000.
* Modifications to Mozilla code or documentation identified per MPL Section 3.3
*
@@ -19,16 +20,16 @@
#define NS_LOCAL_FILE_CID {0x2e23e220, 0x60be, 0x11d3, {0x8c, 0x4a, 0x00, 0x00, 0x64, 0x65, 0x73, 0x74}}
#define NS_DECL_NSLOCALFILE_UNICODE_METHODS \
nsresult AppendUnicode(const char16_t *aNode); \
nsresult GetUnicodeLeafName(char16_t **aLeafName); \
nsresult SetUnicodeLeafName(const char16_t *aLeafName); \
nsresult CopyToUnicode(nsIFile *aNewParentDir, const char16_t *aNewLeafName); \
nsresult CopyToFollowingLinksUnicode(nsIFile *aNewParentDir, const char16_t *aNewLeafName); \
nsresult MoveToUnicode(nsIFile *aNewParentDir, const char16_t *aNewLeafName); \
nsresult GetUnicodeTarget(char16_t **aTarget); \
nsresult GetUnicodePath(char16_t **aPath); \
nsresult InitWithUnicodePath(const char16_t *aPath); \
nsresult AppendRelativeUnicodePath(const char16_t *aRelativePath);
nsresult AppendUnicode(const char16_t *aNode); \
nsresult GetUnicodeLeafName(char16_t **aLeafName); \
nsresult SetUnicodeLeafName(const char16_t *aLeafName); \
nsresult CopyToUnicode(nsIFile *aNewParentDir, const char16_t *aNewLeafName); \
nsresult CopyToFollowingLinksUnicode(nsIFile *aNewParentDir, const char16_t *aNewLeafName); \
nsresult MoveToUnicode(nsIFile *aNewParentDir, const char16_t *aNewLeafName); \
nsresult GetUnicodeTarget(char16_t **aTarget); \
nsresult GetUnicodePath(char16_t **aPath); \
nsresult InitWithUnicodePath(const char16_t *aPath); \
nsresult AppendRelativeUnicodePath(const char16_t *aRelativePath);
// nsXPComInit needs to know about how we are implemented,
// so here we will export it. Other users should not depend
@@ -50,69 +51,69 @@
inline nsresult
nsresultForErrno(int err)
{
switch (err) {
case 0:
return NS_OK;
switch (err) {
case 0:
return NS_OK;
#ifdef EDQUOT
case EDQUOT: /* Quota exceeded */
// FALLTHROUGH to return NS_ERROR_FILE_DISK_FULL
case EDQUOT: /* Quota exceeded */
// FALLTHROUGH to return NS_ERROR_FILE_DISK_FULL
#endif
case ENOSPC:
return NS_ERROR_FILE_DISK_FULL;
case ENOSPC:
return NS_ERROR_FILE_DISK_FULL;
#ifdef EISDIR
case EISDIR: /* Is a directory. */
return NS_ERROR_FILE_IS_DIRECTORY;
case EISDIR: /* Is a directory. */
return NS_ERROR_FILE_IS_DIRECTORY;
#endif
case ENAMETOOLONG:
return NS_ERROR_FILE_NAME_TOO_LONG;
case ENOEXEC: /* Executable file format error. */
return NS_ERROR_FILE_EXECUTION_FAILED;
case ENOENT:
return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST;
case ENOTDIR:
return NS_ERROR_FILE_DESTINATION_NOT_DIR;
case ENAMETOOLONG:
return NS_ERROR_FILE_NAME_TOO_LONG;
case ENOEXEC: /* Executable file format error. */
return NS_ERROR_FILE_EXECUTION_FAILED;
case ENOENT:
return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST;
case ENOTDIR:
return NS_ERROR_FILE_DESTINATION_NOT_DIR;
#ifdef ELOOP
case ELOOP:
return NS_ERROR_FILE_UNRESOLVABLE_SYMLINK;
case ELOOP:
return NS_ERROR_FILE_UNRESOLVABLE_SYMLINK;
#endif /* ELOOP */
#ifdef ENOLINK
case ENOLINK:
return NS_ERROR_FILE_UNRESOLVABLE_SYMLINK;
case ENOLINK:
return NS_ERROR_FILE_UNRESOLVABLE_SYMLINK;
#endif /* ENOLINK */
case EEXIST:
return NS_ERROR_FILE_ALREADY_EXISTS;
case EEXIST:
return NS_ERROR_FILE_ALREADY_EXISTS;
#ifdef EPERM
case EPERM:
case EPERM:
#endif /* EPERM */
case EACCES:
return NS_ERROR_FILE_ACCESS_DENIED;
case EACCES:
return NS_ERROR_FILE_ACCESS_DENIED;
#ifdef EROFS
case EROFS: /* Read-only file system. */
return NS_ERROR_FILE_READ_ONLY;
case EROFS: /* Read-only file system. */
return NS_ERROR_FILE_READ_ONLY;
#endif
/*
* On AIX 4.3, ENOTEMPTY is defined as EEXIST,
* so there can't be cases for both without
* preprocessing.
*/
/*
* On AIX 4.3, ENOTEMPTY is defined as EEXIST,
* so there can't be cases for both without
* preprocessing.
*/
#if ENOTEMPTY != EEXIST
case ENOTEMPTY:
return NS_ERROR_FILE_DIR_NOT_EMPTY;
case ENOTEMPTY:
return NS_ERROR_FILE_DIR_NOT_EMPTY;
#endif /* ENOTEMPTY != EEXIST */
/* Note that nsIFile.createUnique() returns
NS_ERROR_FILE_TOO_BIG when it cannot create a temporary
file with a unique filename.
See https://developer.mozilla.org/en-US/docs/Table_Of_Errors
Other usages of NS_ERROR_FILE_TOO_BIG in the source tree
are in line with the POSIX semantics of EFBIG.
So this is a reasonably good approximation.
*/
case EFBIG: /* File too large. */
return NS_ERROR_FILE_TOO_BIG;
/* Note that nsIFile.createUnique() returns
NS_ERROR_FILE_TOO_BIG when it cannot create a temporary
file with a unique filename.
See https://developer.mozilla.org/en-US/docs/Table_Of_Errors
Other usages of NS_ERROR_FILE_TOO_BIG in the source tree
are in line with the POSIX semantics of EFBIG.
So this is a reasonably good approximation.
*/
case EFBIG: /* File too large. */
return NS_ERROR_FILE_TOO_BIG;
default:
return NS_ERROR_FAILURE;
}
default:
return NS_ERROR_FAILURE;
}
}
#define NSRESULT_FOR_ERRNO() nsresultForErrno(errno)

View File

@@ -1,7 +1,9 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsIServiceManager.h"
#include "nsLocalFile.h" // includes platform-specific headers
@@ -21,26 +23,26 @@
void NS_StartupLocalFile()
{
nsLocalFile::GlobalInit();
nsLocalFile::GlobalInit();
}
void NS_ShutdownLocalFile()
{
nsLocalFile::GlobalShutdown();
nsLocalFile::GlobalShutdown();
}
#if !defined(MOZ_WIDGET_COCOA) && !defined(XP_WIN)
NS_IMETHODIMP
nsLocalFile::InitWithFile(nsIFile *aFile)
{
if (NS_WARN_IF(!aFile))
return NS_ERROR_INVALID_ARG;
nsAutoCString path;
aFile->GetNativePath(path);
if (path.IsEmpty())
return NS_ERROR_INVALID_ARG;
return InitWithNativePath(path);
if (NS_WARN_IF(!aFile))
return NS_ERROR_INVALID_ARG;
nsAutoCString path;
aFile->GetNativePath(path);
if (path.IsEmpty())
return NS_ERROR_INVALID_ARG;
return InitWithNativePath(path);
}
#endif
@@ -52,107 +54,107 @@ nsLocalFile::InitWithFile(nsIFile *aFile)
NS_IMETHODIMP
nsLocalFile::CreateUnique(uint32_t type, uint32_t attributes)
{
nsresult rv;
bool longName;
nsresult rv;
bool longName;
#ifdef XP_WIN
nsAutoString pathName, leafName, rootName, suffix;
rv = GetPath(pathName);
nsAutoString pathName, leafName, rootName, suffix;
rv = GetPath(pathName);
#else
nsAutoCString pathName, leafName, rootName, suffix;
rv = GetNativePath(pathName);
nsAutoCString pathName, leafName, rootName, suffix;
rv = GetNativePath(pathName);
#endif
if (NS_FAILED(rv))
return rv;
if (NS_FAILED(rv))
return rv;
longName = (pathName.Length() + kMaxSequenceNumberLength >
kMaxFilenameLength);
if (!longName)
{
rv = Create(type, attributes);
if (rv != NS_ERROR_FILE_ALREADY_EXISTS)
return rv;
}
longName = (pathName.Length() + kMaxSequenceNumberLength >
kMaxFilenameLength);
if (!longName)
{
rv = Create(type, attributes);
if (rv != NS_ERROR_FILE_ALREADY_EXISTS)
return rv;
}
#ifdef XP_WIN
rv = GetLeafName(leafName);
if (NS_FAILED(rv))
return rv;
rv = GetLeafName(leafName);
if (NS_FAILED(rv))
return rv;
const int32_t lastDot = leafName.RFindChar(char16_t('.'));
const int32_t lastDot = leafName.RFindChar(char16_t('.'));
#else
rv = GetNativeLeafName(leafName);
if (NS_FAILED(rv))
return rv;
rv = GetNativeLeafName(leafName);
if (NS_FAILED(rv))
return rv;
const int32_t lastDot = leafName.RFindChar('.');
const int32_t lastDot = leafName.RFindChar('.');
#endif
if (lastDot == kNotFound)
{
rootName = leafName;
}
else
{
suffix = Substring(leafName, lastDot); // include '.'
rootName = Substring(leafName, 0, lastDot); // strip suffix and dot
}
if (lastDot == kNotFound)
{
rootName = leafName;
}
else
{
suffix = Substring(leafName, lastDot); // include '.'
rootName = Substring(leafName, 0, lastDot); // strip suffix and dot
}
if (longName)
{
int32_t maxRootLength = (kMaxFilenameLength -
(pathName.Length() - leafName.Length()) -
suffix.Length() - kMaxSequenceNumberLength);
if (longName)
{
int32_t maxRootLength = (kMaxFilenameLength -
(pathName.Length() - leafName.Length()) -
suffix.Length() - kMaxSequenceNumberLength);
// We cannot create an item inside a directory whose name is too long.
// Also, ensure that at least one character remains after we truncate
// the root name, as we don't want to end up with an empty leaf name.
if (maxRootLength < 2)
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
// We cannot create an item inside a directory whose name is too long.
// Also, ensure that at least one character remains after we truncate
// the root name, as we don't want to end up with an empty leaf name.
if (maxRootLength < 2)
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
#ifdef XP_WIN
// ensure that we don't cut the name in mid-UTF16-character
rootName.SetLength(NS_IS_LOW_SURROGATE(rootName[maxRootLength]) ?
maxRootLength - 1 : maxRootLength);
SetLeafName(rootName + suffix);
// ensure that we don't cut the name in mid-UTF16-character
rootName.SetLength(NS_IS_LOW_SURROGATE(rootName[maxRootLength]) ?
maxRootLength - 1 : maxRootLength);
SetLeafName(rootName + suffix);
#else
if (NS_IsNativeUTF8())
{
// ensure that we don't cut the name in mid-UTF8-character
// (assume the name is valid UTF8 to begin with)
while (UTF8traits::isInSeq(rootName[maxRootLength]))
--maxRootLength;
// Another check to avoid ending up with an empty leaf name.
if (maxRootLength == 0 && suffix.IsEmpty())
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
}
rootName.SetLength(maxRootLength);
SetNativeLeafName(rootName + suffix);
#endif
nsresult rv = Create(type, attributes);
if (rv != NS_ERROR_FILE_ALREADY_EXISTS)
return rv;
}
for (int indx = 1; indx < 10000; indx++)
if (NS_IsNativeUTF8())
{
// start with "Picture-1.jpg" after "Picture.jpg" exists
#ifdef XP_WIN
SetLeafName(rootName +
NS_ConvertASCIItoUTF16(nsPrintfCString("-%d", indx)) +
suffix);
#else
SetNativeLeafName(rootName + nsPrintfCString("-%d", indx) + suffix);
#endif
rv = Create(type, attributes);
if (NS_SUCCEEDED(rv) || rv != NS_ERROR_FILE_ALREADY_EXISTS)
return rv;
// ensure that we don't cut the name in mid-UTF8-character
// (assume the name is valid UTF8 to begin with)
while (UTF8traits::isInSeq(rootName[maxRootLength]))
--maxRootLength;
// Another check to avoid ending up with an empty leaf name.
if (maxRootLength == 0 && suffix.IsEmpty())
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
}
// The disk is full, sort of
return NS_ERROR_FILE_TOO_BIG;
rootName.SetLength(maxRootLength);
SetNativeLeafName(rootName + suffix);
#endif
nsresult rv = Create(type, attributes);
if (rv != NS_ERROR_FILE_ALREADY_EXISTS)
return rv;
}
for (int indx = 1; indx < 10000; indx++)
{
// start with "Picture-1.jpg" after "Picture.jpg" exists
#ifdef XP_WIN
SetLeafName(rootName +
NS_ConvertASCIItoUTF16(nsPrintfCString("-%d", indx)) +
suffix);
#else
SetNativeLeafName(rootName + nsPrintfCString("-%d", indx) + suffix);
#endif
rv = Create(type, attributes);
if (NS_SUCCEEDED(rv) || rv != NS_ERROR_FILE_ALREADY_EXISTS)
return rv;
}
// The disk is full, sort of
return NS_ERROR_FILE_TOO_BIG;
}
#if defined(XP_WIN)
@@ -165,128 +167,128 @@ static const char16_t kPathSeparatorChar = '/';
static int32_t SplitPath(char16_t *path, char16_t **nodeArray, int32_t arrayLen)
{
if (*path == 0)
return 0;
if (*path == 0)
return 0;
char16_t **nodePtr = nodeArray;
if (*path == kPathSeparatorChar)
path++;
*nodePtr++ = path;
for (char16_t *cp = path; *cp != 0; cp++) {
if (*cp == kPathSeparatorChar) {
*cp++ = 0;
if (*cp == 0)
break;
if (nodePtr - nodeArray >= arrayLen)
return -1;
*nodePtr++ = cp;
}
char16_t **nodePtr = nodeArray;
if (*path == kPathSeparatorChar)
path++;
*nodePtr++ = path;
for (char16_t *cp = path; *cp != 0; cp++) {
if (*cp == kPathSeparatorChar) {
*cp++ = 0;
if (*cp == 0)
break;
if (nodePtr - nodeArray >= arrayLen)
return -1;
*nodePtr++ = cp;
}
return nodePtr - nodeArray;
}
return nodePtr - nodeArray;
}
NS_IMETHODIMP
nsLocalFile::GetRelativeDescriptor(nsIFile *fromFile, nsACString& _retval)
{
if (NS_WARN_IF(!fromFile))
return NS_ERROR_INVALID_ARG;
const int32_t kMaxNodesInPath = 32;
if (NS_WARN_IF(!fromFile))
return NS_ERROR_INVALID_ARG;
const int32_t kMaxNodesInPath = 32;
//
// _retval will be UTF-8 encoded
//
nsresult rv;
_retval.Truncate(0);
//
// _retval will be UTF-8 encoded
//
nsAutoString thisPath, fromPath;
char16_t *thisNodes[kMaxNodesInPath], *fromNodes[kMaxNodesInPath];
int32_t thisNodeCnt, fromNodeCnt, nodeIndex;
rv = GetPath(thisPath);
if (NS_FAILED(rv))
return rv;
rv = fromFile->GetPath(fromPath);
if (NS_FAILED(rv))
return rv;
nsresult rv;
_retval.Truncate(0);
// get raw pointer to mutable string buffer
char16_t *thisPathPtr; thisPath.BeginWriting(thisPathPtr);
char16_t *fromPathPtr; fromPath.BeginWriting(fromPathPtr);
thisNodeCnt = SplitPath(thisPathPtr, thisNodes, kMaxNodesInPath);
fromNodeCnt = SplitPath(fromPathPtr, fromNodes, kMaxNodesInPath);
if (thisNodeCnt < 0 || fromNodeCnt < 0)
return NS_ERROR_FAILURE;
for (nodeIndex = 0; nodeIndex < thisNodeCnt && nodeIndex < fromNodeCnt; ++nodeIndex) {
nsAutoString thisPath, fromPath;
char16_t *thisNodes[kMaxNodesInPath], *fromNodes[kMaxNodesInPath];
int32_t thisNodeCnt, fromNodeCnt, nodeIndex;
rv = GetPath(thisPath);
if (NS_FAILED(rv))
return rv;
rv = fromFile->GetPath(fromPath);
if (NS_FAILED(rv))
return rv;
// get raw pointer to mutable string buffer
char16_t *thisPathPtr; thisPath.BeginWriting(thisPathPtr);
char16_t *fromPathPtr; fromPath.BeginWriting(fromPathPtr);
thisNodeCnt = SplitPath(thisPathPtr, thisNodes, kMaxNodesInPath);
fromNodeCnt = SplitPath(fromPathPtr, fromNodes, kMaxNodesInPath);
if (thisNodeCnt < 0 || fromNodeCnt < 0)
return NS_ERROR_FAILURE;
for (nodeIndex = 0; nodeIndex < thisNodeCnt && nodeIndex < fromNodeCnt; ++nodeIndex) {
#ifdef XP_WIN
if (_wcsicmp(char16ptr_t(thisNodes[nodeIndex]), char16ptr_t(fromNodes[nodeIndex])))
break;
if (_wcsicmp(char16ptr_t(thisNodes[nodeIndex]), char16ptr_t(fromNodes[nodeIndex])))
break;
#else
if (nsCRT::strcmp(thisNodes[nodeIndex], fromNodes[nodeIndex]))
break;
if (nsCRT::strcmp(thisNodes[nodeIndex], fromNodes[nodeIndex]))
break;
#endif
}
int32_t branchIndex = nodeIndex;
for (nodeIndex = branchIndex; nodeIndex < fromNodeCnt; nodeIndex++)
_retval.AppendLiteral("../");
for (nodeIndex = branchIndex; nodeIndex < thisNodeCnt; nodeIndex++) {
NS_ConvertUTF16toUTF8 nodeStr(thisNodes[nodeIndex]);
_retval.Append(nodeStr);
if (nodeIndex + 1 < thisNodeCnt)
_retval.Append('/');
}
return NS_OK;
}
int32_t branchIndex = nodeIndex;
for (nodeIndex = branchIndex; nodeIndex < fromNodeCnt; nodeIndex++)
_retval.AppendLiteral("../");
for (nodeIndex = branchIndex; nodeIndex < thisNodeCnt; nodeIndex++) {
NS_ConvertUTF16toUTF8 nodeStr(thisNodes[nodeIndex]);
_retval.Append(nodeStr);
if (nodeIndex + 1 < thisNodeCnt)
_retval.Append('/');
}
return NS_OK;
}
NS_IMETHODIMP
nsLocalFile::SetRelativeDescriptor(nsIFile *fromFile, const nsACString& relativeDesc)
{
NS_NAMED_LITERAL_CSTRING(kParentDirStr, "../");
nsCOMPtr<nsIFile> targetFile;
nsresult rv = fromFile->Clone(getter_AddRefs(targetFile));
NS_NAMED_LITERAL_CSTRING(kParentDirStr, "../");
nsCOMPtr<nsIFile> targetFile;
nsresult rv = fromFile->Clone(getter_AddRefs(targetFile));
if (NS_FAILED(rv))
return rv;
//
// relativeDesc is UTF-8 encoded
//
nsCString::const_iterator strBegin, strEnd;
relativeDesc.BeginReading(strBegin);
relativeDesc.EndReading(strEnd);
nsCString::const_iterator nodeBegin(strBegin), nodeEnd(strEnd);
nsCString::const_iterator pos(strBegin);
nsCOMPtr<nsIFile> parentDir;
while (FindInReadable(kParentDirStr, nodeBegin, nodeEnd)) {
rv = targetFile->GetParent(getter_AddRefs(parentDir));
if (NS_FAILED(rv))
return rv;
return rv;
if (!parentDir)
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
targetFile = parentDir;
//
// relativeDesc is UTF-8 encoded
//
nodeBegin = nodeEnd;
pos = nodeEnd;
nodeEnd = strEnd;
}
nsCString::const_iterator strBegin, strEnd;
relativeDesc.BeginReading(strBegin);
relativeDesc.EndReading(strEnd);
nsCString::const_iterator nodeBegin(strBegin), nodeEnd(strEnd);
nsCString::const_iterator pos(strBegin);
nsCOMPtr<nsIFile> parentDir;
while (FindInReadable(kParentDirStr, nodeBegin, nodeEnd)) {
rv = targetFile->GetParent(getter_AddRefs(parentDir));
if (NS_FAILED(rv))
return rv;
if (!parentDir)
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
targetFile = parentDir;
nodeBegin = nodeEnd = pos;
while (nodeEnd != strEnd) {
FindCharInReadable('/', nodeEnd, strEnd);
targetFile->Append(NS_ConvertUTF8toUTF16(Substring(nodeBegin, nodeEnd)));
if (nodeEnd != strEnd) // If there's more left in the string, inc over the '/' nodeEnd is on.
++nodeEnd;
nodeBegin = nodeEnd;
}
nodeBegin = nodeEnd;
pos = nodeEnd;
nodeEnd = strEnd;
}
nodeBegin = nodeEnd = pos;
while (nodeEnd != strEnd) {
FindCharInReadable('/', nodeEnd, strEnd);
targetFile->Append(NS_ConvertUTF8toUTF16(Substring(nodeBegin, nodeEnd)));
if (nodeEnd != strEnd) // If there's more left in the string, inc over the '/' nodeEnd is on.
++nodeEnd;
nodeBegin = nodeEnd;
}
return InitWithFile(targetFile);
return InitWithFile(targetFile);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -24,110 +25,110 @@
#include "nsILocalFileMac.h"
#endif
/**
/**
* we need these for statfs()
*/
#ifdef HAVE_SYS_STATVFS_H
#if defined(__osf__) && defined(__DECCXX)
extern "C" int statvfs(const char *, struct statvfs *);
#endif
#include <sys/statvfs.h>
#if defined(__osf__) && defined(__DECCXX)
extern "C" int statvfs(const char *, struct statvfs *);
#endif
#include <sys/statvfs.h>
#endif
#ifdef HAVE_SYS_STATFS_H
#include <sys/statfs.h>
#include <sys/statfs.h>
#endif
#ifdef HAVE_SYS_VFS_H
#include <sys/vfs.h>
#include <sys/vfs.h>
#endif
#ifdef HAVE_SYS_MOUNT_H
#include <sys/param.h>
#include <sys/mount.h>
#include <sys/param.h>
#include <sys/mount.h>
#endif
#if defined(HAVE_STATVFS64) && (!defined(LINUX) && !defined(__osf__))
#define STATFS statvfs64
#define F_BSIZE f_frsize
#define STATFS statvfs64
#define F_BSIZE f_frsize
#elif defined(HAVE_STATVFS) && (!defined(LINUX) && !defined(__osf__))
#define STATFS statvfs
#define F_BSIZE f_frsize
#define STATFS statvfs
#define F_BSIZE f_frsize
#elif defined(HAVE_STATFS64)
#define STATFS statfs64
#define F_BSIZE f_bsize
#define STATFS statfs64
#define F_BSIZE f_bsize
#elif defined(HAVE_STATFS)
#define STATFS statfs
#define F_BSIZE f_bsize
#define STATFS statfs
#define F_BSIZE f_bsize
#endif
// stat64 and lstat64 are deprecated on OS X. Normal stat and lstat are
// 64-bit by default on OS X 10.6+.
#if defined(HAVE_STAT64) && defined(HAVE_LSTAT64) && !defined(XP_MACOSX)
#if defined (AIX)
#if defined STAT
#undef STAT
#endif
#if defined (AIX)
#if defined STAT
#undef STAT
#endif
#define STAT stat64
#define LSTAT lstat64
#define HAVE_STATS64 1
#endif
#define STAT stat64
#define LSTAT lstat64
#define HAVE_STATS64 1
#else
#define STAT stat
#define LSTAT lstat
#define STAT stat
#define LSTAT lstat
#endif
class nsLocalFile MOZ_FINAL :
#ifdef MOZ_WIDGET_COCOA
public nsILocalFileMac,
public nsILocalFileMac,
#else
public nsILocalFile,
public nsILocalFile,
#endif
public nsIHashable
public nsIHashable
{
public:
NS_DEFINE_STATIC_CID_ACCESSOR(NS_LOCAL_FILE_CID)
nsLocalFile();
NS_DEFINE_STATIC_CID_ACCESSOR(NS_LOCAL_FILE_CID)
static nsresult nsLocalFileConstructor(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr);
nsLocalFile();
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIFILE
NS_DECL_NSILOCALFILE
static nsresult nsLocalFileConstructor(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr);
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIFILE
NS_DECL_NSILOCALFILE
#ifdef MOZ_WIDGET_COCOA
NS_DECL_NSILOCALFILEMAC
NS_DECL_NSILOCALFILEMAC
#endif
NS_DECL_NSIHASHABLE
NS_DECL_NSIHASHABLE
public:
static void GlobalInit();
static void GlobalShutdown();
static void GlobalInit();
static void GlobalShutdown();
private:
nsLocalFile(const nsLocalFile& other);
~nsLocalFile() {}
nsLocalFile(const nsLocalFile& other);
~nsLocalFile() {}
protected:
// This stat cache holds the *last stat* - it does not invalidate.
// Call "FillStatCache" whenever you want to stat our file.
struct STAT mCachedStat;
nsCString mPath;
// This stat cache holds the *last stat* - it does not invalidate.
// Call "FillStatCache" whenever you want to stat our file.
struct STAT mCachedStat;
nsCString mPath;
void LocateNativeLeafName(nsACString::const_iterator &,
nsACString::const_iterator &);
void LocateNativeLeafName(nsACString::const_iterator &,
nsACString::const_iterator &);
nsresult CopyDirectoryTo(nsIFile *newParent);
nsresult CreateAllAncestors(uint32_t permissions);
nsresult GetNativeTargetPathName(nsIFile *newParent,
const nsACString &newName,
nsACString &_retval);
nsresult CopyDirectoryTo(nsIFile *newParent);
nsresult CreateAllAncestors(uint32_t permissions);
nsresult GetNativeTargetPathName(nsIFile *newParent,
const nsACString &newName,
nsACString &_retval);
bool FillStatCache();
bool FillStatCache();
nsresult CreateAndKeepOpen(uint32_t type, int flags,
uint32_t permissions, PRFileDesc **_retval);
nsresult CreateAndKeepOpen(uint32_t type, int flags,
uint32_t permissions, PRFileDesc **_retval);
};
#endif /* _nsLocalFileUNIX_H_ */

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -28,83 +29,83 @@ class nsLocalFile MOZ_FINAL : public nsILocalFileWin,
public nsIHashable
{
public:
NS_DEFINE_STATIC_CID_ACCESSOR(NS_LOCAL_FILE_CID)
nsLocalFile();
NS_DEFINE_STATIC_CID_ACCESSOR(NS_LOCAL_FILE_CID)
static nsresult nsLocalFileConstructor(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr);
nsLocalFile();
// nsISupports interface
NS_DECL_THREADSAFE_ISUPPORTS
// nsIFile interface
NS_DECL_NSIFILE
// nsILocalFile interface
NS_DECL_NSILOCALFILE
static nsresult nsLocalFileConstructor(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr);
// nsILocalFileWin interface
NS_DECL_NSILOCALFILEWIN
// nsISupports interface
NS_DECL_THREADSAFE_ISUPPORTS
// nsIHashable interface
NS_DECL_NSIHASHABLE
// nsIFile interface
NS_DECL_NSIFILE
// nsILocalFile interface
NS_DECL_NSILOCALFILE
// nsILocalFileWin interface
NS_DECL_NSILOCALFILEWIN
// nsIHashable interface
NS_DECL_NSIHASHABLE
public:
static void GlobalInit();
static void GlobalShutdown();
static void GlobalInit();
static void GlobalShutdown();
private:
// CopyMove and CopySingleFile constants for |options| parameter:
enum CopyFileOption {
FollowSymlinks = 1u << 0,
Move = 1u << 1,
SkipNtfsAclReset = 1u << 2,
Rename = 1u << 3
};
// CopyMove and CopySingleFile constants for |options| parameter:
enum CopyFileOption {
FollowSymlinks = 1u << 0,
Move = 1u << 1,
SkipNtfsAclReset = 1u << 2,
Rename = 1u << 3
};
nsLocalFile(const nsLocalFile& other);
~nsLocalFile() {}
nsLocalFile(const nsLocalFile& other);
~nsLocalFile() {}
bool mDirty; // cached information can only be used when this is false
bool mResolveDirty;
bool mFollowSymlinks; // should we follow symlinks when working on this file
// this string will always be in native format!
nsString mWorkingPath;
// this will be the resolved path of shortcuts, it will *NEVER*
// be returned to the user
nsString mResolvedPath;
bool mDirty; // cached information can only be used when this is false
bool mResolveDirty;
bool mFollowSymlinks; // should we follow symlinks when working on this file
// this string, if not empty, is the *short* pathname that represents
// mWorkingPath
nsString mShortWorkingPath;
// this string will always be in native format!
nsString mWorkingPath;
PRFileInfo64 mFileInfo64;
// this will be the resolved path of shortcuts, it will *NEVER*
// be returned to the user
nsString mResolvedPath;
void MakeDirty()
{
mDirty = true;
mResolveDirty = true;
mShortWorkingPath.Truncate();
}
// this string, if not empty, is the *short* pathname that represents
// mWorkingPath
nsString mShortWorkingPath;
nsresult ResolveAndStat();
nsresult Resolve();
nsresult ResolveShortcut();
PRFileInfo64 mFileInfo64;
void EnsureShortPath();
nsresult CopyMove(nsIFile *newParentDir, const nsAString &newName,
uint32_t options);
nsresult CopySingleFile(nsIFile *source, nsIFile* dest,
const nsAString &newName,
uint32_t options);
void MakeDirty()
{
mDirty = true;
mResolveDirty = true;
mShortWorkingPath.Truncate();
}
nsresult SetModDate(int64_t aLastModifiedTime, const wchar_t *filePath);
nsresult HasFileAttribute(DWORD fileAttrib, bool *_retval);
nsresult AppendInternal(const nsAFlatString &node,
bool multipleComponents);
nsresult ResolveAndStat();
nsresult Resolve();
nsresult ResolveShortcut();
void EnsureShortPath();
nsresult CopyMove(nsIFile *newParentDir, const nsAString &newName,
uint32_t options);
nsresult CopySingleFile(nsIFile *source, nsIFile* dest,
const nsAString &newName,
uint32_t options);
nsresult SetModDate(int64_t aLastModifiedTime, const wchar_t *filePath);
nsresult HasFileAttribute(DWORD fileAttrib, bool *_retval);
nsresult AppendInternal(const nsAFlatString &node,
bool multipleComponents);
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -15,12 +16,12 @@
#define NS_MULTIPLEXINPUTSTREAM_CONTRACTID "@mozilla.org/io/multiplex-input-stream;1"
#define NS_MULTIPLEXINPUTSTREAM_CID \
{ /* 565e3a2c-1dd2-11b2-8da1-b4cef17e568d */ \
{ /* 565e3a2c-1dd2-11b2-8da1-b4cef17e568d */ \
0x565e3a2c, \
0x1dd2, \
0x11b2, \
{0x8d, 0xa1, 0xb4, 0xce, 0xf1, 0x7e, 0x56, 0x8d} \
}
}
extern nsresult nsMultiplexInputStreamConstructor(nsISupports *outer,
REFNSIID iid,

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,5 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -24,18 +26,18 @@
nsresult NS_CopyNativeToUnicode(const nsACString &input, nsAString &output);
nsresult NS_CopyUnicodeToNative(const nsAString &input, nsACString &output);
/*
/*
* This function indicates whether the character encoding used in the file
* system (more exactly what's used for |GetNativeFoo| and |SetNativeFoo|
* of |nsIFile|) is UTF-8 or not. Knowing that helps us avoid an
* unncessary encoding conversion in some cases. For instance, to get the leaf
* name in UTF-8 out of nsIFile, we can just use |GetNativeLeafName| rather
* than using |GetLeafName| and converting the result to UTF-8 if the file
* than using |GetLeafName| and converting the result to UTF-8 if the file
* system encoding is UTF-8.
* On Unix (but not on Mac OS X), it depends on the locale and is not known
* in advance (at the compilation time) so that this function needs to be
* a real function. On Mac OS X it's always UTF-8 while on Windows
* and other platforms (e.g. OS2), it's never UTF-8.
* in advance (at the compilation time) so that this function needs to be
* a real function. On Mac OS X it's always UTF-8 while on Windows
* and other platforms (e.g. OS2), it's never UTF-8.
*/
#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(ANDROID)
bool NS_IsNativeUTF8();
@@ -43,9 +45,9 @@ bool NS_IsNativeUTF8();
inline bool NS_IsNativeUTF8()
{
#if defined(XP_MACOSX) || defined(ANDROID)
return true;
return true;
#else
return false;
return false;
#endif
}
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -12,105 +12,105 @@ NS_IMPL_ISUPPORTS(nsScriptableInputStream, nsIScriptableInputStream)
// nsIScriptableInputStream methods
NS_IMETHODIMP
nsScriptableInputStream::Close(void) {
if (!mInputStream) return NS_ERROR_NOT_INITIALIZED;
return mInputStream->Close();
if (!mInputStream) return NS_ERROR_NOT_INITIALIZED;
return mInputStream->Close();
}
NS_IMETHODIMP
nsScriptableInputStream::Init(nsIInputStream *aInputStream) {
if (!aInputStream) return NS_ERROR_NULL_POINTER;
mInputStream = aInputStream;
return NS_OK;
if (!aInputStream) return NS_ERROR_NULL_POINTER;
mInputStream = aInputStream;
return NS_OK;
}
NS_IMETHODIMP
nsScriptableInputStream::Available(uint64_t *_retval) {
if (!mInputStream) return NS_ERROR_NOT_INITIALIZED;
return mInputStream->Available(_retval);
if (!mInputStream) return NS_ERROR_NOT_INITIALIZED;
return mInputStream->Available(_retval);
}
NS_IMETHODIMP
nsScriptableInputStream::Read(uint32_t aCount, char **_retval) {
nsresult rv = NS_OK;
uint64_t count64 = 0;
char *buffer = nullptr;
nsresult rv = NS_OK;
uint64_t count64 = 0;
char *buffer = nullptr;
if (!mInputStream) return NS_ERROR_NOT_INITIALIZED;
if (!mInputStream) return NS_ERROR_NOT_INITIALIZED;
rv = mInputStream->Available(&count64);
if (NS_FAILED(rv)) return rv;
rv = mInputStream->Available(&count64);
if (NS_FAILED(rv)) return rv;
// bug716556 - Ensure count+1 doesn't overflow
uint32_t count = XPCOM_MIN((uint32_t)XPCOM_MIN<uint64_t>(count64, aCount), UINT32_MAX - 1);
buffer = (char*)moz_malloc(count+1); // make room for '\0'
if (!buffer) return NS_ERROR_OUT_OF_MEMORY;
// bug716556 - Ensure count+1 doesn't overflow
uint32_t count = XPCOM_MIN((uint32_t)XPCOM_MIN<uint64_t>(count64, aCount), UINT32_MAX - 1);
buffer = (char*)moz_malloc(count+1); // make room for '\0'
if (!buffer) return NS_ERROR_OUT_OF_MEMORY;
rv = ReadHelper(buffer, count);
if (NS_FAILED(rv)) {
nsMemory::Free(buffer);
return rv;
}
rv = ReadHelper(buffer, count);
if (NS_FAILED(rv)) {
nsMemory::Free(buffer);
return rv;
}
buffer[count] = '\0';
*_retval = buffer;
return NS_OK;
buffer[count] = '\0';
*_retval = buffer;
return NS_OK;
}
NS_IMETHODIMP
nsScriptableInputStream::ReadBytes(uint32_t aCount, nsACString &_retval) {
if (!mInputStream) {
return NS_ERROR_NOT_INITIALIZED;
}
if (!mInputStream) {
return NS_ERROR_NOT_INITIALIZED;
}
_retval.SetLength(aCount);
if (_retval.Length() != aCount) {
return NS_ERROR_OUT_OF_MEMORY;
}
_retval.SetLength(aCount);
if (_retval.Length() != aCount) {
return NS_ERROR_OUT_OF_MEMORY;
}
char *ptr = _retval.BeginWriting();
nsresult rv = ReadHelper(ptr, aCount);
if (NS_FAILED(rv)) {
_retval.Truncate();
}
return rv;
char *ptr = _retval.BeginWriting();
nsresult rv = ReadHelper(ptr, aCount);
if (NS_FAILED(rv)) {
_retval.Truncate();
}
return rv;
}
nsresult
nsScriptableInputStream::ReadHelper(char* aBuffer, uint32_t aCount)
{
uint32_t totalBytesRead = 0;
while (1) {
uint32_t bytesRead;
nsresult rv = mInputStream->Read(aBuffer + totalBytesRead,
aCount - totalBytesRead,
&bytesRead);
if (NS_FAILED(rv)) {
return rv;
}
totalBytesRead += bytesRead;
if (totalBytesRead == aCount) {
break;
}
// If we have read zero bytes, we have hit EOF.
if (bytesRead == 0) {
return NS_ERROR_FAILURE;
}
uint32_t totalBytesRead = 0;
while (1) {
uint32_t bytesRead;
nsresult rv = mInputStream->Read(aBuffer + totalBytesRead,
aCount - totalBytesRead,
&bytesRead);
if (NS_FAILED(rv)) {
return rv;
}
return NS_OK;
totalBytesRead += bytesRead;
if (totalBytesRead == aCount) {
break;
}
// If we have read zero bytes, we have hit EOF.
if (bytesRead == 0) {
return NS_ERROR_FAILURE;
}
}
return NS_OK;
}
nsresult
nsScriptableInputStream::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult) {
if (aOuter) return NS_ERROR_NO_AGGREGATION;
if (aOuter) return NS_ERROR_NO_AGGREGATION;
nsScriptableInputStream *sis = new nsScriptableInputStream();
if (!sis) return NS_ERROR_OUT_OF_MEMORY;
nsScriptableInputStream *sis = new nsScriptableInputStream();
if (!sis) return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(sis);
nsresult rv = sis->QueryInterface(aIID, aResult);
NS_RELEASE(sis);
return rv;
NS_ADDREF(sis);
nsresult rv = sis->QueryInterface(aIID, aResult);
NS_RELEASE(sis);
return rv;
}

View File

@@ -1,4 +1,5 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -18,24 +19,24 @@
class nsScriptableInputStream MOZ_FINAL : public nsIScriptableInputStream {
public:
// nsISupports methods
NS_DECL_ISUPPORTS
// nsISupports methods
NS_DECL_ISUPPORTS
// nsIScriptableInputStream methods
NS_DECL_NSISCRIPTABLEINPUTSTREAM
// nsIScriptableInputStream methods
NS_DECL_NSISCRIPTABLEINPUTSTREAM
// nsScriptableInputStream methods
nsScriptableInputStream() {}
// nsScriptableInputStream methods
nsScriptableInputStream() {}
static nsresult
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
static nsresult
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
private:
~nsScriptableInputStream() {}
~nsScriptableInputStream() {}
nsresult ReadHelper(char* aBuffer, uint32_t aCount);
nsresult ReadHelper(char* aBuffer, uint32_t aCount);
nsCOMPtr<nsIInputStream> mInputStream;
nsCOMPtr<nsIInputStream> mInputStream;
};
#endif // ___nsscriptableinputstream___h_

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -9,158 +10,158 @@
nsresult
nsSegmentedBuffer::Init(uint32_t segmentSize, uint32_t maxSize)
{
if (mSegmentArrayCount != 0)
return NS_ERROR_FAILURE; // initialized more than once
mSegmentSize = segmentSize;
mMaxSize = maxSize;
if (mSegmentArrayCount != 0)
return NS_ERROR_FAILURE; // initialized more than once
mSegmentSize = segmentSize;
mMaxSize = maxSize;
#if 0 // testing...
mSegmentArrayCount = 2;
mSegmentArrayCount = 2;
#else
mSegmentArrayCount = NS_SEGMENTARRAY_INITIAL_COUNT;
mSegmentArrayCount = NS_SEGMENTARRAY_INITIAL_COUNT;
#endif
return NS_OK;
return NS_OK;
}
char*
nsSegmentedBuffer::AppendNewSegment()
{
if (GetSize() >= mMaxSize)
return nullptr;
if (GetSize() >= mMaxSize)
return nullptr;
if (mSegmentArray == nullptr) {
uint32_t bytes = mSegmentArrayCount * sizeof(char*);
mSegmentArray = (char**)nsMemory::Alloc(bytes);
if (mSegmentArray == nullptr)
return nullptr;
memset(mSegmentArray, 0, bytes);
}
if (IsFull()) {
uint32_t newArraySize = mSegmentArrayCount * 2;
uint32_t bytes = newArraySize * sizeof(char*);
char** newSegArray = (char**)nsMemory::Realloc(mSegmentArray, bytes);
if (newSegArray == nullptr)
return nullptr;
mSegmentArray = newSegArray;
// copy wrapped content to new extension
if (mFirstSegmentIndex > mLastSegmentIndex) {
// deal with wrap around case
memcpy(&mSegmentArray[mSegmentArrayCount],
mSegmentArray,
mLastSegmentIndex * sizeof(char*));
memset(mSegmentArray, 0, mLastSegmentIndex * sizeof(char*));
mLastSegmentIndex += mSegmentArrayCount;
memset(&mSegmentArray[mLastSegmentIndex], 0,
(newArraySize - mLastSegmentIndex) * sizeof(char*));
}
else {
memset(&mSegmentArray[mLastSegmentIndex], 0,
(newArraySize - mLastSegmentIndex) * sizeof(char*));
}
mSegmentArrayCount = newArraySize;
}
if (mSegmentArray == nullptr) {
uint32_t bytes = mSegmentArrayCount * sizeof(char*);
mSegmentArray = (char**)nsMemory::Alloc(bytes);
if (mSegmentArray == nullptr)
return nullptr;
memset(mSegmentArray, 0, bytes);
}
char* seg = (char*)moz_malloc(mSegmentSize);
if (seg == nullptr) {
return nullptr;
if (IsFull()) {
uint32_t newArraySize = mSegmentArrayCount * 2;
uint32_t bytes = newArraySize * sizeof(char*);
char** newSegArray = (char**)nsMemory::Realloc(mSegmentArray, bytes);
if (newSegArray == nullptr)
return nullptr;
mSegmentArray = newSegArray;
// copy wrapped content to new extension
if (mFirstSegmentIndex > mLastSegmentIndex) {
// deal with wrap around case
memcpy(&mSegmentArray[mSegmentArrayCount],
mSegmentArray,
mLastSegmentIndex * sizeof(char*));
memset(mSegmentArray, 0, mLastSegmentIndex * sizeof(char*));
mLastSegmentIndex += mSegmentArrayCount;
memset(&mSegmentArray[mLastSegmentIndex], 0,
(newArraySize - mLastSegmentIndex) * sizeof(char*));
}
mSegmentArray[mLastSegmentIndex] = seg;
mLastSegmentIndex = ModSegArraySize(mLastSegmentIndex + 1);
return seg;
else {
memset(&mSegmentArray[mLastSegmentIndex], 0,
(newArraySize - mLastSegmentIndex) * sizeof(char*));
}
mSegmentArrayCount = newArraySize;
}
char* seg = (char*)moz_malloc(mSegmentSize);
if (seg == nullptr) {
return nullptr;
}
mSegmentArray[mLastSegmentIndex] = seg;
mLastSegmentIndex = ModSegArraySize(mLastSegmentIndex + 1);
return seg;
}
bool
nsSegmentedBuffer::DeleteFirstSegment()
{
NS_ASSERTION(mSegmentArray[mFirstSegmentIndex] != nullptr, "deleting bad segment");
moz_free(mSegmentArray[mFirstSegmentIndex]);
mSegmentArray[mFirstSegmentIndex] = nullptr;
int32_t last = ModSegArraySize(mLastSegmentIndex - 1);
if (mFirstSegmentIndex == last) {
mLastSegmentIndex = last;
return true;
}
else {
mFirstSegmentIndex = ModSegArraySize(mFirstSegmentIndex + 1);
return false;
}
NS_ASSERTION(mSegmentArray[mFirstSegmentIndex] != nullptr, "deleting bad segment");
moz_free(mSegmentArray[mFirstSegmentIndex]);
mSegmentArray[mFirstSegmentIndex] = nullptr;
int32_t last = ModSegArraySize(mLastSegmentIndex - 1);
if (mFirstSegmentIndex == last) {
mLastSegmentIndex = last;
return true;
}
else {
mFirstSegmentIndex = ModSegArraySize(mFirstSegmentIndex + 1);
return false;
}
}
bool
nsSegmentedBuffer::DeleteLastSegment()
{
int32_t last = ModSegArraySize(mLastSegmentIndex - 1);
NS_ASSERTION(mSegmentArray[last] != nullptr, "deleting bad segment");
moz_free(mSegmentArray[last]);
mSegmentArray[last] = nullptr;
mLastSegmentIndex = last;
return (bool)(mLastSegmentIndex == mFirstSegmentIndex);
int32_t last = ModSegArraySize(mLastSegmentIndex - 1);
NS_ASSERTION(mSegmentArray[last] != nullptr, "deleting bad segment");
moz_free(mSegmentArray[last]);
mSegmentArray[last] = nullptr;
mLastSegmentIndex = last;
return (bool)(mLastSegmentIndex == mFirstSegmentIndex);
}
bool
nsSegmentedBuffer::ReallocLastSegment(size_t newSize)
{
int32_t last = ModSegArraySize(mLastSegmentIndex - 1);
NS_ASSERTION(mSegmentArray[last] != nullptr, "realloc'ing bad segment");
char *newSegment =
(char*)moz_realloc(mSegmentArray[last], newSize);
if (newSegment) {
mSegmentArray[last] = newSegment;
return true;
} else {
return false;
}
int32_t last = ModSegArraySize(mLastSegmentIndex - 1);
NS_ASSERTION(mSegmentArray[last] != nullptr, "realloc'ing bad segment");
char *newSegment =
(char*)moz_realloc(mSegmentArray[last], newSize);
if (newSegment) {
mSegmentArray[last] = newSegment;
return true;
} else {
return false;
}
}
void
nsSegmentedBuffer::Empty()
{
if (mSegmentArray) {
for (uint32_t i = 0; i < mSegmentArrayCount; i++) {
if (mSegmentArray[i])
moz_free(mSegmentArray[i]);
}
nsMemory::Free(mSegmentArray);
mSegmentArray = nullptr;
if (mSegmentArray) {
for (uint32_t i = 0; i < mSegmentArrayCount; i++) {
if (mSegmentArray[i])
moz_free(mSegmentArray[i]);
}
mSegmentArrayCount = NS_SEGMENTARRAY_INITIAL_COUNT;
mFirstSegmentIndex = mLastSegmentIndex = 0;
nsMemory::Free(mSegmentArray);
mSegmentArray = nullptr;
}
mSegmentArrayCount = NS_SEGMENTARRAY_INITIAL_COUNT;
mFirstSegmentIndex = mLastSegmentIndex = 0;
}
#if 0
void
TestSegmentedBuffer()
{
nsSegmentedBuffer* buf = new nsSegmentedBuffer();
NS_ASSERTION(buf, "out of memory");
buf->Init(4, 16);
char* seg;
bool empty;
seg = buf->AppendNewSegment();
NS_ASSERTION(seg, "AppendNewSegment failed");
seg = buf->AppendNewSegment();
NS_ASSERTION(seg, "AppendNewSegment failed");
seg = buf->AppendNewSegment();
NS_ASSERTION(seg, "AppendNewSegment failed");
empty = buf->DeleteFirstSegment();
NS_ASSERTION(!empty, "DeleteFirstSegment failed");
empty = buf->DeleteFirstSegment();
NS_ASSERTION(!empty, "DeleteFirstSegment failed");
seg = buf->AppendNewSegment();
NS_ASSERTION(seg, "AppendNewSegment failed");
seg = buf->AppendNewSegment();
NS_ASSERTION(seg, "AppendNewSegment failed");
seg = buf->AppendNewSegment();
NS_ASSERTION(seg, "AppendNewSegment failed");
empty = buf->DeleteFirstSegment();
NS_ASSERTION(!empty, "DeleteFirstSegment failed");
empty = buf->DeleteFirstSegment();
NS_ASSERTION(!empty, "DeleteFirstSegment failed");
empty = buf->DeleteFirstSegment();
NS_ASSERTION(!empty, "DeleteFirstSegment failed");
empty = buf->DeleteFirstSegment();
NS_ASSERTION(empty, "DeleteFirstSegment failed");
delete buf;
nsSegmentedBuffer* buf = new nsSegmentedBuffer();
NS_ASSERTION(buf, "out of memory");
buf->Init(4, 16);
char* seg;
bool empty;
seg = buf->AppendNewSegment();
NS_ASSERTION(seg, "AppendNewSegment failed");
seg = buf->AppendNewSegment();
NS_ASSERTION(seg, "AppendNewSegment failed");
seg = buf->AppendNewSegment();
NS_ASSERTION(seg, "AppendNewSegment failed");
empty = buf->DeleteFirstSegment();
NS_ASSERTION(!empty, "DeleteFirstSegment failed");
empty = buf->DeleteFirstSegment();
NS_ASSERTION(!empty, "DeleteFirstSegment failed");
seg = buf->AppendNewSegment();
NS_ASSERTION(seg, "AppendNewSegment failed");
seg = buf->AppendNewSegment();
NS_ASSERTION(seg, "AppendNewSegment failed");
seg = buf->AppendNewSegment();
NS_ASSERTION(seg, "AppendNewSegment failed");
empty = buf->DeleteFirstSegment();
NS_ASSERTION(!empty, "DeleteFirstSegment failed");
empty = buf->DeleteFirstSegment();
NS_ASSERTION(!empty, "DeleteFirstSegment failed");
empty = buf->DeleteFirstSegment();
NS_ASSERTION(!empty, "DeleteFirstSegment failed");
empty = buf->DeleteFirstSegment();
NS_ASSERTION(empty, "DeleteFirstSegment failed");
delete buf;
}
#endif

View File

@@ -1,4 +1,5 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -11,74 +12,74 @@
class nsSegmentedBuffer
{
public:
nsSegmentedBuffer()
: mSegmentSize(0), mMaxSize(0),
mSegmentArray(nullptr),
mSegmentArrayCount(0),
mFirstSegmentIndex(0), mLastSegmentIndex(0) {}
nsSegmentedBuffer()
: mSegmentSize(0), mMaxSize(0),
mSegmentArray(nullptr),
mSegmentArrayCount(0),
mFirstSegmentIndex(0), mLastSegmentIndex(0) {}
~nsSegmentedBuffer() {
Empty();
}
~nsSegmentedBuffer() {
Empty();
}
nsresult Init(uint32_t segmentSize, uint32_t maxSize);
nsresult Init(uint32_t segmentSize, uint32_t maxSize);
char* AppendNewSegment(); // pushes at end
char* AppendNewSegment(); // pushes at end
// returns true if no more segments remain:
bool DeleteFirstSegment(); // pops from beginning
// returns true if no more segments remain:
bool DeleteFirstSegment(); // pops from beginning
// returns true if no more segments remain:
bool DeleteLastSegment(); // pops from beginning
// returns true if no more segments remain:
bool DeleteLastSegment(); // pops from beginning
// Call Realloc() on last segment. This is used to reduce memory
// consumption when data is not an exact multiple of segment size.
bool ReallocLastSegment(size_t newSize);
// Call Realloc() on last segment. This is used to reduce memory
// consumption when data is not an exact multiple of segment size.
bool ReallocLastSegment(size_t newSize);
void Empty(); // frees all segments
void Empty(); // frees all segments
inline uint32_t GetSegmentCount() {
if (mFirstSegmentIndex <= mLastSegmentIndex)
return mLastSegmentIndex - mFirstSegmentIndex;
else
return mSegmentArrayCount + mLastSegmentIndex - mFirstSegmentIndex;
}
inline uint32_t GetSegmentCount() {
if (mFirstSegmentIndex <= mLastSegmentIndex)
return mLastSegmentIndex - mFirstSegmentIndex;
else
return mSegmentArrayCount + mLastSegmentIndex - mFirstSegmentIndex;
}
inline uint32_t GetSegmentSize() { return mSegmentSize; }
inline uint32_t GetMaxSize() { return mMaxSize; }
inline uint32_t GetSize() { return GetSegmentCount() * mSegmentSize; }
inline uint32_t GetSegmentSize() { return mSegmentSize; }
inline uint32_t GetMaxSize() { return mMaxSize; }
inline uint32_t GetSize() { return GetSegmentCount() * mSegmentSize; }
inline char* GetSegment(uint32_t indx) {
NS_ASSERTION(indx < GetSegmentCount(), "index out of bounds");
int32_t i = ModSegArraySize(mFirstSegmentIndex + (int32_t)indx);
return mSegmentArray[i];
}
inline char* GetSegment(uint32_t indx) {
NS_ASSERTION(indx < GetSegmentCount(), "index out of bounds");
int32_t i = ModSegArraySize(mFirstSegmentIndex + (int32_t)indx);
return mSegmentArray[i];
}
protected:
inline int32_t ModSegArraySize(int32_t n) {
uint32_t result = n & (mSegmentArrayCount - 1);
NS_ASSERTION(result == n % mSegmentArrayCount,
"non-power-of-2 mSegmentArrayCount");
return result;
}
inline int32_t ModSegArraySize(int32_t n) {
uint32_t result = n & (mSegmentArrayCount - 1);
NS_ASSERTION(result == n % mSegmentArrayCount,
"non-power-of-2 mSegmentArrayCount");
return result;
}
inline bool IsFull() {
return ModSegArraySize(mLastSegmentIndex + 1) == mFirstSegmentIndex;
}
inline bool IsFull() {
return ModSegArraySize(mLastSegmentIndex + 1) == mFirstSegmentIndex;
}
protected:
uint32_t mSegmentSize;
uint32_t mMaxSize;
char** mSegmentArray;
uint32_t mSegmentArrayCount;
int32_t mFirstSegmentIndex;
int32_t mLastSegmentIndex;
uint32_t mSegmentSize;
uint32_t mMaxSize;
char** mSegmentArray;
uint32_t mSegmentArrayCount;
int32_t mFirstSegmentIndex;
int32_t mLastSegmentIndex;
};
// NS_SEGMENTARRAY_INITIAL_SIZE: This number needs to start out as a
// power of 2 given how it gets used. We double the segment array
// when we overflow it, and use that fact that it's a power of 2
// when we overflow it, and use that fact that it's a power of 2
// to compute a fast modulus operation in IsFull.
//
// 32 segment array entries can accommodate 128k of data if segments

View File

@@ -1,5 +1,5 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim:set ts=4 sts=4 sw=4 cin et: */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -39,10 +39,10 @@
static PRLogModuleInfo*
GetStorageStreamLog()
{
static PRLogModuleInfo *sLog;
if (!sLog)
sLog = PR_NewLogModule("nsStorageStream");
return sLog;
static PRLogModuleInfo *sLog;
if (!sLog)
sLog = PR_NewLogModule("nsStorageStream");
return sLog;
}
#endif
#ifdef LOG
@@ -51,15 +51,15 @@ GetStorageStreamLog()
#define LOG(args) PR_LOG(GetStorageStreamLog(), PR_LOG_DEBUG, args)
nsStorageStream::nsStorageStream()
: mSegmentedBuffer(0), mSegmentSize(0), mWriteInProgress(false),
mLastSegmentNum(-1), mWriteCursor(0), mSegmentEnd(0), mLogicalLength(0)
: mSegmentedBuffer(0), mSegmentSize(0), mWriteInProgress(false),
mLastSegmentNum(-1), mWriteCursor(0), mSegmentEnd(0), mLogicalLength(0)
{
LOG(("Creating nsStorageStream [%p].\n", this));
LOG(("Creating nsStorageStream [%p].\n", this));
}
nsStorageStream::~nsStorageStream()
{
delete mSegmentedBuffer;
delete mSegmentedBuffer;
}
NS_IMPL_ISUPPORTS(nsStorageStream,
@@ -69,243 +69,243 @@ NS_IMPL_ISUPPORTS(nsStorageStream,
NS_IMETHODIMP
nsStorageStream::Init(uint32_t segmentSize, uint32_t maxSize)
{
mSegmentedBuffer = new nsSegmentedBuffer();
if (!mSegmentedBuffer)
return NS_ERROR_OUT_OF_MEMORY;
mSegmentSize = segmentSize;
mSegmentSizeLog2 = mozilla::FloorLog2(segmentSize);
mSegmentedBuffer = new nsSegmentedBuffer();
if (!mSegmentedBuffer)
return NS_ERROR_OUT_OF_MEMORY;
// Segment size must be a power of two
if (mSegmentSize != ((uint32_t)1 << mSegmentSizeLog2))
return NS_ERROR_INVALID_ARG;
mSegmentSize = segmentSize;
mSegmentSizeLog2 = mozilla::FloorLog2(segmentSize);
return mSegmentedBuffer->Init(segmentSize, maxSize);
// Segment size must be a power of two
if (mSegmentSize != ((uint32_t)1 << mSegmentSizeLog2))
return NS_ERROR_INVALID_ARG;
return mSegmentedBuffer->Init(segmentSize, maxSize);
}
NS_IMETHODIMP
nsStorageStream::GetOutputStream(int32_t aStartingOffset,
nsStorageStream::GetOutputStream(int32_t aStartingOffset,
nsIOutputStream * *aOutputStream)
{
if (NS_WARN_IF(!aOutputStream))
return NS_ERROR_INVALID_ARG;
if (NS_WARN_IF(!mSegmentedBuffer))
return NS_ERROR_NOT_INITIALIZED;
if (mWriteInProgress)
return NS_ERROR_NOT_AVAILABLE;
if (NS_WARN_IF(!aOutputStream))
return NS_ERROR_INVALID_ARG;
if (NS_WARN_IF(!mSegmentedBuffer))
return NS_ERROR_NOT_INITIALIZED;
nsresult rv = Seek(aStartingOffset);
if (NS_FAILED(rv)) return rv;
if (mWriteInProgress)
return NS_ERROR_NOT_AVAILABLE;
// Enlarge the last segment in the buffer so that it is the same size as
// all the other segments in the buffer. (It may have been realloc'ed
// smaller in the Close() method.)
if (mLastSegmentNum >= 0)
if (mSegmentedBuffer->ReallocLastSegment(mSegmentSize)) {
// Need to re-Seek, since realloc changed segment base pointer
rv = Seek(aStartingOffset);
if (NS_FAILED(rv)) return rv;
}
nsresult rv = Seek(aStartingOffset);
if (NS_FAILED(rv)) return rv;
NS_ADDREF(this);
*aOutputStream = static_cast<nsIOutputStream*>(this);
mWriteInProgress = true;
return NS_OK;
// Enlarge the last segment in the buffer so that it is the same size as
// all the other segments in the buffer. (It may have been realloc'ed
// smaller in the Close() method.)
if (mLastSegmentNum >= 0)
if (mSegmentedBuffer->ReallocLastSegment(mSegmentSize)) {
// Need to re-Seek, since realloc changed segment base pointer
rv = Seek(aStartingOffset);
if (NS_FAILED(rv)) return rv;
}
NS_ADDREF(this);
*aOutputStream = static_cast<nsIOutputStream*>(this);
mWriteInProgress = true;
return NS_OK;
}
NS_IMETHODIMP
nsStorageStream::Close()
{
if (NS_WARN_IF(!mSegmentedBuffer))
return NS_ERROR_NOT_INITIALIZED;
mWriteInProgress = false;
int32_t segmentOffset = SegOffset(mLogicalLength);
if (NS_WARN_IF(!mSegmentedBuffer))
return NS_ERROR_NOT_INITIALIZED;
// Shrink the final segment in the segmented buffer to the minimum size
// needed to contain the data, so as to conserve memory.
if (segmentOffset)
mSegmentedBuffer->ReallocLastSegment(segmentOffset);
mWriteCursor = 0;
mSegmentEnd = 0;
mWriteInProgress = false;
LOG(("nsStorageStream [%p] Close mWriteCursor=%x mSegmentEnd=%x\n",
this, mWriteCursor, mSegmentEnd));
int32_t segmentOffset = SegOffset(mLogicalLength);
return NS_OK;
// Shrink the final segment in the segmented buffer to the minimum size
// needed to contain the data, so as to conserve memory.
if (segmentOffset)
mSegmentedBuffer->ReallocLastSegment(segmentOffset);
mWriteCursor = 0;
mSegmentEnd = 0;
LOG(("nsStorageStream [%p] Close mWriteCursor=%x mSegmentEnd=%x\n",
this, mWriteCursor, mSegmentEnd));
return NS_OK;
}
NS_IMETHODIMP
nsStorageStream::Flush()
{
return NS_OK;
return NS_OK;
}
NS_IMETHODIMP
nsStorageStream::Write(const char *aBuffer, uint32_t aCount, uint32_t *aNumWritten)
{
if (NS_WARN_IF(!aNumWritten) || NS_WARN_IF(!aBuffer))
return NS_ERROR_INVALID_ARG;
if (NS_WARN_IF(!mSegmentedBuffer))
return NS_ERROR_NOT_INITIALIZED;
const char* readCursor;
uint32_t count, availableInSegment, remaining;
nsresult rv = NS_OK;
if (NS_WARN_IF(!aNumWritten) || NS_WARN_IF(!aBuffer))
return NS_ERROR_INVALID_ARG;
if (NS_WARN_IF(!mSegmentedBuffer))
return NS_ERROR_NOT_INITIALIZED;
LOG(("nsStorageStream [%p] Write mWriteCursor=%x mSegmentEnd=%x aCount=%d\n",
this, mWriteCursor, mSegmentEnd, aCount));
const char* readCursor;
uint32_t count, availableInSegment, remaining;
nsresult rv = NS_OK;
remaining = aCount;
readCursor = aBuffer;
// If no segments have been created yet, create one even if we don't have
// to write any data; this enables creating an input stream which reads from
// the very end of the data for any amount of data in the stream (i.e.
// this stream contains N bytes of data and newInputStream(N) is called),
// even for N=0 (with the caveat that we require .write("", 0) be called to
// initialize internal buffers).
bool firstTime = mSegmentedBuffer->GetSegmentCount() == 0;
while (remaining || MOZ_UNLIKELY(firstTime)) {
firstTime = false;
availableInSegment = mSegmentEnd - mWriteCursor;
if (!availableInSegment) {
mWriteCursor = mSegmentedBuffer->AppendNewSegment();
if (!mWriteCursor) {
mSegmentEnd = 0;
rv = NS_ERROR_OUT_OF_MEMORY;
goto out;
}
mLastSegmentNum++;
mSegmentEnd = mWriteCursor + mSegmentSize;
availableInSegment = mSegmentEnd - mWriteCursor;
LOG(("nsStorageStream [%p] Write (new seg) mWriteCursor=%x mSegmentEnd=%x\n",
this, mWriteCursor, mSegmentEnd));
}
count = XPCOM_MIN(availableInSegment, remaining);
memcpy(mWriteCursor, readCursor, count);
remaining -= count;
readCursor += count;
mWriteCursor += count;
LOG(("nsStorageStream [%p] Writing mWriteCursor=%x mSegmentEnd=%x count=%d\n",
this, mWriteCursor, mSegmentEnd, count));
};
LOG(("nsStorageStream [%p] Write mWriteCursor=%x mSegmentEnd=%x aCount=%d\n",
this, mWriteCursor, mSegmentEnd, aCount));
out:
*aNumWritten = aCount - remaining;
mLogicalLength += *aNumWritten;
remaining = aCount;
readCursor = aBuffer;
// If no segments have been created yet, create one even if we don't have
// to write any data; this enables creating an input stream which reads from
// the very end of the data for any amount of data in the stream (i.e.
// this stream contains N bytes of data and newInputStream(N) is called),
// even for N=0 (with the caveat that we require .write("", 0) be called to
// initialize internal buffers).
bool firstTime = mSegmentedBuffer->GetSegmentCount() == 0;
while (remaining || MOZ_UNLIKELY(firstTime)) {
firstTime = false;
availableInSegment = mSegmentEnd - mWriteCursor;
if (!availableInSegment) {
mWriteCursor = mSegmentedBuffer->AppendNewSegment();
if (!mWriteCursor) {
mSegmentEnd = 0;
rv = NS_ERROR_OUT_OF_MEMORY;
goto out;
}
mLastSegmentNum++;
mSegmentEnd = mWriteCursor + mSegmentSize;
availableInSegment = mSegmentEnd - mWriteCursor;
LOG(("nsStorageStream [%p] Write (new seg) mWriteCursor=%x mSegmentEnd=%x\n",
this, mWriteCursor, mSegmentEnd));
}
LOG(("nsStorageStream [%p] Wrote mWriteCursor=%x mSegmentEnd=%x numWritten=%d\n",
this, mWriteCursor, mSegmentEnd, *aNumWritten));
return rv;
count = XPCOM_MIN(availableInSegment, remaining);
memcpy(mWriteCursor, readCursor, count);
remaining -= count;
readCursor += count;
mWriteCursor += count;
LOG(("nsStorageStream [%p] Writing mWriteCursor=%x mSegmentEnd=%x count=%d\n",
this, mWriteCursor, mSegmentEnd, count));
};
out:
*aNumWritten = aCount - remaining;
mLogicalLength += *aNumWritten;
LOG(("nsStorageStream [%p] Wrote mWriteCursor=%x mSegmentEnd=%x numWritten=%d\n",
this, mWriteCursor, mSegmentEnd, *aNumWritten));
return rv;
}
NS_IMETHODIMP
NS_IMETHODIMP
nsStorageStream::WriteFrom(nsIInputStream *inStr, uint32_t count, uint32_t *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
NS_IMETHODIMP
nsStorageStream::WriteSegments(nsReadSegmentFun reader, void * closure, uint32_t count, uint32_t *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
NS_IMETHODIMP
nsStorageStream::IsNonBlocking(bool *aNonBlocking)
{
*aNonBlocking = false;
return NS_OK;
*aNonBlocking = false;
return NS_OK;
}
NS_IMETHODIMP
nsStorageStream::GetLength(uint32_t *aLength)
{
*aLength = mLogicalLength;
return NS_OK;
*aLength = mLogicalLength;
return NS_OK;
}
// Truncate the buffer by deleting the end segments
NS_IMETHODIMP
nsStorageStream::SetLength(uint32_t aLength)
{
if (NS_WARN_IF(!mSegmentedBuffer))
return NS_ERROR_NOT_INITIALIZED;
if (mWriteInProgress)
return NS_ERROR_NOT_AVAILABLE;
if (NS_WARN_IF(!mSegmentedBuffer))
return NS_ERROR_NOT_INITIALIZED;
if (aLength > mLogicalLength)
return NS_ERROR_INVALID_ARG;
if (mWriteInProgress)
return NS_ERROR_NOT_AVAILABLE;
int32_t newLastSegmentNum = SegNum(aLength);
int32_t segmentOffset = SegOffset(aLength);
if (segmentOffset == 0)
newLastSegmentNum--;
if (aLength > mLogicalLength)
return NS_ERROR_INVALID_ARG;
while (newLastSegmentNum < mLastSegmentNum) {
mSegmentedBuffer->DeleteLastSegment();
mLastSegmentNum--;
}
int32_t newLastSegmentNum = SegNum(aLength);
int32_t segmentOffset = SegOffset(aLength);
if (segmentOffset == 0)
newLastSegmentNum--;
mLogicalLength = aLength;
return NS_OK;
while (newLastSegmentNum < mLastSegmentNum) {
mSegmentedBuffer->DeleteLastSegment();
mLastSegmentNum--;
}
mLogicalLength = aLength;
return NS_OK;
}
NS_IMETHODIMP
nsStorageStream::GetWriteInProgress(bool *aWriteInProgress)
{
*aWriteInProgress = mWriteInProgress;
return NS_OK;
*aWriteInProgress = mWriteInProgress;
return NS_OK;
}
NS_METHOD
nsStorageStream::Seek(int32_t aPosition)
{
if (NS_WARN_IF(!mSegmentedBuffer))
return NS_ERROR_NOT_INITIALIZED;
// An argument of -1 means "seek to end of stream"
if (aPosition == -1)
aPosition = mLogicalLength;
if (NS_WARN_IF(!mSegmentedBuffer))
return NS_ERROR_NOT_INITIALIZED;
// Seeking beyond the buffer end is illegal
if ((uint32_t)aPosition > mLogicalLength)
return NS_ERROR_INVALID_ARG;
// An argument of -1 means "seek to end of stream"
if (aPosition == -1)
aPosition = mLogicalLength;
// Seeking backwards in the write stream results in truncation
SetLength(aPosition);
// Seeking beyond the buffer end is illegal
if ((uint32_t)aPosition > mLogicalLength)
return NS_ERROR_INVALID_ARG;
// Special handling for seek to start-of-buffer
if (aPosition == 0) {
mWriteCursor = 0;
mSegmentEnd = 0;
LOG(("nsStorageStream [%p] Seek mWriteCursor=%x mSegmentEnd=%x\n",
this, mWriteCursor, mSegmentEnd));
return NS_OK;
}
// Seeking backwards in the write stream results in truncation
SetLength(aPosition);
// Segment may have changed, so reset pointers
mWriteCursor = mSegmentedBuffer->GetSegment(mLastSegmentNum);
NS_ASSERTION(mWriteCursor, "null mWriteCursor");
mSegmentEnd = mWriteCursor + mSegmentSize;
// Adjust write cursor for current segment offset. This test is necessary
// because SegNum may reference the next-to-be-allocated segment, in which
// case we need to be pointing at the end of the last segment.
int32_t segmentOffset = SegOffset(aPosition);
if (segmentOffset == 0 && (SegNum(aPosition) > (uint32_t) mLastSegmentNum))
mWriteCursor = mSegmentEnd;
else
mWriteCursor += segmentOffset;
// Special handling for seek to start-of-buffer
if (aPosition == 0) {
mWriteCursor = 0;
mSegmentEnd = 0;
LOG(("nsStorageStream [%p] Seek mWriteCursor=%x mSegmentEnd=%x\n",
this, mWriteCursor, mSegmentEnd));
this, mWriteCursor, mSegmentEnd));
return NS_OK;
}
// Segment may have changed, so reset pointers
mWriteCursor = mSegmentedBuffer->GetSegment(mLastSegmentNum);
NS_ASSERTION(mWriteCursor, "null mWriteCursor");
mSegmentEnd = mWriteCursor + mSegmentSize;
// Adjust write cursor for current segment offset. This test is necessary
// because SegNum may reference the next-to-be-allocated segment, in which
// case we need to be pointing at the end of the last segment.
int32_t segmentOffset = SegOffset(aPosition);
if (segmentOffset == 0 && (SegNum(aPosition) > (uint32_t) mLastSegmentNum))
mWriteCursor = mSegmentEnd;
else
mWriteCursor += segmentOffset;
LOG(("nsStorageStream [%p] Seek mWriteCursor=%x mSegmentEnd=%x\n",
this, mWriteCursor, mSegmentEnd));
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
@@ -315,41 +315,41 @@ class nsStorageInputStream MOZ_FINAL : public nsIInputStream
, public nsISeekableStream
{
public:
nsStorageInputStream(nsStorageStream *aStorageStream, uint32_t aSegmentSize)
: mStorageStream(aStorageStream), mReadCursor(0),
mSegmentEnd(0), mSegmentNum(0),
mSegmentSize(aSegmentSize), mLogicalCursor(0),
mStatus(NS_OK)
{
NS_ADDREF(mStorageStream);
}
nsStorageInputStream(nsStorageStream *aStorageStream, uint32_t aSegmentSize)
: mStorageStream(aStorageStream), mReadCursor(0),
mSegmentEnd(0), mSegmentNum(0),
mSegmentSize(aSegmentSize), mLogicalCursor(0),
mStatus(NS_OK)
{
NS_ADDREF(mStorageStream);
}
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIINPUTSTREAM
NS_DECL_NSISEEKABLESTREAM
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIINPUTSTREAM
NS_DECL_NSISEEKABLESTREAM
private:
~nsStorageInputStream()
{
NS_IF_RELEASE(mStorageStream);
}
~nsStorageInputStream()
{
NS_IF_RELEASE(mStorageStream);
}
protected:
NS_METHOD Seek(uint32_t aPosition);
NS_METHOD Seek(uint32_t aPosition);
friend class nsStorageStream;
friend class nsStorageStream;
private:
nsStorageStream* mStorageStream;
uint32_t mReadCursor; // Next memory location to read byte, or 0
uint32_t mSegmentEnd; // One byte past end of current buffer segment
uint32_t mSegmentNum; // Segment number containing read cursor
uint32_t mSegmentSize; // All segments, except the last, are of this size
uint32_t mLogicalCursor; // Logical offset into stream
nsresult mStatus;
nsStorageStream* mStorageStream;
uint32_t mReadCursor; // Next memory location to read byte, or 0
uint32_t mSegmentEnd; // One byte past end of current buffer segment
uint32_t mSegmentNum; // Segment number containing read cursor
uint32_t mSegmentSize; // All segments, except the last, are of this size
uint32_t mLogicalCursor; // Logical offset into stream
nsresult mStatus;
uint32_t SegNum(uint32_t aPosition) {return aPosition >> mStorageStream->mSegmentSizeLog2;}
uint32_t SegOffset(uint32_t aPosition) {return aPosition & (mSegmentSize - 1);}
uint32_t SegNum(uint32_t aPosition) {return aPosition >> mStorageStream->mSegmentSizeLog2;}
uint32_t SegOffset(uint32_t aPosition) {return aPosition & (mSegmentSize - 1);}
};
NS_IMPL_ISUPPORTS(nsStorageInputStream,
@@ -359,184 +359,184 @@ NS_IMPL_ISUPPORTS(nsStorageInputStream,
NS_IMETHODIMP
nsStorageStream::NewInputStream(int32_t aStartingOffset, nsIInputStream* *aInputStream)
{
if (NS_WARN_IF(!mSegmentedBuffer))
return NS_ERROR_NOT_INITIALIZED;
if (NS_WARN_IF(!mSegmentedBuffer))
return NS_ERROR_NOT_INITIALIZED;
nsStorageInputStream *inputStream = new nsStorageInputStream(this, mSegmentSize);
if (!inputStream)
return NS_ERROR_OUT_OF_MEMORY;
nsStorageInputStream *inputStream = new nsStorageInputStream(this, mSegmentSize);
if (!inputStream)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(inputStream);
NS_ADDREF(inputStream);
nsresult rv = inputStream->Seek(aStartingOffset);
if (NS_FAILED(rv)) {
NS_RELEASE(inputStream);
return rv;
}
nsresult rv = inputStream->Seek(aStartingOffset);
if (NS_FAILED(rv)) {
NS_RELEASE(inputStream);
return rv;
}
*aInputStream = inputStream;
return NS_OK;
*aInputStream = inputStream;
return NS_OK;
}
NS_IMETHODIMP
nsStorageInputStream::Close()
{
mStatus = NS_BASE_STREAM_CLOSED;
return NS_OK;
mStatus = NS_BASE_STREAM_CLOSED;
return NS_OK;
}
NS_IMETHODIMP
nsStorageInputStream::Available(uint64_t *aAvailable)
{
if (NS_FAILED(mStatus))
return mStatus;
if (NS_FAILED(mStatus))
return mStatus;
*aAvailable = mStorageStream->mLogicalLength - mLogicalCursor;
return NS_OK;
*aAvailable = mStorageStream->mLogicalLength - mLogicalCursor;
return NS_OK;
}
NS_IMETHODIMP
nsStorageInputStream::Read(char* aBuffer, uint32_t aCount, uint32_t *aNumRead)
{
return ReadSegments(NS_CopySegmentToBuffer, aBuffer, aCount, aNumRead);
return ReadSegments(NS_CopySegmentToBuffer, aBuffer, aCount, aNumRead);
}
NS_IMETHODIMP
NS_IMETHODIMP
nsStorageInputStream::ReadSegments(nsWriteSegmentFun writer, void * closure, uint32_t aCount, uint32_t *aNumRead)
{
*aNumRead = 0;
if (mStatus == NS_BASE_STREAM_CLOSED)
return NS_OK;
if (NS_FAILED(mStatus))
return mStatus;
uint32_t count, availableInSegment, remainingCapacity, bytesConsumed;
nsresult rv;
remainingCapacity = aCount;
while (remainingCapacity) {
availableInSegment = mSegmentEnd - mReadCursor;
if (!availableInSegment) {
uint32_t available = mStorageStream->mLogicalLength - mLogicalCursor;
if (!available)
goto out;
mSegmentNum++;
mReadCursor = 0;
mSegmentEnd = XPCOM_MIN(mSegmentSize, available);
availableInSegment = mSegmentEnd;
}
const char *cur = mStorageStream->mSegmentedBuffer->GetSegment(mSegmentNum);
count = XPCOM_MIN(availableInSegment, remainingCapacity);
rv = writer(this, closure, cur + mReadCursor, aCount - remainingCapacity,
count, &bytesConsumed);
if (NS_FAILED(rv) || (bytesConsumed == 0))
break;
remainingCapacity -= bytesConsumed;
mReadCursor += bytesConsumed;
mLogicalCursor += bytesConsumed;
};
out:
*aNumRead = aCount - remainingCapacity;
bool isWriteInProgress = false;
if (NS_FAILED(mStorageStream->GetWriteInProgress(&isWriteInProgress)))
isWriteInProgress = false;
if (*aNumRead == 0 && isWriteInProgress)
return NS_BASE_STREAM_WOULD_BLOCK;
*aNumRead = 0;
if (mStatus == NS_BASE_STREAM_CLOSED)
return NS_OK;
if (NS_FAILED(mStatus))
return mStatus;
uint32_t count, availableInSegment, remainingCapacity, bytesConsumed;
nsresult rv;
remainingCapacity = aCount;
while (remainingCapacity) {
availableInSegment = mSegmentEnd - mReadCursor;
if (!availableInSegment) {
uint32_t available = mStorageStream->mLogicalLength - mLogicalCursor;
if (!available)
goto out;
mSegmentNum++;
mReadCursor = 0;
mSegmentEnd = XPCOM_MIN(mSegmentSize, available);
availableInSegment = mSegmentEnd;
}
const char *cur = mStorageStream->mSegmentedBuffer->GetSegment(mSegmentNum);
count = XPCOM_MIN(availableInSegment, remainingCapacity);
rv = writer(this, closure, cur + mReadCursor, aCount - remainingCapacity,
count, &bytesConsumed);
if (NS_FAILED(rv) || (bytesConsumed == 0))
break;
remainingCapacity -= bytesConsumed;
mReadCursor += bytesConsumed;
mLogicalCursor += bytesConsumed;
};
out:
*aNumRead = aCount - remainingCapacity;
bool isWriteInProgress = false;
if (NS_FAILED(mStorageStream->GetWriteInProgress(&isWriteInProgress)))
isWriteInProgress = false;
if (*aNumRead == 0 && isWriteInProgress)
return NS_BASE_STREAM_WOULD_BLOCK;
return NS_OK;
}
NS_IMETHODIMP
NS_IMETHODIMP
nsStorageInputStream::IsNonBlocking(bool *aNonBlocking)
{
// TODO: This class should implement nsIAsyncInputStream so that callers
// have some way of dealing with NS_BASE_STREAM_WOULD_BLOCK errors.
*aNonBlocking = true;
return NS_OK;
// TODO: This class should implement nsIAsyncInputStream so that callers
// have some way of dealing with NS_BASE_STREAM_WOULD_BLOCK errors.
*aNonBlocking = true;
return NS_OK;
}
NS_IMETHODIMP
nsStorageInputStream::Seek(int32_t aWhence, int64_t aOffset)
{
if (NS_FAILED(mStatus))
return mStatus;
if (NS_FAILED(mStatus))
return mStatus;
int64_t pos = aOffset;
int64_t pos = aOffset;
switch (aWhence) {
switch (aWhence) {
case NS_SEEK_SET:
break;
break;
case NS_SEEK_CUR:
pos += mLogicalCursor;
break;
pos += mLogicalCursor;
break;
case NS_SEEK_END:
pos += mStorageStream->mLogicalLength;
break;
pos += mStorageStream->mLogicalLength;
break;
default:
NS_NOTREACHED("unexpected whence value");
return NS_ERROR_UNEXPECTED;
}
if (pos == int64_t(mLogicalCursor))
return NS_OK;
NS_NOTREACHED("unexpected whence value");
return NS_ERROR_UNEXPECTED;
}
if (pos == int64_t(mLogicalCursor))
return NS_OK;
return Seek(pos);
return Seek(pos);
}
NS_IMETHODIMP
nsStorageInputStream::Tell(int64_t *aResult)
{
if (NS_FAILED(mStatus))
return mStatus;
if (NS_FAILED(mStatus))
return mStatus;
*aResult = mLogicalCursor;
return NS_OK;
*aResult = mLogicalCursor;
return NS_OK;
}
NS_IMETHODIMP
nsStorageInputStream::SetEOF()
{
NS_NOTREACHED("nsStorageInputStream::SetEOF");
return NS_ERROR_NOT_IMPLEMENTED;
NS_NOTREACHED("nsStorageInputStream::SetEOF");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_METHOD
nsStorageInputStream::Seek(uint32_t aPosition)
{
uint32_t length = mStorageStream->mLogicalLength;
if (aPosition > length)
return NS_ERROR_INVALID_ARG;
uint32_t length = mStorageStream->mLogicalLength;
if (aPosition > length)
return NS_ERROR_INVALID_ARG;
if (length == 0)
return NS_OK;
mSegmentNum = SegNum(aPosition);
mReadCursor = SegOffset(aPosition);
uint32_t available = length - aPosition;
mSegmentEnd = mReadCursor + XPCOM_MIN(mSegmentSize - mReadCursor, available);
mLogicalCursor = aPosition;
if (length == 0)
return NS_OK;
mSegmentNum = SegNum(aPosition);
mReadCursor = SegOffset(aPosition);
uint32_t available = length - aPosition;
mSegmentEnd = mReadCursor + XPCOM_MIN(mSegmentSize - mReadCursor, available);
mLogicalCursor = aPosition;
return NS_OK;
}
nsresult
NS_NewStorageStream(uint32_t segmentSize, uint32_t maxSize, nsIStorageStream **result)
{
nsStorageStream* storageStream = new nsStorageStream();
if (!storageStream) return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(storageStream);
nsresult rv = storageStream->Init(segmentSize, maxSize);
if (NS_FAILED(rv)) {
NS_RELEASE(storageStream);
return rv;
}
*result = storageStream;
return NS_OK;
nsStorageStream* storageStream = new nsStorageStream();
if (!storageStream) return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(storageStream);
nsresult rv = storageStream->Init(segmentSize, maxSize);
if (NS_FAILED(rv)) {
NS_RELEASE(storageStream);
return rv;
}
*result = storageStream;
return NS_OK;
}
// Undefine LOG, so that other .cpp files (or their includes) won't complain

View File

@@ -1,5 +1,6 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -35,31 +36,31 @@ class nsStorageStream MOZ_FINAL : public nsIStorageStream,
public nsIOutputStream
{
public:
nsStorageStream();
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSISTORAGESTREAM
NS_DECL_NSIOUTPUTSTREAM
nsStorageStream();
friend class nsStorageInputStream;
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSISTORAGESTREAM
NS_DECL_NSIOUTPUTSTREAM
friend class nsStorageInputStream;
private:
~nsStorageStream();
~nsStorageStream();
nsSegmentedBuffer* mSegmentedBuffer;
uint32_t mSegmentSize; // All segments, except possibly the last, are of this size
// Must be power-of-2
uint32_t mSegmentSizeLog2; // log2(mSegmentSize)
bool mWriteInProgress; // true, if an un-Close'ed output stream exists
int32_t mLastSegmentNum; // Last segment # in use, -1 initially
char* mWriteCursor; // Pointer to next byte to be written
char* mSegmentEnd; // Pointer to one byte after end of segment
// containing the write cursor
uint32_t mLogicalLength; // Number of bytes written to stream
nsSegmentedBuffer* mSegmentedBuffer;
uint32_t mSegmentSize; // All segments, except possibly the last, are of this size
// Must be power-of-2
uint32_t mSegmentSizeLog2; // log2(mSegmentSize)
bool mWriteInProgress; // true, if an un-Close'ed output stream exists
int32_t mLastSegmentNum; // Last segment # in use, -1 initially
char* mWriteCursor; // Pointer to next byte to be written
char* mSegmentEnd; // Pointer to one byte after end of segment
// containing the write cursor
uint32_t mLogicalLength; // Number of bytes written to stream
NS_METHOD Seek(int32_t aPosition);
uint32_t SegNum(uint32_t aPosition) {return aPosition >> mSegmentSizeLog2;}
uint32_t SegOffset(uint32_t aPosition) {return aPosition & (mSegmentSize - 1);}
NS_METHOD Seek(int32_t aPosition);
uint32_t SegNum(uint32_t aPosition) {return aPosition >> mSegmentSizeLog2;}
uint32_t SegOffset(uint32_t aPosition) {return aPosition & (mSegmentSize - 1);}
};
#endif // _nsStorageStream_h_

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,5 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -33,7 +35,7 @@ NS_NewInputStreamReadyEvent(nsIInputStreamCallback *aNotify,
* A "one-shot" proxy of the OnOutputStreamReady callback. The resulting
* proxy object's OnOutputStreamReady function may only be called once! The
* proxy object ensures that the real notify object will be free'd on the
* thread corresponding to the given event target regardless of what thread
* thread corresponding to the given event target regardless of what thread
* the proxy object is destroyed on.
*
* This function is designed to be used to implement AsyncWait when the
@@ -46,8 +48,8 @@ NS_NewOutputStreamReadyEvent(nsIOutputStreamCallback *aNotify,
/* ------------------------------------------------------------------------- */
enum nsAsyncCopyMode {
NS_ASYNCCOPY_VIA_READSEGMENTS,
NS_ASYNCCOPY_VIA_WRITESEGMENTS
NS_ASYNCCOPY_VIA_READSEGMENTS,
NS_ASYNCCOPY_VIA_WRITESEGMENTS
};
/**

View File

@@ -1,5 +1,5 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim:set ts=4 sts=4 sw=4 cin et: */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -35,45 +35,45 @@ class nsStringInputStream MOZ_FINAL : public nsIStringInputStream
, public nsIIPCSerializableInputStream
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIINPUTSTREAM
NS_DECL_NSISTRINGINPUTSTREAM
NS_DECL_NSISEEKABLESTREAM
NS_DECL_NSISUPPORTSPRIMITIVE
NS_DECL_NSISUPPORTSCSTRING
NS_DECL_NSIIPCSERIALIZABLEINPUTSTREAM
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIINPUTSTREAM
NS_DECL_NSISTRINGINPUTSTREAM
NS_DECL_NSISEEKABLESTREAM
NS_DECL_NSISUPPORTSPRIMITIVE
NS_DECL_NSISUPPORTSCSTRING
NS_DECL_NSIIPCSERIALIZABLEINPUTSTREAM
nsStringInputStream()
{
Clear();
}
nsStringInputStream()
{
Clear();
}
private:
~nsStringInputStream()
{}
~nsStringInputStream()
{}
uint32_t Length() const
{
return mData.Length();
}
uint32_t Length() const
{
return mData.Length();
}
uint32_t LengthRemaining() const
{
return Length() - mOffset;
}
uint32_t LengthRemaining() const
{
return Length() - mOffset;
}
void Clear()
{
mData.SetIsVoid(true);
}
void Clear()
{
mData.SetIsVoid(true);
}
bool Closed()
{
return mData.IsVoid();
}
bool Closed()
{
return mData.IsVoid();
}
nsDependentCSubstring mData;
uint32_t mOffset;
nsDependentCSubstring mData;
uint32_t mOffset;
};
// This class needs to support threadsafe refcounting since people often
@@ -102,36 +102,36 @@ NS_IMPL_CI_INTERFACE_GETTER(nsStringInputStream,
NS_IMETHODIMP
nsStringInputStream::GetType(uint16_t *type)
{
*type = TYPE_CSTRING;
return NS_OK;
*type = TYPE_CSTRING;
return NS_OK;
}
NS_IMETHODIMP
nsStringInputStream::GetData(nsACString &data)
{
// The stream doesn't have any data when it is closed. We could fake it
// and return an empty string here, but it seems better to keep this return
// value consistent with the behavior of the other 'getter' methods.
if (NS_WARN_IF(Closed()))
return NS_BASE_STREAM_CLOSED;
// The stream doesn't have any data when it is closed. We could fake it
// and return an empty string here, but it seems better to keep this return
// value consistent with the behavior of the other 'getter' methods.
if (NS_WARN_IF(Closed()))
return NS_BASE_STREAM_CLOSED;
data.Assign(mData);
return NS_OK;
data.Assign(mData);
return NS_OK;
}
NS_IMETHODIMP
nsStringInputStream::SetData(const nsACString &data)
{
mData.Assign(data);
mOffset = 0;
return NS_OK;
mData.Assign(data);
mOffset = 0;
return NS_OK;
}
NS_IMETHODIMP
nsStringInputStream::ToString(char **result)
{
// NOTE: This method may result in data loss, so we do not implement it.
return NS_ERROR_NOT_IMPLEMENTED;
// NOTE: This method may result in data loss, so we do not implement it.
return NS_ERROR_NOT_IMPLEMENTED;
}
/////////
@@ -141,35 +141,35 @@ nsStringInputStream::ToString(char **result)
NS_IMETHODIMP
nsStringInputStream::SetData(const char *data, int32_t dataLen)
{
if (NS_WARN_IF(!data))
return NS_ERROR_INVALID_ARG;
mData.Assign(data, dataLen);
mOffset = 0;
return NS_OK;
if (NS_WARN_IF(!data))
return NS_ERROR_INVALID_ARG;
mData.Assign(data, dataLen);
mOffset = 0;
return NS_OK;
}
NS_IMETHODIMP
nsStringInputStream::AdoptData(char *data, int32_t dataLen)
{
if (NS_WARN_IF(!data))
return NS_ERROR_INVALID_ARG;
mData.Adopt(data, dataLen);
mOffset = 0;
return NS_OK;
if (NS_WARN_IF(!data))
return NS_ERROR_INVALID_ARG;
mData.Adopt(data, dataLen);
mOffset = 0;
return NS_OK;
}
NS_IMETHODIMP
nsStringInputStream::ShareData(const char *data, int32_t dataLen)
{
if (NS_WARN_IF(!data))
return NS_ERROR_INVALID_ARG;
if (NS_WARN_IF(!data))
return NS_ERROR_INVALID_ARG;
if (dataLen < 0)
dataLen = strlen(data);
if (dataLen < 0)
dataLen = strlen(data);
mData.Rebind(data, dataLen);
mOffset = 0;
return NS_OK;
mData.Rebind(data, dataLen);
mOffset = 0;
return NS_OK;
}
/////////
@@ -179,147 +179,147 @@ nsStringInputStream::ShareData(const char *data, int32_t dataLen)
NS_IMETHODIMP
nsStringInputStream::Close()
{
Clear();
return NS_OK;
Clear();
return NS_OK;
}
NS_IMETHODIMP
nsStringInputStream::Available(uint64_t *aLength)
{
NS_ASSERTION(aLength, "null ptr");
NS_ASSERTION(aLength, "null ptr");
if (Closed())
return NS_BASE_STREAM_CLOSED;
if (Closed())
return NS_BASE_STREAM_CLOSED;
*aLength = LengthRemaining();
return NS_OK;
*aLength = LengthRemaining();
return NS_OK;
}
NS_IMETHODIMP
nsStringInputStream::Read(char* aBuf, uint32_t aCount, uint32_t *aReadCount)
{
NS_ASSERTION(aBuf, "null ptr");
return ReadSegments(NS_CopySegmentToBuffer, aBuf, aCount, aReadCount);
NS_ASSERTION(aBuf, "null ptr");
return ReadSegments(NS_CopySegmentToBuffer, aBuf, aCount, aReadCount);
}
NS_IMETHODIMP
nsStringInputStream::ReadSegments(nsWriteSegmentFun writer, void *closure,
uint32_t aCount, uint32_t *result)
{
NS_ASSERTION(result, "null ptr");
NS_ASSERTION(Length() >= mOffset, "bad stream state");
NS_ASSERTION(result, "null ptr");
NS_ASSERTION(Length() >= mOffset, "bad stream state");
if (Closed())
return NS_BASE_STREAM_CLOSED;
if (Closed())
return NS_BASE_STREAM_CLOSED;
// We may be at end-of-file
uint32_t maxCount = LengthRemaining();
if (maxCount == 0) {
*result = 0;
return NS_OK;
}
if (aCount > maxCount)
aCount = maxCount;
nsresult rv = writer(this, closure, mData.BeginReading() + mOffset, 0, aCount, result);
if (NS_SUCCEEDED(rv)) {
NS_ASSERTION(*result <= aCount,
"writer should not write more than we asked it to write");
mOffset += *result;
}
// errors returned from the writer end here!
// We may be at end-of-file
uint32_t maxCount = LengthRemaining();
if (maxCount == 0) {
*result = 0;
return NS_OK;
}
if (aCount > maxCount)
aCount = maxCount;
nsresult rv = writer(this, closure, mData.BeginReading() + mOffset, 0, aCount, result);
if (NS_SUCCEEDED(rv)) {
NS_ASSERTION(*result <= aCount,
"writer should not write more than we asked it to write");
mOffset += *result;
}
// errors returned from the writer end here!
return NS_OK;
}
NS_IMETHODIMP
nsStringInputStream::IsNonBlocking(bool *aNonBlocking)
{
*aNonBlocking = true;
return NS_OK;
*aNonBlocking = true;
return NS_OK;
}
/////////
// nsISeekableStream implementation
/////////
NS_IMETHODIMP
NS_IMETHODIMP
nsStringInputStream::Seek(int32_t whence, int64_t offset)
{
if (Closed())
return NS_BASE_STREAM_CLOSED;
if (Closed())
return NS_BASE_STREAM_CLOSED;
// Compute new stream position. The given offset may be a negative value.
int64_t newPos = offset;
switch (whence) {
// Compute new stream position. The given offset may be a negative value.
int64_t newPos = offset;
switch (whence) {
case NS_SEEK_SET:
break;
break;
case NS_SEEK_CUR:
newPos += mOffset;
break;
newPos += mOffset;
break;
case NS_SEEK_END:
newPos += Length();
break;
newPos += Length();
break;
default:
NS_ERROR("invalid whence");
return NS_ERROR_INVALID_ARG;
}
NS_ERROR("invalid whence");
return NS_ERROR_INVALID_ARG;
}
if (NS_WARN_IF(newPos < 0) || NS_WARN_IF(newPos > Length()))
return NS_ERROR_INVALID_ARG;
if (NS_WARN_IF(newPos < 0) || NS_WARN_IF(newPos > Length()))
return NS_ERROR_INVALID_ARG;
mOffset = (uint32_t)newPos;
return NS_OK;
mOffset = (uint32_t)newPos;
return NS_OK;
}
NS_IMETHODIMP
nsStringInputStream::Tell(int64_t* outWhere)
{
if (Closed())
return NS_BASE_STREAM_CLOSED;
if (Closed())
return NS_BASE_STREAM_CLOSED;
*outWhere = mOffset;
return NS_OK;
*outWhere = mOffset;
return NS_OK;
}
NS_IMETHODIMP
nsStringInputStream::SetEOF()
{
if (Closed())
return NS_BASE_STREAM_CLOSED;
if (Closed())
return NS_BASE_STREAM_CLOSED;
mOffset = Length();
return NS_OK;
mOffset = Length();
return NS_OK;
}
void
nsStringInputStream::Serialize(InputStreamParams& aParams,
FileDescriptorArray& /* aFDs */)
{
StringInputStreamParams params;
params.data() = PromiseFlatCString(mData);
aParams = params;
StringInputStreamParams params;
params.data() = PromiseFlatCString(mData);
aParams = params;
}
bool
nsStringInputStream::Deserialize(const InputStreamParams& aParams,
const FileDescriptorArray& /* aFDs */)
{
if (aParams.type() != InputStreamParams::TStringInputStreamParams) {
NS_ERROR("Received unknown parameters from the other process!");
return false;
}
if (aParams.type() != InputStreamParams::TStringInputStreamParams) {
NS_ERROR("Received unknown parameters from the other process!");
return false;
}
const StringInputStreamParams& params =
aParams.get_StringInputStreamParams();
const StringInputStreamParams& params =
aParams.get_StringInputStreamParams();
if (NS_FAILED(SetData(params.data()))) {
NS_WARNING("SetData failed!");
return false;
}
if (NS_FAILED(SetData(params.data()))) {
NS_WARNING("SetData failed!");
return false;
}
return true;
return true;
}
nsresult
@@ -327,81 +327,81 @@ NS_NewByteInputStream(nsIInputStream** aStreamResult,
const char* aStringToRead, int32_t aLength,
nsAssignmentType aAssignment)
{
NS_PRECONDITION(aStreamResult, "null out ptr");
NS_PRECONDITION(aStreamResult, "null out ptr");
nsStringInputStream* stream = new nsStringInputStream();
if (! stream)
return NS_ERROR_OUT_OF_MEMORY;
nsStringInputStream* stream = new nsStringInputStream();
if (! stream)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(stream);
NS_ADDREF(stream);
nsresult rv;
switch (aAssignment) {
nsresult rv;
switch (aAssignment) {
case NS_ASSIGNMENT_COPY:
rv = stream->SetData(aStringToRead, aLength);
break;
rv = stream->SetData(aStringToRead, aLength);
break;
case NS_ASSIGNMENT_DEPEND:
rv = stream->ShareData(aStringToRead, aLength);
break;
rv = stream->ShareData(aStringToRead, aLength);
break;
case NS_ASSIGNMENT_ADOPT:
rv = stream->AdoptData(const_cast<char*>(aStringToRead), aLength);
break;
rv = stream->AdoptData(const_cast<char*>(aStringToRead), aLength);
break;
default:
NS_ERROR("invalid assignment type");
rv = NS_ERROR_INVALID_ARG;
}
if (NS_FAILED(rv)) {
NS_RELEASE(stream);
return rv;
}
*aStreamResult = stream;
return NS_OK;
NS_ERROR("invalid assignment type");
rv = NS_ERROR_INVALID_ARG;
}
if (NS_FAILED(rv)) {
NS_RELEASE(stream);
return rv;
}
*aStreamResult = stream;
return NS_OK;
}
nsresult
NS_NewStringInputStream(nsIInputStream** aStreamResult,
const nsAString& aStringToRead)
{
NS_LossyConvertUTF16toASCII data(aStringToRead); // truncates high-order bytes
return NS_NewCStringInputStream(aStreamResult, data);
NS_LossyConvertUTF16toASCII data(aStringToRead); // truncates high-order bytes
return NS_NewCStringInputStream(aStreamResult, data);
}
nsresult
NS_NewCStringInputStream(nsIInputStream** aStreamResult,
const nsACString& aStringToRead)
{
NS_PRECONDITION(aStreamResult, "null out ptr");
NS_PRECONDITION(aStreamResult, "null out ptr");
nsStringInputStream* stream = new nsStringInputStream();
if (! stream)
return NS_ERROR_OUT_OF_MEMORY;
nsStringInputStream* stream = new nsStringInputStream();
if (! stream)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(stream);
NS_ADDREF(stream);
stream->SetData(aStringToRead);
stream->SetData(aStringToRead);
*aStreamResult = stream;
return NS_OK;
*aStreamResult = stream;
return NS_OK;
}
// factory method for constructing a nsStringInputStream object
nsresult
nsStringInputStreamConstructor(nsISupports *outer, REFNSIID iid, void **result)
{
*result = nullptr;
*result = nullptr;
if (NS_WARN_IF(outer))
return NS_ERROR_NO_AGGREGATION;
if (NS_WARN_IF(outer))
return NS_ERROR_NO_AGGREGATION;
nsStringInputStream *inst = new nsStringInputStream();
if (!inst)
return NS_ERROR_OUT_OF_MEMORY;
nsStringInputStream *inst = new nsStringInputStream();
if (!inst)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(inst);
nsresult rv = inst->QueryInterface(iid, result);
NS_RELEASE(inst);
NS_ADDREF(inst);
nsresult rv = inst->QueryInterface(iid, result);
NS_RELEASE(inst);
return rv;
return rv;
}

View File

@@ -70,26 +70,26 @@ StringUnicharInputStream::ReadSegments(nsWriteUnicharSegmentFun aWriter,
nsresult rv;
aCount = XPCOM_MIN(mString.Length() - mPos, aCount);
nsAString::const_iterator iter;
mString.BeginReading(iter);
while (aCount) {
rv = aWriter(this, aClosure, iter.get() + mPos,
totalBytesWritten, aCount, &bytesWritten);
if (NS_FAILED(rv)) {
// don't propagate errors to the caller
break;
}
aCount -= bytesWritten;
totalBytesWritten += bytesWritten;
mPos += bytesWritten;
}
*aReadCount = totalBytesWritten;
return NS_OK;
}
@@ -140,7 +140,7 @@ protected:
nsCOMPtr<nsIInputStream> mInput;
FallibleTArray<char> mByteData;
FallibleTArray<char16_t> mUnicharData;
uint32_t mByteDataOffset;
uint32_t mUnicharDataOffset;
uint32_t mUnicharDataLength;
@@ -153,7 +153,7 @@ UTF8InputStream::UTF8InputStream() :
{
}
nsresult
nsresult
UTF8InputStream::Init(nsIInputStream* aStream)
{
if (!mByteData.SetCapacity(STRING_BUFFER_SIZE) ||
@@ -223,10 +223,10 @@ UTF8InputStream::ReadSegments(nsWriteUnicharSegmentFun aWriter,
}
bytesToWrite = bytesRead;
}
if (bytesToWrite > aCount)
bytesToWrite = aCount;
uint32_t bytesWritten;
uint32_t totalBytesWritten = 0;
@@ -239,14 +239,14 @@ UTF8InputStream::ReadSegments(nsWriteUnicharSegmentFun aWriter,
// don't propagate errors to the caller
break;
}
bytesToWrite -= bytesWritten;
totalBytesWritten += bytesWritten;
mUnicharDataOffset += bytesWritten;
}
*aReadCount = totalBytesWritten;
return NS_OK;
}
@@ -310,22 +310,22 @@ int32_t UTF8InputStream::Fill(nsresult * aErrorCode)
NS_ASSERTION(dstLen <= mUnicharData.Capacity(),
"Ouch. I would overflow my buffer if I wasn't so careful.");
if (dstLen > mUnicharData.Capacity()) return 0;
ConvertUTF8toUTF16 converter(mUnicharData.Elements());
nsASingleFragmentCString::const_char_iterator start = mByteData.Elements();
nsASingleFragmentCString::const_char_iterator end = mByteData.Elements() + srcLen;
copy_string(start, end, converter);
if (converter.Length() != dstLen) {
*aErrorCode = NS_BASE_STREAM_BAD_CONVERSION;
return -1;
}
mUnicharDataOffset = 0;
mUnicharDataLength = dstLen;
mByteDataOffset = srcLen;
return dstLen;
}
@@ -339,7 +339,7 @@ UTF8InputStream::CountValidUTF8Bytes(const char* aBuffer, uint32_t aMaxBytes, ui
while (c < end && *c) {
lastchar = c;
utf16length++;
if (UTF8traits::isASCII(*c))
c++;
else if (UTF8traits::is2byte(*c))
@@ -378,7 +378,7 @@ NS_IMETHODIMP_(MozExternalRefCountType) nsSimpleUnicharStreamFactory::Release()
NS_IMETHODIMP
nsSimpleUnicharStreamFactory::CreateInstance(nsISupports* aOuter, REFNSIID aIID,
void **aResult)
void **aResult)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
@@ -391,7 +391,7 @@ nsSimpleUnicharStreamFactory::LockFactory(bool aLock)
NS_IMETHODIMP
nsSimpleUnicharStreamFactory::CreateInstanceFromString(const nsAString& aString,
nsIUnicharInputStream* *aResult)
nsIUnicharInputStream* *aResult)
{
StringUnicharInputStream* it = new StringUnicharInputStream(aString);
if (!it) {

View File

@@ -14,7 +14,7 @@
{ 0x428dca6f, 0x1a0f, 0x4cda, { 0xb5, 0x16, 0xd, 0x52, 0x44, 0x74, 0x5a, 0x6a } }
class nsSimpleUnicharStreamFactory :
public nsIFactory,
public nsIFactory,
private nsISimpleUnicharStreamFactory
{
public:

View File

@@ -1,5 +1,5 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim:set ts=4 sts=4 sw=4 cin et: */
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@@ -29,29 +29,29 @@ template<class T>
static int
alpha(T c)
{
return ('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z');
return ('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z');
}
template<class T>
static int
alphanumeric(T c)
{
return ('0' <= c && c <= '9') || ::alpha(c);
return ('0' <= c && c <= '9') || ::alpha(c);
}
template<class T>
static int
lower(T c)
{
return ('A' <= c && c <= 'Z') ? c + ('a' - 'A') : c;
return ('A' <= c && c <= 'Z') ? c + ('a' - 'A') : c;
}
template<class T>
static int
upper(T c)
{
return ('a' <= c && c <= 'z') ? c - ('a' - 'A') : c;
return ('a' <= c && c <= 'z') ? c - ('a' - 'A') : c;
}
/* ----------------------------- _valid_subexp ---------------------------- */
@@ -60,73 +60,73 @@ template<class T>
static int
_valid_subexp(const T *expr, T stop1, T stop2)
{
int x;
int nsc = 0; /* Number of special characters */
int np; /* Number of pipe characters in union */
int tld = 0; /* Number of tilde characters */
for (x = 0; expr[x] && (expr[x] != stop1) && (expr[x] != stop2); ++x) {
switch(expr[x]) {
case '~':
if(tld) /* at most one exclusion */
return INVALID_SXP;
if (stop1) /* no exclusions within unions */
return INVALID_SXP;
if (!expr[x+1]) /* exclusion cannot be last character */
return INVALID_SXP;
if (!x) /* exclusion cannot be first character */
return INVALID_SXP;
++tld;
/* fall through */
case '*':
case '?':
case '$':
++nsc;
break;
case '[':
++nsc;
if((!expr[++x]) || (expr[x] == ']'))
return INVALID_SXP;
for(; expr[x] && (expr[x] != ']'); ++x) {
if(expr[x] == '\\' && !expr[++x])
return INVALID_SXP;
}
if(!expr[x])
return INVALID_SXP;
break;
case '(':
++nsc;
if (stop1) /* no nested unions */
return INVALID_SXP;
np = -1;
do {
int t = ::_valid_subexp(&expr[++x], T(')'), T('|'));
if(t == 0 || t == INVALID_SXP)
return INVALID_SXP;
x+=t;
if(!expr[x])
return INVALID_SXP;
++np;
} while (expr[x] == '|' );
if(np < 1) /* must be at least one pipe */
return INVALID_SXP;
break;
case ')':
case ']':
case '|':
int x;
int nsc = 0; /* Number of special characters */
int np; /* Number of pipe characters in union */
int tld = 0; /* Number of tilde characters */
for (x = 0; expr[x] && (expr[x] != stop1) && (expr[x] != stop2); ++x) {
switch(expr[x]) {
case '~':
if(tld) /* at most one exclusion */
return INVALID_SXP;
if (stop1) /* no exclusions within unions */
return INVALID_SXP;
if (!expr[x+1]) /* exclusion cannot be last character */
return INVALID_SXP;
if (!x) /* exclusion cannot be first character */
return INVALID_SXP;
++tld;
/* fall through */
case '*':
case '?':
case '$':
++nsc;
break;
case '[':
++nsc;
if((!expr[++x]) || (expr[x] == ']'))
return INVALID_SXP;
for(; expr[x] && (expr[x] != ']'); ++x) {
if(expr[x] == '\\' && !expr[++x])
return INVALID_SXP;
case '\\':
++nsc;
if(!expr[++x])
return INVALID_SXP;
break;
default:
break;
}
if(!expr[x])
return INVALID_SXP;
break;
case '(':
++nsc;
if (stop1) /* no nested unions */
return INVALID_SXP;
np = -1;
do {
int t = ::_valid_subexp(&expr[++x], T(')'), T('|'));
if(t == 0 || t == INVALID_SXP)
return INVALID_SXP;
x+=t;
if(!expr[x])
return INVALID_SXP;
++np;
} while (expr[x] == '|' );
if(np < 1) /* must be at least one pipe */
return INVALID_SXP;
break;
case ')':
case ']':
case '|':
return INVALID_SXP;
case '\\':
++nsc;
if(!expr[++x])
return INVALID_SXP;
break;
default:
break;
}
if((!stop1) && (!nsc)) /* must be at least one special character */
return NON_SXP;
return ((expr[x] == stop1 || expr[x] == stop2) ? x : INVALID_SXP);
}
if((!stop1) && (!nsc)) /* must be at least one special character */
return NON_SXP;
return ((expr[x] == stop1 || expr[x] == stop2) ? x : INVALID_SXP);
}
@@ -134,20 +134,20 @@ template<class T>
int
NS_WildCardValid_(const T *expr)
{
int x = ::_valid_subexp(expr, T('\0'), T('\0'));
return (x < 0 ? x : VALID_SXP);
int x = ::_valid_subexp(expr, T('\0'), T('\0'));
return (x < 0 ? x : VALID_SXP);
}
int
NS_WildCardValid(const char *expr)
{
return NS_WildCardValid_(expr);
return NS_WildCardValid_(expr);
}
int
NS_WildCardValid(const char16_t *expr)
{
return NS_WildCardValid_(expr);
return NS_WildCardValid_(expr);
}
/* ----------------------------- _shexp_match ----------------------------- */
@@ -174,29 +174,29 @@ template<class T>
static int
_scan_and_copy(const T *expr, T stop1, T stop2, T *dest)
{
int sx; /* source index */
T cc;
int sx; /* source index */
T cc;
for (sx = 0; (cc = expr[sx]) && cc != stop1 && cc != stop2; sx++) {
if (cc == '\\') {
if (!expr[++sx])
return ABORTED; /* should be impossible */
}
else if (cc == '[') {
while ((cc = expr[++sx]) && cc != ']') {
if(cc == '\\' && !expr[++sx])
return ABORTED;
}
if (!cc)
return ABORTED; /* should be impossible */
}
for (sx = 0; (cc = expr[sx]) && cc != stop1 && cc != stop2; sx++) {
if (cc == '\\') {
if (!expr[++sx])
return ABORTED; /* should be impossible */
}
if (dest && sx) {
/* Copy all but the closing delimiter. */
memcpy(dest, expr, sx * sizeof(T));
dest[sx] = 0;
else if (cc == '[') {
while ((cc = expr[++sx]) && cc != ']') {
if(cc == '\\' && !expr[++sx])
return ABORTED;
}
if (!cc)
return ABORTED; /* should be impossible */
}
return cc ? sx : ABORTED; /* index of closing delimiter */
}
if (dest && sx) {
/* Copy all but the closing delimiter. */
memcpy(dest, expr, sx * sizeof(T));
dest[sx] = 0;
}
return cc ? sx : ABORTED; /* index of closing delimiter */
}
/* On input, expr[0] is the opening parenthesis of a union.
@@ -212,50 +212,50 @@ static int
_handle_union(const T *str, const T *expr, bool case_insensitive,
unsigned int level)
{
int sx; /* source index */
int cp; /* source index of closing parenthesis */
int count;
int ret = NOMATCH;
T *e2;
int sx; /* source index */
int cp; /* source index of closing parenthesis */
int count;
int ret = NOMATCH;
T *e2;
/* Find the closing parenthesis that ends this union in the expression */
cp = ::_scan_and_copy(expr, T(')'), T('\0'), static_cast<T*>(nullptr));
if (cp == ABORTED || cp < 4) /* must be at least "(a|b" before ')' */
return ABORTED;
++cp; /* now index of char after closing parenthesis */
e2 = (T *) NS_Alloc((1 + nsCharTraits<T>::length(expr)) * sizeof(T));
if (!e2)
return ABORTED;
for (sx = 1; ; ++sx) {
/* Here, expr[sx] is one character past the preceding '(' or '|'. */
/* Copy everything up to the next delimiter to e2 */
count = ::_scan_and_copy(expr + sx, T(')'), T('|'), e2);
if (count == ABORTED || !count) {
ret = ABORTED;
break;
}
sx += count;
/* Append everything after closing parenthesis to e2. This is safe. */
nsCharTraits<T>::copy(e2 + count, expr + cp, nsCharTraits<T>::length(expr + cp) + 1);
ret = ::_shexp_match(str, e2, case_insensitive, level + 1);
if (ret != NOMATCH || !expr[sx] || expr[sx] == ')')
break;
/* Find the closing parenthesis that ends this union in the expression */
cp = ::_scan_and_copy(expr, T(')'), T('\0'), static_cast<T*>(nullptr));
if (cp == ABORTED || cp < 4) /* must be at least "(a|b" before ')' */
return ABORTED;
++cp; /* now index of char after closing parenthesis */
e2 = (T *) NS_Alloc((1 + nsCharTraits<T>::length(expr)) * sizeof(T));
if (!e2)
return ABORTED;
for (sx = 1; ; ++sx) {
/* Here, expr[sx] is one character past the preceding '(' or '|'. */
/* Copy everything up to the next delimiter to e2 */
count = ::_scan_and_copy(expr + sx, T(')'), T('|'), e2);
if (count == ABORTED || !count) {
ret = ABORTED;
break;
}
NS_Free(e2);
if (sx < 2)
ret = ABORTED;
return ret;
sx += count;
/* Append everything after closing parenthesis to e2. This is safe. */
nsCharTraits<T>::copy(e2 + count, expr + cp, nsCharTraits<T>::length(expr + cp) + 1);
ret = ::_shexp_match(str, e2, case_insensitive, level + 1);
if (ret != NOMATCH || !expr[sx] || expr[sx] == ')')
break;
}
NS_Free(e2);
if (sx < 2)
ret = ABORTED;
return ret;
}
/* returns 1 if val is in range from start..end, case insensitive. */
static int
_is_char_in_range(unsigned char start, unsigned char end, unsigned char val)
{
char map[256];
memset(map, 0, sizeof map);
while (start <= end)
map[lower(start++)] = 1;
return map[lower(val)];
char map[256];
memset(map, 0, sizeof map);
while (start <= end)
map[lower(start++)] = 1;
return map[lower(val)];
}
template<class T>
@@ -263,119 +263,119 @@ static int
_shexp_match(const T *str, const T *expr, bool case_insensitive,
unsigned int level)
{
int x; /* input string index */
int y; /* expression index */
int ret,neg;
int x; /* input string index */
int y; /* expression index */
int ret,neg;
if (level > 20) /* Don't let the stack get too deep. */
return ABORTED;
for(x = 0, y = 0; expr[y]; ++y, ++x) {
if((!str[x]) && (expr[y] != '$') && (expr[y] != '*')) {
if (level > 20) /* Don't let the stack get too deep. */
return ABORTED;
for(x = 0, y = 0; expr[y]; ++y, ++x) {
if((!str[x]) && (expr[y] != '$') && (expr[y] != '*')) {
return NOMATCH;
}
switch(expr[y]) {
case '$':
if(str[x])
return NOMATCH;
--x; /* we don't want loop to increment x */
break;
case '*':
while(expr[++y] == '*'){}
if(!expr[y])
return MATCH;
while(str[x]) {
ret = ::_shexp_match(&str[x++], &expr[y], case_insensitive,
level + 1);
switch(ret) {
case NOMATCH:
continue;
case ABORTED:
return ABORTED;
default:
return MATCH;
}
}
if((expr[y] == '$') && (expr[y+1] == '\0') && (!str[x]))
return MATCH;
else
return NOMATCH;
case '[': {
T start, end = 0;
int i;
neg = ((expr[++y] == '^') && (expr[y+1] != ']'));
if (neg)
++y;
i = y;
start = expr[i++];
if (start == '\\')
start = expr[i++];
if (::alphanumeric(start) && expr[i++] == '-') {
end = expr[i++];
if (end == '\\')
end = expr[i++];
}
if (::alphanumeric(end) && expr[i] == ']') {
/* This is a range form: a-b */
T val = str[x];
if (end < start) { /* swap them */
T tmp = end;
end = start;
start = tmp;
}
if (case_insensitive && ::alpha(val)) {
val = ::_is_char_in_range((unsigned char) start,
(unsigned char) end,
(unsigned char) val);
if (neg == val)
return NOMATCH;
}
else if (neg != ((val < start) || (val > end))) {
return NOMATCH;
}
y = i;
}
else {
/* Not range form */
int matched = 0;
for (; expr[y] != ']'; y++) {
if (expr[y] == '\\')
++y;
if(case_insensitive)
matched |= (::upper(str[x]) == ::upper(expr[y]));
else
matched |= (str[x] == expr[y]);
}
if (neg == matched)
return NOMATCH;
}
switch(expr[y]) {
case '$':
if(str[x])
return NOMATCH;
--x; /* we don't want loop to increment x */
break;
case '*':
while(expr[++y] == '*'){}
if(!expr[y])
return MATCH;
while(str[x]) {
ret = ::_shexp_match(&str[x++], &expr[y], case_insensitive,
level + 1);
switch(ret) {
case NOMATCH:
continue;
case ABORTED:
return ABORTED;
default:
return MATCH;
}
}
if((expr[y] == '$') && (expr[y+1] == '\0') && (!str[x]))
return MATCH;
else
return NOMATCH;
case '[': {
T start, end = 0;
int i;
neg = ((expr[++y] == '^') && (expr[y+1] != ']'));
if (neg)
++y;
i = y;
start = expr[i++];
if (start == '\\')
start = expr[i++];
if (::alphanumeric(start) && expr[i++] == '-') {
end = expr[i++];
if (end == '\\')
end = expr[i++];
}
if (::alphanumeric(end) && expr[i] == ']') {
/* This is a range form: a-b */
T val = str[x];
if (end < start) { /* swap them */
T tmp = end;
end = start;
start = tmp;
}
if (case_insensitive && ::alpha(val)) {
val = ::_is_char_in_range((unsigned char) start,
(unsigned char) end,
(unsigned char) val);
if (neg == val)
return NOMATCH;
}
else if (neg != ((val < start) || (val > end))) {
return NOMATCH;
}
y = i;
}
else {
/* Not range form */
int matched = 0;
for (; expr[y] != ']'; y++) {
if (expr[y] == '\\')
++y;
if(case_insensitive)
matched |= (::upper(str[x]) == ::upper(expr[y]));
else
matched |= (str[x] == expr[y]);
}
if (neg == matched)
return NOMATCH;
}
}
break;
case '(':
if (!expr[y+1])
return ABORTED;
return ::_handle_union(&str[x], &expr[y], case_insensitive, level + 1);
case '?':
break;
case ')':
case ']':
case '|':
return ABORTED;
case '\\':
++y;
/* fall through */
default:
if(case_insensitive) {
if(::upper(str[x]) != ::upper(expr[y]))
return NOMATCH;
}
else {
if(str[x] != expr[y])
return NOMATCH;
}
break;
case '(':
if (!expr[y+1])
return ABORTED;
return ::_handle_union(&str[x], &expr[y], case_insensitive, level + 1);
case '?':
break;
case ')':
case ']':
case '|':
return ABORTED;
case '\\':
++y;
/* fall through */
default:
if(case_insensitive) {
if(::upper(str[x]) != ::upper(expr[y]))
return NOMATCH;
}
else {
if(str[x] != expr[y])
return NOMATCH;
}
break;
}
}
return (str[x] ? NOMATCH : MATCH);
}
return (str[x] ? NOMATCH : MATCH);
}
@@ -383,57 +383,57 @@ template<class T>
static int
ns_WildCardMatch(const T *str, const T *xp, bool case_insensitive)
{
T *expr = nullptr;
int x, ret = MATCH;
T *expr = nullptr;
int x, ret = MATCH;
if (!nsCharTraits<T>::find(xp, nsCharTraits<T>::length(xp), T('~')))
return ::_shexp_match(str, xp, case_insensitive, 0);
if (!nsCharTraits<T>::find(xp, nsCharTraits<T>::length(xp), T('~')))
return ::_shexp_match(str, xp, case_insensitive, 0);
expr = (T *) NS_Alloc((nsCharTraits<T>::length(xp) + 1) * sizeof(T));
if(!expr)
return NOMATCH;
memcpy(expr, xp, (nsCharTraits<T>::length(xp) + 1) * sizeof(T));
expr = (T *) NS_Alloc((nsCharTraits<T>::length(xp) + 1) * sizeof(T));
if(!expr)
return NOMATCH;
memcpy(expr, xp, (nsCharTraits<T>::length(xp) + 1) * sizeof(T));
x = ::_scan_and_copy(expr, T('~'), T('\0'), static_cast<T*>(nullptr));
if (x != ABORTED && expr[x] == '~') {
expr[x++] = '\0';
ret = ::_shexp_match(str, &expr[x], case_insensitive, 0);
switch (ret) {
case NOMATCH: ret = MATCH; break;
case MATCH: ret = NOMATCH; break;
default: break;
}
x = ::_scan_and_copy(expr, T('~'), T('\0'), static_cast<T*>(nullptr));
if (x != ABORTED && expr[x] == '~') {
expr[x++] = '\0';
ret = ::_shexp_match(str, &expr[x], case_insensitive, 0);
switch (ret) {
case NOMATCH: ret = MATCH; break;
case MATCH: ret = NOMATCH; break;
default: break;
}
if (ret == MATCH)
ret = ::_shexp_match(str, expr, case_insensitive, 0);
}
if (ret == MATCH)
ret = ::_shexp_match(str, expr, case_insensitive, 0);
NS_Free(expr);
return ret;
NS_Free(expr);
return ret;
}
template<class T>
int
NS_WildCardMatch_(const T *str, const T *expr, bool case_insensitive)
{
int is_valid = NS_WildCardValid(expr);
switch(is_valid) {
case INVALID_SXP:
return -1;
default:
return ::ns_WildCardMatch(str, expr, case_insensitive);
}
int is_valid = NS_WildCardValid(expr);
switch(is_valid) {
case INVALID_SXP:
return -1;
default:
return ::ns_WildCardMatch(str, expr, case_insensitive);
}
}
int
NS_WildCardMatch(const char *str, const char *xp,
bool case_insensitive)
{
return NS_WildCardMatch_(str, xp, case_insensitive);
return NS_WildCardMatch_(str, xp, case_insensitive);
}
int
NS_WildCardMatch(const char16_t *str, const char16_t *xp,
bool case_insensitive)
{
return NS_WildCardMatch_(str, xp, case_insensitive);
return NS_WildCardMatch_(str, xp, case_insensitive);
}

View File

@@ -55,9 +55,9 @@ int NS_WildCardValid(const char16_t *expr);
*/
int NS_WildCardMatch(const char *str, const char *expr,
bool case_insensitive);
bool case_insensitive);
int NS_WildCardMatch(const char16_t *str, const char16_t *expr,
bool case_insensitive);
bool case_insensitive);
#endif /* nsWildCard_h__ */