Backout bug 299992 - too much odd platform-specific bustage

This commit is contained in:
bsmedberg%covad.net 2005-08-11 22:07:08 +00:00
Родитель e9e90a981a
Коммит 4fb9cbf21d
44 изменённых файлов: 253 добавлений и 2234 удалений

Просмотреть файл

@ -71,6 +71,7 @@ CPPSRCS = nsProfileMigrator.cpp \
nsNetscapeProfileMigratorBase.cpp \
nsSeamonkeyProfileMigrator.cpp \
nsPhoenixProfileMigrator.cpp \
nsINIParser.cpp \
$(NULL)
ifneq ($(OS_ARCH),BeOS)

Просмотреть файл

Просмотреть файл

Просмотреть файл

@ -367,18 +367,15 @@ nsOperaProfileMigrator::SetString(void* aTransform, nsIPrefBranch* aBranch)
nsresult
nsOperaProfileMigrator::CopyPreferences(PRBool aReplace)
{
nsresult rv;
nsCOMPtr<nsIFile> operaPrefs;
mOperaProfile->Clone(getter_AddRefs(operaPrefs));
operaPrefs->Append(OPERA_PREFERENCES_FILE_NAME);
nsCOMPtr<nsILocalFile> lf(do_QueryInterface(operaPrefs));
NS_ENSURE_TRUE(lf, NS_ERROR_UNEXPECTED);
nsINIParser parser;
rv = parser.Init(lf);
NS_ENSURE_SUCCESS(rv, rv);
nsCAutoString path;
operaPrefs->GetNativePath(path);
nsINIParser* parser = new nsINIParser(path.get());
if (!parser)
return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsIPrefBranch> branch(do_GetService(NS_PREFSERVICE_CONTRACTID));
@ -386,6 +383,7 @@ nsOperaProfileMigrator::CopyPreferences(PRBool aReplace)
PrefTransform* transform;
PrefTransform* end = gTransforms + sizeof(gTransforms)/sizeof(PrefTransform);
PRInt32 length;
char* lastSectionName = nsnull;
for (transform = gTransforms; transform < end; ++transform) {
if (transform->sectionName)
@ -404,22 +402,22 @@ nsOperaProfileMigrator::CopyPreferences(PRBool aReplace)
nsCRT::free(colorString);
}
else {
nsCAutoString val;
rv = parser.GetString(lastSectionName,
transform->keyName,
val);
if (NS_SUCCEEDED(rv)) {
nsXPIDLCString val;
PRInt32 err = parser->GetStringAlloc(lastSectionName, transform->keyName, getter_Copies(val), &length);
if (err == nsINIParser::OK) {
PRInt32 strerr;
switch (transform->type) {
case _OPM(STRING):
transform->stringValue = ToNewCString(val);
break;
case _OPM(INT): {
transform->intValue = val.ToInteger(&strerr);
nsCAutoString valStr; valStr = val;
transform->intValue = valStr.ToInteger(&strerr);
}
break;
case _OPM(BOOL): {
transform->boolValue = val.ToInteger(&strerr) != 0;
nsCAutoString valStr; valStr = val;
transform->boolValue = valStr.ToInteger(&strerr) != 0;
}
break;
default:
@ -442,22 +440,23 @@ nsOperaProfileMigrator::CopyPreferences(PRBool aReplace)
if (aReplace)
CopyUserContentSheet(parser);
delete parser;
parser = nsnull;
return NS_OK;
}
nsresult
nsOperaProfileMigrator::CopyProxySettings(nsINIParser &aParser,
nsOperaProfileMigrator::CopyProxySettings(nsINIParser* aParser,
nsIPrefBranch* aBranch)
{
nsresult rv;
PRInt32 networkProxyType = 0;
const char* protocols[4] = { "HTTP", "HTTPS", "FTP", "GOPHER" };
const char* protocols_l[4] = { "http", "https", "ftp", "gopher" };
char toggleBuf[15], serverBuf[20], serverPrefBuf[20],
serverPortPrefBuf[25];
PRInt32 enabled;
PRInt32 length, err, enabled;
for (PRUint32 i = 0; i < 4; ++i) {
sprintf(toggleBuf, "Use %s", protocols[i]);
GetInteger(aParser, "Proxy", toggleBuf, &enabled);
@ -468,9 +467,9 @@ nsOperaProfileMigrator::CopyProxySettings(nsINIParser &aParser,
}
sprintf(serverBuf, "%s Server", protocols[i]);
nsCAutoString proxyServer;
rv = aParser.GetString("Proxy", serverBuf, proxyServer);
if (NS_FAILED(rv))
nsXPIDLCString proxyServer;
err = aParser->GetStringAlloc("Proxy", serverBuf, getter_Copies(proxyServer), &length);
if (err != nsINIParser::OK)
continue;
sprintf(serverPrefBuf, "network.proxy.%s", protocols_l[i]);
@ -481,18 +480,16 @@ nsOperaProfileMigrator::CopyProxySettings(nsINIParser &aParser,
GetInteger(aParser, "Proxy", "Use Automatic Proxy Configuration", &enabled);
if (enabled)
networkProxyType = 2;
nsCAutoString configURL;
rv = aParser.GetString("Proxy", "Automatic Proxy Configuration URL",
configURL);
if (NS_SUCCEEDED(rv))
aBranch->SetCharPref("network.proxy.autoconfig_url", configURL.get());
nsXPIDLCString configURL;
err = aParser->GetStringAlloc("Proxy", "Automatic Proxy Configuration URL", getter_Copies(configURL), &length);
if (err == nsINIParser::OK)
aBranch->SetCharPref("network.proxy.autoconfig_url", configURL);
GetInteger(aParser, "Proxy", "No Proxy Servers Check", &enabled);
if (enabled) {
nsCAutoString servers;
rv = aParser.GetString("Proxy", "No Proxy Servers", servers);
if (NS_SUCCEEDED(rv))
nsXPIDLCString servers;
err = aParser->GetStringAlloc("Proxy", "No Proxy Servers", getter_Copies(servers), &length);
if (err == nsINIParser::OK)
ParseOverrideServers(servers.get(), aBranch);
}
@ -502,26 +499,28 @@ nsOperaProfileMigrator::CopyProxySettings(nsINIParser &aParser,
}
nsresult
nsOperaProfileMigrator::GetInteger(nsINIParser &aParser,
nsOperaProfileMigrator::GetInteger(nsINIParser* aParser,
char* aSectionName,
char* aKeyName,
PRInt32* aResult)
{
nsCAutoString val;
char val[20];
PRInt32 length = 20;
nsresult rv = aParser.GetString(aSectionName, aKeyName, val);
if (NS_FAILED(rv))
return rv;
PRInt32 err = aParser->GetString(aSectionName, aKeyName, val, &length);
if (err != nsINIParser::OK)
return NS_ERROR_FAILURE;
*aResult = val.ToInteger((PRInt32*) &rv);
nsCAutoString valueStr((char*)val);
PRInt32 stringErr;
*aResult = valueStr.ToInteger(&stringErr);
return rv;
return NS_OK;
}
nsresult
nsOperaProfileMigrator::ParseColor(nsINIParser &aParser,
char* aSectionName, char** aResult)
nsOperaProfileMigrator::ParseColor(nsINIParser* aParser, char* aSectionName, char** aResult)
{
nsresult rv;
PRInt32 r, g, b;
@ -542,37 +541,34 @@ nsOperaProfileMigrator::ParseColor(nsINIParser &aParser,
}
nsresult
nsOperaProfileMigrator::CopyUserContentSheet(nsINIParser &aParser)
nsOperaProfileMigrator::CopyUserContentSheet(nsINIParser* aParser)
{
nsresult rv;
nsresult rv = NS_OK;
nsCAutoString userContentCSS;
rv = aParser.GetString("User Prefs", "Local CSS File", userContentCSS);
if (NS_FAILED(rv) || userContentCSS.Length() == 0)
return NS_OK;
nsXPIDLCString userContentCSS;
PRInt32 size;
PRInt32 err = aParser->GetStringAlloc("User Prefs", "Local CSS File", getter_Copies(userContentCSS), &size);
if (err == nsINIParser::OK && userContentCSS.Length() > 0) {
// Copy the file
nsCOMPtr<nsILocalFile> userContentCSSFile(do_CreateInstance("@mozilla.org/file/local;1"));
if (!userContentCSSFile)
return NS_ERROR_OUT_OF_MEMORY;
// Copy the file
nsCOMPtr<nsILocalFile> userContentCSSFile;
rv = NS_NewNativeLocalFile(userContentCSS, PR_TRUE,
getter_AddRefs(userContentCSSFile));
if (NS_FAILED(rv))
return NS_OK;
userContentCSSFile->InitWithNativePath(userContentCSS);
PRBool exists;
userContentCSSFile->Exists(&exists);
if (!exists)
return NS_OK;
PRBool exists;
rv = userContentCSSFile->Exists(&exists);
if (NS_FAILED(rv) || !exists)
return NS_OK;
nsCOMPtr<nsIFile> profileChromeDir;
NS_GetSpecialDirectory(NS_APP_USER_CHROME_DIR,
getter_AddRefs(profileChromeDir));
if (!profileChromeDir)
return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsIFile> profileChromeDir;
NS_GetSpecialDirectory(NS_APP_USER_CHROME_DIR,
getter_AddRefs(profileChromeDir));
if (!profileChromeDir)
return NS_OK;
userContentCSSFile->CopyToNative(profileChromeDir,
NS_LITERAL_CSTRING("userContent.css"));
return NS_OK;
rv = userContentCSSFile->CopyToNative(profileChromeDir, nsDependentCString("userContent.css"));
}
return rv;
}
nsresult
@ -1055,20 +1051,17 @@ nsOperaProfileMigrator::CopySmartKeywords(nsIBookmarksService* aBMS,
nsIStringBundle* aBundle,
nsIRDFResource* aParentFolder)
{
nsresult rv;
nsresult rv = NS_OK;
nsCOMPtr<nsIFile> smartKeywords;
mOperaProfile->Clone(getter_AddRefs(smartKeywords));
smartKeywords->Append(NS_LITERAL_STRING("search.ini"));
nsCOMPtr<nsILocalFile> lf(do_QueryInterface(smartKeywords));
if (!lf)
return NS_OK;
nsINIParser parser;
rv = parser.Init(lf);
if (NS_FAILED(rv))
return NS_OK;
nsCAutoString path;
smartKeywords->GetNativePath(path);
nsINIParser* parser = new nsINIParser(path.get());
if (!parser)
return NS_ERROR_OUT_OF_MEMORY;
nsXPIDLString sourceNameOpera;
aBundle->GetStringFromName(NS_LITERAL_STRING("sourceNameOpera").get(),
@ -1085,32 +1078,31 @@ nsOperaProfileMigrator::CopySmartKeywords(nsIBookmarksService* aBMS,
aParentFolder, -1, getter_AddRefs(keywordsFolder));
PRInt32 sectionIndex = 1;
nsCAutoString name, url, keyword;
char section[35];
nsXPIDLCString name, url, keyword;
PRInt32 keyValueLength = 0;
do {
nsCAutoString section("Search Engine ");
section.AppendInt(sectionIndex++);
rv = parser.GetString(section.get(), "Name", name);
if (NS_FAILED(rv))
sprintf(section, "Search Engine %d", sectionIndex++);
PRInt32 err = parser->GetStringAlloc(section, "Name", getter_Copies(name), &keyValueLength);
if (err != nsINIParser::OK)
break;
rv = parser.GetString(section.get(), "URL", url);
if (NS_FAILED(rv))
err = parser->GetStringAlloc(section, "URL", getter_Copies(url), &keyValueLength);
if (err != nsINIParser::OK)
continue;
rv = parser.GetString(section.get(), "Key", keyword);
if (NS_FAILED(rv))
err = parser->GetStringAlloc(section, "Key", getter_Copies(keyword), &keyValueLength);
if (err != nsINIParser::OK)
continue;
PRInt32 post;
rv = GetInteger(parser, section.get(), "Is post", &post);
if (NS_SUCCEEDED(rv) && post)
err = GetInteger(parser, section, "Is post", &post);
if (post)
continue;
if (url.IsEmpty() || keyword.IsEmpty() || name.IsEmpty())
continue;
NS_ConvertUTF8toUCS2 nameStr(name);
nsAutoString nameStr; nameStr.Assign(NS_ConvertUTF8toUCS2(name));
PRUint32 length = nameStr.Length();
PRInt32 index = 0;
do {
@ -1160,6 +1152,11 @@ nsOperaProfileMigrator::CopySmartKeywords(nsIBookmarksService* aBMS,
}
while (1);
if (parser) {
delete parser;
parser = nsnull;
}
return rv;
}
#endif

Просмотреть файл

@ -92,10 +92,10 @@ public:
protected:
nsresult CopyPreferences(PRBool aReplace);
nsresult ParseColor(nsINIParser &aParser, char* aSectionName, char** aResult);
nsresult CopyUserContentSheet(nsINIParser &aParser);
nsresult CopyProxySettings(nsINIParser &aParser, nsIPrefBranch* aBranch);
nsresult GetInteger(nsINIParser &aParser, char* aSectionName,
nsresult ParseColor(nsINIParser* aParser, char* aSectionName, char** aResult);
nsresult CopyUserContentSheet(nsINIParser* aParser);
nsresult CopyProxySettings(nsINIParser* aParser, nsIPrefBranch* aBranch);
nsresult GetInteger(nsINIParser* aParser, char* aSectionName,
char* aKeyName, PRInt32* aResult);
nsresult CopyCookies(PRBool aReplace);

Просмотреть файл

@ -51,7 +51,6 @@
#include "xptinfo.h"
#include "nsXPIDLString.h"
#include "nsReadableUtils.h"
#include "nsHashKeys.h"
#include "nsDOMClassInfo.h"
#include "nsCRT.h"

Просмотреть файл

@ -207,9 +207,7 @@ JS_DHashTableInit(JSDHashTable *table, const JSDHashTableOps *ops, void *data,
table->data = data;
if (capacity < JS_DHASH_MIN_SIZE)
capacity = JS_DHASH_MIN_SIZE;
JS_CEILING_LOG2(log2, capacity);
log2 = JS_CeilingLog2(capacity);
capacity = JS_BIT(log2);
if (capacity >= JS_DHASH_SIZE_LIMIT)
return JS_FALSE;
@ -603,7 +601,7 @@ JS_PUBLIC_API(uint32)
JS_DHashTableEnumerate(JSDHashTable *table, JSDHashEnumerator etor, void *arg)
{
char *entryAddr, *entryLimit;
uint32 i, capacity, entrySize, ceiling;
uint32 i, capacity, entrySize;
JSBool didRemove;
JSDHashEntryHdr *entry;
JSDHashOperator op;
@ -645,11 +643,9 @@ JS_DHashTableEnumerate(JSDHashTable *table, JSDHashEnumerator etor, void *arg)
capacity += capacity >> 1;
if (capacity < JS_DHASH_MIN_SIZE)
capacity = JS_DHASH_MIN_SIZE;
JS_CEILING_LOG2(ceiling, capacity);
ceiling -= JS_DHASH_BITS - table->hashShift;
(void) ChangeTable(table, ceiling);
(void) ChangeTable(table,
JS_CeilingLog2(capacity)
- (JS_DHASH_BITS - table->hashShift));
}
return i;
}

Просмотреть файл

@ -439,7 +439,7 @@ JS_DHashTableInit(JSDHashTable *table, const JSDHashTableOps *ops, void *data,
* we don't shrink on the very next remove after growing a table upon adding
* an entry that brings entryCount past maxAlpha * tableSize.
*/
extern JS_PUBLIC_API(void)
JS_PUBLIC_API(void)
JS_DHashTableSetAlphaBounds(JSDHashTable *table,
float maxAlpha,
float minAlpha);

Просмотреть файл

@ -4,7 +4,7 @@
* GENERATED BY js/src/plify_jsdhash.sed -- DO NOT EDIT!!!
s/jsdhash_h___/pldhash_h___/
s/jsdhash\.bigdump/pldhash.bigdump/
s/jstypes\.h/nscore.h/
s/jstypes\.h/prtypes.h/
s/jsbit\.h/prbit.h/
s/jsdhash\.h/pldhash.h/
s/jsdhash\.c/pldhash.c/
@ -23,8 +23,8 @@ s/\([^U]\)int32/\1PRInt32/g
s/uint16/PRUint16/g
s/\([^U]\)int16/\1PRInt16/g
s/JSBool/PRBool/g
s/extern JS_PUBLIC_API(\([^()]*\))/NS_COM_GLUE \1/
s/JS_PUBLIC_API(\([^()]*\))/\1/
s/extern JS_PUBLIC_API/PR_EXTERN/
s/JS_PUBLIC_API/PR_IMPLEMENT/
s/JS_DLL_CALLBACK/PR_CALLBACK/
s/JS_STATIC_DLL_CALLBACK/PR_STATIC_CALLBACK/
s/JS_NewDHashTable/PL_NewDHashTable/

Просмотреть файл

@ -91,7 +91,6 @@
#include "nsITextContent.h"
#include "prlog.h"
#include "nsCOMPtr.h"
#include "nsHashKeys.h"
#include "nsStyleUtil.h"
#include "nsQuickSort.h"
#include "nsContentUtils.h"

Просмотреть файл

@ -60,6 +60,7 @@ LOCAL_INCLUDES = \
CPPSRCS = \
nsProfileLock.cpp \
nsToolkitProfileService.cpp \
nsINIParser.cpp \
$(NULL)
GARBAGE += nsProfileLock.cpp

Просмотреть файл

Просмотреть файл

Просмотреть файл

@ -403,37 +403,37 @@ nsToolkitProfileService::Init()
nsINIParser parser;
rv = parser.Init(mListFile);
// Init does not fail on parsing errors, only on OOM/really unexpected
// conditions.
if (NS_FAILED(rv))
return rv;
// Parsing errors are troublesome... we're gonna continue even on
// parsing errors, and let people manually re-locate their profile
// if something goes wacky
nsCAutoString buffer;
rv = parser.GetString("General", "StartWithLastProfile", buffer);
if (NS_SUCCEEDED(rv) && buffer.EqualsLiteral("0"))
char parserBuf[MAXPATHLEN];
rv = parser.GetString("General", "StartWithLastProfile", parserBuf, MAXPATHLEN);
if (NS_SUCCEEDED(rv) && strcmp("0", parserBuf) == 0)
mStartWithLast = PR_FALSE;
nsToolkitProfile* currentProfile = nsnull;
nsCAutoString filePath;
unsigned int c = 0;
for (c = 0; PR_TRUE; ++c) {
nsCAutoString profileID("Profile");
profileID.AppendInt(c);
char profileID[12];
sprintf(profileID, "Profile%u", c);
rv = parser.GetString(profileID.get(), "IsRelative", buffer);
rv = parser.GetString(profileID, "IsRelative", parserBuf, MAXPATHLEN);
if (NS_FAILED(rv)) break;
PRBool isRelative = buffer.EqualsLiteral("1");
PRBool isRelative = (strcmp(parserBuf, "1") == 0);
nsCAutoString filePath;
rv = parser.GetString(profileID.get(), "Path", filePath);
rv = parser.GetString(profileID, "Path", parserBuf, MAXPATHLEN);
if (NS_FAILED(rv)) {
NS_ERROR("Malformed profiles.ini: Path= not found");
continue;
}
rv = parser.GetString(profileID.get(), "Name", buffer);
filePath = parserBuf;
rv = parser.GetString(profileID, "Name", parserBuf, MAXPATHLEN);
if (NS_FAILED(rv)) {
NS_ERROR("Malformed profiles.ini: Name= not found");
continue;
@ -462,13 +462,13 @@ nsToolkitProfileService::Init()
localDir = rootDir;
}
currentProfile = new nsToolkitProfile(buffer,
currentProfile = new nsToolkitProfile(nsDependentCString(parserBuf),
rootDir, localDir,
currentProfile);
NS_ENSURE_TRUE(currentProfile, NS_ERROR_OUT_OF_MEMORY);
rv = parser.GetString(profileID.get(), "Default", buffer);
if (NS_SUCCEEDED(rv) && buffer.EqualsLiteral("1"))
rv = parser.GetString(profileID, "Default", parserBuf, MAXPATHLEN);
if (NS_SUCCEEDED(rv) && strcmp("1", parserBuf) == 0)
mChosen = currentProfile;
}

Просмотреть файл

@ -1647,20 +1647,21 @@ CheckCompatibility(nsIFile* aProfileDir, const nsCString& aVersion,
if (NS_FAILED(rv))
return PR_FALSE;
nsCAutoString buf;
rv = parser.GetString("Compatibility", "LastVersion", buf);
char buffer[MAXPATHLEN];
rv = parser.GetString("Compatibility", "LastVersion", buffer, sizeof(buffer));
if (NS_FAILED(rv))
return PR_FALSE;
if (!aVersion.Equals(buf))
if (!aVersion.Equals(buffer))
return PR_FALSE;
rv = parser.GetString("Compatibility", "LastPlatformDir", buf);
rv = parser.GetString("Compatibility", "LastPlatformDir",
buffer, sizeof(buffer));
if (NS_FAILED(rv))
return PR_FALSE;
nsCOMPtr<nsILocalFile> lf;
rv = NS_NewNativeLocalFile(buf, PR_FALSE,
rv = NS_NewNativeLocalFile(nsDependentCString(buffer), PR_FALSE,
getter_AddRefs(lf));
if (NS_FAILED(rv))
return PR_FALSE;
@ -1671,11 +1672,12 @@ CheckCompatibility(nsIFile* aProfileDir, const nsCString& aVersion,
return PR_FALSE;
if (aAppDir) {
rv = parser.GetString("Compatibility", "LastAppDir", buf);
rv = parser.GetString("Compatibility", "LastAppDir",
buffer, sizeof(buffer));
if (NS_FAILED(rv))
return PR_FALSE;
rv = NS_NewNativeLocalFile(buf, PR_FALSE,
rv = NS_NewNativeLocalFile(nsDependentCString(buffer), PR_FALSE,
getter_AddRefs(lf));
if (NS_FAILED(rv))
return PR_FALSE;

Просмотреть файл

@ -314,9 +314,7 @@ LoadDirsIntoArray(nsIFile* aComponentsList, const char* aSection,
{
nsINIParser parser;
nsCOMPtr<nsILocalFile> lf(do_QueryInterface(aComponentsList));
nsresult rv = parser.Init(lf);
if (NS_FAILED(rv))
return;
parser.Init(lf);
NS_NAMED_LITERAL_CSTRING(platform, "platform");
NS_NAMED_LITERAL_CSTRING(osTarget, OS_TARGET);
@ -324,13 +322,14 @@ LoadDirsIntoArray(nsIFile* aComponentsList, const char* aSection,
NS_NAMED_LITERAL_CSTRING(targetOSABI, TARGET_OS_ABI);
#endif
nsresult rv;
char parserBuf[MAXPATHLEN];
char buf[18];
PRInt32 i = 0;
do {
nsCAutoString buf("Extension");
buf.AppendInt(i++);
sprintf(buf, "Extension%d", i++);
nsCAutoString path;
rv = parser.GetString(aSection, buf.get(), path);
rv = parser.GetString(aSection, buf, parserBuf, MAXPATHLEN);
if (NS_FAILED(rv))
break;
@ -342,7 +341,7 @@ LoadDirsIntoArray(nsIFile* aComponentsList, const char* aSection,
#ifdef TARGET_OS_ABI
nsCOMPtr<nsIFile> platformABIDir;
#endif
rv = dir->SetPersistentDescriptor(path);
rv = dir->SetPersistentDescriptor(nsDependentCString(parserBuf));
if (NS_FAILED(rv))
continue;

Просмотреть файл

@ -73,13 +73,9 @@ ifneq (,$(filter mac cocoa,$(MOZ_WIDGET_TOOLKIT)))
REQUIRES += macmorefiles
endif
CSRCS = \
$(XPCOM_GLUE_SRC_LCSRCS) \
$(NULL)
CPPSRCS = \
$(XPCOM_GLUE_SRC_LCPPSRCS) \
$(XPCOM_GLUENS_SRC_LCPPSRCS) \
$(XPCOM_GLUE_SRC_LCSRCS) \
$(XPCOM_GLUENS_SRC_LCSRCS) \
nsXPComInit.cpp \
nsStringAPI.cpp \
$(NULL)
@ -182,5 +178,5 @@ EXTRA_DSO_LDOPTS += $(call EXPAND_LIBNAME,imagehlp)
endif
endif # WINNT
export:: $(XPCOM_GLUE_SRC_CSRCS) $(XPCOM_GLUE_SRC_CPPSRCS) $(XPCOM_GLUENS_SRC_CPPSRCS)
export:: $(XPCOM_GLUE_SRC_CSRCS) $(XPCOM_GLUENS_SRC_CSRCS)
$(INSTALL) $^ .

Просмотреть файл

@ -52,6 +52,10 @@ REQUIRES = \
string \
$(NULL)
CSRCS = \
pldhash.c \
$(NULL)
CPPSRCS = \
nsAtomTable.cpp \
nsAtomService.cpp \
@ -75,6 +79,7 @@ CPPSRCS = \
nsSupportsArray.cpp \
nsSupportsArrayEnumerator.cpp \
nsSupportsPrimitives.cpp \
nsTHashtable.cpp \
nsUnicharBuffer.cpp \
nsVariant.cpp \
nsVoidArray.cpp \
@ -89,29 +94,37 @@ CPPSRCS = \
EXPORTS = \
nsAtomService.h \
nsBaseHashtable.h \
nsCheapSets.h \
nsClassHashtable.h \
nsCppSharedAllocator.h \
nsCRT.h \
nsDataHashtable.h \
nsDeque.h \
nsDoubleHashtable.h \
nsEnumeratorUtils.h \
nsFixedSizeAllocator.h \
nsHashSets.h \
nsHashKeys.h \
nsHashtable.h \
nsIByteBuffer.h \
nsIUnicharBuffer.h \
nsInt64.h \
nsInterfaceHashtable.h \
nsObserverService.h \
nsQuickSort.h \
nsRecyclingAllocator.h \
nsRefPtrHashtable.h \
nsStaticNameTable.h \
nsStaticAtom.h \
nsSupportsArray.h \
nsSupportsPrimitives.h \
nsTHashtable.h \
nsTime.h \
nsUnitConversion.h \
nsVariant.h \
nsVoidArray.h \
pldhash.h \
nsTextFormatter.h \
nsValueArray.h \
nsArray.h \

Просмотреть файл

Просмотреть файл

Просмотреть файл

@ -45,7 +45,7 @@
#include "pldhash.h"
#include "nscore.h"
#include "nsString.h"
#include "nsHashKeys.h"
#include "nsReadableUtils.h"
/*
* This file provides several major things to make PLDHashTable easier to use:

0
xpcom/ds/nsHashKeys.h Normal file
Просмотреть файл

Просмотреть файл

Просмотреть файл

@ -37,7 +37,6 @@
#include "nsProperties.h"
#include "nsString.h"
#include "nsCRT.h"
////////////////////////////////////////////////////////////////////////////////

Просмотреть файл

0
xpcom/ds/nsTHashtable.h Normal file
Просмотреть файл

0
xpcom/ds/pldhash.c Normal file
Просмотреть файл

0
xpcom/ds/pldhash.h Normal file
Просмотреть файл

Просмотреть файл

@ -56,25 +56,9 @@ LOCAL_INCLUDES = \
-I$(srcdir)/../build \
$(NULL)
CSRCS = \
$(XPCOM_GLUE_SRC_LCSRCS) \
$(NULL)
CPPSRCS = \
$(XPCOM_GLUE_SRC_LCPPSRCS) \
$(XPCOM_GLUENS_SRC_LCPPSRCS) \
$(NULL)
EXPORTS = \
pldhash.h \
nsBaseHashtable.h \
nsClassHashtable.h \
nsDataHashtable.h \
nsHashKeys.h \
nsINIParser.h \
nsInterfaceHashtable.h \
nsRefPtrHashtable.h \
nsTHashtable.h \
$(XPCOM_GLUE_SRC_LCSRCS) \
$(XPCOM_GLUENS_SRC_LCSRCS) \
$(NULL)
SDK_HEADERS = \

Просмотреть файл

@ -38,22 +38,16 @@
#ifndef nsTHashKeys_h__
#define nsTHashKeys_h__
#include "nsAString.h"
#include "nsString.h"
#include "nsID.h"
#include "nsCRT.h"
#include "nsReadableUtils.h"
#include "nsISupports.h"
#include "nsCOMPtr.h"
#include "pldhash.h"
#include NEW_H
#ifdef MOZILLA_INTERNAL_API
#include "nsAString.h"
#include "nsString.h"
#else
#include "nsStringAPI.h"
#endif
#include <stdlib.h>
#include <string.h>
/** @file nsHashKeys.h
* standard HashKey classes for nsBaseHashtable and relatives. Each of these
* classes follows the nsTHashtable::EntryType specification
@ -67,10 +61,6 @@
* nsDepCharHashKey
*/
NS_COM_GLUE PRUint32 HashString(const nsAString& aStr);
NS_COM_GLUE PRUint32 HashString(const nsACString& aStr);
NS_COM_GLUE PRUint32 HashCString(const char* aKey);
/**
* hashkey wrapper using nsAString KeyType
*
@ -284,7 +274,7 @@ public:
}
static const char* KeyToPointer(const char* aKey) { return aKey; }
static PLDHashNumber HashKey(const char* aKey) { return HashCString(aKey); }
static PLDHashNumber HashKey(const char* aKey) { return nsCRT::HashCode(aKey); }
enum { ALLOW_MEMMOVE = PR_TRUE };
private:
@ -314,7 +304,7 @@ public:
}
static KeyTypePointer KeyToPointer(KeyType aKey) { return aKey; }
static PLDHashNumber HashKey(KeyTypePointer aKey) { return HashCString(aKey); }
static PLDHashNumber HashKey(KeyTypePointer aKey) { return nsCRT::HashCode(aKey); }
enum { ALLOW_MEMMOVE = PR_TRUE };

Просмотреть файл

@ -1,310 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Samir Gehani <sgehani@netscape.com>
* Benjamin Smedberg <bsmedberg@covad.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsINIParser.h"
#include "nsError.h"
#include "nsILocalFile.h"
#include <stdlib.h>
#include <stdio.h>
// Stack based FILE wrapper to ensure that fclose is called, copied from
// toolkit/mozapps/update/src/updater/readstrings.cpp
class AutoFILE {
public:
AutoFILE(FILE *fp = nsnull) : fp_(fp) {}
~AutoFILE() { if (fp_) fclose(fp_); }
operator FILE *() { return fp_; }
FILE** operator &() { return &fp_; }
private:
FILE *fp_;
};
nsresult
nsINIParser::Init(nsILocalFile* aFile)
{
nsresult rv;
/* open the file */
AutoFILE fd;
rv = aFile->OpenANSIFileDesc("r", &fd);
if (NS_FAILED(rv))
return rv;
return InitFromFILE(fd);
}
nsresult
nsINIParser::Init(const char *aPath)
{
/* open the file */
AutoFILE fd = fopen(aPath, "r");
if (!fd)
return NS_ERROR_FAILURE;
return InitFromFILE(fd);
}
// copied from toolkit/mozapps/updater/src/updater/updater.cpp
// we could use nsCRT::strtok except that nsCRT isn't part of the glue,
// and may never be due to NSPR dependencies. This should probably be declared
// and exported in a string-management glue header.
static char*
mstrtok(const char *delims, char **str)
{
if (!*str || !**str)
return NULL;
// skip leading "whitespace"
char *ret = *str;
const char *d;
do {
for (d = delims; *d != '\0'; ++d) {
if (*ret == *d) {
++ret;
break;
}
}
} while (*d);
if (!*ret) {
*str = ret;
return NULL;
}
char *i = ret;
do {
for (d = delims; *d != '\0'; ++d) {
if (*i == *d) {
*i = '\0';
*str = ++i;
return ret;
}
}
++i;
} while (*i);
*str = NULL;
return ret;
}
static const char kNL[] = "\r\n";
static const char kEquals[] = "=";
static const char kWhitespace[] = " \t";
static const char kRBracket[] = "]";
nsresult
nsINIParser::InitFromFILE(FILE *fd)
{
if (!mSections.Init())
return NS_ERROR_OUT_OF_MEMORY;
/* get file size */
if (fseek(fd, 0, SEEK_END) != 0)
return NS_ERROR_FAILURE;
long flen = ftell(fd);
if (flen == 0)
return NS_ERROR_FAILURE;
/* malloc an internal buf the size of the file */
mFileContents = new char[flen + 1];
if (!mFileContents)
return NS_ERROR_OUT_OF_MEMORY;
/* read the file in one swoop */
if (fseek(fd, 0, SEEK_SET) != 0)
return NS_BASE_STREAM_OSERROR;
int rd = fread(mFileContents, sizeof(char), flen, fd);
if (rd != flen)
return NS_BASE_STREAM_OSERROR;
mFileContents[flen] = '\0';
char *buffer = mFileContents;
char *currSection = nsnull;
INIValue *last = nsnull;
// outer loop tokenizes into lines
while (char *line = mstrtok(kNL, &buffer)) {
if (line[0] == '#') // it's a comment
continue;
char *token = mstrtok(kWhitespace, &line);
if (!token) // empty line
continue;
if (token[0] == '[') { // section header!
++token;
currSection = token;
last = nsnull;
char *rb = mstrtok(kRBracket, &token);
if (!rb || mstrtok(kWhitespace, &token)) {
// there's either an unclosed [Section or a [Section]Moretext!
// we could frankly decide that this INI file is malformed right
// here and stop, but we won't... keep going, looking for
// a well-formed [section] to continue working with
currSection = nsnull;
}
continue;
}
if (!currSection) {
// If we haven't found a section header (or we found a malformed
// section header), don't bother parsing this line.
continue;
}
char *key = token;
char *e = mstrtok(kEquals, &token);
if (!e)
continue;
INIValue *val = new INIValue(key, token);
if (!val)
return NS_ERROR_OUT_OF_MEMORY;
// If we haven't already added something to this section, "last" will
// be null.
if (!last) {
mSections.Get(currSection, &last);
while (last && last->next)
last = last->next;
}
if (last) {
// Add this element on to the tail of the existing list
last->next = val;
last = val;
continue;
}
// We've never encountered this section before, add it to the head
mSections.Put(currSection, val);
}
return NS_OK;
}
nsresult
nsINIParser::GetString(const char *aSection, const char *aKey,
nsACString &aResult)
{
INIValue *val;
mSections.Get(aSection, &val);
while (val) {
if (strcmp(val->key, aKey) == 0) {
aResult.Assign(val->value);
return NS_OK;
}
val = val->next;
}
return NS_ERROR_FAILURE;
}
nsresult
nsINIParser::GetString(const char *aSection, const char *aKey,
char *aResult, PRUint32 aResultLen)
{
INIValue *val;
mSections.Get(aSection, &val);
while (val) {
if (strcmp(val->key, aKey) == 0) {
strncpy(aResult, val->value, aResultLen);
aResult[aResultLen - 1] = '\0';
if (strlen(val->value) >= aResultLen)
return NS_ERROR_LOSS_OF_SIGNIFICANT_DATA;
return NS_OK;
}
val = val->next;
}
return NS_ERROR_FAILURE;
}
PLDHashOperator
nsINIParser::GetSectionsCB(const char *aKey, INIValue *aData,
void *aClosure)
{
GSClosureStruct *cs = NS_REINTERPRET_CAST(GSClosureStruct*, aClosure);
return cs->usercb(aKey, cs->userclosure) ? PL_DHASH_NEXT : PL_DHASH_STOP;
}
nsresult
nsINIParser::GetSections(INISectionCallback aCB, void *aClosure)
{
GSClosureStruct gs = {
aCB,
aClosure
};
mSections.EnumerateRead(GetSectionsCB, &gs);
return NS_OK;
}
nsresult
nsINIParser::GetStrings(const char *aSection,
INIStringCallback aCB, void *aClosure)
{
INIValue *val;
for (mSections.Get(aSection, &val);
val;
val = val->next) {
if (!aCB(val->key, val->value, aClosure))
return NS_OK;
}
return NS_OK;
}

Просмотреть файл

@ -1,158 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Samir Gehani <sgehani@netscape.com>
* Benjamin Smedberg <bsmedberg@covad.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// This file was shamelessly copied from mozilla/xpinstall/wizard/unix/src2
#ifndef nsINIParser_h__
#define nsINIParser_h__
#include "nscore.h"
#include "nsClassHashtable.h"
#include "nsAutoPtr.h"
#include <stdio.h>
class nsILocalFile;
class NS_COM_GLUE nsINIParser
{
public:
nsINIParser() { }
~nsINIParser() { }
/**
* Initialize the INIParser with a nsILocalFile. If this method fails, no
* other methods should be called. This method reads and parses the file,
* the class does not hold a file handle open. An instance must only be
* initialized once.
*/
nsresult Init(nsILocalFile* aFile);
/**
* Initialize the INIParser with a file path. If this method fails, no
* other methods should be called. This method reads and parses the file,
* the class does not hold a file handle open. An instance must only
* be initialized once.
*/
nsresult Init(const char *aPath);
/**
* Callback for GetSections
* @return PR_FALSE to stop enumeration, or PR_TRUE to continue.
*/
typedef PRBool
(* PR_CALLBACK INISectionCallback)(const char *aSection,
void *aClosure);
/**
* Enumerate the sections within the INI file.
*/
nsresult GetSections(INISectionCallback aCB, void *aClosure);
/**
* Callback for GetStrings
* @return PR_FALSE to stop enumeration, or PR_TRUE to continue
*/
typedef PRBool
(* PR_CALLBACK INIStringCallback)(const char *aString,
const char *aValue,
void *aClosure);
/**
* Enumerate the strings within a section. If the section does
* not exist, this function will silently return.
*/
nsresult GetStrings(const char *aSection,
INIStringCallback aCB, void *aClosure);
/**
* Get the value of the specified key in the specified section
* of the INI file represented by this instance.
*
* @param aSection section name
* @param aKey key name
* @param aResult the value found
* @throws NS_ERROR_FAILURE if the specified section/key could not be
* found.
*/
nsresult GetString(const char *aSection, const char *aKey,
nsACString &aResult);
/**
* Alternate signature of GetString that uses a pre-allocated buffer
* instead of a nsACString (for use in the standalone glue before
* the glue is initialized).
*
* @throws NS_ERROR_LOSS_OF_SIGNIFICANT_DATA if the aResult buffer is not
* large enough for the data. aResult will be filled with as
* much data as possible.
*
* @see GetString [1]
*/
nsresult GetString(const char *aSection, const char* aKey,
char *aResult, PRUint32 aResultLen);
private:
struct INIValue
{
INIValue(const char *aKey, const char *aValue)
: key(aKey), value(aValue) { }
const char *key;
const char *value;
nsAutoPtr<INIValue> next;
};
struct GSClosureStruct
{
INISectionCallback usercb;
void *userclosure;
};
nsClassHashtable<nsDepCharHashKey, INIValue> mSections;
nsAutoArrayPtr<char> mFileContents;
nsresult InitFromFILE(FILE *fd);
static PLDHashOperator GetSectionsCB(const char *aKey,
INIValue *aData, void *aClosure);
};
#endif /* nsINIParser_h__ */

Просмотреть файл

@ -38,65 +38,6 @@
#include "nsTHashtable.h"
#include "nsHashKeys.h"
PRUint32
HashString( const nsAString& aStr )
{
PRUint32 code = 0;
#ifdef MOZILLA_INTERNAL_API
nsAString::const_iterator begin, end;
aStr.BeginReading(begin);
aStr.EndReading(end);
#else
const PRUnichar *begin, *end;
PRUint32 len = NS_StringGetData(aStr, &begin);
end = begin + len;
#endif
while (begin != end) {
code = (code>>28) ^ (code<<4) ^ PRUint32(*begin);
++begin;
}
return code;
}
PRUint32
HashString( const nsACString& aStr )
{
PRUint32 code = 0;
#ifdef MOZILLA_INTERNAL_API
nsACString::const_iterator begin, end;
aStr.BeginReading(begin);
aStr.EndReading(end);
#else
const char *begin, *end;
PRUint32 len = NS_CStringGetData(aStr, &begin);
end = begin + len;
#endif
while (begin != end) {
code = (code>>28) ^ (code<<4) ^ PRUint32(*begin);
++begin;
}
return code;
}
PRUint32
HashCString(const char *str)
{
PRUint32 code = 0;
while (*str) {
code = (code>>28) ^ (code<<4) ^ PRUint32(*str);
++str;
}
return code;
}
PR_IMPLEMENT(PLDHashOperator)
PL_DHashStubEnumRemove(PLDHashTable *table,
PLDHashEntryHdr *entry,

Просмотреть файл

@ -34,35 +34,27 @@
#
# ***** END LICENSE BLOCK *****
XPCOM_GLUE_SRC_LCSRCS = \
pldhash.c \
$(NULL)
XPCOM_GLUE_SRC_LCSRCS = \
nsCOMPtr.cpp \
nsComponentManagerUtils.cpp \
nsDebug.cpp \
nsID.cpp \
nsIInterfaceRequestorUtils.cpp \
nsMemory.cpp \
nsTraceRefcnt.cpp \
nsWeakReference.cpp \
nsGREGlue.cpp \
nsVersionComparator.cpp \
$(NULL)
XPCOM_GLUE_SRC_CSRCS = $(addprefix $(topsrcdir)/xpcom/glue/, $(XPCOM_GLUE_SRC_LCSRCS))
XPCOM_GLUE_SRC_LCPPSRCS = \
nsCOMPtr.cpp \
nsComponentManagerUtils.cpp \
nsDebug.cpp \
nsID.cpp \
nsIInterfaceRequestorUtils.cpp \
nsINIParser.cpp \
nsMemory.cpp \
nsTraceRefcnt.cpp \
nsWeakReference.cpp \
nsGREGlue.cpp \
nsVersionComparator.cpp \
nsTHashtable.cpp \
$(NULL)
XPCOM_GLUE_SRC_CPPSRCS = $(addprefix $(topsrcdir)/xpcom/glue/, $(XPCOM_GLUE_SRC_LCPPSRCS))
XPCOM_GLUE_SRC_CSRCS := $(addprefix $(topsrcdir)/xpcom/glue/, $(XPCOM_GLUE_SRC_LCSRCS))
# nsGenericFactory is not really all that helpful in the standalone glue,
# and it has a bad dependency on the NSPR AtomicIncrement function, so we
# only build it for the dependent XPCOM glue and builtin to xpcom-core.
XPCOM_GLUENS_SRC_LCPPSRCS = \
nsGenericFactory.cpp \
$(NULL)
XPCOM_GLUENS_SRC_LCSRCS = \
nsGenericFactory.cpp \
$(NULL)
XPCOM_GLUENS_SRC_CPPSRCS = $(addprefix $(topsrcdir)/xpcom/glue/,$(XPCOM_GLUENS_SRC_LCPPSRCS))
XPCOM_GLUENS_SRC_CSRCS := $(addprefix $(topsrcdir)/xpcom/glue/,$(XPCOM_GLUENS_SRC_LCSRCS))

Просмотреть файл

@ -1,768 +0,0 @@
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla JavaScript code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1999-2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Brendan Eich <brendan@mozilla.org> (Original Author)
* Chris Waterson <waterson@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* Double hashing implementation.
* GENERATED BY js/src/plify_jsdhash.sed -- DO NOT EDIT!!!
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "prbit.h"
#include "pldhash.h"
#include "prlog.h" /* for PR_ASSERT */
#ifdef PL_DHASHMETER
# if defined MOZILLA_CLIENT && defined DEBUG_XXXbrendan
# include "nsTraceMalloc.h"
# endif
# define METER(x) x
#else
# define METER(x) /* nothing */
#endif
void *
PL_DHashAllocTable(PLDHashTable *table, PRUint32 nbytes)
{
return malloc(nbytes);
}
void
PL_DHashFreeTable(PLDHashTable *table, void *ptr)
{
free(ptr);
}
PLDHashNumber
PL_DHashStringKey(PLDHashTable *table, const void *key)
{
PLDHashNumber h;
const unsigned char *s;
h = 0;
for (s = key; *s != '\0'; s++)
h = (h >> (PL_DHASH_BITS - 4)) ^ (h << 4) ^ *s;
return h;
}
const void *
PL_DHashGetKeyStub(PLDHashTable *table, PLDHashEntryHdr *entry)
{
PLDHashEntryStub *stub = (PLDHashEntryStub *)entry;
return stub->key;
}
PLDHashNumber
PL_DHashVoidPtrKeyStub(PLDHashTable *table, const void *key)
{
return (PLDHashNumber)(unsigned long)key >> 2;
}
PRBool
PL_DHashMatchEntryStub(PLDHashTable *table,
const PLDHashEntryHdr *entry,
const void *key)
{
const PLDHashEntryStub *stub = (const PLDHashEntryStub *)entry;
return stub->key == key;
}
PRBool
PL_DHashMatchStringKey(PLDHashTable *table,
const PLDHashEntryHdr *entry,
const void *key)
{
const PLDHashEntryStub *stub = (const PLDHashEntryStub *)entry;
/* XXX tolerate null keys on account of sloppy Mozilla callers. */
return stub->key == key ||
(stub->key && key && strcmp(stub->key, key) == 0);
}
void
PL_DHashMoveEntryStub(PLDHashTable *table,
const PLDHashEntryHdr *from,
PLDHashEntryHdr *to)
{
memcpy(to, from, table->entrySize);
}
void
PL_DHashClearEntryStub(PLDHashTable *table, PLDHashEntryHdr *entry)
{
memset(entry, 0, table->entrySize);
}
void
PL_DHashFreeStringKey(PLDHashTable *table, PLDHashEntryHdr *entry)
{
const PLDHashEntryStub *stub = (const PLDHashEntryStub *)entry;
free((void *) stub->key);
memset(entry, 0, table->entrySize);
}
void
PL_DHashFinalizeStub(PLDHashTable *table)
{
}
static const PLDHashTableOps stub_ops = {
PL_DHashAllocTable,
PL_DHashFreeTable,
PL_DHashGetKeyStub,
PL_DHashVoidPtrKeyStub,
PL_DHashMatchEntryStub,
PL_DHashMoveEntryStub,
PL_DHashClearEntryStub,
PL_DHashFinalizeStub,
NULL
};
const PLDHashTableOps *
PL_DHashGetStubOps(void)
{
return &stub_ops;
}
PLDHashTable *
PL_NewDHashTable(const PLDHashTableOps *ops, void *data, PRUint32 entrySize,
PRUint32 capacity)
{
PLDHashTable *table;
table = (PLDHashTable *) malloc(sizeof *table);
if (!table)
return NULL;
if (!PL_DHashTableInit(table, ops, data, entrySize, capacity)) {
free(table);
return NULL;
}
return table;
}
void
PL_DHashTableDestroy(PLDHashTable *table)
{
PL_DHashTableFinish(table);
free(table);
}
PRBool
PL_DHashTableInit(PLDHashTable *table, const PLDHashTableOps *ops, void *data,
PRUint32 entrySize, PRUint32 capacity)
{
int log2;
PRUint32 nbytes;
#ifdef DEBUG
if (entrySize > 10 * sizeof(void *)) {
fprintf(stderr,
"pldhash: for the table at address %p, the given entrySize"
" of %lu %s favors chaining over double hashing.\n",
(void *)table,
(unsigned long) entrySize,
(entrySize > 16 * sizeof(void*)) ? "definitely" : "probably");
}
#endif
table->ops = ops;
table->data = data;
if (capacity < PL_DHASH_MIN_SIZE)
capacity = PL_DHASH_MIN_SIZE;
PR_CEILING_LOG2(log2, capacity);
capacity = PR_BIT(log2);
if (capacity >= PL_DHASH_SIZE_LIMIT)
return PR_FALSE;
table->hashShift = PL_DHASH_BITS - log2;
table->maxAlphaFrac = 0xC0; /* .75 */
table->minAlphaFrac = 0x40; /* .25 */
table->entrySize = entrySize;
table->entryCount = table->removedCount = 0;
table->generation = 0;
nbytes = capacity * entrySize;
table->entryStore = ops->allocTable(table, nbytes);
if (!table->entryStore)
return PR_FALSE;
memset(table->entryStore, 0, nbytes);
METER(memset(&table->stats, 0, sizeof table->stats));
return PR_TRUE;
}
/*
* Compute max and min load numbers (entry counts) from table params.
*/
#define MAX_LOAD(table, size) (((table)->maxAlphaFrac * (size)) >> 8)
#define MIN_LOAD(table, size) (((table)->minAlphaFrac * (size)) >> 8)
void
PL_DHashTableSetAlphaBounds(PLDHashTable *table,
float maxAlpha,
float minAlpha)
{
PRUint32 size;
/*
* Reject obviously insane bounds, rather than trying to guess what the
* buggy caller intended.
*/
PR_ASSERT(0.5 <= maxAlpha && maxAlpha < 1 && 0 <= minAlpha);
if (maxAlpha < 0.5 || 1 <= maxAlpha || minAlpha < 0)
return;
/*
* Ensure that at least one entry will always be free. If maxAlpha at
* minimum size leaves no entries free, reduce maxAlpha based on minimum
* size and the precision limit of maxAlphaFrac's fixed point format.
*/
PR_ASSERT(PL_DHASH_MIN_SIZE - (maxAlpha * PL_DHASH_MIN_SIZE) >= 1);
if (PL_DHASH_MIN_SIZE - (maxAlpha * PL_DHASH_MIN_SIZE) < 1) {
maxAlpha = (float)
(PL_DHASH_MIN_SIZE - PR_MAX(PL_DHASH_MIN_SIZE / 256, 1))
/ PL_DHASH_MIN_SIZE;
}
/*
* Ensure that minAlpha is strictly less than half maxAlpha. Take care
* not to truncate an entry's worth of alpha when storing in minAlphaFrac
* (8-bit fixed point format).
*/
PR_ASSERT(minAlpha < maxAlpha / 2);
if (minAlpha >= maxAlpha / 2) {
size = PL_DHASH_TABLE_SIZE(table);
minAlpha = (size * maxAlpha - PR_MAX(size / 256, 1)) / (2 * size);
}
table->maxAlphaFrac = (uint8)(maxAlpha * 256);
table->minAlphaFrac = (uint8)(minAlpha * 256);
}
/*
* Double hashing needs the second hash code to be relatively prime to table
* size, so we simply make hash2 odd.
*/
#define HASH1(hash0, shift) ((hash0) >> (shift))
#define HASH2(hash0,log2,shift) ((((hash0) << (log2)) >> (shift)) | 1)
/*
* Reserve keyHash 0 for free entries and 1 for removed-entry sentinels. Note
* that a removed-entry sentinel need be stored only if the removed entry had
* a colliding entry added after it. Therefore we can use 1 as the collision
* flag in addition to the removed-entry sentinel value. Multiplicative hash
* uses the high order bits of keyHash, so this least-significant reservation
* should not hurt the hash function's effectiveness much.
*
* If you change any of these magic numbers, also update PL_DHASH_ENTRY_IS_LIVE
* in pldhash.h. It used to be private to pldhash.c, but then became public to
* assist iterator writers who inspect table->entryStore directly.
*/
#define COLLISION_FLAG ((PLDHashNumber) 1)
#define MARK_ENTRY_FREE(entry) ((entry)->keyHash = 0)
#define MARK_ENTRY_REMOVED(entry) ((entry)->keyHash = 1)
#define ENTRY_IS_REMOVED(entry) ((entry)->keyHash == 1)
#define ENTRY_IS_LIVE(entry) PL_DHASH_ENTRY_IS_LIVE(entry)
#define ENSURE_LIVE_KEYHASH(hash0) if (hash0 < 2) hash0 -= 2; else (void)0
/* Match an entry's keyHash against an unstored one computed from a key. */
#define MATCH_ENTRY_KEYHASH(entry,hash0) \
(((entry)->keyHash & ~COLLISION_FLAG) == (hash0))
/* Compute the address of the indexed entry in table. */
#define ADDRESS_ENTRY(table, index) \
((PLDHashEntryHdr *)((table)->entryStore + (index) * (table)->entrySize))
void
PL_DHashTableFinish(PLDHashTable *table)
{
char *entryAddr, *entryLimit;
PRUint32 entrySize;
PLDHashEntryHdr *entry;
#ifdef DEBUG_XXXbrendan
static FILE *dumpfp = NULL;
if (!dumpfp) dumpfp = fopen("/tmp/pldhash.bigdump", "w");
if (dumpfp) {
#ifdef MOZILLA_CLIENT
NS_TraceStack(1, dumpfp);
#endif
PL_DHashTableDumpMeter(table, NULL, dumpfp);
fputc('\n', dumpfp);
}
#endif
/* Call finalize before clearing entries, so it can enumerate them. */
table->ops->finalize(table);
/* Clear any remaining live entries. */
entryAddr = table->entryStore;
entrySize = table->entrySize;
entryLimit = entryAddr + PL_DHASH_TABLE_SIZE(table) * entrySize;
while (entryAddr < entryLimit) {
entry = (PLDHashEntryHdr *)entryAddr;
if (ENTRY_IS_LIVE(entry)) {
METER(table->stats.removeEnums++);
table->ops->clearEntry(table, entry);
}
entryAddr += entrySize;
}
/* Free entry storage last. */
table->ops->freeTable(table, table->entryStore);
}
static PLDHashEntryHdr * PL_DHASH_FASTCALL
SearchTable(PLDHashTable *table, const void *key, PLDHashNumber keyHash,
PLDHashOperator op)
{
PLDHashNumber hash1, hash2;
int hashShift, sizeLog2;
PLDHashEntryHdr *entry, *firstRemoved;
PLDHashMatchEntry matchEntry;
PRUint32 sizeMask;
METER(table->stats.searches++);
PR_ASSERT(!(keyHash & COLLISION_FLAG));
/* Compute the primary hash address. */
hashShift = table->hashShift;
hash1 = HASH1(keyHash, hashShift);
entry = ADDRESS_ENTRY(table, hash1);
/* Miss: return space for a new entry. */
if (PL_DHASH_ENTRY_IS_FREE(entry)) {
METER(table->stats.misses++);
return entry;
}
/* Hit: return entry. */
matchEntry = table->ops->matchEntry;
if (MATCH_ENTRY_KEYHASH(entry, keyHash) && matchEntry(table, entry, key)) {
METER(table->stats.hits++);
return entry;
}
/* Collision: double hash. */
sizeLog2 = PL_DHASH_BITS - table->hashShift;
hash2 = HASH2(keyHash, sizeLog2, hashShift);
sizeMask = PR_BITMASK(sizeLog2);
/* Save the first removed entry pointer so PL_DHASH_ADD can recycle it. */
if (ENTRY_IS_REMOVED(entry)) {
firstRemoved = entry;
} else {
firstRemoved = NULL;
if (op == PL_DHASH_ADD)
entry->keyHash |= COLLISION_FLAG;
}
for (;;) {
METER(table->stats.steps++);
hash1 -= hash2;
hash1 &= sizeMask;
entry = ADDRESS_ENTRY(table, hash1);
if (PL_DHASH_ENTRY_IS_FREE(entry)) {
METER(table->stats.misses++);
return (firstRemoved && op == PL_DHASH_ADD) ? firstRemoved : entry;
}
if (MATCH_ENTRY_KEYHASH(entry, keyHash) &&
matchEntry(table, entry, key)) {
METER(table->stats.hits++);
return entry;
}
if (ENTRY_IS_REMOVED(entry)) {
if (!firstRemoved)
firstRemoved = entry;
} else {
if (op == PL_DHASH_ADD)
entry->keyHash |= COLLISION_FLAG;
}
}
/* NOTREACHED */
return NULL;
}
static PRBool
ChangeTable(PLDHashTable *table, int deltaLog2)
{
int oldLog2, newLog2;
PRUint32 oldCapacity, newCapacity;
char *newEntryStore, *oldEntryStore, *oldEntryAddr;
PRUint32 entrySize, i, nbytes;
PLDHashEntryHdr *oldEntry, *newEntry;
PLDHashGetKey getKey;
PLDHashMoveEntry moveEntry;
/* Look, but don't touch, until we succeed in getting new entry store. */
oldLog2 = PL_DHASH_BITS - table->hashShift;
newLog2 = oldLog2 + deltaLog2;
oldCapacity = PR_BIT(oldLog2);
newCapacity = PR_BIT(newLog2);
if (newCapacity >= PL_DHASH_SIZE_LIMIT)
return PR_FALSE;
entrySize = table->entrySize;
nbytes = newCapacity * entrySize;
newEntryStore = table->ops->allocTable(table, nbytes);
if (!newEntryStore)
return PR_FALSE;
/* We can't fail from here on, so update table parameters. */
table->hashShift = PL_DHASH_BITS - newLog2;
table->removedCount = 0;
table->generation++;
/* Assign the new entry store to table. */
memset(newEntryStore, 0, nbytes);
oldEntryAddr = oldEntryStore = table->entryStore;
table->entryStore = newEntryStore;
getKey = table->ops->getKey;
moveEntry = table->ops->moveEntry;
/* Copy only live entries, leaving removed ones behind. */
for (i = 0; i < oldCapacity; i++) {
oldEntry = (PLDHashEntryHdr *)oldEntryAddr;
if (ENTRY_IS_LIVE(oldEntry)) {
oldEntry->keyHash &= ~COLLISION_FLAG;
newEntry = SearchTable(table, getKey(table, oldEntry),
oldEntry->keyHash, PL_DHASH_ADD);
PR_ASSERT(PL_DHASH_ENTRY_IS_FREE(newEntry));
moveEntry(table, oldEntry, newEntry);
newEntry->keyHash = oldEntry->keyHash;
}
oldEntryAddr += entrySize;
}
table->ops->freeTable(table, oldEntryStore);
return PR_TRUE;
}
PLDHashEntryHdr * PL_DHASH_FASTCALL
PL_DHashTableOperate(PLDHashTable *table, const void *key, PLDHashOperator op)
{
PLDHashNumber keyHash;
PLDHashEntryHdr *entry;
PRUint32 size;
int deltaLog2;
keyHash = table->ops->hashKey(table, key);
keyHash *= PL_DHASH_GOLDEN_RATIO;
/* Avoid 0 and 1 hash codes, they indicate free and removed entries. */
ENSURE_LIVE_KEYHASH(keyHash);
keyHash &= ~COLLISION_FLAG;
switch (op) {
case PL_DHASH_LOOKUP:
METER(table->stats.lookups++);
entry = SearchTable(table, key, keyHash, op);
break;
case PL_DHASH_ADD:
/*
* If alpha is >= .75, grow or compress the table. If key is already
* in the table, we may grow once more than necessary, but only if we
* are on the edge of being overloaded.
*/
size = PL_DHASH_TABLE_SIZE(table);
if (table->entryCount + table->removedCount >= MAX_LOAD(table, size)) {
/* Compress if a quarter or more of all entries are removed. */
if (table->removedCount >= size >> 2) {
METER(table->stats.compresses++);
deltaLog2 = 0;
} else {
METER(table->stats.grows++);
deltaLog2 = 1;
}
/*
* Grow or compress table, returning null if ChangeTable fails and
* falling through might claim the last free entry.
*/
if (!ChangeTable(table, deltaLog2) &&
table->entryCount + table->removedCount == size - 1) {
METER(table->stats.addFailures++);
return NULL;
}
}
/*
* Look for entry after possibly growing, so we don't have to add it,
* then skip it while growing the table and re-add it after.
*/
entry = SearchTable(table, key, keyHash, op);
if (!ENTRY_IS_LIVE(entry)) {
/* Initialize the entry, indicating that it's no longer free. */
METER(table->stats.addMisses++);
if (ENTRY_IS_REMOVED(entry)) {
METER(table->stats.addOverRemoved++);
table->removedCount--;
keyHash |= COLLISION_FLAG;
}
if (table->ops->initEntry &&
!table->ops->initEntry(table, entry, key)) {
/* We haven't claimed entry yet; fail with null return. */
memset(entry + 1, 0, table->entrySize - sizeof *entry);
return NULL;
}
entry->keyHash = keyHash;
table->entryCount++;
}
METER(else table->stats.addHits++);
break;
case PL_DHASH_REMOVE:
entry = SearchTable(table, key, keyHash, op);
if (ENTRY_IS_LIVE(entry)) {
/* Clear this entry and mark it as "removed". */
METER(table->stats.removeHits++);
PL_DHashTableRawRemove(table, entry);
/* Shrink if alpha is <= .25 and table isn't too small already. */
size = PL_DHASH_TABLE_SIZE(table);
if (size > PL_DHASH_MIN_SIZE &&
table->entryCount <= MIN_LOAD(table, size)) {
METER(table->stats.shrinks++);
(void) ChangeTable(table, -1);
}
}
METER(else table->stats.removeMisses++);
entry = NULL;
break;
default:
PR_ASSERT(0);
entry = NULL;
}
return entry;
}
void
PL_DHashTableRawRemove(PLDHashTable *table, PLDHashEntryHdr *entry)
{
PLDHashNumber keyHash; /* load first in case clearEntry goofs it */
PR_ASSERT(PL_DHASH_ENTRY_IS_LIVE(entry));
keyHash = entry->keyHash;
table->ops->clearEntry(table, entry);
if (keyHash & COLLISION_FLAG) {
MARK_ENTRY_REMOVED(entry);
table->removedCount++;
} else {
METER(table->stats.removeFrees++);
MARK_ENTRY_FREE(entry);
}
table->entryCount--;
}
PRUint32
PL_DHashTableEnumerate(PLDHashTable *table, PLDHashEnumerator etor, void *arg)
{
char *entryAddr, *entryLimit;
PRUint32 i, capacity, entrySize, ceiling;
PRBool didRemove;
PLDHashEntryHdr *entry;
PLDHashOperator op;
entryAddr = table->entryStore;
entrySize = table->entrySize;
capacity = PL_DHASH_TABLE_SIZE(table);
entryLimit = entryAddr + capacity * entrySize;
i = 0;
didRemove = PR_FALSE;
while (entryAddr < entryLimit) {
entry = (PLDHashEntryHdr *)entryAddr;
if (ENTRY_IS_LIVE(entry)) {
op = etor(table, entry, i++, arg);
if (op & PL_DHASH_REMOVE) {
METER(table->stats.removeEnums++);
PL_DHashTableRawRemove(table, entry);
didRemove = PR_TRUE;
}
if (op & PL_DHASH_STOP)
break;
}
entryAddr += entrySize;
}
/*
* Shrink or compress if a quarter or more of all entries are removed, or
* if the table is underloaded according to the configured minimum alpha,
* and is not minimal-size already. Do this only if we removed above, so
* non-removing enumerations can count on stable table->entryStore until
* the next non-lookup-Operate or removing-Enumerate.
*/
if (didRemove &&
(table->removedCount >= capacity >> 2 ||
(capacity > PL_DHASH_MIN_SIZE &&
table->entryCount <= MIN_LOAD(table, capacity)))) {
METER(table->stats.enumShrinks++);
capacity = table->entryCount;
capacity += capacity >> 1;
if (capacity < PL_DHASH_MIN_SIZE)
capacity = PL_DHASH_MIN_SIZE;
PR_CEILING_LOG2(ceiling, capacity);
ceiling -= PL_DHASH_BITS - table->hashShift;
(void) ChangeTable(table, ceiling);
}
return i;
}
#ifdef PL_DHASHMETER
#include <math.h>
void
PL_DHashTableDumpMeter(PLDHashTable *table, PLDHashEnumerator dump, FILE *fp)
{
char *entryAddr;
PRUint32 entrySize, entryCount;
int hashShift, sizeLog2;
PRUint32 i, tableSize, sizeMask, chainLen, maxChainLen, chainCount;
PLDHashNumber hash1, hash2, saveHash1, maxChainHash1, maxChainHash2;
double sqsum, mean, variance, sigma;
PLDHashEntryHdr *entry, *probe;
entryAddr = table->entryStore;
entrySize = table->entrySize;
hashShift = table->hashShift;
sizeLog2 = PL_DHASH_BITS - hashShift;
tableSize = PL_DHASH_TABLE_SIZE(table);
sizeMask = PR_BITMASK(sizeLog2);
chainCount = maxChainLen = 0;
hash2 = 0;
sqsum = 0;
for (i = 0; i < tableSize; i++) {
entry = (PLDHashEntryHdr *)entryAddr;
entryAddr += entrySize;
if (!ENTRY_IS_LIVE(entry))
continue;
hash1 = HASH1(entry->keyHash & ~COLLISION_FLAG, hashShift);
saveHash1 = hash1;
probe = ADDRESS_ENTRY(table, hash1);
chainLen = 1;
if (probe == entry) {
/* Start of a (possibly unit-length) chain. */
chainCount++;
} else {
hash2 = HASH2(entry->keyHash & ~COLLISION_FLAG, sizeLog2,
hashShift);
do {
chainLen++;
hash1 -= hash2;
hash1 &= sizeMask;
probe = ADDRESS_ENTRY(table, hash1);
} while (probe != entry);
}
sqsum += chainLen * chainLen;
if (chainLen > maxChainLen) {
maxChainLen = chainLen;
maxChainHash1 = saveHash1;
maxChainHash2 = hash2;
}
}
entryCount = table->entryCount;
if (entryCount && chainCount) {
mean = (double)entryCount / chainCount;
variance = chainCount * sqsum - entryCount * entryCount;
if (variance < 0 || chainCount == 1)
variance = 0;
else
variance /= chainCount * (chainCount - 1);
sigma = sqrt(variance);
} else {
mean = sigma = 0;
}
fprintf(fp, "Double hashing statistics:\n");
fprintf(fp, " table size (in entries): %u\n", tableSize);
fprintf(fp, " number of entries: %u\n", table->entryCount);
fprintf(fp, " number of removed entries: %u\n", table->removedCount);
fprintf(fp, " number of searches: %u\n", table->stats.searches);
fprintf(fp, " number of hits: %u\n", table->stats.hits);
fprintf(fp, " number of misses: %u\n", table->stats.misses);
fprintf(fp, " mean steps per search: %g\n", table->stats.searches ?
(double)table->stats.steps
/ table->stats.searches :
0.);
fprintf(fp, " mean hash chain length: %g\n", mean);
fprintf(fp, " standard deviation: %g\n", sigma);
fprintf(fp, " maximum hash chain length: %u\n", maxChainLen);
fprintf(fp, " number of lookups: %u\n", table->stats.lookups);
fprintf(fp, " adds that made a new entry: %u\n", table->stats.addMisses);
fprintf(fp, "adds that recycled removeds: %u\n", table->stats.addOverRemoved);
fprintf(fp, " adds that found an entry: %u\n", table->stats.addHits);
fprintf(fp, " add failures: %u\n", table->stats.addFailures);
fprintf(fp, " useful removes: %u\n", table->stats.removeHits);
fprintf(fp, " useless removes: %u\n", table->stats.removeMisses);
fprintf(fp, "removes that freed an entry: %u\n", table->stats.removeFrees);
fprintf(fp, " removes while enumerating: %u\n", table->stats.removeEnums);
fprintf(fp, " number of grows: %u\n", table->stats.grows);
fprintf(fp, " number of shrinks: %u\n", table->stats.shrinks);
fprintf(fp, " number of compresses: %u\n", table->stats.compresses);
fprintf(fp, "number of enumerate shrinks: %u\n", table->stats.enumShrinks);
if (dump && maxChainLen && hash2) {
fputs("Maximum hash chain:\n", fp);
hash1 = maxChainHash1;
hash2 = maxChainHash2;
entry = ADDRESS_ENTRY(table, hash1);
i = 0;
do {
if (dump(table, entry, i++, fp) != PL_DHASH_NEXT)
break;
hash1 -= hash2;
hash1 &= sizeMask;
entry = ADDRESS_ENTRY(table, hash1);
} while (PL_DHASH_ENTRY_IS_BUSY(entry));
}
}
#endif /* PL_DHASHMETER */

Просмотреть файл

@ -1,580 +0,0 @@
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla JavaScript code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1999-2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Brendan Eich <brendan@mozilla.org> (Original Author)
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef pldhash_h___
#define pldhash_h___
/*
* Double hashing, a la Knuth 6.
* GENERATED BY js/src/plify_jsdhash.sed -- DO NOT EDIT!!!
*/
#include "nscore.h"
PR_BEGIN_EXTERN_C
#if defined(__GNUC__) && defined(__i386__) && (__GNUC__ >= 3) && !defined(XP_OS2) && !defined(XP_MACOSX)
#define PL_DHASH_FASTCALL __attribute__ ((regparm (3),stdcall))
#else
#define PL_DHASH_FASTCALL
#endif
#ifdef DEBUG_XXXbrendan
#define PL_DHASHMETER 1
#endif
/* Table size limit, do not equal or exceed (see min&maxAlphaFrac, below). */
#undef PL_DHASH_SIZE_LIMIT
#define PL_DHASH_SIZE_LIMIT PR_BIT(24)
/* Minimum table size, or gross entry count (net is at most .75 loaded). */
#ifndef PL_DHASH_MIN_SIZE
#define PL_DHASH_MIN_SIZE 16
#elif (PL_DHASH_MIN_SIZE & (PL_DHASH_MIN_SIZE - 1)) != 0
#error "PL_DHASH_MIN_SIZE must be a power of two!"
#endif
/*
* Multiplicative hash uses an unsigned 32 bit integer and the golden ratio,
* expressed as a fixed-point 32-bit fraction.
*/
#define PL_DHASH_BITS 32
#define PL_DHASH_GOLDEN_RATIO 0x9E3779B9U
/* Primitive and forward-struct typedefs. */
typedef PRUint32 PLDHashNumber;
typedef struct PLDHashEntryHdr PLDHashEntryHdr;
typedef struct PLDHashEntryStub PLDHashEntryStub;
typedef struct PLDHashTable PLDHashTable;
typedef struct PLDHashTableOps PLDHashTableOps;
/*
* Table entry header structure.
*
* In order to allow in-line allocation of key and value, we do not declare
* either here. Instead, the API uses const void *key as a formal parameter,
* and asks each entry for its key when necessary via a getKey callback, used
* when growing or shrinking the table. Other callback types are defined
* below and grouped into the PLDHashTableOps structure, for single static
* initialization per hash table sub-type.
*
* Each hash table sub-type should nest the PLDHashEntryHdr structure at the
* front of its particular entry type. The keyHash member contains the result
* of multiplying the hash code returned from the hashKey callback (see below)
* by PL_DHASH_GOLDEN_RATIO, then constraining the result to avoid the magic 0
* and 1 values. The stored keyHash value is table size invariant, and it is
* maintained automatically by PL_DHashTableOperate -- users should never set
* it, and its only uses should be via the entry macros below.
*
* The PL_DHASH_ENTRY_IS_LIVE macro tests whether entry is neither free nor
* removed. An entry may be either busy or free; if busy, it may be live or
* removed. Consumers of this API should not access members of entries that
* are not live.
*
* However, use PL_DHASH_ENTRY_IS_BUSY for faster liveness testing of entries
* returned by PL_DHashTableOperate, as PL_DHashTableOperate never returns a
* non-live, busy (i.e., removed) entry pointer to its caller. See below for
* more details on PL_DHashTableOperate's calling rules.
*/
struct PLDHashEntryHdr {
PLDHashNumber keyHash; /* every entry must begin like this */
};
#define PL_DHASH_ENTRY_IS_FREE(entry) ((entry)->keyHash == 0)
#define PL_DHASH_ENTRY_IS_BUSY(entry) (!PL_DHASH_ENTRY_IS_FREE(entry))
#define PL_DHASH_ENTRY_IS_LIVE(entry) ((entry)->keyHash >= 2)
/*
* A PLDHashTable is currently 8 words (without the PL_DHASHMETER overhead)
* on most architectures, and may be allocated on the stack or within another
* structure or class (see below for the Init and Finish functions to use).
*
* To decide whether to use double hashing vs. chaining, we need to develop a
* trade-off relation, as follows:
*
* Let alpha be the load factor, esize the entry size in words, count the
* entry count, and pow2 the power-of-two table size in entries.
*
* (PLDHashTable overhead) > (PLHashTable overhead)
* (unused table entry space) > (malloc and .next overhead per entry) +
* (buckets overhead)
* (1 - alpha) * esize * pow2 > 2 * count + pow2
*
* Notice that alpha is by definition (count / pow2):
*
* (1 - alpha) * esize * pow2 > 2 * alpha * pow2 + pow2
* (1 - alpha) * esize > 2 * alpha + 1
*
* esize > (1 + 2 * alpha) / (1 - alpha)
*
* This assumes both tables must keep keyHash, key, and value for each entry,
* where key and value point to separately allocated strings or structures.
* If key and value can be combined into one pointer, then the trade-off is:
*
* esize > (1 + 3 * alpha) / (1 - alpha)
*
* If the entry value can be a subtype of PLDHashEntryHdr, rather than a type
* that must be allocated separately and referenced by an entry.value pointer
* member, and provided key's allocation can be fused with its entry's, then
* k (the words wasted per entry with chaining) is 4.
*
* To see these curves, feed gnuplot input like so:
*
* gnuplot> f(x,k) = (1 + k * x) / (1 - x)
* gnuplot> plot [0:.75] f(x,2), f(x,3), f(x,4)
*
* For k of 2 and a well-loaded table (alpha > .5), esize must be more than 4
* words for chaining to be more space-efficient than double hashing.
*
* Solving for alpha helps us decide when to shrink an underloaded table:
*
* esize > (1 + k * alpha) / (1 - alpha)
* esize - alpha * esize > 1 + k * alpha
* esize - 1 > (k + esize) * alpha
* (esize - 1) / (k + esize) > alpha
*
* alpha < (esize - 1) / (esize + k)
*
* Therefore double hashing should keep alpha >= (esize - 1) / (esize + k),
* assuming esize is not too large (in which case, chaining should probably be
* used for any alpha). For esize=2 and k=3, we want alpha >= .2; for esize=3
* and k=2, we want alpha >= .4. For k=4, esize could be 6, and alpha >= .5
* would still obtain. See the PL_DHASH_MIN_ALPHA macro further below.
*
* The current implementation uses a configurable lower bound on alpha, which
* defaults to .25, when deciding to shrink the table (while still respecting
* PL_DHASH_MIN_SIZE).
*
* Note a qualitative difference between chaining and double hashing: under
* chaining, entry addresses are stable across table shrinks and grows. With
* double hashing, you can't safely hold an entry pointer and use it after an
* ADD or REMOVE operation, unless you sample table->generation before adding
* or removing, and compare the sample after, dereferencing the entry pointer
* only if table->generation has not changed.
*
* The moral of this story: there is no one-size-fits-all hash table scheme,
* but for small table entry size, and assuming entry address stability is not
* required, double hashing wins.
*/
struct PLDHashTable {
const PLDHashTableOps *ops; /* virtual operations, see below */
void *data; /* ops- and instance-specific data */
PRInt16 hashShift; /* multiplicative hash shift */
uint8 maxAlphaFrac; /* 8-bit fixed point max alpha */
uint8 minAlphaFrac; /* 8-bit fixed point min alpha */
PRUint32 entrySize; /* number of bytes in an entry */
PRUint32 entryCount; /* number of entries in table */
PRUint32 removedCount; /* removed entry sentinels in table */
PRUint32 generation; /* entry storage generation number */
char *entryStore; /* entry storage */
#ifdef PL_DHASHMETER
struct PLDHashStats {
PRUint32 searches; /* total number of table searches */
PRUint32 steps; /* hash chain links traversed */
PRUint32 hits; /* searches that found key */
PRUint32 misses; /* searches that didn't find key */
PRUint32 lookups; /* number of PL_DHASH_LOOKUPs */
PRUint32 addMisses; /* adds that miss, and do work */
PRUint32 addOverRemoved; /* adds that recycled a removed entry */
PRUint32 addHits; /* adds that hit an existing entry */
PRUint32 addFailures; /* out-of-memory during add growth */
PRUint32 removeHits; /* removes that hit, and do work */
PRUint32 removeMisses; /* useless removes that miss */
PRUint32 removeFrees; /* removes that freed entry directly */
PRUint32 removeEnums; /* removes done by Enumerate */
PRUint32 grows; /* table expansions */
PRUint32 shrinks; /* table contractions */
PRUint32 compresses; /* table compressions */
PRUint32 enumShrinks; /* contractions after Enumerate */
} stats;
#endif
};
/*
* Size in entries (gross, not net of free and removed sentinels) for table.
* We store hashShift rather than sizeLog2 to optimize the collision-free case
* in SearchTable.
*/
#define PL_DHASH_TABLE_SIZE(table) PR_BIT(PL_DHASH_BITS - (table)->hashShift)
/*
* Table space at entryStore is allocated and freed using these callbacks.
* The allocator should return null on error only (not if called with nbytes
* equal to 0; but note that pldhash.c code will never call with 0 nbytes).
*/
typedef void *
(* PR_CALLBACK PLDHashAllocTable)(PLDHashTable *table, PRUint32 nbytes);
typedef void
(* PR_CALLBACK PLDHashFreeTable) (PLDHashTable *table, void *ptr);
/*
* When a table grows or shrinks, each entry is queried for its key using this
* callback. NB: in that event, entry is not in table any longer; it's in the
* old entryStore vector, which is due to be freed once all entries have been
* moved via moveEntry callbacks.
*/
typedef const void *
(* PR_CALLBACK PLDHashGetKey) (PLDHashTable *table,
PLDHashEntryHdr *entry);
/*
* Compute the hash code for a given key to be looked up, added, or removed
* from table. A hash code may have any PLDHashNumber value.
*/
typedef PLDHashNumber
(* PR_CALLBACK PLDHashHashKey) (PLDHashTable *table, const void *key);
/*
* Compare the key identifying entry in table with the provided key parameter.
* Return PR_TRUE if keys match, PR_FALSE otherwise.
*/
typedef PRBool
(* PR_CALLBACK PLDHashMatchEntry)(PLDHashTable *table,
const PLDHashEntryHdr *entry,
const void *key);
/*
* Copy the data starting at from to the new entry storage at to. Do not add
* reference counts for any strong references in the entry, however, as this
* is a "move" operation: the old entry storage at from will be freed without
* any reference-decrementing callback shortly.
*/
typedef void
(* PR_CALLBACK PLDHashMoveEntry)(PLDHashTable *table,
const PLDHashEntryHdr *from,
PLDHashEntryHdr *to);
/*
* Clear the entry and drop any strong references it holds. This callback is
* invoked during a PL_DHASH_REMOVE operation (see below for operation codes),
* but only if the given key is found in the table.
*/
typedef void
(* PR_CALLBACK PLDHashClearEntry)(PLDHashTable *table,
PLDHashEntryHdr *entry);
/*
* Called when a table (whether allocated dynamically by itself, or nested in
* a larger structure, or allocated on the stack) is finished. This callback
* allows table->ops-specific code to finalize table->data.
*/
typedef void
(* PR_CALLBACK PLDHashFinalize) (PLDHashTable *table);
/*
* Initialize a new entry, apart from keyHash. This function is called when
* PL_DHashTableOperate's PL_DHASH_ADD case finds no existing entry for the
* given key, and must add a new one. At that point, entry->keyHash is not
* set yet, to avoid claiming the last free entry in a severely overloaded
* table.
*/
typedef PRBool
(* PR_CALLBACK PLDHashInitEntry)(PLDHashTable *table,
PLDHashEntryHdr *entry,
const void *key);
/*
* Finally, the "vtable" structure for PLDHashTable. The first eight hooks
* must be provided by implementations; they're called unconditionally by the
* generic pldhash.c code. Hooks after these may be null.
*
* Summary of allocation-related hook usage with C++ placement new emphasis:
* allocTable Allocate raw bytes with malloc, no ctors run.
* freeTable Free raw bytes with free, no dtors run.
* initEntry Call placement new using default key-based ctor.
* Return PR_TRUE on success, PR_FALSE on error.
* moveEntry Call placement new using copy ctor, run dtor on old
* entry storage.
* clearEntry Run dtor on entry.
* finalize Stub unless table->data was initialized and needs to
* be finalized.
*
* Note the reason why initEntry is optional: the default hooks (stubs) clear
* entry storage: On successful PL_DHashTableOperate(tbl, key, PL_DHASH_ADD),
* the returned entry pointer addresses an entry struct whose keyHash member
* has been set non-zero, but all other entry members are still clear (null).
* PL_DHASH_ADD callers can test such members to see whether the entry was
* newly created by the PL_DHASH_ADD call that just succeeded. If placement
* new or similar initialization is required, define an initEntry hook. Of
* course, the clearEntry hook must zero or null appropriately.
*
* XXX assumes 0 is null for pointer types.
*/
struct PLDHashTableOps {
/* Mandatory hooks. All implementations must provide these. */
PLDHashAllocTable allocTable;
PLDHashFreeTable freeTable;
PLDHashGetKey getKey;
PLDHashHashKey hashKey;
PLDHashMatchEntry matchEntry;
PLDHashMoveEntry moveEntry;
PLDHashClearEntry clearEntry;
PLDHashFinalize finalize;
/* Optional hooks start here. If null, these are not called. */
PLDHashInitEntry initEntry;
};
/*
* Default implementations for the above ops.
*/
NS_COM_GLUE void *
PL_DHashAllocTable(PLDHashTable *table, PRUint32 nbytes);
NS_COM_GLUE void
PL_DHashFreeTable(PLDHashTable *table, void *ptr);
NS_COM_GLUE PLDHashNumber
PL_DHashStringKey(PLDHashTable *table, const void *key);
/* A minimal entry contains a keyHash header and a void key pointer. */
struct PLDHashEntryStub {
PLDHashEntryHdr hdr;
const void *key;
};
NS_COM_GLUE const void *
PL_DHashGetKeyStub(PLDHashTable *table, PLDHashEntryHdr *entry);
NS_COM_GLUE PLDHashNumber
PL_DHashVoidPtrKeyStub(PLDHashTable *table, const void *key);
NS_COM_GLUE PRBool
PL_DHashMatchEntryStub(PLDHashTable *table,
const PLDHashEntryHdr *entry,
const void *key);
NS_COM_GLUE PRBool
PL_DHashMatchStringKey(PLDHashTable *table,
const PLDHashEntryHdr *entry,
const void *key);
NS_COM_GLUE void
PL_DHashMoveEntryStub(PLDHashTable *table,
const PLDHashEntryHdr *from,
PLDHashEntryHdr *to);
NS_COM_GLUE void
PL_DHashClearEntryStub(PLDHashTable *table, PLDHashEntryHdr *entry);
NS_COM_GLUE void
PL_DHashFreeStringKey(PLDHashTable *table, PLDHashEntryHdr *entry);
NS_COM_GLUE void
PL_DHashFinalizeStub(PLDHashTable *table);
/*
* If you use PLDHashEntryStub or a subclass of it as your entry struct, and
* if your entries move via memcpy and clear via memset(0), you can use these
* stub operations.
*/
NS_COM_GLUE const PLDHashTableOps *
PL_DHashGetStubOps(void);
/*
* Dynamically allocate a new PLDHashTable using malloc, initialize it using
* PL_DHashTableInit, and return its address. Return null on malloc failure.
* Note that the entry storage at table->entryStore will be allocated using
* the ops->allocTable callback.
*/
NS_COM_GLUE PLDHashTable *
PL_NewDHashTable(const PLDHashTableOps *ops, void *data, PRUint32 entrySize,
PRUint32 capacity);
/*
* Finalize table's data, free its entry storage (via table->ops->freeTable),
* and return the memory starting at table to the malloc heap.
*/
NS_COM_GLUE void
PL_DHashTableDestroy(PLDHashTable *table);
/*
* Initialize table with ops, data, entrySize, and capacity. Capacity is a
* guess for the smallest table size at which the table will usually be less
* than 75% loaded (the table will grow or shrink as needed; capacity serves
* only to avoid inevitable early growth from PL_DHASH_MIN_SIZE).
*/
NS_COM_GLUE PRBool
PL_DHashTableInit(PLDHashTable *table, const PLDHashTableOps *ops, void *data,
PRUint32 entrySize, PRUint32 capacity);
/*
* Set maximum and minimum alpha for table. The defaults are 0.75 and .25.
* maxAlpha must be in [0.5, 0.9375] for the default PL_DHASH_MIN_SIZE; or if
* MinSize=PL_DHASH_MIN_SIZE <= 256, in [0.5, (float)(MinSize-1)/MinSize]; or
* else in [0.5, 255.0/256]. minAlpha must be in [0, maxAlpha / 2), so that
* we don't shrink on the very next remove after growing a table upon adding
* an entry that brings entryCount past maxAlpha * tableSize.
*/
NS_COM_GLUE void
PL_DHashTableSetAlphaBounds(PLDHashTable *table,
float maxAlpha,
float minAlpha);
/*
* Call this macro with k, the number of pointer-sized words wasted per entry
* under chaining, to compute the minimum alpha at which double hashing still
* beats chaining.
*/
#define PL_DHASH_MIN_ALPHA(table, k) \
((float)((table)->entrySize / sizeof(void *) - 1) \
/ ((table)->entrySize / sizeof(void *) + (k)))
/*
* Finalize table's data, free its entry storage using table->ops->freeTable,
* and leave its members unchanged from their last live values (which leaves
* pointers dangling). If you want to burn cycles clearing table, it's up to
* your code to call memset.
*/
NS_COM_GLUE void
PL_DHashTableFinish(PLDHashTable *table);
/*
* To consolidate keyHash computation and table grow/shrink code, we use a
* single entry point for lookup, add, and remove operations. The operation
* codes are declared here, along with codes returned by PLDHashEnumerator
* functions, which control PL_DHashTableEnumerate's behavior.
*/
typedef enum PLDHashOperator {
PL_DHASH_LOOKUP = 0, /* lookup entry */
PL_DHASH_ADD = 1, /* add entry */
PL_DHASH_REMOVE = 2, /* remove entry, or enumerator says remove */
PL_DHASH_NEXT = 0, /* enumerator says continue */
PL_DHASH_STOP = 1 /* enumerator says stop */
} PLDHashOperator;
/*
* To lookup a key in table, call:
*
* entry = PL_DHashTableOperate(table, key, PL_DHASH_LOOKUP);
*
* If PL_DHASH_ENTRY_IS_BUSY(entry) is true, key was found and it identifies
* entry. If PL_DHASH_ENTRY_IS_FREE(entry) is true, key was not found.
*
* To add an entry identified by key to table, call:
*
* entry = PL_DHashTableOperate(table, key, PL_DHASH_ADD);
*
* If entry is null upon return, then either the table is severely overloaded,
* and memory can't be allocated for entry storage via table->ops->allocTable;
* Or if table->ops->initEntry is non-null, the table->ops->initEntry op may
* have returned false.
*
* Otherwise, entry->keyHash has been set so that PL_DHASH_ENTRY_IS_BUSY(entry)
* is true, and it is up to the caller to initialize the key and value parts
* of the entry sub-type, if they have not been set already (i.e. if entry was
* not already in the table, and if the optional initEntry hook was not used).
*
* To remove an entry identified by key from table, call:
*
* (void) PL_DHashTableOperate(table, key, PL_DHASH_REMOVE);
*
* If key's entry is found, it is cleared (via table->ops->clearEntry) and
* the entry is marked so that PL_DHASH_ENTRY_IS_FREE(entry). This operation
* returns null unconditionally; you should ignore its return value.
*/
NS_COM_GLUE PLDHashEntryHdr * PL_DHASH_FASTCALL
PL_DHashTableOperate(PLDHashTable *table, const void *key, PLDHashOperator op);
/*
* Remove an entry already accessed via LOOKUP or ADD.
*
* NB: this is a "raw" or low-level routine, intended to be used only where
* the inefficiency of a full PL_DHashTableOperate (which rehashes in order
* to find the entry given its key) is not tolerable. This function does not
* shrink the table if it is underloaded. It does not update stats #ifdef
* PL_DHASHMETER, either.
*/
NS_COM_GLUE void
PL_DHashTableRawRemove(PLDHashTable *table, PLDHashEntryHdr *entry);
/*
* Enumerate entries in table using etor:
*
* count = PL_DHashTableEnumerate(table, etor, arg);
*
* PL_DHashTableEnumerate calls etor like so:
*
* op = etor(table, entry, number, arg);
*
* where number is a zero-based ordinal assigned to live entries according to
* their order in table->entryStore.
*
* The return value, op, is treated as a set of flags. If op is PL_DHASH_NEXT,
* then continue enumerating. If op contains PL_DHASH_REMOVE, then clear (via
* table->ops->clearEntry) and free entry. Then we check whether op contains
* PL_DHASH_STOP; if so, stop enumerating and return the number of live entries
* that were enumerated so far. Return the total number of live entries when
* enumeration completes normally.
*
* If etor calls PL_DHashTableOperate on table with op != PL_DHASH_LOOKUP, it
* must return PL_DHASH_STOP; otherwise undefined behavior results.
*
* If any enumerator returns PL_DHASH_REMOVE, table->entryStore may be shrunk
* or compressed after enumeration, but before PL_DHashTableEnumerate returns.
* Such an enumerator therefore can't safely set aside entry pointers, but an
* enumerator that never returns PL_DHASH_REMOVE can set pointers to entries
* aside, e.g., to avoid copying live entries into an array of the entry type.
* Copying entry pointers is cheaper, and safe so long as the caller of such a
* "stable" Enumerate doesn't use the set-aside pointers after any call either
* to PL_DHashTableOperate, or to an "unstable" form of Enumerate, which might
* grow or shrink entryStore.
*
* If your enumerator wants to remove certain entries, but set aside pointers
* to other entries that it retains, it can use PL_DHashTableRawRemove on the
* entries to be removed, returning PL_DHASH_NEXT to skip them. Likewise, if
* you want to remove entries, but for some reason you do not want entryStore
* to be shrunk or compressed, you can call PL_DHashTableRawRemove safely on
* the entry being enumerated, rather than returning PL_DHASH_REMOVE.
*/
typedef PLDHashOperator
(* PR_CALLBACK PLDHashEnumerator)(PLDHashTable *table, PLDHashEntryHdr *hdr,
PRUint32 number, void *arg);
NS_COM_GLUE PRUint32
PL_DHashTableEnumerate(PLDHashTable *table, PLDHashEnumerator etor, void *arg);
#ifdef PL_DHASHMETER
#include <stdio.h>
NS_COM_GLUE void
PL_DHashTableDumpMeter(PLDHashTable *table, PLDHashEnumerator dump, FILE *fp);
#endif
PR_END_EXTERN_C
#endif /* pldhash_h___ */

Просмотреть файл

@ -71,12 +71,8 @@ LINKSRC = nsGlueLinkingNull.cpp
$(warning TinderboxPrint:<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=298044">Error: XPCOM Glue</a>)
endif
CSRCS = \
$(XPCOM_GLUE_SRC_LCSRCS) \
$(NULL)
CPPSRCS = \
$(XPCOM_GLUE_SRC_LCPPSRCS) \
$(XPCOM_GLUE_SRC_LCSRCS) \
nsXPCOMGlue.cpp \
nsGREDirServiceProvider.cpp \
$(LINKSRC) \
@ -102,7 +98,7 @@ SRCS_IN_OBJDIR = 1
include $(topsrcdir)/config/rules.mk
export:: $(XPCOM_GLUE_SRC_CSRCS) $(XPCOM_GLUE_SRC_CPPSRCS)
export:: $(XPCOM_GLUE_SRC_CSRCS)
$(INSTALL) $^ .
DEFINES += -DXPCOM_GLUE

Просмотреть файл

@ -360,6 +360,9 @@ StringEndsWith( const nsACString& aSource, const nsACString& aSubstring,
const nsCStringComparator& aComparator =
nsDefaultCStringComparator() );
NS_COM PRUint32 HashString( const nsAString& aStr );
NS_COM PRUint32 HashString( const nsACString& aStr );
NS_COM const nsAFlatString& EmptyString();
NS_COM const nsAFlatCString& EmptyCString();

Просмотреть файл

@ -38,8 +38,6 @@
#ifndef nsStringAPI_h__
#define nsStringAPI_h__
#include <string.h>
/**
* nsStringAPI.h
*
@ -923,18 +921,6 @@ public:
NS_HIDDEN_(void) Cut( index_type cutStart, size_type cutLength ) { Replace(cutStart, cutLength, nsnull, 0); }
NS_HIDDEN_(PRBool) Equals( const self_type &other ) const {
const char_type *cself;
const char_type *cother;
PRUint32 selflen = NS_StringGetData(*this, &cself);
PRUint32 otherlen = NS_StringGetData(other, &cother);
if (selflen != otherlen)
return PR_FALSE;
return memcmp(cself, cother, selflen * sizeof(char_type)) == 0;
}
#endif // MOZILLA_INTERNAL_API
protected:
@ -1040,18 +1026,6 @@ public:
NS_HIDDEN_(void) Cut( index_type cutStart, size_type cutLength ) { Replace(cutStart, cutLength, nsnull, 0); }
NS_HIDDEN_(PRBool) Equals( const self_type &other ) const {
const char_type *cself;
const char_type *cother;
PRUint32 selflen = NS_CStringGetData(*this, &cself);
PRUint32 otherlen = NS_CStringGetData(other, &cother);
if (selflen != otherlen)
return PR_FALSE;
return memcmp(cself, cother, selflen * sizeof(char_type)) == 0;
}
#endif // MOZILLA_INTERNAL_API
protected:

Просмотреть файл

@ -1079,6 +1079,48 @@ StringEndsWith( const nsACString& aSource, const nsACString& aSubstring,
template <class CharT>
class CalculateHashCode
{
public:
typedef CharT char_type;
typedef PRUint32 hashcode_type;
typedef CharT value_type;
CalculateHashCode() : mHashCode(0) { }
hashcode_type GetHashCode() const { return mHashCode; }
PRUint32 write( const CharT* chars, PRUint32 N )
{
for ( const CharT *end = chars + N; chars < end; ++chars)
mHashCode = (mHashCode>>28) ^ (mHashCode<<4) ^ PRUint32(*chars);
return N;
}
private:
hashcode_type mHashCode;
};
NS_COM PRUint32 HashString( const nsAString& aStr )
{
CalculateHashCode<nsAString::char_type> sink;
nsAString::const_iterator begin, end;
aStr.BeginReading(begin);
aStr.EndReading(end);
copy_string(begin, end, sink);
return sink.GetHashCode();
}
NS_COM PRUint32 HashString( const nsACString& aStr )
{
CalculateHashCode<nsACString::char_type> sink;
nsACString::const_iterator begin, end;
aStr.BeginReading(begin);
aStr.EndReading(end);
copy_string(begin, end, sink);
return sink.GetHashCode();
}
static const PRUnichar empty_buffer[1] = { '\0' };
NS_COM const nsAFlatString& EmptyString()

Просмотреть файл

@ -67,7 +67,6 @@ CPPSRCS = \
TestFactory.cpp \
TestHashtables.cpp \
TestID.cpp \
TestINIParser.cpp \
TestObserverService.cpp \
TestPermanentAtoms.cpp \
TestPipes.cpp \

Просмотреть файл

@ -1,93 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla XPCOM tests.
*
* The Initial Developer of the Original Code is
* Benjamin Smedberg <benjamin@smedbergs.us>.
*
* Portions created by the Initial Developer are Copyright (C) 2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <string.h>
#include "nsINIParser.h"
#include "nsILocalFile.h"
static PRBool
StringCB(const char *aKey, const char *aValue, void* aClosure)
{
printf("%s=%s\n", aKey, aValue);
return PR_TRUE;
}
static PRBool
SectionCB(const char *aSection, void* aClosure)
{
nsINIParser *ini = NS_REINTERPRET_CAST(nsINIParser*, aClosure);
printf("[%s]\n", aSection);
ini->GetStrings(aSection, StringCB, nsnull);
printf("\n");
return PR_TRUE;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: %s <ini-file>\n", argv[0]);
return 255;
}
nsCOMPtr<nsILocalFile> lf;
nsresult rv = NS_NewNativeLocalFile(nsDependentCString(argv[1]),
PR_TRUE,
getter_AddRefs(lf));
if (NS_FAILED(rv)) {
fprintf(stderr, "Error: NS_NewNativeLocalFile failed\n");
return 1;
}
nsINIParser ini;
rv = ini.Init(lf);
if (NS_FAILED(rv)) {
fprintf(stderr, "Error: Init failed.");
return 2;
}
ini.GetSections(SectionCB, &ini);
return 0;
}

Просмотреть файл

@ -82,6 +82,10 @@ CPPSRCS += nsRegisterGREUnix.cpp
endif
endif
ifdef MOZ_ENABLE_LIBXUL
CPPSRCS += nsINIParser.cpp
endif
LOCAL_INCLUDES += \
-I$(topsrcdir)/toolkit/xre \
-I$(topsrcdir)/toolkit/profile/src \
@ -325,6 +329,11 @@ endif
README_FILE = $(topsrcdir)/README.txt
ifdef MOZ_ENABLE_LIBXUL
export::
$(INSTALL) $(topsrcdir)/toolkit/profile/src/nsINIParser.cpp .
endif
libs::
$(INSTALL) $(README_FILE) $(DIST)/bin
$(INSTALL) $(topsrcdir)/LICENSE $(DIST)/bin

Просмотреть файл

@ -139,11 +139,10 @@ static PRBool CheckMaxVersion(const char *versionStr)
/**
* Parse application data.
*/
static int LoadAppData(const char* appDataFile, nsXREAppData* aResult,
nsCString& vendor, nsCString& name, nsCString& version,
nsCString& buildID, nsCString& appID,
nsCString& copyright)
static int LoadAppData(const char* appDataFile, nsXREAppData* aResult)
{
static char vendor[256], name[256], version[32], buildID[32], appID[256], copyright[512];
nsresult rv;
nsCOMPtr<nsILocalFile> lf;
@ -170,16 +169,15 @@ static int LoadAppData(const char* appDataFile, nsXREAppData* aResult,
// TODO: If these version checks fail, then look for a compatible XULRunner
// version on the system, and launch it instead.
nsCAutoString gkVersion;
rv = parser.GetString("Gecko", "MinVersion", gkVersion);
if (NS_FAILED(rv) || !CheckMinVersion(gkVersion.get())) {
char gkVersion[32];
rv = parser.GetString("Gecko", "MinVersion", gkVersion, sizeof(gkVersion));
if (NS_FAILED(rv) || !CheckMinVersion(gkVersion)) {
Output(PR_TRUE, "Error: Gecko MinVersion requirement not met.\n");
return 1;
}
rv = parser.GetString("Gecko", "MaxVersion", gkVersion);
if (NS_SUCCEEDED(rv) && !CheckMaxVersion(gkVersion.get())) {
rv = parser.GetString("Gecko", "MaxVersion", gkVersion, sizeof(gkVersion));
if (NS_SUCCEEDED(rv) && !CheckMaxVersion(gkVersion)) {
Output(PR_TRUE, "Error: Gecko MaxVersion requirement not met.\n");
return 1;
}
@ -190,21 +188,22 @@ static int LoadAppData(const char* appDataFile, nsXREAppData* aResult,
const struct {
const char *key;
const char **fill;
nsCString &buf;
char *buf;
size_t bufLen;
PRBool required;
} string_fields[] = {
{ "Vendor", &aResult->vendor, vendor, PR_FALSE },
{ "Name", &aResult->name, name, PR_TRUE },
{ "Version", &aResult->version, version, PR_FALSE },
{ "BuildID", &aResult->buildID, buildID, PR_TRUE },
{ "ID", &aResult->ID, appID, PR_FALSE },
{ "Copyright", &aResult->copyright, copyright, PR_FALSE }
{ "Vendor", &aResult->vendor, vendor, sizeof(vendor), PR_FALSE },
{ "Name", &aResult->name, name, sizeof(name), PR_TRUE },
{ "Version", &aResult->version, version, sizeof(version), PR_FALSE },
{ "BuildID", &aResult->buildID, buildID, sizeof(buildID), PR_TRUE },
{ "ID", &aResult->ID, appID, sizeof(appID), PR_FALSE },
{ "Copyright", &aResult->copyright, copyright, sizeof(copyright), PR_FALSE }
};
for (i = 0; i < NS_ARRAY_LENGTH(string_fields); ++i) {
rv = parser.GetString("App", string_fields[i].key,
string_fields[i].buf);
rv = parser.GetString("App", string_fields[i].key, string_fields[i].buf,
string_fields[i].bufLen);
if (NS_SUCCEEDED(rv)) {
*string_fields[i].fill = string_fields[i].buf.get();
*string_fields[i].fill = string_fields[i].buf;
}
else if (string_fields[i].required) {
Output(PR_TRUE, "Error: %x: No \"%s\" field.\n",
@ -402,12 +401,9 @@ int main(int argc, char* argv[])
PR_SetEnv(kAppEnv);
}
nsCAutoString vendor, name, version, buildID, appID, copyright;
nsXREAppData appData = { sizeof(nsXREAppData), 0 };
int rv = LoadAppData(appDataFile, &appData,
vendor, name, version, buildID, appID, copyright);
int rv = LoadAppData(appDataFile, &appData);
if (!rv)
rv = XRE_main(argc, argv, &appData);