Compare commits

..

6 Commits

Author SHA1 Message Date
gagan%netscape.com
92a6946fd0 Fix for 3731. Thanks peterl and bruce@cybersight
git-svn-id: svn://10.0.0.236/branches/N3@24979 18797224-902f-48f8-a5cc-f745e15eee43
1999-03-24 06:56:41 +00:00
gagan%netscape.com
415adf0c07 Move to N3
git-svn-id: svn://10.0.0.236/branches/N3@24772 18797224-902f-48f8-a5cc-f745e15eee43
1999-03-23 01:56:43 +00:00
gagan%netscape.com
8b5c749a4f to N3
git-svn-id: svn://10.0.0.236/branches/N3@24771 18797224-902f-48f8-a5cc-f745e15eee43
1999-03-23 01:54:03 +00:00
gagan%netscape.com
a9c4bd2999 N3
git-svn-id: svn://10.0.0.236/branches/N3@24768 18797224-902f-48f8-a5cc-f745e15eee43
1999-03-23 01:51:34 +00:00
gagan%netscape.com
f48dde1d23 All changes in N3
git-svn-id: svn://10.0.0.236/branches/N3@24764 18797224-902f-48f8-a5cc-f745e15eee43
1999-03-23 01:37:12 +00:00
(no author)
28e0fd2310 This commit was manufactured by cvs2svn to create branch 'N3'.
git-svn-id: svn://10.0.0.236/branches/N3@24735 18797224-902f-48f8-a5cc-f745e15eee43
1999-03-22 23:46:38 +00:00
6618 changed files with 173199 additions and 857737 deletions

View File

@@ -26,11 +26,12 @@ include $(DEPTH)/config/autoconf.mk
# nglayout test program. The order is important.
DIRS = \
config \
build \
$(NULL)
ifndef MOZ_NATIVE_NSPR
DIRS += $(topsrcdir)/nsprpub
ifdef MOZ_BUILD_NSPR
DIRS += \
nsprpub \
$(NULL)
endif
DIRS += \
@@ -40,11 +41,15 @@ DIRS += \
$(NULL)
ifndef MOZ_NATIVE_ZLIB
DIRS += modules/zlib
DIRS += \
modules/zlib \
$(NULL)
endif
ifndef MOZ_NATIVE_JPEG
DIRS += jpeg
DIRS += \
jpeg \
$(NULL)
endif
DIRS += \
@@ -57,7 +62,6 @@ DIRS += \
modules/libimg \
modules/oji \
modules/plugin \
modules/libjar \
caps \
lib/xp \
lib/libpwcac \
@@ -73,19 +77,19 @@ DIRS += \
webshell \
editor \
silentdl \
xpinstall \
sun-java \
profile \
$(NULL)
ifdef MOZ_BUILD_XPFE
DIRS += xpfe extensions
DIRS += xpfe
endif
ifdef MOZ_MAIL_NEWS
DIRS += mailnews
endif
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk
real_all: all

2
mozilla/aclocal.m4 vendored
View File

@@ -3,8 +3,6 @@ dnl Local autoconf macros used with mozilla
dnl The contents of this file are under the Public Domain.
dnl
builtin(include, build/autoconf/glib.m4)dnl
builtin(include, build/autoconf/gtk.m4)dnl
builtin(include, build/autoconf/libIDL.m4)dnl
builtin(include, build/autoconf/altoptions.m4)dnl

View File

@@ -43,22 +43,15 @@ Makefile
base/Makefile
base/public/Makefile
base/src/Makefile
base/src/gtk/Makefile
base/src/motif/Makefile
base/src/photon/Makefile
base/src/rhapsody/Makefile
base/src/xlib/Makefile
base/src/gtk/Makefile
base/tests/Makefile
build/Makefile
build/unix/Makefile
build/unix/nspr_my_config.mk
build/unix/nspr_my_overrides.mk
build/package/rpm/mozilla.spec
build/package/rpm/nspr-pthreads.spec
config/Makefile
config/autoconf.mk
config/mkdepend/Makefile
config/mkdetect/Makefile
config/ports/Makefile
dbm/Makefile
dbm/include/Makefile
dbm/src/Makefile
@@ -70,7 +63,6 @@ dom/public/coreDom/Makefile
dom/public/coreEvents/Makefile
dom/public/css/Makefile
dom/public/events/Makefile
dom/public/range/Makefile
dom/public/html/Makefile
dom/src/Makefile
dom/src/base/Makefile
@@ -78,7 +70,6 @@ dom/src/build/Makefile
dom/src/coreDOM/Makefile
dom/src/css/Makefile
dom/src/events/Makefile
dom/src/range/Makefile
dom/src/html/Makefile
dom/src/jsurl/Makefile
dom/tools/Makefile
@@ -87,24 +78,13 @@ editor/public/Makefile
expat/Makefile
expat/xmlparse/Makefile
expat/xmltok/Makefile
extensions/Makefile
extensions/wallet/Makefile
extensions/wallet/public/Makefile
extensions/wallet/src/Makefile
# extensions/wallet/module/Makefile
extensions/pics/Makefile
extensions/pics/public/Makefile
extensions/pics/src/Makefile
extensions/pics/tests/Makefile
gfx/Makefile
gfx/public/Makefile
gfx/src/Makefile
gfx/src/gtk/Makefile
gfx/src/ps/Makefile
gfx/src/motif/Makefile
gfx/src/photon/Makefile
gfx/src/rhapsody/Makefile
gfx/src/xlib/Makefile
gfx/tests/Makefile
htmlparser/Makefile
htmlparser/robot/Makefile
@@ -114,9 +94,6 @@ htmlparser/tests/grabpage/Makefile
htmlparser/tests/logparse/Makefile
include/Makefile
intl/Makefile
intl/chardet/Makefile
intl/chardet/public/Makefile
intl/chardet/src/Makefile
intl/uconv/Makefile
intl/uconv/public/Makefile
intl/uconv/src/Makefile
@@ -124,7 +101,6 @@ intl/uconv/tests/Makefile
intl/uconv/ucvja/Makefile
intl/uconv/ucvlatin/Makefile
intl/uconv/ucvja2/Makefile
intl/uconv/ucvcn/Makefile
intl/locale/Makefile
intl/locale/public/Makefile
intl/locale/src/Makefile
@@ -145,24 +121,17 @@ intl/strres/src/Makefile
intl/strres/tests/Makefile
jpeg/Makefile
js/Makefile
#js/jsd/Makefile
#js/jsd/classes/Makefile
js/jsd/Makefile
js/jsd/classes/Makefile
js/src/Makefile
js/src/fdlibm/Makefile
js/src/liveconnect/Makefile
js/src/liveconnect/classes/Makefile
# js/src/xpcom/Makefile
js/src/xpconnect/Makefile
js/src/xpconnect/public/Makefile
js/src/xpconnect/idl/Makefile
js/src/xpconnect/shell/Makefile
js/src/xpconnect/src/Makefile
js/src/xpconnect/tests/Makefile
js/src/xpconnect/tests/components/Makefile
js/src/xpconnect/shell/Makefile
# js/src/xpconnect/md/Makefile
# js/src/xpconnect/md/unix/Makefile
# js/src/xpconnect/test/Makefile
js/src/xpconnect/md/Makefile
js/src/xpconnect/md/unix/Makefile
js/src/xpconnect/test/Makefile
layout/Makefile
layout/base/Makefile
layout/base/public/Makefile
@@ -179,7 +148,6 @@ layout/html/content/Makefile
layout/html/content/public/Makefile
layout/html/content/src/Makefile
layout/html/document/Makefile
layout/html/document/public/Makefile
layout/html/document/src/Makefile
layout/html/forms/Makefile
layout/html/forms/public/Makefile
@@ -210,17 +178,12 @@ layout/xul/content/src/Makefile
lib/libpwcac/Makefile
lib/xp/Makefile
modules/libimg/Makefile
# modules/libimg/classes/Makefile
# modules/libimg/classes/netscape/Makefile
# modules/libimg/classes/netscape/libimg/Makefile
modules/libimg/classes/Makefile
modules/libimg/classes/netscape/Makefile
modules/libimg/classes/netscape/libimg/Makefile
modules/libimg/png/Makefile
modules/libimg/public/Makefile
modules/libimg/public_com/Makefile
modules/libimg/src/Makefile
modules/libimg/gifcom/Makefile
modules/libimg/jpgcom/Makefile
modules/libimg/pngcom/Makefile
modules/libjar/Makefile
modules/libpref/Makefile
modules/libpref/admin/Makefile
modules/libpref/l10n/Makefile
@@ -278,27 +241,14 @@ network/protocol/marimba/Makefile
network/protocol/remote/Makefile
network/protocol/sockstub/Makefile
network/util/Makefile
profile/Makefile
profile/src/Makefile
profile/public/Makefile
profile/resources/Makefile
rdf/Makefile
rdf/base/Makefile
rdf/base/idl/Makefile
rdf/base/public/Makefile
rdf/base/src/Makefile
rdf/brprof/Makefile
rdf/brprof/public/Makefile
rdf/brprof/src/Makefile
rdf/brprof/build/Makefile
rdf/chrome/Makefile
rdf/chrome/build/Makefile
rdf/chrome/public/Makefile
rdf/chrome/src/Makefile
rdf/util/Makefile
rdf/util/public/Makefile
rdf/util/src/Makefile
rdf/resources/Makefile
rdf/build/Makefile
rdf/content/Makefile
rdf/content/public/Makefile
@@ -309,8 +259,6 @@ rdf/datasource/src/Makefile
rdf/tests/Makefile
rdf/tests/localfile/Makefile
rdf/tests/rdfsink/Makefile
rdf/tests/rdfcat/Makefile
rdf/tests/rdfpoll/Makefile
sun-java/Makefile
sun-java/stubs/Makefile
sun-java/stubs/include/Makefile
@@ -333,11 +281,9 @@ widget/Makefile
widget/public/Makefile
widget/src/Makefile
widget/src/build/Makefile
widget/src/gtk/Makefile
widget/src/motif/Makefile
widget/src/photon/Makefile
widget/src/rhapsody/Makefile
widget/src/xlib/Makefile
widget/src/gtk/Makefile
widget/src/xpwidgets/Makefile
widget/tests/Makefile
widget/tests/scribble/Makefile
@@ -345,37 +291,21 @@ widget/tests/widget/Makefile
xpcom/Makefile
xpcom/public/Makefile
xpcom/src/Makefile
xpcom/sample/Makefile
xpcom/tests/Makefile
xpcom/tests/dynamic/Makefile
xpcom/tools/Makefile
xpcom/tools/xpidl/Makefile
xpcom/tools/registry/Makefile
xpcom/libxpt/Makefile
xpcom/libxpt/public/Makefile
xpcom/libxpt/src/Makefile
xpcom/libxpt/tests/Makefile
xpcom/libxpt/tools/Makefile
xpcom/libxpt/xptcall/Makefile
xpcom/libxpt/xptcall/public/Makefile
xpcom/libxpt/xptcall/src/Makefile
xpcom/libxpt/xptcall/src/md/Makefile
xpcom/libxpt/xptcall/src/md/unix/Makefile
xpcom/libxpt/xptcall/src/md/test/Makefile
xpcom/libxpt/xptcall/tests/Makefile
xpcom/libxpt/xptinfo/Makefile
xpcom/libxpt/xptinfo/public/Makefile
xpcom/libxpt/xptinfo/src/Makefile
xpcom/libxpt/xptinfo/tests/Makefile
xpcom/idl/Makefile
xpcom/proxy/Makefile
xpcom/proxy/public/Makefile
xpcom/proxy/src/Makefile
xpcom/proxy/tests/Makefile
silentdl/Makefile
xpinstall/Makefile
xpinstall/public/Makefile
xpinstall/src/Makefile
xpfe/Makefile
xpfe/AppCores/Makefile
xpfe/AppCores/public/Makefile
@@ -385,30 +315,9 @@ xpfe/AppCores/idl/Makefile
xpfe/browser/Makefile
xpfe/browser/public/Makefile
xpfe/browser/src/Makefile
xpfe/browser/samples/Makefile
xpfe/browser/samples/sampleimages/Makefile
xpfe/components/Makefile
xpfe/components/public/Makefile
xpfe/components/sample/Makefile
xpfe/components/sample/public/Makefile
xpfe/components/sample/src/Makefile
xpfe/components/sample/resources/Makefile
xpfe/components/find/Makefile
xpfe/components/find/public/Makefile
xpfe/components/find/src/Makefile
xpfe/components/find/resources/Makefile
xpfe/components/history/Makefile
xpfe/components/history/src/Makefile
xpfe/components/history/public/Makefile
xpfe/components/history/resources/Makefile
xpfe/components/xfer/Makefile
xpfe/components/xfer/public/Makefile
xpfe/components/xfer/src/Makefile
xpfe/components/xfer/resources/Makefile
xpfe/components/ucth/Makefile
xpfe/components/ucth/public/Makefile
xpfe/components/ucth/src/Makefile
xpfe/components/ucth/resources/Makefile
# xpfe/xpviewer/Makefile
# xpfe/xpviewer/src/Makefile
# xpfe/xpviewer/public/Makefile
xpfe/appshell/Makefile
xpfe/appshell/src/Makefile
xpfe/appshell/public/Makefile
@@ -425,27 +334,12 @@ editor/txmgr/Makefile
editor/txmgr/public/Makefile
editor/txmgr/src/Makefile
editor/txmgr/tests/Makefile
editor/txtsvc/Makefile
editor/txtsvc/public/Makefile
editor/txtsvc/src/Makefile
editor/guimgr/Makefile
editor/guimgr/src/Makefile
editor/guimgr/public/Makefile
editor/ui/Makefile
editor/ui/composer/Makefile
editor/ui/composer/content/Makefile
editor/ui/composer/skin/Makefile
editor/ui/dialogs/Makefile
editor/ui/dialogs/content/Makefile
editor/ui/dialogs/skin/Makefile
END_EDITOR_MAKEFILES
fi
if [ "$MOZ_MAIL_NEWS" ]; then
add_makefiles < ${srcdir}/mailnews/makefiles
fi
if [ -d ${srcdir}/netwerk ]; then
add_makefiles < ${srcdir}/netwerk/makefiles
fi

Binary file not shown.

View File

@@ -18,6 +18,6 @@
DEPTH=..
IGNORE_MANIFEST=1
DIRS=public src tests
DIRS=public src
include <$(DEPTH)\config\rules.mak>

View File

@@ -6,21 +6,9 @@ nsAutoLock.h
nsISizeOfHandler.h
nsFileStream.h
nsIFileStream.h
nsIString.h
nsIStringStream.h
nsFileSpec.h
nsFileSpecStreaming.h
nsRepeater.h
nsIProperties.h
nsIScriptable.h
nsIVariant.h
nsCaretProperties.h
nsSpecialSystemDirectory.h
nsIObserverService.h
nsIObserverList.h
nsIObserver.h
nsEscape.h
nsStdFileStream.h
nsQuickSort.h
nsIThread.h
nsIByteBufferInputStream.h

View File

@@ -27,26 +27,14 @@ DEFINES += -D_IMPL_NS_BASE
EXPORTS = \
nsAutoLock.h \
nsIProperties.h \
nsIScriptable.h \
nsIVariant.h \
nsISizeOfHandler.h \
nsIString.h \
nsCaretProperties.h \
nsEscape.h \
nsFileSpec.h \
nsFileStream.h \
nsIFileStream.h \
nsIStringStream.h \
nsFileSpecStreaming.h \
nsSpecialSystemDirectory.h \
nsIObserverService.h \
nsIObserverList.h \
nsIObserver.h \
nsQuickSort.h \
nsIPageManager.h \
nsIBuffer.h \
nsIByteBufferInputStream.h \
nsIThread.h \
$(NULL)
EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS))

View File

@@ -24,25 +24,13 @@ EXPORTS = \
nsAutoLock.h \
nsCaretProperties.h \
nsIProperties.h \
nsIScriptable.h \
nsIVariant.h \
nsISizeOfHandler.h \
nsEscape.h \
nsFileSpec.h \
nsFileSpecStreaming.h \
nsFileStream.h \
nsIFileStream.h \
nsIString.h \
nsIStringStream.h \
nsIThread.h \
nsSpecialSystemDirectory.h \
nsIByteBufferInputStream.h \
nsIObserverService.h \
nsIObserverList.h \
nsIObserver.h \
nsQuickSort.h \
nsIPageManager.h \
nsIBuffer.h \
$(NULL)
MODULE = raptor

View File

@@ -105,75 +105,12 @@ public:
PR_Lock(mLock);
}
~nsAutoLock(void) {
PR_Unlock(mLock);
}
};
////////////////////////////////////////////////////////////////////////////////
// Same sort of shit here. Imagine if you will:
//
// nsresult MyClass::MyMethod(...) {
// nsAutoMonitor mon(this); // or some random object as a monitor
// ...
// // go ahead and do deeply nested returns...
// return NS_ERROR_FAILURE;
// ...
// // or call Wait or Notify...
// mon.Wait();
// ...
// // cleanup is automatic
// }
#include "prcmon.h"
#include "nsError.h"
class nsAutoMonitor {
public:
nsAutoMonitor(void* lockObject)
: mLockObject(lockObject)
{
NS_ASSERTION(lockObject, "null lock object");
PR_CEnterMonitor(mLockObject);
}
~nsAutoMonitor() {
PR_CExitMonitor(mLockObject);
}
nsresult Wait(PRIntervalTime interval = PR_INTERVAL_NO_TIMEOUT) {
return PR_CWait(mLockObject, interval) == PR_SUCCESS
? NS_OK : NS_ERROR_FAILURE;
}
nsresult Notify() {
return PR_CNotify(mLockObject) == PR_SUCCESS
? NS_OK : NS_ERROR_FAILURE;
}
nsresult NotifyAll() {
return PR_CNotifyAll(mLockObject) == PR_SUCCESS
? NS_OK : NS_ERROR_FAILURE;
}
private:
void* mLockObject;
// Not meant to be implemented. This makes it a compiler error to
// construct or assign an nsAutoLock object incorrectly.
nsAutoMonitor(void) {}
nsAutoMonitor(nsAutoMonitor& aMon) {}
nsAutoMonitor& operator =(nsAutoMonitor& aMon) {
return *this;
}
// Not meant to be implemented. This makes it a compiler error to
// attempt to create an nsAutoLock object on the heap.
static void* operator new(size_t size) {
return nsnull;
}
static void operator delete(void* memory) {}
};
#endif // nsAutoLock_h__

View File

@@ -53,12 +53,6 @@ NS_BASE PRInt32 nsUnescapeCount (char * str);
* (result may contain \0's).
*/
NS_BASE char *
nsEscapeHTML(const char * string);
/*
* Escape problem char's for HTML display
*/
#ifdef __cplusplus
}
#endif

View File

@@ -53,7 +53,7 @@
//
// nsFilePath myPath("/Development/iotest.txt");
//
// nsOutputFileStream testStream(nsFileSpec(myPath));
// nsOutputFileStream testStream(myPath);
// testStream << "Hello World" << nsEndl;
//
// 4. Handy methods for manipulating file specifiers safely, e.g. MakeUnique(),
@@ -63,35 +63,35 @@
//
// Examples:
//
// Initialize a URL from a string
// Initialize a URL from a string without suffix
//
// nsFileURL fileURL("file:///Development/MPW/MPW%20Shell");
//
// Initialize a Unix-style path from a URL
// Initialize a Unix path from a URL
//
// nsFilePath filePath(fileURL);
//
// Initialize a file spec from a URL
// Initialize a native file spec from a URL
//
// nsFileSpec fileSpec(fileURL);
//
// Make the spec unique.
// Make the spec unique (this one has no suffix).
//
// fileSpec.MakeUnique();
//
// Assign the spec to a URL (causing conversion)
// Assign the spec to a URL
//
// fileURL = fileSpec;
//
// Assign a unix path using a string
// Assign a unix path using a string with a suffix.
//
// filePath = "/Development/MPW/SysErrs.err";
//
// Assign to a file spec using a unix path (causing conversion).
// Assign to a file spec using a unix path.
//
// fileSpec = filePath;
//
// Make this unique.
// Make this unique (this one has a suffix).
//
// fileSpec.MakeUnique();
//
@@ -103,6 +103,10 @@
// is solved by holding a "private" native file spec inside the
// nsFilePath and nsFileURL classes, which is used when appropriate.
//
// Not yet done:
//
// Equality operators... much more.
//
//========================================================================================
#ifndef _FILESPEC_H_
@@ -111,7 +115,6 @@
#include "nscore.h"
#include "nsError.h"
#include "nsString.h"
#include "nsCRT.h"
//========================================================================================
// Compiler-specific macros, as needed
@@ -140,7 +143,7 @@
#include <Files.h>
#elif defined(XP_UNIX) || defined (XP_OS2)
#include <dirent.h>
#elif defined(XP_PC)
#elif XP_PC
#include "prio.h"
#endif
@@ -149,9 +152,8 @@
//========================================================================================
class nsFileSpec; // Preferred. For i/o use nsInputFileStream, nsOutputFileStream
class nsFilePath;
class nsFilePath; // This can be passed to NSPR file I/O routines, if you must.
class nsFileURL;
class nsNSPRPath; // This can be passed to NSPR file I/O routines, if you must.
class nsPersistentFileDescriptor; // Used for storage across program launches.
#define kFileURLPrefix "file://"
@@ -164,7 +166,6 @@ class nsIInputStream;
class nsOutputFileStream;
class nsInputFileStream;
class nsOutputConsoleStream;
class nsString;
//========================================================================================
@@ -200,87 +201,11 @@ public:
NS_EXPLICIT nsAutoCString(const nsString& other) : mCString(other.ToNewCString()) {}
virtual ~nsAutoCString();
operator const char*() const { return mCString; }
// operator const char*() { return mCString; }
// don't need this, since |operator const char*() const| can
// serve for both |const| and non-|const| callers
operator const char*() { return mCString; }
protected:
const char* mCString;
}; // class nsAutoCString
//========================================================================================
class NS_BASE nsSimpleCharString
// An envelope for char*: reference counted. Used internally by all the nsFileSpec
// classes below.
//========================================================================================
{
public:
nsSimpleCharString();
nsSimpleCharString(const char*);
nsSimpleCharString(const nsString&);
nsSimpleCharString(const nsSimpleCharString&);
nsSimpleCharString(const char* inData, PRUint32 inLength);
~nsSimpleCharString();
void operator = (const char*);
void operator = (const nsString&);
void operator = (const nsSimpleCharString&);
operator const char*() const { return mData ? mData->mString : 0; }
operator char* ()
{
ReallocData(Length()); // requires detaching if shared...
return mData ? mData->mString : 0;
}
PRBool operator == (const char*);
PRBool operator == (const nsString&);
PRBool operator == (const nsSimpleCharString&);
void operator += (const char* inString);
nsSimpleCharString operator + (const char* inString) const;
char operator [](int i) const { return mData ? mData->mString[i] : 0; }
char& operator [](int i)
{
if (i >= (int)Length())
ReallocData((PRUint32)i + 1);
return mData->mString[i]; // caveat appelator
}
char& operator [](unsigned int i) { return (*this)[(int)i]; }
void Catenate(const char* inString1, const char* inString2);
void SetToEmpty();
PRBool IsEmpty() const { return Length() == 0; }
PRUint32 Length() const { return mData ? mData->mLength : 0; }
void SetLength(PRUint32 inLength) { ReallocData(inLength); }
void CopyFrom(const char* inData, PRUint32 inLength);
void LeafReplace(char inSeparator, const char* inLeafName);
char* GetLeaf(char inSeparator) const; // use PR_Free()
void Unescape();
protected:
void AddRefData();
void ReleaseData();
void ReallocData(PRUint32 inLength);
//--------------------------------------------------
// Data
//--------------------------------------------------
protected:
struct Data {
int mRefCount;
PRUint32 mLength;
char mString[1];
};
Data* mData;
}; // class nsSimpleCharString
//========================================================================================
class NS_BASE nsFileSpec
// This is whatever each platform really prefers to describe files as. Declared first
@@ -289,26 +214,20 @@ class NS_BASE nsFileSpec
{
public:
nsFileSpec();
// These two meathods take *native* file paths.
NS_EXPLICIT nsFileSpec(const char* inNativePath, PRBool inCreateDirs = PR_FALSE);
NS_EXPLICIT nsFileSpec(const nsString& inNativePath, PRBool inCreateDirs = PR_FALSE);
NS_EXPLICIT nsFileSpec(const char* inString, PRBool inCreateDirs = PR_FALSE);
NS_EXPLICIT nsFileSpec(const nsString& inString, PRBool inCreateDirs = PR_FALSE);
NS_EXPLICIT nsFileSpec(const nsFilePath& inPath);
NS_EXPLICIT nsFileSpec(const nsFileURL& inURL);
NS_EXPLICIT nsFileSpec(const nsPersistentFileDescriptor& inURL);
nsFileSpec(const nsFileSpec& inPath);
virtual ~nsFileSpec();
// These two operands take *native* file paths.
void operator = (const char* inNativePath);
void operator = (const nsString& inNativePath)
void operator = (const char* inPath);
void operator = (const nsString& inPath)
{
const nsAutoCString path(inNativePath);
const nsAutoCString path(inPath);
*this = path;
}
void operator = (const nsFilePath& inPath);
void operator = (const nsFileURL& inURL);
void operator = (const nsFileSpec& inOther);
@@ -319,19 +238,14 @@ class NS_BASE nsFileSpec
operator const char* () const { return GetCString(); }
// Same as GetCString (please read the comments).
// Do not try to free this!
const char* GetNativePathCString() const { return GetCString(); }
// Same as GetCString (please read the comments).
// Do not try to free this!
const char* GetCString() const;
// Returns a native path, and allows the
// This is the only conversion to const char*
// that is provided, and it allows the
// path to be "passed" to legacy code. This practice
// is VERY EVIL and should only be used to support legacy
// code. Using it guarantees bugs on Macintosh.
// The path is cached and freed by the nsFileSpec destructor
// so do not delete (or free) it. See also nsNSPRPath below,
// if you really must pass a string to PR_OpenFile().
// Doing so will introduce two automatic bugs.
// so do not delete (or free) it.
#ifdef XP_MAC
// For Macintosh people, this is meant to be useful in its own right as a C++ version
@@ -341,7 +255,7 @@ class NS_BASE nsFileSpec
long parID,
ConstStr255Param name);
nsFileSpec(const FSSpec& inSpec)
: mSpec(inSpec), mError(NS_OK) {}
: mSpec(inSpec), mError(NS_OK), mPath(nsnull) {}
void operator = (const FSSpec& inSpec)
{ mSpec = inSpec; mError = NS_OK; }
@@ -364,27 +278,31 @@ class NS_BASE nsFileSpec
void MakeUnique(ConstStr255Param inSuggestedLeafName);
StringPtr GetLeafPName() { return mSpec.name; }
ConstStr255Param GetLeafPName() const { return mSpec.name; }
OSErr GetCatInfo(CInfoPBRec& outInfo) const;
#endif // end of Macintosh utility methods.
PRBool Valid() const { return NS_SUCCEEDED(Error()); }
nsresult Error() const
{
#ifndef XP_MAC
if (mPath.IsEmpty() && NS_SUCCEEDED(mError))
((nsFileSpec*)this)->mError = NS_ERROR_NOT_INITIALIZED;
if (!mPath && NS_SUCCEEDED(mError))
((nsFileSpec*)this)->mError = NS_FILE_FAILURE;
#endif
return mError;
}
PRBool Failed() const { return (PRBool)NS_FAILED(Error()); }
PRBool Failed() const { return NS_FAILED(Error()); }
//--------------------------------------------------
// Queries and path algebra. These do not modify the disk.
//--------------------------------------------------
char* GetLeafName() const; // Allocated. Use nsCRT::free().
friend NS_BASE nsOutputStream& operator << (
nsOutputStream& s,
const nsFileSpec& spec); // THIS IS FOR DEBUGGING ONLY.
// see PersistentFileDescriptor for the real deal.
//--------------------------------------------------
// Queries and path algebra. These do not modify the disk.
//--------------------------------------------------
char* GetLeafName() const; // Allocated. Use delete [].
void SetLeafName(const char* inLeafName);
// inLeafName can be a relative path, so this allows
// one kind of concatenation of "paths".
@@ -422,14 +340,14 @@ class NS_BASE nsFileSpec
PRUint32 GetFileSize() const;
PRUint32 GetDiskSpaceAvailable() const;
nsFileSpec operator + (const char* inRelativeUnixPath) const;
nsFileSpec operator + (const nsString& inRelativeUnixPath) const
nsFileSpec operator + (const char* inRelativePath) const;
nsFileSpec operator + (const nsString& inRelativePath) const
{
const nsAutoCString
relativePath(inRelativeUnixPath);
relativePath(inRelativePath);
return *this + relativePath;
}
void operator += (const char* inRelativeUnixPath);
void operator += (const char* inRelativePath);
// Concatenate the relative path to this directory.
// Used for constructing the filespec of a descendant.
// This must be a directory for this to work. This differs
@@ -438,9 +356,9 @@ class NS_BASE nsFileSpec
// away its leaf information, whereas this one assumes
// this is a directory, and the relative path starts
// "below" this.
void operator += (const nsString& inRelativeUnixPath)
void operator += (const nsString& inRelativePath)
{
const nsAutoCString relativePath(inRelativeUnixPath);
const nsAutoCString relativePath(inRelativePath);
*this += relativePath;
}
@@ -458,13 +376,11 @@ class NS_BASE nsFileSpec
// More stringent than Exists()
PRBool Exists() const;
//--------------------------------------------------
// Creation and deletion of objects. These can modify the disk.
//--------------------------------------------------
//--------------------------------------------------
// Creation and deletion of objects. These can modify the disk.
//--------------------------------------------------
void CreateDirectory(int mode = 0700 /* for unix */);
void CreateDir(int mode = 0700) { CreateDirectory(mode); }
// workaround for yet another VC++ bug with long identifiers.
void Delete(PRBool inRecursive) const;
nsresult Rename(const char* inNewName); // not const: gets updated
@@ -474,16 +390,21 @@ class NS_BASE nsFileSpec
return Rename(newName);
}
nsresult Copy(const nsFileSpec& inNewParentDirectory) const;
nsresult Move(const nsFileSpec& inNewParentDirectory);
nsresult Move(const nsFileSpec& inNewParentDirectory) const;
nsresult Execute(const char* args) const;
nsresult Execute(const nsString& args) const
{
const nsAutoCString argsString(args);
return Execute(argsString);
}
//--------------------------------------------------
// Data
//--------------------------------------------------
protected:
#ifdef XP_MAC
OSErr GetCatInfo(CInfoPBRec& outInfo) const;
#endif
//--------------------------------------------------
// Data
//--------------------------------------------------
protected:
friend class nsFilePath;
@@ -492,7 +413,7 @@ class NS_BASE nsFileSpec
#ifdef XP_MAC
FSSpec mSpec;
#endif
nsSimpleCharString mPath;
char* mPath;
nsresult mError;
}; // class nsFileSpec
@@ -509,8 +430,8 @@ class NS_BASE nsFileURL
{
public:
nsFileURL(const nsFileURL& inURL);
NS_EXPLICIT nsFileURL(const char* inURLString, PRBool inCreateDirs = PR_FALSE);
NS_EXPLICIT nsFileURL(const nsString& inURLString, PRBool inCreateDirs = PR_FALSE);
NS_EXPLICIT nsFileURL(const char* inString, PRBool inCreateDirs = PR_FALSE);
NS_EXPLICIT nsFileURL(const nsString& inString, PRBool inCreateDirs = PR_FALSE);
NS_EXPLICIT nsFileURL(const nsFilePath& inPath);
NS_EXPLICIT nsFileURL(const nsFileSpec& inPath);
virtual ~nsFileURL();
@@ -520,36 +441,31 @@ class NS_BASE nsFileURL
// but should not provide a conversion constructor.
void operator = (const nsFileURL& inURL);
void operator = (const char* inURLString);
void operator = (const nsString& inURLString)
void operator = (const char* inString);
void operator = (const nsString& inString)
{
const nsAutoCString string(inURLString);
const nsAutoCString string(inString);
*this = string;
}
void operator = (const nsFilePath& inOther);
void operator = (const nsFileSpec& inOther);
void operator +=(const char* inRelativeUnixPath);
nsFileURL operator +(const char* inRelativeUnixPath) const;
operator const char* () const { return (const char*)mURL; } // deprecated.
const char* GetURLString() const { return (const char*)mURL; }
// Not allocated, so don't free it.
const char* GetAsString() const { return (const char*)mURL; }
// Not allocated, so don't free it.
operator const char* () const { return mURL; } // deprecated.
const char* GetAsString() const { return mURL; }
friend NS_BASE nsOutputStream& operator << (
nsOutputStream& s, const nsFileURL& spec);
#ifdef XP_MAC
// Accessor to allow quick assignment to a mFileSpec
const nsFileSpec& GetFileSpec() const { return mFileSpec; }
#endif
//--------------------------------------------------
// Data
//--------------------------------------------------
private:
// Should not be defined (only nsFilePath is to be treated as strings.
operator char* ();
protected:
friend class nsFilePath; // to allow construction of nsFilePath
nsSimpleCharString mURL;
char* mURL;
#ifdef XP_MAC
// Since the path on the macintosh does not uniquely specify a file (volumes
// can have the same name), stash the secret nsFileSpec, too.
@@ -566,44 +482,41 @@ class NS_BASE nsFilePath
{
public:
nsFilePath(const nsFilePath& inPath);
NS_EXPLICIT nsFilePath(const char* inUnixPathString, PRBool inCreateDirs = PR_FALSE);
NS_EXPLICIT nsFilePath(const nsString& inUnixPathString, PRBool inCreateDirs = PR_FALSE);
NS_EXPLICIT nsFilePath(const char* inString, PRBool inCreateDirs = PR_FALSE);
NS_EXPLICIT nsFilePath(const nsString& inString, PRBool inCreateDirs = PR_FALSE);
NS_EXPLICIT nsFilePath(const nsFileURL& inURL);
NS_EXPLICIT nsFilePath(const nsFileSpec& inPath);
virtual ~nsFilePath();
operator const char* () const { return mPath; }
// This will return a UNIX string. If you
// need a string that can be passed into
// NSPR, take a look at the nsNSPRPath class.
// This is the only automatic conversion to const char*
// that is provided, and it allows the
// path to be "passed" to NSPR file routines.
operator char* () { return mPath; }
// This is the only automatic conversion to string
// that is provided, because a naked string should
// only mean a standard file path.
void operator = (const nsFilePath& inPath);
void operator = (const char* inUnixPathString);
void operator = (const nsString& inUnixPathString)
void operator = (const char* inString);
void operator = (const nsString& inString)
{
const nsAutoCString string(inUnixPathString);
const nsAutoCString string(inString);
*this = string;
}
void operator = (const nsFileURL& inURL);
void operator = (const nsFileSpec& inOther);
void operator +=(const char* inRelativeUnixPath);
nsFilePath operator +(const char* inRelativeUnixPath) const;
#ifdef XP_MAC
public:
// Accessor to allow quick assignment to a mFileSpec
const nsFileSpec& GetFileSpec() const { return mFileSpec; }
#endif
//--------------------------------------------------
// Data
//--------------------------------------------------
private:
nsSimpleCharString mPath;
char* mPath;
#ifdef XP_MAC
// Since the path on the macintosh does not uniquely specify a file (volumes
// can have the same name), stash the secret nsFileSpec, too.
@@ -620,7 +533,7 @@ class NS_BASE nsPersistentFileDescriptor
//========================================================================================
{
public:
nsPersistentFileDescriptor() {}
nsPersistentFileDescriptor() : mDescriptorString(nsnull) {}
// For use prior to reading in from a stream
nsPersistentFileDescriptor(const nsPersistentFileDescriptor& inPath);
virtual ~nsPersistentFileDescriptor();
@@ -630,11 +543,8 @@ class NS_BASE nsPersistentFileDescriptor
NS_EXPLICIT nsPersistentFileDescriptor(const nsFileSpec& inPath);
void operator = (const nsFileSpec& inPath);
// The following four functions are declared here (as friends). Their implementations
// are in mozilla/base/src/nsFileSpecStreaming.cpp.
friend nsresult Read(nsIInputStream* aStream, nsPersistentFileDescriptor&);
friend nsresult Write(nsIOutputStream* aStream, const nsPersistentFileDescriptor&);
nsresult Read(nsIInputStream* aStream);
nsresult Write(nsIOutputStream* aStream);
// writes the data to a file
friend NS_BASE nsInputStream& operator >> (nsInputStream&, nsPersistentFileDescriptor&);
// reads the data from a file
@@ -642,18 +552,15 @@ class NS_BASE nsPersistentFileDescriptor
// writes the data to a file
friend class nsFileSpec;
void GetData(nsSimpleCharString& outData) const;
void SetData(const nsSimpleCharString& inData);
void GetData(nsSimpleCharString& outData, PRInt32& outSize) const;
void SetData(const nsSimpleCharString& inData, PRInt32 inSize);
//--------------------------------------------------
// Data
//--------------------------------------------------
private:
// Here are the ways to get data in and out of a file.
void GetData(void*& outData, PRInt32& outSize) const;
// DON'T FREE the returned data!
void SetData(const void* inData, PRInt32 inSize);
protected:
nsSimpleCharString mDescriptorString;
char* mDescriptorString;
}; // class nsPersistentFileDescriptor
@@ -662,16 +569,16 @@ class NS_BASE nsDirectoryIterator
// Example:
//
// nsFileSpec parentDir(...); // directory over whose children we shall iterate
// for (nsDirectoryIterator i(parentDir); i.Exists(); i++)
// for (nsDirectoryIterator i(parentDir); i; i++)
// {
// // do something with i.Spec()
// // do something with (const nsFileSpec&)i
// }
//
// or:
//
// for (nsDirectoryIterator i(parentDir, -1); i.Exists(); i--)
// for (nsDirectoryIterator i(parentDir, PR_FALSE); i; i--)
// {
// // do something with i.Spec()
// // do something with (const nsFileSpec&)i
// }
//
// Currently, the only platform on which backwards iteration actually goes backwards
@@ -692,65 +599,19 @@ class NS_BASE nsDirectoryIterator
nsDirectoryIterator& operator --(); // moves to the previous item, if any.
nsDirectoryIterator& operator --(int) { return --(*this); } // post-decrement.
operator nsFileSpec&() { return mCurrent; }
nsFileSpec& Spec() { return mCurrent; }
private:
#if defined(XP_MAC)
OSErr SetToIndex();
#endif
//--------------------------------------------------
// Data
//--------------------------------------------------
private:
nsFileSpec mCurrent;
PRBool mExists;
#if defined(XP_UNIX)
DIR* mDir;
#elif defined(XP_PC)
PRDir* mDir; // XXX why not use PRDir for Unix too?
PRDir* mDir; // XXX why not use PRDir for Unix & Mac, too?
#elif defined(XP_MAC)
OSErr SetToIndex();
short mIndex;
short mMaxIndex;
#endif
}; // class nsDirectoryIterator
//========================================================================================
class NS_BASE nsNSPRPath
// This class will allow you to pass any one of the nsFile* classes directly into NSPR
// without the need to worry about whether you have the right kind of filepath or not.
// It will also take care of cleaning up any allocated memory.
//========================================================================================
{
public:
NS_EXPLICIT nsNSPRPath(const nsFileSpec& inSpec)
: mFilePath(inSpec), modifiedNSPRPath(nsnull) {}
NS_EXPLICIT nsNSPRPath(const nsFileURL& inURL)
: mFilePath(inURL), modifiedNSPRPath(nsnull) {}
NS_EXPLICIT nsNSPRPath(const nsFilePath& inUnixPath)
: mFilePath(inUnixPath), modifiedNSPRPath(nsnull) {}
virtual ~nsNSPRPath();
operator const char*() const;
// Returns the path
// that NSPR file routines expect on each platform.
// Concerning constness, this can modify
// modifiedNSPRPath, but it's really just "mutable".
//--------------------------------------------------
// Data
//--------------------------------------------------
private:
nsFilePath mFilePath;
char* modifiedNSPRPath; // Currently used only on XP_PC
}; // class nsNSPRPath
#endif // _FILESPEC_H_

View File

@@ -1,47 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
// Functions for nsPersistentFileDescriptor that depend on streams, and so
// cannot be made independent of base.
#include "nscore.h"
#include "nsError.h"
class nsPersistentFileDescriptor;
class nsInputStream;
class nsOutputStream;
class nsIInputStream;
class nsIOutputStream;
class nsFileURL;
class nsFileSpec;
NS_BASE nsOutputStream& operator << (nsOutputStream& s, const nsFileURL& spec);
NS_BASE nsresult ReadDescriptor(
nsIInputStream* aStream, nsPersistentFileDescriptor&);
NS_BASE nsresult WriteDescriptor(
nsIOutputStream* aStream,
const nsPersistentFileDescriptor&);
// writes the data to a file
NS_BASE nsInputStream& operator >> (
nsInputStream&,
nsPersistentFileDescriptor&);
// reads the data from a stream (file or string)
NS_BASE nsOutputStream& operator << (
nsOutputStream&,
const nsPersistentFileDescriptor&);
// writes the data to a stream (file or string)

View File

@@ -171,7 +171,7 @@ public:
{
return mInputStream;
}
PRBool eof() const { return get_at_eof(); }
char eof() const { return get_at_eof(); }
char get();
void close()
{

View File

@@ -1,83 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIBuffer_h___
#define nsIBuffer_h___
#include "nsISupports.h"
#include "nscore.h"
class nsIInputStream;
class nsIAllocator;
class nsIInputStream;
class nsIOutputStream;
#define NS_IBUFFER_IID \
{ /* 1eebb300-fb8b-11d2-9324-00104ba0fd40 */ \
0x1eebb300, \
0xfb8b, \
0x11d2, \
{0x93, 0x24, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \
}
#define NS_BUFFER_CID \
{ /* 5dbe4de0-fbab-11d2-9324-00104ba0fd40 */ \
0x5dbe4de0, \
0xfbab, \
0x11d2, \
{0x93, 0x24, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \
}
class nsIBuffer : public nsISupports {
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_IBUFFER_IID);
NS_IMETHOD Init(PRUint32 growBySize, PRUint32 maxSize,
nsIAllocator* allocator) = 0;
NS_IMETHOD Read(char* toBuf, PRUint32 bufLen, PRUint32 *readCount) = 0;
NS_IMETHOD GetReadBuffer(PRUint32 *readBufferLength, char* *result) = 0;
NS_IMETHOD Write(const char* fromBuf, PRUint32 bufLen, PRUint32 *writeCount) = 0;
NS_IMETHOD Write(nsIInputStream* fromStream, PRUint32 *writeCount) = 0;
NS_IMETHOD GetWriteBuffer(PRUint32 *writeBufferLength, char* *result) = 0;
NS_IMETHOD SetEOF() = 0;
};
extern NS_BASE nsresult
NS_NewBuffer(nsIBuffer* *result,
PRUint32 growBySize, PRUint32 maxSize);
extern NS_BASE nsresult
NS_NewPageBuffer(nsIBuffer* *result,
PRUint32 growBySize, PRUint32 maxSize);
extern NS_BASE nsresult
NS_NewBufferInputStream(nsIInputStream* *result,
nsIBuffer* buffer, PRBool blocking = PR_FALSE);
extern NS_BASE nsresult
NS_NewBufferOutputStream(nsIOutputStream* *result,
nsIBuffer* buffer, PRBool blocking = PR_FALSE);
extern NS_BASE nsresult
NS_NewPipe2(nsIInputStream* *inStrResult,
nsIOutputStream* *outStrResult,
PRUint32 growBySize, PRUint32 maxSize);
#endif // nsIBuffer_h___

View File

@@ -1,58 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIByteBufferInputStream_h___
#define nsIByteBufferInputStream_h___
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#define NS_IBYTEBUFFERINPUTSTREAM_IID \
{ /* 40767100-eb9c-11d2-931c-00104ba0fd40 */ \
0x40767100, \
0xeb9c, \
0x11d2, \
{0x93, 0x1c, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \
}
class nsIByteBufferInputStream : public nsIInputStream {
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_IBYTEBUFFERINPUTSTREAM_IID);
NS_IMETHOD Fill(nsIInputStream* stream, PRUint32 *aWriteCount) = 0;
NS_IMETHOD Fill(const char* aBuf, PRUint32 aCount, PRUint32 *aWriteCount) = 0;
};
////////////////////////////////////////////////////////////////////////////////
extern NS_BASE nsresult
NS_NewByteBufferInputStream(nsIByteBufferInputStream* *result,
PRBool blocking = PR_FALSE,
PRUint32 size = 4096);
extern NS_BASE nsresult
NS_NewPipe(nsIInputStream* *inStrResult,
nsIOutputStream* *outStrResult,
PRBool blocking = PR_TRUE,
PRUint32 bufferSize = 4096);
////////////////////////////////////////////////////////////////////////////////
#endif /* nsByteBufferInputStream_h___ */

View File

@@ -101,6 +101,8 @@ class nsIFileOutputStream
{
public:
static const nsIID& GetIID() { static nsIID iid = NS_IFILEOUTPUTSTREAM_IID; return iid; }
NS_IMETHOD Flush() = 0;
// Forces a write to disk.
}; // class nsIFileOutputStream
//----------------------------------------------------------------------------------------

View File

@@ -1,45 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIObserver_h__
#define nsIObserver_h__
#include "nsISupports.h"
#include "nscore.h"
// {DB242E01-E4D9-11d2-9DDE-000064657374}
#define NS_IOBSERVER_IID \
{ 0xdb242e01, 0xe4d9, 0x11d2, { 0x9d, 0xde, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74 } }
// {DB242E03-E4D9-11d2-9DDE-000064657374}
#define NS_OBSERVER_CID \
{ 0xdb242e03, 0xe4d9, 0x11d2, { 0x9d, 0xde, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74 } }
class nsIObserver : public nsISupports {
public:
static const nsIID& GetIID() { static nsIID iid = NS_IOBSERVER_IID; return iid; }
NS_IMETHOD Notify(nsISupports** result) = 0;
};
extern NS_BASE nsresult NS_NewObserver(nsIObserver** anObserver);
#define NS_OBSERVER_PROGID "component:||netscape|Observer"
#endif /* nsIObserver_h__ */

View File

@@ -1,48 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIObserverList_h__
#define nsIObserverList_h__
#include "nsISupports.h"
#include "nsIObserver.h"
#include "nsIEnumerator.h"
#include "nscore.h"
// {E777D482-E6E3-11d2-8ACD-00105A1B8860}
#define NS_IOBSERVERLIST_IID \
{ 0xe777d482, 0xe6e3, 0x11d2, { 0x8a, 0xcd, 0x0, 0x10, 0x5a, 0x1b, 0x88, 0x60 } }
// {E777D484-E6E3-11d2-8ACD-00105A1B8860}
#define NS_OBSERVERLIST_CID \
{ 0xe777d484, 0xe6e3, 0x11d2, { 0x8a, 0xcd, 0x0, 0x10, 0x5a, 0x1b, 0x88, 0x60 } }
class nsIObserverList : public nsISupports {
public:
static const nsIID& GetIID() { static nsIID iid = NS_IOBSERVERLIST_IID; return iid; }
NS_IMETHOD AddObserver(nsIObserver** anObserver) = 0;
NS_IMETHOD RemoveObserver(nsIObserver** anObserver) = 0;
NS_IMETHOD EnumerateObserverList(nsIEnumerator** anEnumerator) = 0;
};
extern NS_BASE nsresult NS_NewObserverList(nsIObserverList** anObserverList);
#endif /* nsIObserverList_h__ */

View File

@@ -1,51 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIObserverService_h__
#define nsIObserverService_h__
#include "nsISupports.h"
#include "nsIObserverList.h"
#include "nsString.h"
// {D07F5192-E3D1-11d2-8ACD-00105A1B8860}
#define NS_IOBSERVERSERVICE_IID \
{ 0xd07f5192, 0xe3d1, 0x11d2, { 0x8a, 0xcd, 0x0, 0x10, 0x5a, 0x1b, 0x88, 0x60 } }
// {D07F5195-E3D1-11d2-8ACD-00105A1B8860}
#define NS_OBSERVERSERVICE_CID \
{ 0xd07f5195, 0xe3d1, 0x11d2, { 0x8a, 0xcd, 0x0, 0x10, 0x5a, 0x1b, 0x88, 0x60 } }
class nsIObserverService : public nsISupports {
public:
static const nsIID& GetIID() { static nsIID iid = NS_IOBSERVERSERVICE_IID; return iid; }
NS_IMETHOD AddObserver(nsIObserver** anObserver, nsString* aTopic) = 0;
NS_IMETHOD RemoveObserver(nsIObserver** anObserver, nsString* aTopic) = 0;
NS_IMETHOD EnumerateObserverList(nsIEnumerator** anEnumerator, nsString* aTopic) = 0;
};
extern NS_BASE nsresult NS_NewObserverService(nsIObserverService** anObserverService);
#define NS_OBSERVERSERVICE_PROGID "component:||netscape|ObserverService"
#endif /* nsIObserverService_h__ */

View File

@@ -1,55 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIPageManager_h__
#define nsIPageManager_h__
#include "nsISupports.h"
#define NS_PAGEMGR_PAGE_BITS 12 // 4k pages
#define NS_PAGEMGR_PAGE_SIZE (1 << NS_PAGEMGR_PAGE_BITS)
#define NS_PAGEMGR_PAGE_MASK (NS_PAGEMGR_PAGE_SIZE - 1)
#define NS_PAGEMGR_PAGE_COUNT(bytes) (((bytes) + NS_PAGEMGR_PAGE_MASK) >> NS_PAGEMGR_PAGE_BITS)
#define NS_IPAGEMANAGER_IID \
{ /* bea98210-fb7b-11d2-9324-00104ba0fd40 */ \
0xbea98210, \
0xfb7b, \
0x11d2, \
{0x93, 0x24, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \
}
#define NS_PAGEMANAGER_CID \
{ /* cac907e0-fb7b-11d2-9324-00104ba0fd40 */ \
0xcac907e0, \
0xfb7b, \
0x11d2, \
{0x93, 0x24, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \
}
class nsIPageManager : public nsISupports {
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_IPAGEMANAGER_IID);
NS_IMETHOD AllocPages(PRUint32 pageCount, void* *result) = 0;
NS_IMETHOD DeallocPages(PRUint32 pageCount, void* pages) = 0;
};
#endif // nsIPageManager_h__

View File

@@ -19,89 +19,30 @@
#ifndef nsIProperties_h___
#define nsIProperties_h___
#include "nsISupports.h"
#define NS_IPROPERTIES_IID \
{ /* f42bc870-dc17-11d2-9311-00e09805570f */ \
0xf42bc870, \
0xdc17, \
0x11d2, \
{0x93, 0x11, 0x00, 0xe0, 0x98, 0x05, 0x57, 0x0f} \
}
class nsIProperties : public nsISupports {
public:
static const nsIID& GetIID() { static nsIID iid = NS_IPROPERTIES_IID; return iid; }
/**
* Defines a new property.
* @return NS_ERROR_FAILURE if a property is already defined.
*/
NS_IMETHOD DefineProperty(const char* prop, nsISupports* initialValue) = 0;
/**
* Undefines a property.
* @return NS_ERROR_FAILURE if a property is not already defined.
*/
NS_IMETHOD UndefineProperty(const char* prop) = 0;
/**
* Gets a property.
* @return NS_ERROR_FAILURE if a property is not already defined.
*/
NS_IMETHOD GetProperty(const char* prop, nsISupports* *result) = 0;
/**
* Sets a property.
* @return NS_ERROR_FAILURE if a property is not already defined.
*/
NS_IMETHOD SetProperty(const char* prop, nsISupports* value) = 0;
/**
* @return NS_OK if the property exists with the specified value
* @return NS_COMFALSE if the property does not exist, or doesn't have
* the specified value (values are compared with ==)
*/
NS_IMETHOD HasProperty(const char* prop, nsISupports* value) = 0;
};
// Returns a default implementation of an nsIProperties object.
extern nsresult
NS_NewIProperties(nsIProperties* *result);
////////////////////////////////////////////////////////////////////////////////
#include "nsID.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsISupports.h"
#include "nsString.h"
// {1A180F60-93B2-11d2-9B8B-00805F8A16D9}
#define NS_IPERSISTENTPROPERTIES_IID \
#define NS_IPROPERTIES_IID \
{ 0x1a180f60, 0x93b2, 0x11d2, \
{ 0x9b, 0x8b, 0x0, 0x80, 0x5f, 0x8a, 0x16, 0xd9 } }
// {2245E573-9464-11d2-9B8B-00805F8A16D9}
NS_DECLARE_ID(kPersistentPropertiesCID,
NS_DECLARE_ID(kPropertiesCID,
0x2245e573, 0x9464, 0x11d2, 0x9b, 0x8b, 0x0, 0x80, 0x5f, 0x8a, 0x16, 0xd9);
class nsIPersistentProperties : public nsIProperties
class nsIProperties : public nsISupports
{
public:
static const nsIID& GetIID() { static nsIID iid = NS_IPERSISTENTPROPERTIES_IID; return iid; }
NS_IMETHOD Load(nsIInputStream* aIn) = 0;
NS_IMETHOD Save(nsIOutputStream* aOut, const nsString& aHeader) = 0;
NS_IMETHOD Subclass(nsIPersistentProperties* aSubclass) = 0;
// XXX these 2 methods will be subsumed by the ones from
// nsIProperties once we figure this all out
NS_IMETHOD GetProperty(const nsString& aKey, nsString& aValue) = 0;
NS_IMETHOD SetProperty(const nsString& aKey, nsString& aNewValue,
nsString& aOldValue) = 0;
NS_IMETHOD Save(nsIOutputStream* aOut, const nsString& aHeader) = 0;
NS_IMETHOD Subclass(nsIProperties* aSubclass) = 0;
};
////////////////////////////////////////////////////////////////////////////////
#endif // nsIProperties_h___
#endif /* nsIProperties_h___ */

View File

@@ -1,49 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIScriptable_h___
#define nsIScriptable_h___
#include "nsIProperties.h"
#include "nsISupportsArray.h"
#define NS_ISCRIPTABLE_IID \
{ /* db941bf0-dc17-11d2-9311-00e09805570f */ \
0xdb941bf0, \
0xdc17, \
0x11d2, \
{0x93, 0x11, 0x00, 0xe0, 0x98, 0x05, 0x57, 0x0f} \
}
class nsIScriptable : public nsIProperties {
public:
static const nsIID& GetIID() { static nsIID iid = NS_ISCRIPTABLE_IID; return iid; }
NS_IMETHOD Call(const char* command,
nsISupportsArray* arguments,
nsISupports* *result) = 0;
};
// Returns an implementation of an nsIScriptable that accesses attributes
// and invokes methods of the interface specified by aIID on the specified object.
extern nsresult
NS_NewIScriptable(REFNSIID aIID, nsISupports* object, nsIScriptable* *result);
////////////////////////////////////////////////////////////////////////////////
#endif /* nsIScriptable_h___ */

View File

@@ -1,74 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
/*
A reference-counted XPCOM wrapper for the nsStr structure. Allows for
efficient passing of string objects through multiple layers.
*/
#ifndef nsIString_h__
#define nsIString_h__
#include "nsISupports.h"
#include "nsStr.h" // need to include it for eCharSize
// {4C541410-E0B9-11d2-BDB3-000064657374}
#define NS_ISTRING_IID \
{ 0x4c541410, 0xe0b9, 0x11d2, { 0xbd, 0xb3, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74 } }
class nsIString : public nsISupports
{
public:
static const nsID& GetIID() { static nsIID iid = NS_ISTRING_IID; return iid; }
/**
* Set the character size to something other than the default character
* size. By default, nsIString objects will have kDefaultCharSize (as defined
* in nsStr.h) as the default char size for their representation.
*/
NS_IMETHOD Init(eCharSize aCharSize) = 0;
/**
* Copy the caller's nsStr into the object's internal nsStr by performing an
* assignment operation.
*/
NS_IMETHOD SetStr(nsStr* aStr) = 0;
/**
* Copy the object's internal nsStr into the caller's nsStr struct by performing
* an assignment operation.
*/
NS_IMETHOD GetStr(nsStr* aStr) = 0;
/**
* Return a pointer to the nsIString object's _actual_ string buffer. The caller
* must treat this struct as an immutable object (hence the "const" qualifier).
* The pointer will become invalid as soon as the nsIString interface is released.
*/
NS_IMETHOD GetImmutableStr(const nsStr** aStr) = 0;
};
PR_EXTERN(nsresult)
NS_NewString(nsIString** aString);
#endif // nsIString_h__

View File

@@ -1,126 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIThread_h__
#define nsIThread_h__
#include "nsISupports.h"
#include "prthread.h"
#include "nscore.h"
////////////////////////////////////////////////////////////////////////////////
// XXX regenerate:
#define NS_IRUNNABLE_IID \
{ /* 677d9a90-93ee-11d2-816a-006008119d7a */ \
0x677d9a90, \
0x93ee, \
0x11d2, \
{0x81, 0x6a, 0x00, 0x60, 0x19, 0x11, 0x9d, 0x7a} \
}
class nsIRunnable : public nsISupports
{
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_IRUNNABLE_IID);
NS_IMETHOD Run() = 0;
};
////////////////////////////////////////////////////////////////////////////////
// XXX regenerate:
#define NS_ITHREAD_IID \
{ /* 677d9a90-93ee-11d2-816a-006008119d7a */ \
0x677d9a90, \
0x93ee, \
0x11d2, \
{0x81, 0x6a, 0x00, 0x60, 0x29, 0x11, 0x9d, 0x7a} \
}
class nsIThread : public nsISupports
{
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_ITHREAD_IID);
// returns the nsIThread for the current thread:
static NS_BASE nsresult GetCurrent(nsIThread* *result);
// returns the nsIThread for an arbitrary PRThread:
static NS_BASE nsresult GetIThread(PRThread* prthread, nsIThread* *result);
NS_IMETHOD Join() = 0;
NS_IMETHOD GetPriority(PRThreadPriority *result) = 0;
NS_IMETHOD SetPriority(PRThreadPriority value) = 0;
NS_IMETHOD Interrupt() = 0;
NS_IMETHOD GetScope(PRThreadScope *result) = 0;
NS_IMETHOD GetState(PRThreadState *result) = 0;
NS_IMETHOD GetPRThread(PRThread* *result) = 0;
};
extern NS_BASE nsresult
NS_NewThread(nsIThread* *result,
nsIRunnable* runnable,
PRUint32 stackSize = 0,
PRThreadPriority priority = PR_PRIORITY_NORMAL,
PRThreadScope scope = PR_GLOBAL_THREAD,
PRThreadState state = PR_JOINABLE_THREAD);
////////////////////////////////////////////////////////////////////////////////
// XXX regenerate:
#define NS_ITHREADPOOL_IID \
{ /* 677d9a90-93ee-11d2-816a-006008119d7a */ \
0x677d9a90, \
0x93ee, \
0x11d2, \
{0x81, 0x6a, 0x00, 0x60, 0x39, 0x11, 0x9d, 0x7a} \
}
/**
* A thread pool is used to create a group of worker threads that
* share in the servicing of requests. Requests are run in the
* context of the worker thread.
*/
class nsIThreadPool : public nsISupports
{
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_ITHREADPOOL_IID);
NS_IMETHOD DispatchRequest(nsIRunnable* runnable) = 0;
NS_IMETHOD ProcessPendingRequests() = 0;
NS_IMETHOD Shutdown() = 0;
};
extern NS_BASE nsresult
NS_NewThreadPool(nsIThreadPool* *result,
PRUint32 minThreads, PRUint32 maxThreads,
PRUint32 stackSize = 0,
PRThreadPriority priority = PR_PRIORITY_NORMAL,
PRThreadScope scope = PR_GLOBAL_THREAD);
////////////////////////////////////////////////////////////////////////////////
#endif // nsIThread_h__

View File

@@ -1,149 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIVariant_h___
#define nsIVariant_h___
#include "nsISupports.h"
#include "nscore.h"
#include "prtime.h"
enum nsVariantType {
// primitive values
nsVariantType_PRBool,
nsVariantType_PRInt16,
nsVariantType_PRUint16,
nsVariantType_PRInt32,
nsVariantType_PRUint32,
nsVariantType_PRInt64,
nsVariantType_PRUint64,
nsVariantType_float,
nsVariantType_PRFloat64,
nsVariantType_PRTime,
// only pointers after this point -- these will be deleted
// when the variant is deleted
nsVariantType_voidPtr,
nsVariantType_charPtr,
nsVariantType_PRUnicharPtr
};
class nsVariantValue {
public:
nsVariantValue() {}
// nsVariantValue(PRBool value) { mUnion._PRBool = value; }
nsVariantValue(PRInt16 value) { mUnion._PRInt16 = value; }
nsVariantValue(PRUint16 value) { mUnion._PRUint16 = value; }
nsVariantValue(PRInt32 value) { mUnion._PRInt32 = value; }
nsVariantValue(PRUint32 value) { mUnion._PRUint32 = value; }
nsVariantValue(PRInt64 value) { mUnion._PRInt64 = value; }
nsVariantValue(PRUint64 value) { mUnion._PRUint64 = value; }
nsVariantValue(float value) { mUnion._float = value; }
nsVariantValue(PRFloat64 value) { mUnion._PRFloat64 = value; }
// nsVariantValue(PRTime value) { mUnion._PRTime = value; }
nsVariantValue(void* value) { mUnion._voidPtr = value; }
nsVariantValue(char* value) { mUnion._charPtr = value; }
nsVariantValue(PRUnichar* value) { mUnion._PRUnicharPtr = value; }
// operator PRBool() { return mUnion._PRBool; }
operator PRInt16() { return mUnion._PRInt16; }
operator PRUint16() { return mUnion._PRUint16; }
operator PRInt32() { return mUnion._PRInt32; }
operator PRUint32() { return mUnion._PRUint32; }
operator PRInt64() { return mUnion._PRInt64; }
operator PRUint64() { return mUnion._PRUint64; }
operator float() { return mUnion._float; }
operator PRFloat64() { return mUnion._PRFloat64; }
// operator PRTime() { return mUnion._PRTime; }
operator void*() { return mUnion._voidPtr; }
operator const char*() { return mUnion._charPtr; }
operator const PRUnichar*() { return mUnion._PRUnicharPtr; }
friend class nsVariant;
protected:
union nsVariantValueUnion {
PRBool _PRBool;
PRInt16 _PRInt16;
PRUint16 _PRUint16;
PRInt32 _PRInt32;
PRUint32 _PRUint32;
PRInt64 _PRInt64;
PRUint64 _PRUint64;
float _float;
PRFloat64 _PRFloat64;
PRTime _PRTime;
void* _voidPtr;
char* _charPtr;
PRUnichar* _PRUnicharPtr;
};
nsVariantValueUnion mUnion;
};
#define NS_IVARIANT_IID \
{ /* 3b5799d0-dc28-11d2-9311-00e09805570f */ \
0x3b5799d0, \
0xdc28, \
0x11d2, \
{0x93, 0x11, 0x00, 0xe0, 0x98, 0x05, 0x57, 0x0f} \
}
class nsIVariant : public nsISupports {
public:
static const nsIID& GetIID() { static nsIID iid = NS_IVARIANT_IID; return iid; }
/**
* Gets the type and value of a Variant.
* When the value is a pointer type, the pointer points into the variant's
* internal storage. It is the caller's responsibility to copy.
*/
NS_IMETHOD GetValue(nsVariantType *type, nsVariantValue *value) = 0;
/**
* Gets the value of a Variant.
* @return NS_ERROR_FAILURE if the value is not of the expected type.
* When the value is a pointer type, the pointer points into the variant's
* internal storage. It is the caller's responsibility to copy.
*/
NS_IMETHOD GetValue(nsVariantType expectedType, nsVariantValue *value) = 0;
/**
* Sets the type and value of a Variant.
* When the value is a pointer type, the variant takes ownership of the
* pointer. When the variant is released, the pointer will be deleted.
*/
NS_IMETHOD SetValue(nsVariantType type, nsVariantValue& value) = 0;
/**
* Determines whether two variants have the same internal type and value.
* @return NS_OK if they are equal
* @return NS_COMFALSE if not, or if the other parameter is not an nsIVariant
*/
NS_IMETHOD Equals(nsISupports* other) = 0;
#ifdef NS_DEBUG
NS_IMETHOD GetDescription(char* *result) = 0;
#endif
};
extern NS_BASE nsresult
NS_NewIVariant(nsVariantType initialType, nsVariantValue& initialValue,
nsIVariant* *result);
#endif // nsIVariant_h___

View File

@@ -1,41 +0,0 @@
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
/* We need this because Solaris' version of qsort is broken and
* causes array bounds reads.
*/
#ifndef nsQuickSort_h___
#define nsQuickSort_h___
#include "nscore.h"
#include "prtypes.h"
/* Had to pull the following define out of xp_core.h
* to avoid including xp_core.h.
* That brought in too many header file dependencies.
*/
NS_BEGIN_EXTERN_C
PR_EXTERN(void) NS_QuickSort(void *, unsigned int, unsigned int,
int (*)(const void *, const void *, void *),
void *);
NS_END_EXTERN_C
#endif /* nsQuickSort_h___ */

View File

@@ -29,7 +29,7 @@
#include "nsFileSpec.h"
#ifdef XP_MAC
#include <Types.h>
#include "Types.h"
#endif
// SEE ALSO:
@@ -44,7 +44,6 @@ class NS_BASE nsSpecialSystemDirectory : public nsFileSpec
OS_DriveDirectory = 1
, OS_TemporaryDirectory = 2
, OS_CurrentProcessDirectory= 3
, OS_CurrentWorkingDirectory= 4
, Mac_SystemDirectory = 101
, Mac_DesktopDirectory = 102
@@ -60,35 +59,9 @@ class NS_BASE nsSpecialSystemDirectory : public nsFileSpec
, 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
, Unix_LocalDirectory = 301
, Unix_LibDirectory = 302
, Unix_HomeDirectory = 303
, Unix_LibDirectory = 302
};
//nsSpecialSystemDirectory();

View File

@@ -14,9 +14,7 @@ nsITimerCallback.h
nsIUnicharBuffer.h
nsRBTree.h
nsIUnicharInputStream.h
nsStr.h
nsString.h
nsString2.h
nsVoidArray.h
nsUnitConversion.h
nsIBaseStream.h
@@ -24,5 +22,3 @@ nsIInputStream.h
nsIOutputStream.h
nsInt64.h
nsTime.h
nsStr.h
nsString2.h

View File

@@ -40,30 +40,17 @@ CPPSRCS = \
nsDeque.cpp \
nsEscape.cpp \
nsFileSpec.cpp \
nsFileSpecStreaming.cpp \
nsFileStream.cpp \
nsIFileStream.cpp \
nsIStringStream.cpp \
nsProperties.cpp \
nsVariant.cpp \
nsRBTree.cpp \
nsSizeOfHandler.cpp \
nsStr.cpp \
nsSizeOfHandler.cpp \
nsString.cpp \
nsString2.cpp \
nsUnicharBuffer.cpp \
nsUnicharInputStream.cpp \
nsVoidArray.cpp \
nsSpecialSystemDirectory.cpp\
nsObserverService.cpp \
nsObserverList.cpp \
nsObserver.cpp \
nsQuickSort.cpp \
nsPageMgr.cpp \
nsBuffer.cpp \
nsByteBufferInputStream.cpp \
nsThread.cpp \
nsPipe.cpp \
$(NULL)
EXPORTS = \
@@ -83,9 +70,7 @@ EXPORTS = \
nsIUnicharInputStream.h \
nsInt64.h \
nsRBTree.h \
nsStr.h \
nsString.h \
nsString2.h \
nsTime.h \
nsVoidArray.h \
nsUnitConversion.h \
@@ -103,3 +88,5 @@ TARGET = $(LIBARY)
include $(topsrcdir)/config/rules.mk
test:
@echo OS_ARCH = $(OS_ARCH)

View File

@@ -1,894 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
/******************************************************************************************
MODULE NOTES:
This file contains the workhorse copy and shift functions used in nsStrStruct.
Ultimately, I plan to make the function pointers in this system available for
use by external modules. They'll be able to install their own "handlers".
Not so, today though.
*******************************************************************************************/
#ifndef _BUFFERROUTINES_H
#define _BUFFERROUTINES_H
#include "nsCRT.h"
#ifndef RICKG_TESTBED
#include "nsUnicharUtilCIID.h"
#include "nsIServiceManager.h"
#include "nsICaseConversion.h"
#endif
inline PRUnichar GetUnicharAt(const char* aString,PRUint32 anIndex) {
return ((PRUnichar*)aString)[anIndex];
}
inline PRUnichar GetCharAt(const char* aString,PRUint32 anIndex) {
return (PRUnichar)aString[anIndex];
}
//----------------------------------------------------------------------------------------
//
// This set of methods is used to shift the contents of a char buffer.
// The functions are differentiated by shift direction and the underlying charsize.
//
/**
* This method shifts single byte characters left by a given amount from an given offset.
* @update gess 01/04/99
* @param aDest is a ptr to a cstring where left-shift is to be performed
* @param aLength is the known length of aDest
* @param anOffset is the index into aDest where shifting shall begin
* @param aCount is the number of chars to be "cut"
*/
void ShiftCharsLeft(char* aDest,PRUint32 aLength,PRUint32 anOffset,PRUint32 aCount) {
PRUint32 theMax=aLength-anOffset;
PRUint32 theLength=(theMax<aCount) ? theMax : aCount;
char* first= aDest+anOffset+aCount;
char* last = aDest+aLength;
char* to = aDest+anOffset;
//now loop over characters, shifting them left...
while(first<=last) {
*to=*first;
to++;
first++;
}
}
/**
* This method shifts single byte characters right by a given amount from an given offset.
* @update gess 01/04/99
* @param aDest is a ptr to a cstring where the shift is to be performed
* @param aLength is the known length of aDest
* @param anOffset is the index into aDest where shifting shall begin
* @param aCount is the number of chars to be "inserted"
*/
void ShiftCharsRight(char* aDest,PRUint32 aLength,PRUint32 anOffset,PRUint32 aCount) {
char* last = aDest+aLength;
char* first= aDest+anOffset-1;
char* to = aDest+aLength+aCount;
//Copy rightmost chars, up to offset+theDelta...
while(first<=last) {
*to=*last;
to--;
last--;
}
}
/**
* This method shifts unicode characters by a given amount from an given offset.
* @update gess 01/04/99
* @param aDest is a ptr to a cstring where the shift is to be performed
* @param aLength is the known length of aDest
* @param anOffset is the index into aDest where shifting shall begin
* @param aCount is the number of chars to be "cut"
*/
void ShiftDoubleCharsLeft(char* aDest,PRUint32 aLength,PRUint32 anOffset,PRUint32 aCount) {
PRUint32 theMax=aLength-anOffset;
PRUint32 theLength=(theMax<aCount) ? theMax : aCount;
PRUnichar* theBuf=(PRUnichar*)aDest;
PRUnichar* first= theBuf+anOffset+aCount;
PRUnichar* last = theBuf+aLength;
PRUnichar* to = theBuf+anOffset;
//now loop over characters, shifting them left...
while(first<=last) {
*to=*first;
to++;
first++;
}
}
/**
* This method shifts unicode characters by a given amount from an given offset.
* @update gess 01/04/99
* @param aDest is a ptr to a cstring where the shift is to be performed
* @param aLength is the known length of aDest
* @param anOffset is the index into aDest where shifting shall begin
* @param aCount is the number of chars to be "inserted"
*/
void ShiftDoubleCharsRight(char* aDest,PRUint32 aLength,PRUint32 anOffset,PRUint32 aCount) {
PRUnichar* theBuf=(PRUnichar*)aDest;
PRUnichar* last = theBuf+aLength;
PRUnichar* first= theBuf+anOffset-1;
PRUnichar* to = theBuf+aLength+aCount;
//Copy rightmost chars, up to offset+theDelta...
while(first<=last) {
*to=*last;
to--;
last--;
}
}
typedef void (*ShiftChars)(char* aDest,PRUint32 aLength,PRUint32 anOffset,PRUint32 aCount);
ShiftChars gShiftChars[2][2]= {
{&ShiftCharsLeft,&ShiftCharsRight},
{&ShiftDoubleCharsLeft,&ShiftDoubleCharsRight}
};
//----------------------------------------------------------------------------------------
//
// This set of methods is used to copy one buffer onto another.
// The functions are differentiated by the size of source and dest character sizes.
// WARNING: Your destination buffer MUST be big enough to hold all the source bytes.
// We don't validate these ranges here (this should be done in higher level routines).
//
/**
* Going 1 to 1 is easy, since we assume ascii. No conversions are necessary.
* @update gess 01/04/99
* @param aDest is the destination buffer
* @param aDestOffset is the pos to start copy to in the dest buffer
* @param aSource is the source buffer
* @param anOffset is the offset to start copying from in the source buffer
* @param aCount is the (max) number of chars to copy
*/
void CopyChars1To1(char* aDest,PRInt32 anDestOffset,const char* aSource,PRUint32 anOffset,PRUint32 aCount) {
char* to = aDest+anDestOffset;
const char* first= aSource+anOffset;
const char* last = first+aCount;
//now loop over characters, shifting them left...
while(first<last) {
*to=*first;
to++;
first++;
}
*to=0;
}
/**
* Going 1 to 2 requires a conversion from ascii to unicode. This can be expensive.
* @param aDest is the destination buffer
* @param aDestOffset is the pos to start copy to in the dest buffer
* @param aSource is the source buffer
* @param anOffset is the offset to start copying from in the source buffer
* @param aCount is the (max) number of chars to copy
*/
void CopyChars1To2(char* aDest,PRInt32 anDestOffset,const char* aSource,PRUint32 anOffset,PRUint32 aCount) {
PRUnichar* theDest=(PRUnichar*)aDest;
PRUnichar* to = theDest+anDestOffset;
const char* first= aSource+anOffset;
const char* last = first+aCount;
//now loop over characters, shifting them left...
while(first<last) {
*to=kIsoLatin1ToUCS2[*first];
to++;
first++;
}
*to=0;
}
/**
* Going 2 to 1 requires a conversion from unicode down to ascii. This can be lossy.
* @update gess 01/04/99
* @param aDest is the destination buffer
* @param aDestOffset is the pos to start copy to in the dest buffer
* @param aSource is the source buffer
* @param anOffset is the offset to start copying from in the source buffer
* @param aCount is the (max) number of chars to copy
*/
void CopyChars2To1(char* aDest,PRInt32 anDestOffset,const char* aSource,PRUint32 anOffset,PRUint32 aCount) {
char* to = aDest+anDestOffset;
PRUnichar* theSource=(PRUnichar*)aSource;
const PRUnichar* first= theSource+anOffset;
const PRUnichar* last = first+aCount;
//now loop over characters, shifting them left...
while(first<last) {
if(*first<255)
*to=(char)*first;
else *to='.';
to++;
first++;
}
*to=0;
}
/**
* Going 2 to 2 is fast and efficient.
* @update gess 01/04/99
* @param aDest is the destination buffer
* @param aDestOffset is the pos to start copy to in the dest buffer
* @param aSource is the source buffer
* @param anOffset is the offset to start copying from in the source buffer
* @param aCount is the (max) number of chars to copy
*/
void CopyChars2To2(char* aDest,PRInt32 anDestOffset,const char* aSource,PRUint32 anOffset,PRUint32 aCount) {
PRUnichar* theDest=(PRUnichar*)aDest;
PRUnichar* to = theDest+anDestOffset;
PRUnichar* theSource=(PRUnichar*)aSource;
PRUnichar* from= theSource+anOffset;
memcpy((void*)to,(void*)from,aCount*2);
}
//--------------------------------------------------------------------------------------
typedef void (*CopyChars)(char* aDest,PRInt32 anDestOffset,const char* aSource,PRUint32 anOffset,PRUint32 aCount);
CopyChars gCopyChars[2][2]={
{&CopyChars1To1,&CopyChars1To2},
{&CopyChars2To1,&CopyChars2To2}
};
//----------------------------------------------------------------------------------------
//
// This set of methods is used to search a buffer looking for a char.
//
/**
* This methods cans the given buffer for the given char
*
* @update gess 3/25/98
* @param aDest is the buffer to be searched
* @param aLength is the size (in char-units, not bytes) of the buffer
* @param anOffset is the start pos to begin searching
* @param aChar is the target character we're looking for
* @param aIgnorecase tells us whether to use a case sensitive search
* @return index of pos if found, else -1 (kNotFound)
*/
inline PRInt32 FindChar1(const char* aDest,PRUint32 aLength,PRUint32 anOffset,const PRUnichar aChar,PRBool aIgnoreCase) {
PRUnichar theCmpChar=(aIgnoreCase ? nsCRT::ToUpper(aChar) : aChar);
PRUint32 theIndex=0;
for(theIndex=anOffset;theIndex<aLength;theIndex++){
PRUnichar theChar=GetCharAt(aDest,theIndex);
if(aIgnoreCase)
theChar=nsCRT::ToUpper(theChar);
if(theChar==theCmpChar)
return theIndex;
}
return kNotFound;
}
/**
* This methods cans the given buffer for the given char
*
* @update gess 3/25/98
* @param aDest is the buffer to be searched
* @param aLength is the size (in char-units, not bytes) of the buffer
* @param anOffset is the start pos to begin searching
* @param aChar is the target character we're looking for
* @param aIgnorecase tells us whether to use a case sensitive search
* @return index of pos if found, else -1 (kNotFound)
*/
inline PRInt32 FindChar2(const char* aDest,PRUint32 aLength,PRUint32 anOffset,const PRUnichar aChar,PRBool aIgnoreCase) {
PRUnichar theCmpChar=(aIgnoreCase ? nsCRT::ToUpper(aChar) : aChar);
PRUint32 theIndex=0;
for(theIndex=anOffset;theIndex<aLength;theIndex++){
PRUnichar theChar=GetUnicharAt(aDest,theIndex);
if(aIgnoreCase)
theChar=nsCRT::ToUpper(theChar);
if(theChar==theCmpChar)
return theIndex;
}
return kNotFound;
}
/**
* This methods cans the given buffer (in reverse) for the given char
*
* @update gess 3/25/98
* @param aDest is the buffer to be searched
* @param aLength is the size (in char-units, not bytes) of the buffer
* @param anOffset is the start pos to begin searching
* @param aChar is the target character we're looking for
* @param aIgnorecase tells us whether to use a case sensitive search
* @return index of pos if found, else -1 (kNotFound)
*/
inline PRInt32 RFindChar1(const char* aDest,PRUint32 aLength,PRUint32 anOffset,const PRUnichar aChar,PRBool aIgnoreCase) {
PRUnichar theCmpChar=(aIgnoreCase ? nsCRT::ToUpper(aChar) : aChar);
PRUint32 theIndex=0;
for(theIndex=aLength-1;theIndex>=0;theIndex--){
PRUnichar theChar=GetCharAt(aDest,theIndex);
if(aIgnoreCase)
theChar=nsCRT::ToUpper(theChar);
if(theChar==theCmpChar)
return theIndex;
}
return kNotFound;
}
/**
* This methods cans the given buffer for the given char
*
* @update gess 3/25/98
* @param aDest is the buffer to be searched
* @param aLength is the size (in char-units, not bytes) of the buffer
* @param anOffset is the start pos to begin searching
* @param aChar is the target character we're looking for
* @param aIgnorecase tells us whether to use a case sensitive search
* @return index of pos if found, else -1 (kNotFound)
*/
inline PRInt32 RFindChar2(const char* aDest,PRUint32 aLength,PRUint32 anOffset,const PRUnichar aChar,PRBool aIgnoreCase) {
PRUnichar theCmpChar=(aIgnoreCase ? nsCRT::ToUpper(aChar) : aChar);
PRUint32 theIndex=0;
for(theIndex=aLength-1;theIndex>=0;theIndex--){
PRUnichar theChar=GetUnicharAt(aDest,theIndex);
if(aIgnoreCase)
theChar=nsCRT::ToUpper(theChar);
if(theChar==theCmpChar)
return theIndex;
}
return kNotFound;
}
typedef PRInt32 (*FindChars)(const char* aDest,PRUint32 aLength,PRUint32 anOffset,const PRUnichar aChar,PRBool aIgnoreCase);
FindChars gFindChars[]={&FindChar1,&FindChar2};
FindChars gRFindChars[]={&RFindChar1,&RFindChar2};
//----------------------------------------------------------------------------------------
//
// This set of methods is used to compare one buffer onto another.
// The functions are differentiated by the size of source and dest character sizes.
// WARNING: Your destination buffer MUST be big enough to hold all the source bytes.
// We don't validate these ranges here (this should be done in higher level routines).
//
/**
* This method compares the data in one buffer with another
* @update gess 01/04/99
* @param aStr1 is the first buffer to be compared
* @param aStr2 is the 2nd buffer to be compared
* @param aCount is the number of chars to compare
* @param aIgnorecase tells us whether to use a case-sensitive comparison
* @return -1,0,1 depending on <,==,>
*/
PRInt32 Compare1To1(const char* aStr1,const char* aStr2,PRUint32 aCount,PRBool aIgnoreCase){
PRInt32 result=0;
if(aIgnoreCase)
result=nsCRT::strncasecmp(aStr1,aStr2,aCount);
else result=strncmp(aStr1,aStr2,aCount);
return result;
}
/**
* This method compares the data in one buffer with another
* @update gess 01/04/99
* @param aStr1 is the first buffer to be compared
* @param aStr2 is the 2nd buffer to be compared
* @param aCount is the number of chars to compare
* @param aIgnorecase tells us whether to use a case-sensitive comparison
* @return -1,0,1 depending on <,==,>
*/
PRInt32 Compare2To2(const char* aStr1,const char* aStr2,PRUint32 aCount,PRBool aIgnoreCase){
PRInt32 result=0;
if(aIgnoreCase)
result=nsCRT::strncasecmp((PRUnichar*)aStr1,(PRUnichar*)aStr2,aCount);
else result=nsCRT::strncmp((PRUnichar*)aStr1,(PRUnichar*)aStr2,aCount);
return result;
}
/**
* This method compares the data in one buffer with another
* @update gess 01/04/99
* @param aStr1 is the first buffer to be compared
* @param aStr2 is the 2nd buffer to be compared
* @param aCount is the number of chars to compare
* @param aIgnorecase tells us whether to use a case-sensitive comparison
* @return -1,0,1 depending on <,==,>
*/
PRInt32 Compare2To1(const char* aStr1,const char* aStr2,PRUint32 aCount,PRBool aIgnoreCase){
PRInt32 result;
if(aIgnoreCase)
result=nsCRT::strncasecmp((PRUnichar*)aStr1,aStr2,aCount);
else result=nsCRT::strncmp((PRUnichar*)aStr1,aStr2,aCount);
return result;
}
/**
* This method compares the data in one buffer with another
* @update gess 01/04/99
* @param aStr1 is the first buffer to be compared
* @param aStr2 is the 2nd buffer to be compared
* @param aCount is the number of chars to compare
* @param aIgnorecase tells us whether to use a case-sensitive comparison
* @return -1,0,1 depending on <,==,>
*/
PRInt32 Compare1To2(const char* aStr1,const char* aStr2,PRUint32 aCount,PRBool aIgnoreCase){
PRInt32 result;
if(aIgnoreCase)
result=nsCRT::strncasecmp((PRUnichar*)aStr2,aStr1,aCount)*-1;
else result=nsCRT::strncasecmp((PRUnichar*)aStr2,aStr1,aCount)*-1;
return result;
}
typedef PRInt32 (*CompareChars)(const char* aStr1,const char* aStr2,PRUint32 aCount,PRBool aIgnoreCase);
CompareChars gCompare[2][2]={
{&Compare1To1,&Compare1To2},
{&Compare2To1,&Compare2To2},
};
//----------------------------------------------------------------------------------------
//
// This set of methods is used to convert the case of strings...
//
/**
* This method performs a case conversion the data in the given buffer
*
* @update gess 01/04/99
* @param aString is the buffer to be case shifted
* @param aCount is the number of chars to compare
* @param aToUpper tells us whether to convert to upper or lower
* @return 0
*/
PRInt32 ConvertCase1(char* aString,PRUint32 aCount,PRBool aToUpper){
PRInt32 result=0;
typedef char chartype;
chartype* cp = (chartype*)aString;
chartype* end = cp + aCount-1;
while (cp <= end) {
chartype ch = *cp;
if(aToUpper) {
if ((ch >= 'a') && (ch <= 'z')) {
*cp = 'A' + (ch - 'a');
}
}
else {
if ((ch >= 'A') && (ch <= 'Z')) {
*cp = 'a' + (ch - 'A');
}
}
cp++;
}
return result;
}
//----------------------------------------------------------------------------------------
#ifndef RICKG_TESTBED
class HandleCaseConversionShutdown3 : public nsIShutdownListener {
public :
NS_IMETHOD OnShutdown(const nsCID& cid, nsISupports* service);
HandleCaseConversionShutdown3(void) { NS_INIT_REFCNT(); }
virtual ~HandleCaseConversionShutdown3(void) {}
NS_DECL_ISUPPORTS
};
static NS_DEFINE_CID(kUnicharUtilCID, NS_UNICHARUTIL_CID);
static NS_DEFINE_IID(kICaseConversionIID, NS_ICASECONVERSION_IID);
static NS_DEFINE_IID(kIShutdownListenerIID, NS_ISHUTDOWNLISTENER_IID);
static nsICaseConversion * gCaseConv = 0;
NS_IMPL_ISUPPORTS(HandleCaseConversionShutdown3, kIShutdownListenerIID);
nsresult HandleCaseConversionShutdown3::OnShutdown(const nsCID& cid, nsISupports* service) {
if (cid.Equals(kUnicharUtilCID)) {
NS_ASSERTION(service == gCaseConv, "wrong service!");
if(gCaseConv){
gCaseConv->Release();
gCaseConv = 0;
}
}
return NS_OK;
}
class CCaseConversionServiceInitializer {
public:
CCaseConversionServiceInitializer(){
mListener = new HandleCaseConversionShutdown3();
if(mListener){
mListener->AddRef();
nsresult result=nsServiceManager::GetService(kUnicharUtilCID, kICaseConversionIID,(nsISupports**) &gCaseConv, mListener);
}
}
protected:
HandleCaseConversionShutdown3* mListener;
};
#endif
//----------------------------------------------------------------------------------------
/**
* This method performs a case conversion the data in the given buffer
*
* @update gess 01/04/99
* @param aString is the buffer to be case shifted
* @param aCount is the number of chars to compare
* @param aToUpper tells us whether to convert to upper or lower
* @return 0
*/
PRInt32 ConvertCase2(char* aString,PRUint32 aCount,PRBool aToUpper){
PRUnichar* cp = (PRUnichar*)aString;
PRUnichar* end = cp + aCount-1;
PRInt32 result=0;
#ifndef RICKG_TESTBED
static CCaseConversionServiceInitializer gCaseConversionServiceInitializer;
// I18N code begin
if(gCaseConv) {
nsresult err=(aToUpper) ? gCaseConv->ToUpper(cp, cp, aCount) : gCaseConv->ToLower(cp, cp, aCount);
if(NS_SUCCEEDED(err))
return 0;
}
// I18N code end
#endif
while (cp <= end) {
PRUnichar ch = *cp;
if(aToUpper) {
if ((ch >= 'a') && (ch <= 'z')) {
*cp = 'A' + (ch - 'a');
}
}
else {
if ((ch >= 'A') && (ch <= 'Z')) {
*cp = 'a' + (ch - 'A');
}
}
cp++;
}
return result;
}
typedef PRInt32 (*CaseConverters)(char*,PRUint32,PRBool);
CaseConverters gCaseConverters[]={&ConvertCase1,&ConvertCase2};
//----------------------------------------------------------------------------------------
//
// This set of methods is used strip chars from a given buffer...
//
/**
* This method removes chars (given in aSet) from the given buffer
*
* @update gess 01/04/99
* @param aString is the buffer to be manipulated
* @param anOffset is starting pos in buffer for manipulation
* @param aCount is the number of chars to compare
* @param aSet tells us which chars to remove from given buffer
* @return the new length of the given buffer
*/
PRInt32 StripChars1(char* aString,PRUint32 anOffset,PRUint32 aCount,const char* aSet){
PRInt32 result=0;
typedef char chartype;
chartype* from = (chartype*)&aString[anOffset];
chartype* end = (chartype*)from + aCount-1;
chartype* to = from;
if(aSet){
PRUint32 aSetLen=strlen(aSet);
while (from <= end) {
chartype ch = *from;
if(kNotFound==FindChar1(aSet,aSetLen,0,ch,PR_FALSE)){
*to++=*from;
}
from++;
}
*to = 0;
}
return to - (chartype*)aString;
}
/**
* This method removes chars (given in aSet) from the given buffer
*
* @update gess 01/04/99
* @param aString is the buffer to be manipulated
* @param anOffset is starting pos in buffer for manipulation
* @param aCount is the number of chars to compare
* @param aSet tells us which chars to remove from given buffer
* @return the new length of the given buffer
*/
PRInt32 StripChars2(char* aString,PRUint32 anOffset,PRUint32 aCount,const char* aSet){
PRInt32 result=0;
typedef PRUnichar chartype;
chartype* from = (chartype*)&aString[anOffset];
chartype* end = (chartype*)from + aCount-1;
chartype* to = from;
if(aSet){
PRUint32 aSetLen=strlen(aSet);
while (from <= end) {
chartype ch = *from;
if(kNotFound==FindChar1(aSet,aSetLen,0,ch,PR_FALSE)){
*to++=*from;
}
from++;
}
*to = 0;
}
return to - (chartype*)aString;
}
typedef PRInt32 (*StripChars)(char* aString,PRUint32 aDestOffset,PRUint32 aCount,const char* aSet);
StripChars gStripChars[]={&StripChars1,&StripChars2};
//----------------------------------------------------------------------------------------
//
// This set of methods is used trim chars from the edges of a buffer...
//
/**
* This method trims chars (given in aSet) from the edges of given buffer
*
* @update gess 01/04/99
* @param aString is the buffer to be manipulated
* @param aLength is the length of the buffer
* @param aSet tells us which chars to remove from given buffer
* @param aEliminateLeading tells us whether to strip chars from the start of the buffer
* @param aEliminateTrailing tells us whether to strip chars from the start of the buffer
* @return the new length of the given buffer
*/
PRInt32 TrimChars1(char* aString,PRUint32 aLength,const char* aSet,PRBool aEliminateLeading,PRBool aEliminateTrailing){
PRInt32 result=0;
typedef char chartype;
chartype* from = (chartype*)aString;
chartype* end = from + aLength -1;
chartype* to = from;
if(aSet) {
PRUint32 aSetLen=strlen(aSet);
//begin by find the first char not in aTrimSet
if(aEliminateLeading) {
while (from <= end) {
chartype ch = *from;
if(kNotFound==FindChar1(aSet,aSetLen,0,ch,PR_FALSE)){
break;
}
from++;
}
}
//Now, find last char not in aTrimSet
if(aEliminateTrailing) {
while(from<=end) {
chartype ch = *end;
if(kNotFound==FindChar1(aSet,aSetLen,0,ch,PR_FALSE)){
break;
}
end--;
}
}
//now rewrite your string without unwanted
//leading or trailing characters.
if (from != to) {
while (from <= end) {
*to++ = *from++;
}
}
else {
to = ++end;
}
*to = 0;
}
return to - (chartype*)aString;
}
/**
* This method trims chars (given in aSet) from the edges of given buffer
*
* @update gess 01/04/99
* @param aString is the buffer to be manipulated
* @param aLength is the length of the buffer
* @param aSet tells us which chars to remove from given buffer
* @param aEliminateLeading tells us whether to strip chars from the start of the buffer
* @param aEliminateTrailing tells us whether to strip chars from the start of the buffer
* @return the new length of the given buffer
*/
PRInt32 TrimChars2(char* aString,PRUint32 aLength,const char* aSet,PRBool aEliminateLeading,PRBool aEliminateTrailing){
PRInt32 result=0;
typedef PRUnichar chartype;
chartype* from = (chartype*)aString;
chartype* end = from + aLength -1;
chartype* to = from;
if(aSet) {
PRUint32 aSetLen=strlen(aSet);
//begin by find the first char not in aTrimSet
if(aEliminateLeading) {
while (from <= end) {
chartype ch = *from;
if(kNotFound==FindChar1(aSet,aSetLen,0,ch,PR_FALSE)){
break;
}
from++;
}
}
//Now, find last char not in aTrimSet
if(aEliminateTrailing) {
while(from<=end) {
chartype ch = *end;
if(kNotFound==FindChar1(aSet,aSetLen,0,ch,PR_FALSE)){
break;
}
end--;
}
}
//now rewrite your string without unwanted
//leading or trailing characters.
if (from != to) {
while (from <= end) {
*to++ = *from++;
}
}
else {
to = ++end;
}
*to = 0;
}
return to - (chartype*)aString;
}
typedef PRInt32 (*TrimChars)(char* aString,PRUint32 aCount,const char* aSet,PRBool aEliminateLeading,PRBool aEliminateTrailing);
TrimChars gTrimChars[]={&TrimChars1,&TrimChars2};
//----------------------------------------------------------------------------------------
//
// This set of methods is used compress char sequences in a buffer...
//
/**
* This method compresses duplicate runs of a given char from the given buffer
*
* @update gess 01/04/99
* @param aString is the buffer to be manipulated
* @param aLength is the length of the buffer
* @param aSet tells us which chars to compress from given buffer
* @param aEliminateLeading tells us whether to strip chars from the start of the buffer
* @param aEliminateTrailing tells us whether to strip chars from the start of the buffer
* @return the new length of the given buffer
*/
PRInt32 CompressChars1(char* aString,PRUint32 aLength,const char* aSet,PRUint32 aChar,PRBool aEliminateLeading,PRBool aEliminateTrailing){
PRInt32 result=0;
TrimChars1(aString,aLength,aSet,aEliminateLeading,aEliminateTrailing);
typedef char chartype;
chartype* from = aString;
chartype* end = aString + aLength-1;
chartype* to = from;
//this code converts /n, /t, /r into normal space ' ';
//it also compresses runs of whitespace down to a single char...
if(aSet){
PRUint32 aSetLen=strlen(aSet);
while (from <= end) {
chartype ch = *from++;
if(kNotFound!=FindChar1(aSet,aSetLen,0,ch,PR_FALSE)){
*to++ = ' ';
while (from <= end) {
ch = *from++;
if(kNotFound==FindChar1(aSet,aSetLen,0,ch,PR_FALSE)){
*to++ = ch;
break;
}
}
} else {
*to++ = ch;
}
}
*to = 0;
}
return to - (chartype*)aString;
}
/**
* This method compresses duplicate runs of a given char from the given buffer
*
* @update gess 01/04/99
* @param aString is the buffer to be manipulated
* @param aLength is the length of the buffer
* @param aSet tells us which chars to compress from given buffer
* @param aEliminateLeading tells us whether to strip chars from the start of the buffer
* @param aEliminateTrailing tells us whether to strip chars from the start of the buffer
* @return the new length of the given buffer
*/
PRInt32 CompressChars2(char* aString,PRUint32 aLength,const char* aSet,PRUint32 aChar,PRBool aEliminateLeading,PRBool aEliminateTrailing){
PRInt32 result=0;
TrimChars2(aString,aLength,aSet,aEliminateLeading,aEliminateTrailing);
typedef PRUnichar chartype;
chartype* from = (chartype*)aString;
chartype* end = from + aLength-1;
chartype* to = from;
//this code converts /n, /t, /r into normal space ' ';
//it also compresses runs of whitespace down to a single char...
if(aSet){
PRUint32 aSetLen=strlen(aSet);
while (from <= end) {
chartype ch = *from++;
if(kNotFound!=FindChar1(aSet,aSetLen,0,ch,PR_FALSE)){
*to++ = ' ';
while (from <= end) {
ch = *from++;
if(kNotFound==FindChar1(aSet,aSetLen,0,ch,PR_FALSE)){
*to++ = ch;
break;
}
}
} else {
*to++ = ch;
}
}
*to = 0;
}
return to - (chartype*)aString;
}
typedef PRInt32 (*CompressChars)(char* aString,PRUint32 aCount,const char* aSet,PRUint32 aChar,PRBool aEliminateLeading,PRBool aEliminateTrailing);
CompressChars gCompressChars[]={&CompressChars1,&CompressChars2};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -219,11 +219,18 @@ void TimerImpl::Fire()
//----------------------------------------------------------------------------------------
{
NS_PRECONDITION(mRefCnt > 0, "Firing a disposed Timer!");
if (mCallbackFunc != NULL) {
if (mCallbackFunc != NULL)
{
(*mCallbackFunc)(this, mClosure);
}
else if (mCallbackObject != NULL) {
mCallbackObject->Notify(this); // Fire the timer
else if (mCallbackObject != NULL)
{
nsITimerCallback* object = mCallbackObject;
mCallbackObject = nsnull;
// because the Notify call will release it.
// We will release again it in the destructor if
// it is not null when we go away!
object->Notify(this); // Fire the timer
}
}

View File

@@ -29,16 +29,12 @@ CPPSRCS = \
nsBaseDLL.cpp \
nsBTree.cpp \
nsByteBuffer.cpp \
nsByteBufferInputStream.cpp \
nsCRT.cpp \
nsDeque.cpp \
nsProperties.cpp \
nsVariant.cpp \
nsRBTree.cpp \
nsSizeOfHandler.cpp \
nsStr.cpp \
nsString.cpp \
nsString2.cpp \
nsUnicharBuffer.cpp \
nsUnicharInputStream.cpp \
nsVoidArray.cpp \
@@ -46,16 +42,8 @@ CPPSRCS = \
nsFileStream.cpp \
nsStringStream.cpp \
nsEscape.cpp \
nsIFileStream.cpp \
nsThread.cpp \
nsSpecialSystemDirectory.cpp \
nsObserverService.cpp \
nsObserverList.cpp \
nsObserver.cpp \
nsQuickSort.cpp \
nsPageMgr.cpp \
nsBuffer.cpp \
nsPipe.cpp \
nsIFileStream.cpp \
nsSpecialSystemDirectory.cpp \
$(NULL)
CPP_OBJS = \
@@ -64,41 +52,28 @@ CPP_OBJS = \
.\$(OBJDIR)\nsBaseDLL.obj \
.\$(OBJDIR)\nsBTree.obj \
.\$(OBJDIR)\nsByteBuffer.obj \
.\$(OBJDIR)\nsByteBufferInputStream.obj \
.\$(OBJDIR)\nsCRT.obj \
.\$(OBJDIR)\nsDeque.obj \
.\$(OBJDIR)\nsProperties.obj \
.\$(OBJDIR)\nsVariant.obj \
.\$(OBJDIR)\nsRBTree.obj \
.\$(OBJDIR)\nsSizeOfHandler.obj \
.\$(OBJDIR)\nsStr.obj \
.\$(OBJDIR)\nsString.obj \
.\$(OBJDIR)\nsString2.obj \
.\$(OBJDIR)\nsUnicharBuffer.obj \
.\$(OBJDIR)\nsUnicharInputStream.obj \
.\$(OBJDIR)\nsVoidArray.obj \
.\$(OBJDIR)\nsFileSpec.obj \
.\$(OBJDIR)\nsFileSpecStreaming.obj \
.\$(OBJDIR)\nsFileStream.obj \
.\$(OBJDIR)\nsEscape.obj \
.\$(OBJDIR)\nsIFileStream.obj \
.\$(OBJDIR)\nsThread.obj \
.\$(OBJDIR)\nsIStringStream.obj \
.\$(OBJDIR)\nsSpecialSystemDirectory.obj \
.\$(OBJDIR)\nsObserverService.obj \
.\$(OBJDIR)\nsObserverList.obj \
.\$(OBJDIR)\nsObserver.obj \
.\$(OBJDIR)\nsQuickSort.obj \
.\$(OBJDIR)\nsPageMgr.obj \
.\$(OBJDIR)\nsBuffer.obj \
.\$(OBJDIR)\nsPipe.obj \
.\$(OBJDIR)\nsIFileStream.obj \
.\$(OBJDIR)\nsIStringStream.obj \
.\$(OBJDIR)\nsSpecialSystemDirectory.obj \
$(NULL)
EXPORTS=nscore.h nsIArena.h nsIAtom.h nsIByteBuffer.h \
nsBTree.h nsCRT.h nsDeque.h nsITimer.h \
nsITimerCallback.h nsIUnicharBuffer.h nsRBTree.h \
nsIUnicharInputStream.h nsString.h nsVoidArray.h \
nsStr.h nsString2.h nsUnitConversion.h \
nsUnitConversion.h \
nsIBaseStream.h nsIInputStream.h nsIOutputStream.h \
nsInt64.h nsTime.h
@@ -121,11 +96,10 @@ LCFLAGS = \
$(NULL)
# These are the libraries we need to link with to create the dll
LLIBS= \
$(DIST)\lib\xpcom32.lib \
$(DIST)\lib\plc3.lib \
shell32.lib \
$(LIBNSPR)
LLIBS= \
$(DIST)\lib\xpcom32.lib \
$(DIST)\lib\plc3.lib \
$(LIBNSPR)
!if "$(MOZ_BITS)"=="32" && defined(MOZ_DEBUG) && defined(GLOWCODE)
LLIBS=$(LLIBS) $(GLOWDIR)\glowcode.lib
!endif

View File

@@ -33,7 +33,7 @@ public:
virtual void* Alloc(PRInt32 aSize);
protected:
virtual ~ArenaImpl();
~ArenaImpl();
PLArenaPool mPool;
PRInt32 mBlockSize;

View File

@@ -30,7 +30,7 @@ static struct PLHashTable* gAtomHashTable;
class AtomImpl : public nsIAtom {
public:
AtomImpl();
virtual ~AtomImpl();
~AtomImpl();
NS_DECL_ISUPPORTS

View File

@@ -1,4 +1,4 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
@@ -23,192 +23,31 @@
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsCOMPtr.h"
#include "nsIObserverService.h"
#include "nsObserverService.h"
#include "nsIObserver.h"
#include "nsObserver.h"
#include "nsProperties.h"
#include "nsPageMgr.h"
#include "pratom.h"
#include "nsBuffer.h"
static NS_DEFINE_CID(kComponentManagerCID, NS_COMPONENTMANAGER_CID);
static NS_DEFINE_CID(kPageManagerCID, NS_PAGEMANAGER_CID);
static NS_DEFINE_CID(kObserverServiceCID, NS_OBSERVERSERVICE_CID);
static NS_DEFINE_CID(kObserverCID, NS_OBSERVER_CID);
static NS_DEFINE_CID(kBufferCID, NS_BUFFER_CID);
////////////////////////////////////////////////////////////////////////////////
PRInt32 gLockCount = 0;
class nsBaseFactory : public nsIFactory
{
public:
// nsISupports methods
NS_DECL_ISUPPORTS
nsBaseFactory(const nsCID &aClass);
// nsIFactory methods
NS_IMETHOD CreateInstance(nsISupports *aOuter, const nsIID &aIID, void **aResult);
NS_IMETHOD LockFactory(PRBool aLock);
protected:
virtual ~nsBaseFactory();
static PRInt32 gLockCount;
nsCID mClassID;
};
PRInt32 nsBaseFactory::gLockCount = 0;
nsBaseFactory::nsBaseFactory(const nsCID &aClass)
: mClassID(aClass)
{
NS_INIT_REFCNT();
}
nsBaseFactory::~nsBaseFactory()
{
NS_ASSERTION(mRefCnt == 0, "non-zero refcnt at destruction");
}
nsresult
nsBaseFactory::QueryInterface(const nsIID &aIID, void **aResult)
{
if (aResult == nsnull)
return NS_ERROR_NULL_POINTER;
*aResult = nsnull;
if (aIID.Equals(nsIFactory::GetIID()) ||
aIID.Equals(nsISupports::GetIID())) {
*aResult = (void *)(nsIFactory*)this;
}
if (*aResult == nsnull)
return NS_NOINTERFACE;
NS_ADDREF_THIS();
return NS_OK;
}
NS_IMPL_ADDREF(nsBaseFactory)
NS_IMPL_RELEASE(nsBaseFactory)
nsresult
nsBaseFactory::CreateInstance(nsISupports *aOuter, const nsIID &aIID, void **aResult)
{
nsresult rv = NS_OK;
if (aOuter) {
return NS_ERROR_NO_AGGREGATION;
}
if (aResult == nsnull) {
return NS_ERROR_NULL_POINTER;
}
*aResult = nsnull;
if (mClassID.Equals(kPersistentPropertiesCID)) {
nsPersistentProperties* props = new nsPersistentProperties();
if (props == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
rv = props->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
delete props;
}
return rv;
}
if (mClassID.Equals(kObserverServiceCID)) {
return NS_NewObserverService((nsIObserverService**)aResult);
}
if (mClassID.Equals(kObserverCID)) {
return NS_NewObserver((nsIObserver**)aResult);
}
#ifdef XP_PC // XXX for now until i fix the build
if (mClassID.Equals(kPageManagerCID)) {
nsPageMgr* pageMgr = new nsPageMgr();
if (pageMgr == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
rv = pageMgr->Init();
if (NS_FAILED(rv)) {
delete pageMgr;
return rv;
}
rv = pageMgr->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
delete pageMgr;
return rv;
}
return NS_OK;
}
if (mClassID.Equals(kBufferCID)) {
nsBuffer* buffer = new nsBuffer();
if (buffer == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
rv = buffer->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) {
delete buffer;
return rv;
}
return NS_OK;
}
#endif
return NS_NOINTERFACE;
}
nsresult nsBaseFactory::LockFactory(PRBool aLock)
{
if (aLock) {
PR_AtomicIncrement(&gLockCount);
} else {
PR_AtomicDecrement(&gLockCount);
}
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
NS_DEFINE_IID(kIFactoryIID, NS_IFACTORY_IID);
extern "C" NS_EXPORT nsresult
NSRegisterSelf(nsISupports* aServMgr, const char* path)
{
nsresult rv;
NS_WITH_SERVICE1(nsIComponentManager, compMgr,
aServMgr, kComponentManagerCID, &rv);
nsCOMPtr<nsIServiceManager> servMgr(do_QueryInterface(aServMgr, &rv));
if (NS_FAILED(rv)) return rv;
rv = compMgr->RegisterComponent(kPersistentPropertiesCID,
"Persistent Properties", NULL,
nsIComponentManager* compMgr;
rv = servMgr->GetService(kComponentManagerCID,
nsIComponentManager::GetIID(),
(nsISupports**)&compMgr);
if (NS_FAILED(rv)) return rv;
rv = compMgr->RegisterComponent(kPropertiesCID, NULL, NULL,
path, PR_TRUE, PR_TRUE);
if (NS_FAILED(rv)) return rv;
rv = compMgr->RegisterComponent(kObserverServiceCID,
"ObserverService",
NS_OBSERVERSERVICE_PROGID,
path, PR_TRUE, PR_TRUE);
if (NS_FAILED(rv)) return rv;
rv = compMgr->RegisterComponent(kObserverCID,
"Observer",
NS_OBSERVER_PROGID,
path, PR_TRUE, PR_TRUE);
if (NS_FAILED(rv)) return rv;
rv = compMgr->RegisterComponent(kPageManagerCID,
"Page Manager", NULL,
path, PR_TRUE, PR_TRUE);
if (NS_FAILED(rv)) return rv;
rv = compMgr->RegisterComponent(kBufferCID,
"Buffer", NULL,
path, PR_TRUE, PR_TRUE);
if (NS_FAILED(rv)) return rv;
(void)servMgr->ReleaseService(kComponentManagerCID, compMgr);
return rv;
}
@@ -217,25 +56,18 @@ NSUnregisterSelf(nsISupports* aServMgr, const char* path)
{
nsresult rv;
NS_WITH_SERVICE1(nsIComponentManager, compMgr,
aServMgr, kComponentManagerCID, &rv);
nsCOMPtr<nsIServiceManager> servMgr(do_QueryInterface(aServMgr, &rv));
if (NS_FAILED(rv)) return rv;
rv = compMgr->UnregisterComponent(kPersistentPropertiesCID, path);
nsIComponentManager* compMgr;
rv = servMgr->GetService(kComponentManagerCID,
nsIComponentManager::GetIID(),
(nsISupports**)&compMgr);
if (NS_FAILED(rv)) return rv;
rv = compMgr->UnregisterComponent(kObserverServiceCID, path);
if (NS_FAILED(rv)) return rv;
rv = compMgr->UnregisterComponent(kObserverCID, path);
if (NS_FAILED(rv)) return rv;
rv = compMgr->UnregisterComponent(kPageManagerCID, path);
if (NS_FAILED(rv)) return rv;
rv = compMgr->UnregisterComponent(kBufferCID, path);
if (NS_FAILED(rv)) return rv;
rv = compMgr->UnregisterFactory(kPropertiesCID, path);
(void)servMgr->ReleaseService(kComponentManagerCID, compMgr);
return rv;
}
@@ -246,16 +78,27 @@ NSGetFactory(nsISupports* aServMgr,
const char *aProgID,
nsIFactory** aFactory)
{
nsresult res;
if (!aFactory) {
return NS_ERROR_NULL_POINTER;
}
nsBaseFactory* factory = new nsBaseFactory(aClass);
if (factory == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(factory);
*aFactory = factory;
return NS_OK;
if (aClass.Equals(kPropertiesCID)) {
nsPropertiesFactory *propsFactory = new nsPropertiesFactory();
if (!propsFactory) {
return NS_ERROR_OUT_OF_MEMORY;
}
res = propsFactory->QueryInterface(kIFactoryIID, (void**) aFactory);
if (NS_FAILED(res)) {
*aFactory = nsnull;
delete propsFactory;
}
return res;
}
return NS_NOINTERFACE;
}
extern "C" NS_EXPORT PRBool
@@ -263,6 +106,3 @@ NSCanUnload(nsISupports* serviceMgr)
{
return PR_FALSE; // XXX can we unload this?
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,367 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsBuffer.h"
#include "nsAutoLock.h"
#include "nsCRT.h"
#include "nsIInputStream.h"
#include "nsIServiceManager.h"
#include "nsIPageManager.h"
////////////////////////////////////////////////////////////////////////////////
nsBuffer::nsBuffer()
: mGrowBySize(0),
mMaxSize(0),
mAllocator(nsnull),
mBufferSize(0),
mReadSegment(nsnull),
mReadCursor(0),
mWriteSegment(nsnull),
mWriteCursor(0),
mEOF(PR_FALSE)
{
NS_INIT_REFCNT();
PR_INIT_CLIST(&mSegments);
}
NS_IMETHODIMP
nsBuffer::Init(PRUint32 growBySize, PRUint32 maxSize,
nsIAllocator* allocator)
{
mGrowBySize = growBySize;
mMaxSize = maxSize;
mAllocator = allocator;
NS_ADDREF(mAllocator);
return NS_OK;
}
nsBuffer::~nsBuffer()
{
NS_IF_RELEASE(mAllocator);
}
NS_IMPL_ISUPPORTS(nsBuffer, nsIBuffer::GetIID());
////////////////////////////////////////////////////////////////////////////////
nsresult
nsBuffer::PushWriteSegment()
{
nsAutoMonitor mon(this); // protect mSegments
if (mBufferSize >= mMaxSize) {
return NS_ERROR_FAILURE;
}
// allocate a new segment to write into
char* seg;
PRCList* header;
seg = (char*)mAllocator->Alloc(mGrowBySize);
if (seg == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
mBufferSize += mGrowBySize;
header = (PRCList*)seg;
PR_INSERT_BEFORE(header, &mSegments); // insert at end
// initialize the write segment
mWriteSegment = seg;
mWriteSegmentEnd = mWriteSegment + mGrowBySize;
mWriteCursor = mWriteSegment + sizeof(PRCList);
return NS_OK;
}
nsresult
nsBuffer::PopReadSegment()
{
nsresult rv;
nsAutoMonitor mon(this); // protect mSegments
PRCList* header = (PRCList*)mSegments.next;
char* segment = (char*)header;
NS_ASSERTION(mReadSegment == segment, "wrong segment");
// make sure that the writer isn't still in this segment (that the
// reader is removing)
NS_ASSERTION(!(segment <= mWriteCursor && mWriteCursor < segment + mGrowBySize),
"removing writer's segment");
PR_REMOVE_LINK(header); // unlink from mSegments
mBufferSize -= mGrowBySize;
rv = mAllocator->Free(segment);
if (NS_FAILED(rv)) return rv;
// initialize the read segment
if (PR_CLIST_IS_EMPTY(&mSegments)) {
mReadSegment = nsnull;
mReadSegmentEnd = nsnull;
mReadCursor = nsnull;
}
else {
mReadSegment = (char*)mSegments.next;
mReadSegmentEnd = mReadSegment + mGrowBySize;
mReadCursor = mReadSegment + sizeof(PRCList);
}
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIBuffer methods:
NS_IMETHODIMP
nsBuffer::Read(char* toBuf, PRUint32 bufLen, PRUint32 *readCount)
{
nsresult rv;
PRUint32 readBufferLen;
char* readBuffer;
*readCount = 0;
while (bufLen > 0) {
rv = GetReadBuffer(&readBufferLen, &readBuffer);
if (rv == NS_BASE_STREAM_EOF) // all we're going to get
return *readCount > 0 ? NS_OK : NS_BASE_STREAM_EOF;
if (NS_FAILED(rv)) return rv;
if (readBufferLen == 0)
return mEOF && *readCount == 0 ? NS_BASE_STREAM_EOF : NS_OK;
PRUint32 count = PR_MIN(bufLen, readBufferLen);
nsCRT::memcpy(toBuf, readBuffer, count);
*readCount += count;
toBuf += count;
bufLen -= count;
if (mReadCursor + count == mReadSegmentEnd) {
rv = PopReadSegment();
if (NS_FAILED(rv)) return rv;
}
else {
mReadCursor += count;
}
}
return NS_OK;
}
NS_IMETHODIMP
nsBuffer::GetReadBuffer(PRUint32 *readBufferLength, char* *result)
{
if (mReadSegment == nsnull) {
if (PR_CLIST_IS_EMPTY(&mSegments)) {
*readBufferLength = 0;
*result = nsnull;
return mEOF ? NS_BASE_STREAM_EOF : NS_OK;
}
else {
mReadSegment = (char*)mSegments.next;
mReadSegmentEnd = mReadSegment + mGrowBySize;
mReadCursor = mReadSegment + sizeof(PRCList);
}
}
// snapshot the write cursor into a local variable -- this allows
// a writer to freely change it while we're reading while avoiding
// using a lock
char* snapshotWriteCursor = mWriteCursor; // atomic
// next check if the write cursor is in our segment
if (mReadCursor <= snapshotWriteCursor &&
snapshotWriteCursor < mReadSegmentEnd) {
// same segment -- read up to the snapshotWriteCursor
*readBufferLength = snapshotWriteCursor - mReadCursor;
}
else {
// otherwise, read up to the end of this segment
*readBufferLength = mReadSegmentEnd - mReadCursor;
}
*result = mReadCursor;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
NS_IMETHODIMP
nsBuffer::Write(const char* fromBuf, PRUint32 bufLen, PRUint32 *writeCount)
{
nsresult rv;
if (mEOF)
return NS_BASE_STREAM_EOF;
*writeCount = 0;
while (bufLen > 0) {
PRUint32 writeBufLen;
char* writeBuf;
rv = GetWriteBuffer(&writeBufLen, &writeBuf);
if (NS_FAILED(rv)) {
// if we failed to allocate a new segment, we're probably out
// of memory, but we don't care -- just report what we were
// able to write so far
return NS_OK;
}
PRUint32 count = PR_MIN(writeBufLen, bufLen);
nsCRT::memcpy(writeBuf, fromBuf, count);
bufLen -= count;
*writeCount += count;
// set the write cursor after the data is valid
if (mWriteCursor + count == mWriteSegmentEnd) {
mWriteSegment = nsnull; // allocate a new segment next time around
mWriteSegmentEnd = nsnull;
mWriteCursor = nsnull;
}
else
mWriteCursor += count;
}
return NS_OK;
}
NS_IMETHODIMP
nsBuffer::Write(nsIInputStream* fromStream, PRUint32 *writeCount)
{
nsresult rv;
if (mEOF)
return NS_BASE_STREAM_EOF;
*writeCount = 0;
while (PR_TRUE) {
PRUint32 writeBufLen;
char* writeBuf;
rv = GetWriteBuffer(&writeBufLen, &writeBuf);
if (NS_FAILED(rv)) {
// if we failed to allocate a new segment, we're probably out
// of memory, but we don't care -- just report what we were
// able to write so far
return NS_OK;
}
PRUint32 readCount;
rv = fromStream->Read(writeBuf, writeBufLen, &readCount);
if (NS_FAILED(rv)) {
// if we failed to read just report what we were
// able to write so far
return NS_OK;
}
*writeCount += readCount;
// set the write cursor after the data is valid
if (mWriteCursor + readCount == mWriteSegmentEnd) {
mWriteSegment = nsnull; // allocate a new segment next time around
mWriteSegmentEnd = nsnull;
mWriteCursor = nsnull;
}
else
mWriteCursor += readCount;
}
return NS_OK;
}
NS_IMETHODIMP
nsBuffer::GetWriteBuffer(PRUint32 *writeBufferLength, char* *result)
{
if (mEOF)
return NS_BASE_STREAM_EOF;
nsresult rv;
if (mWriteSegment == nsnull) {
if (mBufferSize >= mMaxSize)
return NS_ERROR_FAILURE;
rv = PushWriteSegment();
if (NS_FAILED(rv)) return rv;
NS_ASSERTION(mWriteSegment != nsnull, "failed to allocate segment");
}
*writeBufferLength = mWriteSegmentEnd - mWriteCursor;
*result = mWriteCursor;
return NS_OK;
}
NS_IMETHODIMP
nsBuffer::SetEOF()
{
if (mEOF)
return NS_BASE_STREAM_EOF;
mEOF = PR_TRUE;
mWriteSegment = nsnull; // allows reader to free last segment w/o asserting
mWriteSegmentEnd = nsnull;
// don't reset mWriteCursor here -- we need it for the EOF point in the buffer
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
static NS_DEFINE_CID(kAllocatorCID, NS_ALLOCATOR_CID);
NS_BASE nsresult
NS_NewBuffer(nsIBuffer* *result,
PRUint32 growBySize, PRUint32 maxSize)
{
nsresult rv;
NS_WITH_SERVICE(nsIAllocator, alloc, kAllocatorCID, &rv);
if (NS_FAILED(rv)) return rv;
nsBuffer* buf = new nsBuffer();
if (buf == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
rv = buf->Init(growBySize, maxSize, alloc);
if (NS_FAILED(rv)) {
delete buf;
return rv;
}
NS_ADDREF(buf);
*result = buf;
return NS_OK;
}
static NS_DEFINE_CID(kPageManagerCID, NS_PAGEMANAGER_CID);
NS_BASE nsresult
NS_NewPageBuffer(nsIBuffer* *result,
PRUint32 growBySize, PRUint32 maxSize)
{
nsresult rv;
NS_WITH_SERVICE(nsIAllocator, alloc, kPageManagerCID, &rv);
if (NS_FAILED(rv)) return rv;
nsBuffer* buf = new nsBuffer();
if (buf == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
rv = buf->Init(growBySize, maxSize, alloc);
if (NS_FAILED(rv)) {
delete buf;
return rv;
}
NS_ADDREF(buf);
*result = buf;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,68 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsBuffer_h___
#define nsBuffer_h___
#include "nsIBuffer.h"
#include "nscore.h"
#include "prclist.h"
#include "nsIAllocator.h"
class nsBuffer : public nsIBuffer {
public:
NS_DECL_ISUPPORTS
// nsIBuffer methods:
NS_IMETHOD Init(PRUint32 growBySize, PRUint32 maxSize,
nsIAllocator* allocator);
NS_IMETHOD Read(char* toBuf, PRUint32 bufLen, PRUint32 *readCount);
NS_IMETHOD GetReadBuffer(PRUint32 *readBufferLength, char* *result);
NS_IMETHOD Write(const char* fromBuf, PRUint32 bufLen, PRUint32 *writeCount);
NS_IMETHOD Write(nsIInputStream* fromStream, PRUint32 *writeCount);
NS_IMETHOD GetWriteBuffer(PRUint32 *writeBufferLength, char* *result);
NS_IMETHOD SetEOF();
// nsBuffer methods:
nsBuffer();
virtual ~nsBuffer();
nsresult PushWriteSegment();
nsresult PopReadSegment();
protected:
PRUint32 mGrowBySize;
PRUint32 mMaxSize;
nsIAllocator* mAllocator;
PRCList mSegments;
PRUint32 mBufferSize;
char* mReadSegment;
char* mReadSegmentEnd;
char* mReadCursor;
char* mWriteSegment;
char* mWriteSegmentEnd;
char* mWriteCursor;
PRBool mEOF;
};
#endif // nsBuffer_h___

View File

@@ -24,15 +24,15 @@
class ByteBufferImpl : public nsIByteBuffer {
public:
ByteBufferImpl(PRUint32 aBufferSize);
virtual ~ByteBufferImpl();
~ByteBufferImpl();
NS_DECL_ISUPPORTS
NS_IMETHOD_(PRUint32) GetLength(void) const;
NS_IMETHOD_(PRUint32) GetBufferSize(void) const;
NS_IMETHOD_(char*) GetBuffer() const;
NS_IMETHOD_(PRBool) Grow(PRUint32 aNewSize);
NS_IMETHOD_(PRInt32) Fill(nsresult* aErrorCode, nsIInputStream* aStream,
PRUint32 aKeep);
virtual PRUint32 GetLength(void) const;
virtual PRUint32 GetBufferSize(void) const;
virtual char* GetBuffer() const;
virtual PRBool Grow(PRUint32 aNewSize);
virtual PRInt32 Fill(nsresult* aErrorCode, nsIInputStream* aStream,
PRUint32 aKeep);
char* mBuffer;
PRUint32 mSpace;
@@ -62,26 +62,22 @@ ByteBufferImpl::~ByteBufferImpl()
mLength = 0;
}
NS_IMETHODIMP_(PRUint32)
ByteBufferImpl::GetLength(void) const
PRUint32 ByteBufferImpl::GetLength(void) const
{
return mLength;
}
NS_IMETHODIMP_(PRUint32)
ByteBufferImpl::GetBufferSize(void) const
PRUint32 ByteBufferImpl::GetBufferSize(void) const
{
return mSpace;
}
NS_IMETHODIMP_(char*)
ByteBufferImpl::GetBuffer(void) const
char* ByteBufferImpl::GetBuffer(void) const
{
return mBuffer;
}
NS_IMETHODIMP_(PRBool)
ByteBufferImpl::Grow(PRUint32 aNewSize)
PRBool ByteBufferImpl::Grow(PRUint32 aNewSize)
{
if (aNewSize < MIN_BUFFER_SIZE) {
aNewSize = MIN_BUFFER_SIZE;
@@ -98,9 +94,8 @@ ByteBufferImpl::Grow(PRUint32 aNewSize)
return PR_FALSE;
}
NS_IMETHODIMP_(PRInt32)
ByteBufferImpl::Fill(nsresult* aErrorCode, nsIInputStream* aStream,
PRUint32 aKeep)
PRInt32 ByteBufferImpl::Fill(nsresult* aErrorCode, nsIInputStream* aStream,
PRUint32 aKeep)
{
NS_PRECONDITION(nsnull != aStream, "null stream");
NS_PRECONDITION(aKeep <= mLength, "illegal keep count");

View File

@@ -1,575 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsIByteBufferInputStream.h"
#include "nsCRT.h"
#include "prcmon.h"
class nsByteBufferInputStream;
////////////////////////////////////////////////////////////////////////////////
class nsByteBufferOutputStream : public nsIOutputStream
{
public:
NS_DECL_ISUPPORTS
// nsIBaseStream methods:
NS_IMETHOD Close(void);
// nsIOutputStream methods:
NS_IMETHOD Write(const char* aBuf, PRUint32 aCount, PRUint32 *aWriteCount);
NS_IMETHOD Write(nsIInputStream* fromStream, PRUint32 *aWriteCount);
NS_IMETHOD Flush(void);
// nsByteBufferOutputStream methods:
nsByteBufferOutputStream(nsByteBufferInputStream* in);
virtual ~nsByteBufferOutputStream();
protected:
nsByteBufferInputStream* mInputStream;
};
////////////////////////////////////////////////////////////////////////////////
class nsByteBufferInputStream : public nsIByteBufferInputStream
{
public:
NS_DECL_ISUPPORTS
// nsIBaseStream methods:
NS_IMETHOD Close(void);
// nsIInputStream methods:
NS_IMETHOD GetLength(PRUint32 *aLength);
NS_IMETHOD Read(char* aBuf, PRUint32 aCount, PRUint32 *aReadCount);
// nsIByteBufferInputStream methods:
NS_IMETHOD Fill(nsIInputStream* stream, PRUint32 *aWriteCount);
NS_IMETHOD Fill(const char* aBuf, PRUint32 aCount, PRUint32 *aWriteCount);
// nsByteBufferInputStream methods:
nsByteBufferInputStream(PRBool blocking, PRUint32 size);
virtual ~nsByteBufferInputStream();
friend class nsByteBufferOutputStream;
nsresult Init(void);
nsresult SetEOF(void);
nsresult Drain(void);
PRBool AtEOF() { return mEOF && (mReadCursor == mWriteCursor) && !mFull; }
PRUint32 ReadableAmount() {
if (mReadCursor < mWriteCursor)
return mWriteCursor - mReadCursor;
else if (mReadCursor == mWriteCursor && !mFull)
return 0;
else
return (mLength - mReadCursor) + mWriteCursor;
}
PRUint32 WritableAmount() {
if (mWriteCursor < mReadCursor)
return mWriteCursor - mReadCursor;
else if (mReadCursor == mWriteCursor && mFull)
return 0;
else
return (mLength - mWriteCursor) + mReadCursor;
}
void ReadChunk(char* toBuf, PRUint32 max,
PRUint32 end, PRUint32 *totalRef)
{
NS_ASSERTION(mReadCursor <= end, "bad range");
PRUint32 diff = end - mReadCursor;
PRInt32 amt = PR_MIN(max, diff);
if (amt > 0) {
nsCRT::memcpy(toBuf, &mBuffer[mReadCursor], amt);
#ifdef DEBUG_warren
// nsCRT::memset(&mBuffer[mReadCursor], 0xDD, amt);
#endif
mReadCursor += amt;
*totalRef += amt;
}
}
nsresult WriteChunk(nsIInputStream* in,
PRUint32 end, PRUint32 *totalRef)
{
NS_ASSERTION(mWriteCursor <= end, "bad range");
PRUint32 amt = end - mWriteCursor;
if (amt > 0) {
PRUint32 readAmt;
nsresult rv = in->Read(&mBuffer[mWriteCursor], amt, &readAmt);
if (NS_FAILED(rv)) return rv;
mWriteCursor += readAmt;
*totalRef += readAmt;
}
return NS_OK;
}
protected:
char* mBuffer;
PRUint32 mLength;
PRUint32 mReadCursor;
PRUint32 mWriteCursor;
PRBool mFull;
PRBool mClosed;
PRBool mEOF;
PRBool mBlocking;
};
////////////////////////////////////////////////////////////////////////////////
class nsDummyBufferStream : public nsIInputStream
{
public:
NS_DECL_ISUPPORTS
// nsIBaseStream methods:
NS_IMETHOD Close(void) {
NS_NOTREACHED("nsDummyBufferStream::Close");
return NS_ERROR_FAILURE;
}
// nsIInputStream methods:
NS_IMETHOD GetLength(PRUint32 *aLength) {
*aLength = mLength;
return NS_OK;
}
NS_IMETHOD Read(char* aBuf, PRUint32 aCount, PRUint32 *aReadCount) {
PRUint32 amt = PR_MIN(aCount, mLength);
if (amt > 0) {
nsCRT::memcpy(aBuf, mBuffer, amt);
mBuffer += amt;
mLength -= amt;
}
*aReadCount = amt;
return NS_OK;
}
// nsDummyBufferStream methods:
nsDummyBufferStream(const char* buffer, PRUint32 length)
: mBuffer(buffer), mLength(length) {}
virtual ~nsDummyBufferStream() {}
protected:
const char* mBuffer;
PRUint32 mLength;
};
NS_IMETHODIMP
nsDummyBufferStream::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
NS_NOTREACHED("nsDummyBufferStream::QueryInterface");
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP_(nsrefcnt)
nsDummyBufferStream::AddRef(void)
{
NS_NOTREACHED("nsDummyBufferStream::AddRef");
return 1;
}
NS_IMETHODIMP_(nsrefcnt)
nsDummyBufferStream::Release(void)
{
NS_NOTREACHED("nsDummyBufferStream::Release");
return 1;
}
////////////////////////////////////////////////////////////////////////////////
// nsByteBufferInputStream methods:
////////////////////////////////////////////////////////////////////////////////
nsByteBufferInputStream::nsByteBufferInputStream(PRBool blocking, PRUint32 size)
: mBuffer(nsnull), mLength(size), mReadCursor(0), mWriteCursor(0),
mFull(PR_FALSE), mClosed(PR_FALSE), mEOF(PR_FALSE), mBlocking(blocking)
{
NS_INIT_REFCNT();
}
nsresult
nsByteBufferInputStream::Init(void)
{
mBuffer = new char[mLength];
if (mBuffer == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
nsByteBufferInputStream::~nsByteBufferInputStream()
{
(void)Close();
if (mBuffer) delete mBuffer;
}
NS_IMPL_ADDREF(nsByteBufferInputStream);
NS_IMPL_RELEASE(nsByteBufferInputStream);
NS_IMETHODIMP
nsByteBufferInputStream::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (aInstancePtr == nsnull)
return NS_ERROR_NULL_POINTER;
if (aIID.Equals(nsIByteBufferInputStream::GetIID()) ||
aIID.Equals(nsIInputStream::GetIID()) ||
aIID.Equals(nsIBaseStream::GetIID()) ||
aIID.Equals(nsISupports::GetIID())) {
*aInstancePtr = this;
NS_ADDREF_THIS();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMETHODIMP
nsByteBufferInputStream::Close(void)
{
nsresult rv = NS_OK;
if (mBlocking)
PR_CEnterMonitor(this);
mClosed = PR_TRUE;
if (mBlocking) {
PRStatus status = PR_CNotify(this); // wake up the writer
if (status != PR_SUCCESS)
rv = NS_ERROR_FAILURE;
PR_CExitMonitor(this);
}
return rv;
}
NS_IMETHODIMP
nsByteBufferInputStream::GetLength(PRUint32 *aLength)
{
if (mClosed)
return NS_BASE_STREAM_CLOSED;
if (mBlocking)
PR_CEnterMonitor(this);
*aLength = ReadableAmount();
if (mBlocking)
PR_CExitMonitor(this);
return NS_OK;
}
NS_IMETHODIMP
nsByteBufferInputStream::Read(char* aBuf, PRUint32 aCount, PRUint32 *aReadCount)
{
nsresult rv = NS_OK;
if (mClosed)
return NS_BASE_STREAM_CLOSED;
if (AtEOF())
return NS_BASE_STREAM_EOF;
if (mBlocking)
PR_CEnterMonitor(this);
*aReadCount = 0;
/*while (aCount > 0)*/ {
if (ReadableAmount() == 0) {
if (mBlocking) {
PRStatus status = PR_CWait(this, PR_INTERVAL_NO_TIMEOUT);
if (status != PR_SUCCESS) {
rv = NS_ERROR_FAILURE;
goto done;
}
}
if (mEOF) {
rv = NS_BASE_STREAM_EOF;
goto done;
}
else if (!mBlocking) {
rv = NS_BASE_STREAM_WOULD_BLOCK;
goto done;
}
}
// wrap-around buffer:
PRUint32 amt = 0;
if (mReadCursor >= mWriteCursor || mFull) {
ReadChunk(aBuf, aCount, mLength, &amt);
*aReadCount += amt;
aBuf += amt;
aCount -= amt;
if (mReadCursor == mLength) {
mReadCursor = 0;
amt = 0;
ReadChunk(aBuf, aCount, mWriteCursor, &amt);
*aReadCount += amt;
aBuf += amt;
aCount -= amt;
}
}
else {
ReadChunk(aBuf, aCount, mWriteCursor, &amt);
*aReadCount += amt;
aBuf += amt;
aCount -= amt;
}
if (*aReadCount)
mFull = PR_FALSE;
if (mBlocking) {
PRStatus status = PR_CNotify(this); // tell the writer there's space
if (status != PR_SUCCESS)
rv = NS_ERROR_FAILURE;
}
}
done:
if (mBlocking)
PR_CExitMonitor(this);
return rv;
}
NS_IMETHODIMP
nsByteBufferInputStream::Fill(const char* aBuf, PRUint32 aCount, PRUint32 *aWriteCount)
{
nsDummyBufferStream in(aBuf, aCount);
return Fill(&in, aWriteCount);
}
NS_IMETHODIMP
nsByteBufferInputStream::Fill(nsIInputStream* stream, PRUint32 *aWriteCount)
{
nsresult rv = NS_OK;
if (mClosed || mEOF)
return NS_BASE_STREAM_CLOSED;
*aWriteCount = 0;
PRUint32 aCount;
rv = stream->GetLength(&aCount);
if (NS_FAILED(rv)) return rv;
if (mBlocking)
PR_CEnterMonitor(this);
while (aCount > 0) {
if (WritableAmount() == 0) {
if (mBlocking) {
PRStatus status = PR_CWait(this, PR_INTERVAL_NO_TIMEOUT);
if (status != PR_SUCCESS) {
rv = NS_ERROR_FAILURE;
goto done;
}
}
if (mClosed) {
rv = NS_BASE_STREAM_CLOSED;
goto done;
}
else if (!mBlocking) {
rv = NS_BASE_STREAM_WOULD_BLOCK;
goto done;
}
}
// wrap-around buffer:
PRUint32 amt = 0;
if (mReadCursor <= mWriteCursor && !mFull) {
rv = WriteChunk(stream, mLength, &amt);
if (NS_FAILED(rv)) goto done;
*aWriteCount += amt;
aCount -= amt;
if (mWriteCursor == mLength) {
mWriteCursor = 0;
amt = 0;
rv = WriteChunk(stream, mReadCursor, &amt);
if (NS_FAILED(rv)) goto done;
*aWriteCount += amt;
aCount -= amt;
}
}
else {
rv = WriteChunk(stream, mReadCursor, &amt);
if (NS_FAILED(rv)) goto done;
*aWriteCount += amt;
aCount -= amt;
}
if (mWriteCursor == mReadCursor)
mFull = PR_TRUE;
if (mBlocking) {
PRStatus status = PR_CNotify(this); // tell the reader there's more
if (status != PR_SUCCESS)
rv = NS_ERROR_FAILURE;
}
}
done:
if (mBlocking)
PR_CExitMonitor(this);
return rv;
}
nsresult
nsByteBufferInputStream::SetEOF()
{
nsresult rv = NS_OK;
if (mBlocking)
PR_CEnterMonitor(this);
mEOF = PR_TRUE;
if (mBlocking) {
PRStatus status = PR_CNotify(this); // wake up the reader
if (status != PR_SUCCESS)
rv = NS_ERROR_FAILURE;
PR_CExitMonitor(this);
}
return rv;
}
nsresult
nsByteBufferInputStream::Drain()
{
nsresult rv = NS_OK;
if (mBlocking) {
PR_CEnterMonitor(this);
while (ReadableAmount() != 0) {
PRStatus status = PR_CNotify(this); // wake up the reader
if (status != PR_SUCCESS) {
rv = NS_ERROR_FAILURE;
break;
}
else {
// wait for the reader to take all the data
status = PR_CWait(this, PR_INTERVAL_NO_TIMEOUT);
if (status != PR_SUCCESS) {
rv = NS_ERROR_FAILURE;
break;
}
}
}
PR_CExitMonitor(this);
}
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsByteBufferOutputStream methods:
////////////////////////////////////////////////////////////////////////////////
nsByteBufferOutputStream::nsByteBufferOutputStream(nsByteBufferInputStream* in)
: mInputStream(in)
{
NS_INIT_REFCNT();
NS_ADDREF(mInputStream);
}
nsByteBufferOutputStream::~nsByteBufferOutputStream()
{
(void)Close();
NS_IF_RELEASE(mInputStream);
}
NS_IMPL_ADDREF(nsByteBufferOutputStream);
NS_IMPL_RELEASE(nsByteBufferOutputStream);
NS_IMETHODIMP
nsByteBufferOutputStream::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (aInstancePtr == nsnull)
return NS_ERROR_NULL_POINTER;
if (aIID.Equals(nsIOutputStream::GetIID()) ||
aIID.Equals(nsIBaseStream::GetIID()) ||
aIID.Equals(nsISupports::GetIID())) {
*aInstancePtr = this;
NS_ADDREF_THIS();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMETHODIMP
nsByteBufferOutputStream::Close(void)
{
mInputStream->SetEOF();
return NS_OK;
}
NS_IMETHODIMP
nsByteBufferOutputStream::Write(const char* aBuf, PRUint32 aCount, PRUint32 *aWriteCount)
{
return mInputStream->Fill(aBuf, aCount, aWriteCount);
}
NS_IMETHODIMP
nsByteBufferOutputStream::Write(nsIInputStream* fromStream, PRUint32 *aWriteCount)
{
return mInputStream->Fill(fromStream, aWriteCount);
}
NS_IMETHODIMP
nsByteBufferOutputStream::Flush(void)
{
return mInputStream->Drain();
}
////////////////////////////////////////////////////////////////////////////////
NS_BASE nsresult
NS_NewByteBufferInputStream(nsIByteBufferInputStream* *result,
PRBool blocking, PRUint32 size)
{
nsresult rv;
nsByteBufferInputStream* inStr = nsnull;
inStr = new nsByteBufferInputStream(blocking, size);
if (inStr == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
rv = inStr->Init();
if (NS_FAILED(rv)) {
delete inStr;
return rv;
}
NS_ADDREF(inStr);
*result = inStr;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
NS_BASE nsresult
NS_NewPipe(nsIInputStream* *inStrResult,
nsIOutputStream* *outStrResult,
PRBool blocking, PRUint32 size)
{
nsresult rv;
nsIByteBufferInputStream* in;
nsByteBufferInputStream* inStr;
nsByteBufferOutputStream* outStr;
rv = NS_NewByteBufferInputStream(&in, blocking, size);
if (NS_FAILED(rv)) return rv;
// this cast is safe, because we know how NS_NewByteBufferInputStream works:
inStr = NS_STATIC_CAST(nsByteBufferInputStream*, in);
outStr = new nsByteBufferOutputStream(inStr);
if (outStr == nsnull) {
NS_RELEASE(inStr);
return NS_ERROR_OUT_OF_MEMORY;
}
NS_ADDREF(outStr);
*inStrResult = inStr;
*outStrResult = outStr;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -91,7 +91,7 @@ static const unsigned char kLower2Upper[256] = {
};
// XXX bug: this doesn't map 0x80 to 0x9f properly
const PRUnichar kIsoLatin1ToUCS2[256] = {
static const PRUnichar kIsoLatin1ToUCS2[256] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
@@ -134,15 +134,14 @@ static NS_DEFINE_IID(kIShutdownListenerIID, NS_ISHUTDOWNLISTENER_IID);
NS_IMPL_ISUPPORTS(HandleCaseConversionShutdown, kIShutdownListenerIID);
nsresult
HandleCaseConversionShutdown::OnShutdown(const nsCID& cid,
nsISupports* aService)
HandleCaseConversionShutdown::OnShutdown(const nsCID& cid, nsISupports* service)
{
if (cid.Equals(kUnicharUtilCID)) {
NS_ASSERTION(aService == gCaseConv, "wrong service!");
gCaseConv->Release();
gCaseConv = NULL;
}
return NS_OK;
if (cid.Equals(kUnicharUtilCID)) {
NS_ASSERTION(service == gCaseConv, "wrong service!");
nsrefcnt cnt = gCaseConv->Release();
gCaseConv = NULL;
}
return NS_OK;
}
static HandleCaseConversionShutdown* gListener = NULL;
@@ -352,8 +351,8 @@ PRInt32 nsCRT::strcasecmp(const PRUnichar* s1, const PRUnichar* s2)
PRInt32 nsCRT::strncasecmp(const PRUnichar* s1, const PRUnichar* s2, PRUint32 n)
{
if(s1 && s2) {
if(n != 0){
do {
if(0<n){
while (--n >= 0) {
PRUnichar c1 = *s1++;
PRUnichar c2 = *s2++;
if (c1 != c2) {
@@ -365,7 +364,7 @@ PRInt32 nsCRT::strncasecmp(const PRUnichar* s1, const PRUnichar* s2, PRUint32 n)
}
}
if ((0==c1) || (0==c2)) break;
} while (--n != 0);
}
}
}
return 0;

View File

@@ -22,7 +22,6 @@
#include <string.h>
#include "plstr.h"
#include "nscore.h"
#include "prtypes.h"
#define CR '\015'
#define LF '\012'
@@ -32,9 +31,6 @@
#define CRLF "\015\012" /* A CR LF equivalent string */
extern const PRUnichar kIsoLatin1ToUCS2[256];
// This macro can be used in a class declaration for classes that want
// to ensure that their instance memory is zeroed.
#define NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW \
@@ -129,12 +125,7 @@ public:
return PL_strdup(str);
}
static void free(char* str) {
PL_strfree(str);
}
/**
How to use this fancy (thread-safe) version of strtok:
void main( void ) {
@@ -149,8 +140,7 @@ public:
token = nsCRT::strtok( newStr, seps, &newStr );
}
}
* WARNING - STRTOK WHACKS str THE FIRST TIME IT IS CALLED *
* MAKE A COPY OF str IF YOU NEED TO USE IT AFTER strtok() *
*/
static char* strtok(char* str, const char* delims, char* *newStr);
@@ -185,10 +175,6 @@ public:
// free the memory
static PRUnichar* strdup(const PRUnichar* str);
static void free(PRUnichar* str) {
delete[] str;
}
/// Compute a hashcode for a ucs2 string
static PRUint32 HashValue(const PRUnichar* s1);

View File

@@ -100,35 +100,6 @@ nsDeque& nsDeque::Erase() {
}
/**
* This method adds an item to the end of the deque.
* This operation has the potential to cause the
* underlying buffer to resize.
*
* @update gess4/18/98
* @param anItem: new item to be added to deque
* @return nada
*/
nsDeque& nsDeque::GrowCapacity(void) {
void** temp=new void*[mCapacity+eGrowthDelta];
//Here's the interesting part: You can't just move the elements
//directy (in situ) from the old buffer to the new one.
//Since capacity has changed, the old origin doesn't make
//sense anymore. It's better to resequence the elements now.
int tempi=0;
int i=0;
int j=0;
for(i=mOrigin;i<mCapacity;i++) temp[tempi++]=mData[i]; //copy the leading elements...
for(j=0;j<mOrigin;j++) temp[tempi++]=mData[j]; //copy the trailing elements...
mCapacity+=eGrowthDelta;
mOrigin=0; //now realign the origin...
delete[]mData;
mData=temp;
return *this;
}
/**
* This method adds an item to the end of the deque.
* This operation has the potential to cause the
@@ -140,7 +111,22 @@ nsDeque& nsDeque::GrowCapacity(void) {
*/
nsDeque& nsDeque::Push(void* anItem) {
if(mSize==mCapacity) {
GrowCapacity();
void** temp=new void*[mCapacity+eGrowthDelta];
//Here's the interesting part: You can't just move the elements
//directy (in situ) from the old buffer to the new one.
//Since capacity has changed, the old origin doesn't make
//sense anymore. It's better to resequence the elements now.
int tempi=0;
int i=0;
int j=0;
for(i=mOrigin;i<mCapacity;i++) temp[tempi++]=mData[i]; //copy the leading elements...
for(j=0;j<mOrigin;j++) temp[tempi++]=mData[j]; //copy the trailing elements...
mCapacity+=eGrowthDelta;
mOrigin=0; //now realign the origin...
delete[]mData;
mData=temp;
}
int offset=mOrigin+mSize;
if(offset<mCapacity)
@@ -150,6 +136,7 @@ nsDeque& nsDeque::Push(void* anItem) {
return *this;
}
/**
* This method adds an item to the front of the deque.
* This operation has the potential to cause the
@@ -160,18 +147,15 @@ nsDeque& nsDeque::Push(void* anItem) {
* @return nada
*/
nsDeque& nsDeque::PushFront(void* anItem) {
if(mSize==mCapacity) {
GrowCapacity();
}
if(0==mOrigin){ //case1: [xxx..]
//mOrigin=mCapacity-1-mSize++;
mOrigin=mCapacity-1;
if(mOrigin>0) {
mOrigin-=1;
mData[mOrigin]=anItem;
mSize++;
}
else {// if(mCapacity==(mOrigin+mSize-1)){ //case2: [..xxx] and case3: [.xxx.]
mData[--mOrigin]=anItem;
else {
Push(anItem);
mOrigin=mSize-1;
}
mSize++;
return *this;
}

View File

@@ -252,8 +252,6 @@ private:
*/
nsDeque& operator=(const nsDeque& anOther);
nsDeque& GrowCapacity(void);
};
/******************************************************
@@ -402,7 +400,6 @@ public:
const void* FirstThat(nsDequeFunctor& aFunctor) const;
protected:
PRInt32 mIndex;
const nsDeque& mDeque;
};

View File

@@ -21,7 +21,6 @@
#include "nsEscape.h"
#include "plstr.h"
#include "prmem.h"
const int netCharType[256] =
/* Bit 0 xalpha -- the alphas
@@ -167,48 +166,3 @@ NS_BASE PRInt32 nsUnescapeCount(char * str)
} /* NET_UnEscapeCnt */
NS_BASE char *
nsEscapeHTML(const char * string)
{
char *rv = (char *) PR_Malloc(PL_strlen(string)*4 + 1); /* The +1 is for
the trailing
null! */
char *ptr = rv;
if(rv)
{
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
{
*ptr++ = *string;
}
}
*ptr = '\0';
}
return(rv);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,82 +0,0 @@
#include "nsFileSpecStreaming.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsFileStream.h"
#include "nsFileSpec.h"
#define MAX_PERSISTENT_DATA_SIZE 1000
//----------------------------------------------------------------------------------------
nsOutputStream& operator << (nsOutputStream& s, const nsFileURL& url)
//----------------------------------------------------------------------------------------
{
return s << url.GetAsString();
}
//----------------------------------------------------------------------------------------
nsresult ReadDescriptor(
nsIInputStream* aStream,
nsPersistentFileDescriptor& desc)
//----------------------------------------------------------------------------------------
{
nsInputStream inputStream(aStream);
inputStream >> desc;
return NS_OK;
}
//----------------------------------------------------------------------------------------
nsresult WriteDescriptor(
nsIOutputStream* aStream,
const nsPersistentFileDescriptor& desc)
//----------------------------------------------------------------------------------------
{
nsOutputStream outputStream(aStream);
outputStream << desc;
return NS_OK;
}
//----------------------------------------------------------------------------------------
nsInputStream& operator >> (nsInputStream& s, nsPersistentFileDescriptor& d)
// reads the data from a file
//----------------------------------------------------------------------------------------
{
char bigBuffer[MAX_PERSISTENT_DATA_SIZE + 1];
// The first 8 bytes of the data should be a hex version of the data size to follow.
PRInt32 bytesRead = 8;
bytesRead = s.read(bigBuffer, bytesRead);
if (bytesRead != 8)
return s;
bigBuffer[8] = '\0';
sscanf(bigBuffer, "%x", (PRUint32*)&bytesRead);
if (bytesRead > MAX_PERSISTENT_DATA_SIZE)
{
// Try to tolerate encoded values with no length header
bytesRead = 8 + s.read(bigBuffer + 8, MAX_PERSISTENT_DATA_SIZE - 8);
}
else
{
// Now we know how many bytes to read, do it.
bytesRead = s.read(bigBuffer, bytesRead);
}
d.SetData(bigBuffer, bytesRead);
return s;
}
//----------------------------------------------------------------------------------------
nsOutputStream& operator << (nsOutputStream& s, const nsPersistentFileDescriptor& d)
// writes the data to a file
//----------------------------------------------------------------------------------------
{
char littleBuf[9];
PRInt32 dataSize;
nsSimpleCharString data;
d.GetData(data, dataSize);
// First write (in hex) the length of the data to follow. Exactly 8 bytes
sprintf(littleBuf, "%0.8x", dataSize);
s << littleBuf;
// Now write the data itself
s << (const char*)data;
return s;
}

View File

@@ -43,9 +43,8 @@ char nsInputStream::get()
//----------------------------------------------------------------------------------------
{
char c;
if (read(&c, sizeof(c)) == sizeof(c))
return c;
return 0;
read(&c, sizeof(c));
return c;
}
//----------------------------------------------------------------------------------------
@@ -316,11 +315,7 @@ void nsOutputFileStream::flush()
nsOutputStream& nsEndl(nsOutputStream& os)
//----------------------------------------------------------------------------------------
{
#ifdef XP_PC
os.write("\r\n", 2);
#else
os.put('\n');
#endif
os.flush();
return os;
} // nsEndl
} // nsEndl

View File

@@ -37,8 +37,6 @@
*/
class nsIArena : public nsISupports {
public:
static const nsIID& GetIID() { static nsIID iid = NS_IARENA_IID; return iid; }
virtual void* Alloc(PRInt32 size) = 0;
};

View File

@@ -52,8 +52,6 @@ public:
#define NS_BASE_STREAM_NO_CONVERTER NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_BASE, 5)
/// For unichar streams
#define NS_BASE_STREAM_BAD_CONVERSION NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_BASE, 6)
#define NS_BASE_STREAM_WOULD_BLOCK NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_BASE, 7)
//@}

View File

@@ -15,7 +15,6 @@
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIByteBuffer_h___
#define nsIByteBuffer_h___
@@ -32,28 +31,27 @@ class nsIInputStream;
class nsIByteBuffer : public nsISupports {
public:
/** @return length of buffer, i.e. how many bytes are currently in it. */
NS_IMETHOD_(PRUint32) GetLength(void) const = 0;
virtual PRUint32 GetLength(void) const = 0;
/** @return number of bytes allocated in the buffer */
NS_IMETHOD_(PRUint32) GetBufferSize(void) const = 0;
virtual PRUint32 GetBufferSize(void) const = 0;
/** @return the buffer */
NS_IMETHOD_(char*) GetBuffer(void) const = 0;
virtual char* GetBuffer(void) const = 0;
/** Grow buffer to aNewSize bytes. */
NS_IMETHOD_(PRBool) Grow(PRUint32 aNewSize) = 0;
virtual PRBool Grow(PRUint32 aNewSize) = 0;
/** Fill the buffer with data from aStream. Don't grow the buffer, only
* read until length of buffer equals buffer size. */
NS_IMETHOD_(PRInt32) Fill(nsresult* aErrorCode, nsIInputStream* aStream,
PRUint32 aKeep) = 0;
virtual PRInt32 Fill(nsresult* aErrorCode, nsIInputStream* aStream,
PRUint32 aKeep) = 0;
};
/** Create a new byte buffer using the given buffer size. */
extern NS_BASE nsresult
NS_NewByteBuffer(nsIByteBuffer** aInstancePtrResult,
nsISupports* aOuter,
PRUint32 aBufferSize = 0);
extern NS_BASE nsresult NS_NewByteBuffer(nsIByteBuffer** aInstancePtrResult,
nsISupports* aOuter,
PRUint32 aBufferSize = 0);
#endif /* nsIByteBuffer_h___ */

View File

@@ -1,21 +1,3 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsIFileStream.h"
#include "nsFileSpec.h"
@@ -115,10 +97,6 @@ class FileImpl
mFailed = PR_TRUE;
return NS_FILE_RESULT(PR_GetError());
}
else if (bytesRead == 0) {
mEOF = PR_TRUE;
return NS_BASE_STREAM_EOF;
}
*aReadCount = bytesRead;
return NS_OK;
}
@@ -154,10 +132,6 @@ class FileImpl
*aWriteCount = bytesWrit;
return NS_OK;
}
NS_IMETHOD Write(nsIInputStream* fromStream, PRUint32 *aWriteCount)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHOD Flush();
NS_IMETHOD GetAtEOF(PRBool* outAtEOF)

View File

@@ -40,6 +40,7 @@ public:
GetLength(PRUint32 *aLength) = 0;
/** Read data from the stream.
* @param aErrorCode the error code if an error occurs
* @param aBuf the buffer into which the data is read
* @param aCount the maximum number of bytes to read
* @param aReadCount out parameter to hold the number of

View File

@@ -1,4 +1,4 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
@@ -15,14 +15,11 @@
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIOutputStream_h___
#define nsIOutputStream_h___
#include "nsIBaseStream.h"
class nsIInputStream;
/* 7f13b870-e95f-11d1-beae-00805f8a66dc */
#define NS_IOUTPUTSTREAM_IID \
{ 0x7f13b870, 0xe95f, 0x11d1, \
@@ -35,8 +32,8 @@ public:
static const nsIID& GetIID() { static nsIID iid = NS_IOUTPUTSTREAM_IID; return iid; }
/** Write data into the stream.
* @param aBuf the buffer from which the data is read
* @param aCount the maximum number of bytes to write
* @param aBuf the buffer into which the data is read
* @param aCount the maximum number of bytes to read
* @param aWriteCount out parameter to hold the number of
* bytes written. if an error occurs, the writecount
* is undefined
@@ -44,29 +41,6 @@ public:
*/
NS_IMETHOD
Write(const char* aBuf, PRUint32 aCount, PRUint32 *aWriteCount) = 0;
/**
* Writes data into the stream from an input stream.
* Implementer's note: This method is defined by this interface in order
* to allow the output stream to efficiently copy the data from the input
* stream into its internal buffer (if any). If this method was provide
* as an external facility, a separate char* buffer would need to be used
* in order to call the output stream's other Write method.
* @param fromStream the stream from which the data is read
* @param aWriteCount out parameter to hold the number of
* bytes written. if an error occurs, the writecount
* is undefined
* @return error status
*/
NS_IMETHOD
Write(nsIInputStream* fromStream, PRUint32 *aWriteCount) = 0;
/**
* Flushes the stream.
*/
NS_IMETHOD
Flush(void) = 0;
};

View File

@@ -1,21 +1,3 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsIStringStream.h"
#include "nsIFileStream.h"
@@ -32,9 +14,9 @@ class BasicStringImpl
{
public:
BasicStringImpl()
: mOffset(0)
, mLastResult(NS_OK)
: mResult(NS_OK)
, mEOF(PR_FALSE)
, mOffset(0)
{
NS_INIT_REFCNT();
}
@@ -78,16 +60,16 @@ class BasicStringImpl
NS_PRECONDITION(aReadCount != nsnull, "null ptr");
if (!aReadCount)
return NS_ERROR_NULL_POINTER;
if (NS_FAILED(mLastResult))
return mLastResult;
if (NS_FAILED(mResult))
return mResult;
PRInt32 bytesRead = read(aBuf, aCount);
if (NS_FAILED(mLastResult))
if (NS_FAILED(mResult))
{
*aReadCount = 0;
return mLastResult;
return mResult;
}
*aReadCount = bytesRead;
if (bytesRead < (PRInt32)aCount)
if (bytesRead < aCount)
SetAtEOF(PR_TRUE);
return NS_OK;
}
@@ -99,21 +81,17 @@ class BasicStringImpl
NS_PRECONDITION(aBuf != nsnull, "null ptr");
NS_PRECONDITION(aWriteCount != nsnull, "null ptr");
if (NS_FAILED(mLastResult))
return mLastResult;
if (NS_FAILED(mResult))
return mResult;
PRInt32 bytesWrit = write(aBuf, aCount);
if (NS_FAILED(mLastResult))
if (NS_FAILED(mResult))
{
*aWriteCount = 0;
return mLastResult;
return mResult;
}
*aWriteCount = bytesWrit;
return NS_OK;
}
NS_IMETHOD Write(nsIInputStream* fromStream, PRUint32 *aWriteCount)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
public:
// nsISupports interface
@@ -126,7 +104,7 @@ class BasicStringImpl
public:
nsresult get_result() const { return mLastResult; }
nsresult get_result() const { return mResult; }
protected:
@@ -135,14 +113,14 @@ class BasicStringImpl
virtual PRInt32 write(const char*, PRUint32)
{
NS_ASSERTION(PR_FALSE, "Write to a const string");
mLastResult = NS_FILE_RESULT(PR_ILLEGAL_ACCESS_ERROR);
mResult = NS_FILE_RESULT(PR_ILLEGAL_ACCESS_ERROR);
return -1;
}
protected:
PRUint32 mOffset;
nsresult mLastResult;
nsresult mResult;
PRBool mEOF;
}; // class BasicStringImpl
@@ -168,7 +146,7 @@ class ConstCharImpl
virtual PRInt32 read(char* buf, PRUint32 aCount)
{
PRInt32 maxCount = mLength - mOffset;
if ((PRInt32)aCount > maxCount)
if (aCount > maxCount)
aCount = maxCount;
memcpy(buf, mConstString + mOffset, aCount);
mOffset += aCount;
@@ -203,7 +181,7 @@ class CharImpl
mString = new char[mAllocLength];
if (!mString)
{
mLastResult = NS_ERROR_OUT_OF_MEMORY;
mResult = NS_ERROR_OUT_OF_MEMORY;
return;
}
mConstString = mString;
@@ -215,17 +193,17 @@ class CharImpl
virtual PRInt32 write(const char* buf, PRUint32 aCount)
{
PRInt32 maxCount = mAllocLength - 1 - mOffset;
if ((PRInt32)aCount > maxCount)
if (aCount > maxCount)
{
do {
maxCount += kAllocQuantum;
} while ((PRInt32)aCount > maxCount);
} while (aCount > maxCount);
mAllocLength = maxCount + 1 + mOffset;
char* newString = new char[mAllocLength];
if (!newString)
{
mLastResult = NS_ERROR_OUT_OF_MEMORY;
mResult = NS_ERROR_OUT_OF_MEMORY;
return 0;
}
strcpy(newString, mString);
@@ -242,8 +220,8 @@ class CharImpl
protected:
char*& mString;
size_t mAllocLength;
size_t mOriginalLength;
size_t mAllocLength;
}; // class CharImpl
@@ -293,7 +271,7 @@ class StringImpl
chars.Seek(PR_SEEK_SET, mOffset);
// Get the bytecount and result from the CharImpl
PRInt32 result = chars.write(buf,count);
mLastResult = chars.get_result();
mResult = chars.get_result();
// Set our string to match the new chars
mString = cstring;
// Set our const string also...
@@ -353,10 +331,10 @@ NS_IMETHODIMP BasicStringImpl::QueryInterface(REFNSIID aIID, void** aInstancePtr
NS_IMETHODIMP BasicStringImpl::Seek(PRSeekWhence whence, PRInt32 offset)
//----------------------------------------------------------------------------------------
{
mLastResult = NS_OK; // reset on a seek.
mResult = NS_OK; // reset on a seek.
mEOF = PR_FALSE; // reset on a seek.
PRInt32 fileSize = length();
PRInt32 newPosition=-1;
PRInt32 newPosition;
switch (whence)
{
case PR_SEEK_CUR: newPosition = mOffset + offset; break;
@@ -366,7 +344,7 @@ NS_IMETHODIMP BasicStringImpl::Seek(PRSeekWhence whence, PRInt32 offset)
if (newPosition < 0)
{
newPosition = 0;
mLastResult = NS_FILE_RESULT(PR_FILE_SEEK_ERROR);
mResult = NS_FILE_RESULT(PR_FILE_SEEK_ERROR);
}
if (newPosition >= fileSize)
{

View File

@@ -1,83 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#define NS_IMPL_IDS
#include "pratom.h"
#include "nsIFactory.h"
#include "nsIServiceManager.h"
#include "nsRepository.h"
#include "nsIObserver.h"
#include "nsObserver.h"
#include "nsString.h"
static NS_DEFINE_IID(kIObserverIID, NS_IOBSERVER_IID);
static NS_DEFINE_IID(kObserverCID, NS_OBSERVER_CID);
////////////////////////////////////////////////////////////////////////////////
// nsObserver Implementation
NS_IMPL_AGGREGATED(nsObserver);
NS_BASE nsresult NS_NewObserver(nsIObserver** anObserver)
{
if (anObserver == NULL)
{
return NS_ERROR_NULL_POINTER;
}
nsObserver* it = new nsObserver();
if (it == 0) {
return NS_ERROR_OUT_OF_MEMORY;
}
return it->QueryInterface(kIObserverIID, (void **) anObserver);
}
nsObserver::nsObserver()
{
NS_INIT_REFCNT();
}
nsObserver::~nsObserver(void)
{
}
NS_IMETHODIMP
nsObserver::AggregatedQueryInterface(const nsIID& aIID, void** aInstancePtr)
{
if (aInstancePtr == nsnull)
return NS_ERROR_NULL_POINTER;
if (aIID.Equals(nsIObserver::GetIID()) ||
aIID.Equals(nsISupports::GetIID())) {
*aInstancePtr = this;
NS_ADDREF_THIS();
return NS_OK;
}
return NS_NOINTERFACE;
}
nsresult nsObserver::Notify(nsISupports** result)
{
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,40 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsObserver_h___
#define nsObserver_h___
#include "nsIObserver.h"
#include "nsAgg.h"
class nsObserver : public nsIObserver {
public:
NS_IMETHOD Notify(nsISupports** result);
nsObserver();
virtual ~nsObserver(void);
NS_DECL_AGGREGATED
private:
};
#endif /* nsObserver_h___ */

View File

@@ -1,133 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#define NS_IMPL_IDS
#include "pratom.h"
#include "nsIObserverList.h"
#include "nsObserverList.h"
#include "nsString.h"
#include "nsAutoLock.h"
#define NS_AUTOLOCK(__monitor) nsAutoLock __lock(__monitor)
static NS_DEFINE_IID(kIObserverListIID, NS_IOBSERVERLIST_IID);
static NS_DEFINE_IID(kObserverListCID, NS_OBSERVERLIST_CID);
////////////////////////////////////////////////////////////////////////////////
// nsObserverList Implementation
NS_IMPL_ISUPPORTS(nsObserverList, kIObserverListIID);
NS_BASE nsresult NS_NewObserverList(nsIObserverList** anObserverList)
{
if (anObserverList == NULL)
{
return NS_ERROR_NULL_POINTER;
}
nsObserverList* it = new nsObserverList();
if (it == 0) {
return NS_ERROR_OUT_OF_MEMORY;
}
return it->QueryInterface(kIObserverListIID, (void **) anObserverList);
}
nsObserverList::nsObserverList()
: mObserverList(NULL),
mLock(nsnull)
{
NS_INIT_REFCNT();
mLock = PR_NewLock();
}
nsObserverList::~nsObserverList(void)
{
PR_DestroyLock(mLock);
}
nsresult nsObserverList::AddObserver(nsIObserver** anObserver)
{
nsresult rv;
PRBool inserted;
NS_AUTOLOCK(mLock);
if (anObserver == NULL)
{
return NS_ERROR_NULL_POINTER;
}
if(!mObserverList) {
rv = NS_NewISupportsArray(&mObserverList);
if (NS_FAILED(rv)) return rv;
}
if(*anObserver) {
inserted = mObserverList->AppendElement(*anObserver);
return inserted ? NS_OK : NS_ERROR_FAILURE;
}
return NS_ERROR_FAILURE;
}
nsresult nsObserverList::RemoveObserver(nsIObserver** anObserver)
{
PRBool removed;
NS_AUTOLOCK(mLock);
if (anObserver == NULL)
{
return NS_ERROR_NULL_POINTER;
}
if(!mObserverList) {
return NS_ERROR_FAILURE;
}
if(*anObserver) {
removed = mObserverList->RemoveElement(*anObserver);
return removed ? NS_OK : NS_ERROR_FAILURE;
}
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP nsObserverList::EnumerateObserverList(nsIEnumerator** anEnumerator)
{
NS_AUTOLOCK(mLock);
if (anEnumerator == NULL)
{
return NS_ERROR_NULL_POINTER;
}
if(!mObserverList) {
return NS_ERROR_FAILURE;
}
return mObserverList->Enumerate(anEnumerator);
}

View File

@@ -1,51 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsObserverList_h___
#define nsObserverList_h___
#include "nsIObserverList.h"
#include "nsIEnumerator.h"
#include "nsISupportsArray.h"
class nsObserverList : public nsIObserverList {
public:
NS_IMETHOD AddObserver(nsIObserver** anObserver);
NS_IMETHOD RemoveObserver(nsIObserver** anObserver);
NS_IMETHOD EnumerateObserverList(nsIEnumerator** anEnumerator);
nsObserverList();
virtual ~nsObserverList(void);
// This is ObserverList monitor object.
PRLock* mLock;
NS_DECL_ISUPPORTS
private:
nsISupportsArray *mObserverList;
};
#endif /* nsObserverList_h___ */

View File

@@ -1,226 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#define NS_IMPL_IDS
#include "prlock.h"
#include "nsIFactory.h"
#include "nsIServiceManager.h"
#include "nsRepository.h"
#include "nsIObserverService.h"
#include "nsObserverService.h"
#include "nsIObserverList.h"
#include "nsObserverList.h"
#include "nsHashtable.h"
#include "nsString.h"
static NS_DEFINE_IID(kIObserverServiceIID, NS_IOBSERVERSERVICE_IID);
static NS_DEFINE_IID(kObserverServiceCID, NS_OBSERVERSERVICE_CID);
////////////////////////////////////////////////////////////////////////////////
class nsObserverService : public nsIObserverService {
public:
static nsresult GetObserverService(nsIObserverService** anObserverService);
NS_IMETHOD AddObserver(nsIObserver** anObserver, nsString* aTopic);
NS_IMETHOD RemoveObserver(nsIObserver** anObserver, nsString* aTopic);
NS_IMETHOD EnumerateObserverList(nsIEnumerator** anEnumerator, nsString* aTopic);
nsObserverService();
virtual ~nsObserverService(void);
NS_DECL_ISUPPORTS
private:
NS_IMETHOD GetObserverList(nsIObserverList** anObserverList, nsString* aTopic);
nsHashtable *mObserverTopicTable;
};
static nsObserverService* gObserverService = nsnull; // The one-and-only ObserverService
////////////////////////////////////////////////////////////////////////////////
// nsObserverService Implementation
NS_IMPL_ISUPPORTS(nsObserverService, kIObserverServiceIID);
NS_BASE nsresult NS_NewObserverService(nsIObserverService** anObserverService)
{
return nsObserverService::GetObserverService(anObserverService);
}
nsObserverService::nsObserverService()
: mObserverTopicTable(NULL)
{
NS_INIT_REFCNT();
mObserverTopicTable = nsnull;
}
nsObserverService::~nsObserverService(void)
{
if(mObserverTopicTable)
delete mObserverTopicTable;
gObserverService = nsnull;
}
nsresult nsObserverService::GetObserverService(nsIObserverService** anObserverService)
{
if (! gObserverService) {
nsObserverService* it = new nsObserverService();
if (! it)
return NS_ERROR_OUT_OF_MEMORY;
gObserverService = it;
}
NS_ADDREF(gObserverService);
*anObserverService = gObserverService;
return NS_OK;
}
nsresult nsObserverService::GetObserverList(nsIObserverList** anObserverList, nsString* aTopic)
{
if (anObserverList == NULL)
{
return NS_ERROR_NULL_POINTER;
}
if(mObserverTopicTable == NULL) {
mObserverTopicTable = new nsHashtable(256, PR_TRUE);
if (mObserverTopicTable == NULL)
return NS_ERROR_OUT_OF_MEMORY;
}
// Safely convert to a C-string
char buf[128];
char* topic = buf;
if ((*aTopic).Length() >= sizeof(buf))
topic = new char[(*aTopic).Length() + 1];
if (topic == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
(*aTopic).ToCString(topic, (*aTopic).Length() + 1);
nsCStringKey key(topic);
nsIObserverList *topicObservers = nsnull;
if (mObserverTopicTable->Exists(&key)) {
topicObservers = (nsIObserverList *) mObserverTopicTable->Get(&key);
if (topicObservers != NULL) {
*anObserverList = topicObservers;
} else {
NS_NewObserverList(&topicObservers);
mObserverTopicTable->Put(&key, topicObservers);
}
} else {
NS_NewObserverList(&topicObservers);
*anObserverList = topicObservers;
mObserverTopicTable->Put(&key, topicObservers);
}
return NS_OK;
}
nsresult nsObserverService::AddObserver(nsIObserver** anObserver, nsString* aTopic)
{
nsIObserverList* anObserverList;
nsresult rv;
if (anObserver == NULL)
{
return NS_ERROR_NULL_POINTER;
}
if (aTopic == NULL)
{
return NS_ERROR_NULL_POINTER;
}
rv = GetObserverList(&anObserverList, aTopic);
if (NS_FAILED(rv)) return rv;
if (anObserverList) {
return anObserverList->AddObserver(anObserver);
}
return NS_ERROR_FAILURE;
}
nsresult nsObserverService::RemoveObserver(nsIObserver** anObserver, nsString* aTopic)
{
nsIObserverList* anObserverList;
nsresult rv;
if (anObserver == NULL)
{
return NS_ERROR_NULL_POINTER;
}
if (aTopic == NULL)
{
return NS_ERROR_NULL_POINTER;
}
rv = GetObserverList(&anObserverList, aTopic);
if (NS_FAILED(rv)) return rv;
if (anObserverList) {
return anObserverList->RemoveObserver(anObserver);
}
return NS_ERROR_FAILURE;
}
nsresult nsObserverService::EnumerateObserverList(nsIEnumerator** anEnumerator, nsString* aTopic)
{
nsIObserverList* anObserverList;
nsresult rv;
if (anEnumerator == NULL)
{
return NS_ERROR_NULL_POINTER;
}
if (aTopic == NULL)
{
return NS_ERROR_NULL_POINTER;
}
rv = GetObserverList(&anObserverList, aTopic);
if (NS_FAILED(rv)) return rv;
if (anObserverList) {
return anObserverList->EnumerateObserverList(anEnumerator);
}
return NS_ERROR_FAILURE;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,22 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsObserverService_h___
#define nsObserverService_h___
#endif /* nsObserverService_h___ */

View File

@@ -1,759 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsPageMgr.h"
#include "prmem.h"
#if defined(XP_PC)
#include <windows.h>
#elif defined(XP_MAC)
#include <stdlib.h>
#elif defined(XP_UNIX)
#include <sys/mman.h>
#include <fcntl.h>
#ifndef MAP_FAILED
#if defined (__STDC__) && __STDC__
#define MAP_FAILED ((void *) -1)
#else
#define MAP_FAILED ((char *) -1)
#endif
#endif
#endif
/******************************************************************************/
#define NS_PAGEMGR_CLUSTERDESC_CLUMPSIZE 16
void
nsPageMgr::DeleteFreeClusterDesc(nsClusterDesc *desc)
{
desc->mNext = mUnusedClusterDescs;
mUnusedClusterDescs = desc;
}
nsPageMgr::nsClusterDesc*
nsPageMgr::NewFreeClusterDesc(void)
{
nsClusterDesc *desc = mUnusedClusterDescs;
if (desc)
mUnusedClusterDescs = desc->mNext;
else {
/* Allocate a clump of cluster records at once, and link all except
the first onto the list of mUnusedClusterDescs */
desc = (nsClusterDesc*)PR_Malloc(NS_PAGEMGR_CLUSTERDESC_CLUMPSIZE * sizeof(nsClusterDesc));
if (desc) {
nsClusterDesc* desc2 = desc + (NS_PAGEMGR_CLUSTERDESC_CLUMPSIZE - 1);
while (desc2 != desc) {
DeleteFreeClusterDesc(desc2--);
}
}
}
return desc;
}
/* Search the mFreeClusters looking for the first cluster of consecutive free
pages that is at least size bytes long. If there is one, remove these pages
from the free page list and return their address; if not, return nil. */
nsPage*
nsPageMgr::AllocClusterFromFreeList(PRUword nPages)
{
nsClusterDesc **p = &mFreeClusters;
nsClusterDesc *desc;
while ((desc = *p) != NULL) {
if (desc->mPageCount >= nPages) {
nsPage* addr = desc->mAddr;
if (desc->mPageCount == nPages) {
*p = desc->mNext;
DeleteFreeClusterDesc(desc);
}
else {
desc->mAddr += nPages;
desc->mPageCount -= nPages;
}
return addr;
}
p = &desc->mNext;
}
return NULL;
}
/* Add the segment to the nsClusterDesc list, coalescing it with any
clusters already in the list when possible. */
void
nsPageMgr::AddClusterToFreeList(nsPage* addr, PRWord nPages)
{
nsClusterDesc **p = &mFreeClusters;
nsClusterDesc *desc;
nsClusterDesc *newDesc;
while ((desc = *p) != NULL) {
if (desc->mAddr + desc->mPageCount == addr) {
/* Coalesce with the previous cluster. */
nsClusterDesc *next = desc->mNext;
desc->mPageCount += nPages;
if (next && next->mAddr == addr + nPages) {
/* We can coalesce with both the previous and the next cluster. */
desc->mPageCount += next->mPageCount;
desc->mNext = next->mNext;
DeleteFreeClusterDesc(next);
}
return;
}
if (desc->mAddr == addr + nPages) {
/* Coalesce with the next cluster. */
desc->mAddr -= nPages;
desc->mPageCount += nPages;
return;
}
if (desc->mAddr > addr) {
PR_ASSERT(desc->mAddr > addr + nPages);
break;
}
PR_ASSERT(desc->mAddr + desc->mPageCount < addr);
p = &desc->mNext;
}
newDesc = NewFreeClusterDesc();
/* In the unlikely event that this malloc fails, we drop the free cluster
on the floor. The only consequence is that the memory mapping table
becomes slightly larger. */
if (newDesc) {
newDesc->mNext = desc;
newDesc->mAddr = addr;
newDesc->mPageCount = nPages;
*p = newDesc;
}
}
#ifdef NS_PAGEMGR_VERIFYCLUSTERS
#ifndef XP_PC
#define OutputDebugString(x) puts(x)
#endif
void
nsPageMgr::VerifyClusters(PRWord nPagesDelta)
{
static PRUword expectedPagesUsed = 0;
nsPageCount calculatedPagesUsed;
nsPage* lastDescEnd = 0;
nsClusterDesc* desc;
char str[256];
expectedPagesUsed += nPagesDelta;
calculatedPagesUsed = mBoundary - mMemoryBase;
sprintf(str, "[Clusters: %p", mMemoryBase);
OutputDebugString(str);
for (desc = mFreeClusters; desc; desc = desc->mNext) {
PR_ASSERT(desc->mAddr > lastDescEnd);
calculatedPagesUsed -= desc->mPageCount;
lastDescEnd = desc->mAddr + desc->mPageCount;
sprintf(str, "..%p, %p", desc->mAddr-1, desc->mAddr + desc->mPageCount);
OutputDebugString(str);
}
sprintf(str, "..%p]\n", mBoundary);
OutputDebugString(str);
PR_ASSERT(lastDescEnd < mBoundary);
PR_ASSERT(calculatedPagesUsed == expectedPagesUsed);
}
#endif /* NS_PAGEMGR_VERIFYCLUSTERS */
/*******************************************************************************
* Machine-dependent stuff
******************************************************************************/
#if defined(XP_PC)
#define GC_VMBASE 0x40000000 /* XXX move */
#define GC_VMLIMIT 0x0FFFFFFF
#elif defined(XP_MAC)
#define NS_PAGEMGR_MAC_SEGMENT_SIZE
#define NS_PAGEMGR_MAC_SEGMENT_COUNT
#endif
PRStatus
nsPageMgr::InitPages(nsPageCount minPages, nsPageCount maxPages)
{
#if defined(XP_PC)
nsPage* addr = NULL;
nsPageCount size = maxPages;
#ifdef NS_PAGEMGR_DEBUG
/* first try to place the heap at a well-known address for debugging */
addr = (nsPage*)VirtualAlloc((void*)GC_VMBASE, size << NS_PAGEMGR_PAGE_BITS,
MEM_RESERVE, PAGE_READWRITE);
#endif
while (addr == NULL) {
/* let the system place the heap */
addr = (nsPage*)VirtualAlloc(0, size << NS_PAGEMGR_PAGE_BITS,
MEM_RESERVE, PAGE_READWRITE);
if (addr == NULL) {
size--;
if (size < minPages) {
return PR_FAILURE;
}
}
}
PR_ASSERT(NS_PAGEMGR_IS_ALIGNED(addr, NS_PAGEMGR_PAGE_BITS));
mMemoryBase = addr;
mPageCount = size;
mBoundary = addr;
return PR_SUCCESS;
#elif defined(XP_MAC)
OSErr err;
void* seg;
void* segLimit;
Handle h;
PRUword segSize = (minPages + 1) * NS_PAGEMGR_PAGE_SIZE;
nsPage* firstPage;
nsPage* lastPage;
nsSegmentDesc* mSegTable;
int mSegTableCount, otherCount;
h = TempNewHandle(segSize, &err);
if (err || h == NULL) goto fail;
MoveHHi(h);
TempHLock(h, &err);
if (err) goto fail;
seg = *h;
segLimit = (void*)((char*)seg + segSize);
firstPage = NS_PAGEMGR_PAGE_ROUNDUP(seg);
lastPage = NS_PAGEMGR_PAGE_ROUNDDN(((char*)seg + segSize));
/* Put the segment table in the otherwise wasted space at one
end of the segment. We'll put it at which ever end is bigger. */
mSegTable = (nsSegmentDesc*)seg;
mSegTableCount = ((char*)firstPage - (char*)seg) / sizeof(nsSegmentDesc);
otherCount = ((char*)segLimit - (char*)lastPage) / sizeof(nsSegmentDesc);
if (otherCount > mSegTableCount) {
mSegTable = (nsSegmentDesc*)lastPage;
mSegTableCount = otherCount;
}
else if (mSegTableCount == 0) {
mSegTable = (nsSegmentDesc*)firstPage;
firstPage++;
mSegTableCount = NS_PAGEMGR_PAGE_SIZE / sizeof(nsSegmentDesc);
}
PR_ASSERT(mSegTableCount > 0);
mSegTable = mSegTable;
mSegTableCount = mSegTableCount;
mSegTable[0].handle = h;
mSegTable[0].firstPage = firstPage;
mSegTable[0].lastPage = lastPage;
/* XXX hack for now -- just one segment */
mMemoryBase = firstPage;
mBoundary = firstPage;
mPageCount = lastPage - firstPage;
return PR_SUCCESS;
fail:
if (h) {
TempDisposeHandle(h, &err);
}
return PR_FAILURE;
#else
nsPage* addr = NULL;
nsPageCount size = maxPages;
int zero_fd;
zero_fd = open("/dev/zero", O_RDWR);
while (addr == NULL) {
/* let the system place the heap */
addr = (nsPage*)mmap(0, size << NS_PAGEMGR_PAGE_BITS,
PROT_READ | PROT_WRITE,
MAP_PRIVATE,
zero_fd, 0);
if (addr == (nsPage*)MAP_FAILED) {
addr = NULL;
size--;
if (size < minPages) {
return PR_FAILURE;
}
}
}
PR_ASSERT(NS_PAGEMGR_IS_ALIGNED(addr, NS_PAGEMGR_PAGE_BITS));
mMemoryBase = addr;
mPageCount = size;
mBoundary = addr;
return PR_SUCCESS;
#endif
}
void
nsPageMgr::FinalizePages()
{
#if defined(XP_PC)
BOOL ok;
ok = VirtualFree((void*)mMemoryBase, 0, MEM_RELEASE);
PR_ASSERT(ok);
mMemoryBase = NULL;
mPageCount = 0;
PR_DestroyMonitor(mMonitor);
mMonitor = NULL;
#elif defined(XP_MAC)
OSErr err;
PRUword i;
for (i = 0; i < mSegTableCount; i++) {
if (mSegTable[i].handle) {
TempDisposeHandle(mSegTable[i].handle, &err);
PR_ASSERT(err == 0);
}
}
#else
munmap((caddr_t)mMemoryBase, mPageCount << NS_PAGEMGR_PAGE_BITS);
#endif
}
/*******************************************************************************
* Page Manager
******************************************************************************/
nsPageMgr::nsPageMgr()
: mUnusedClusterDescs(nsnull),
mFreeClusters(nsnull),
mInUseClusters(nsnull),
mMonitor(nsnull),
mMemoryBase(nsnull),
mBoundary(nsnull),
#ifdef XP_PC
mLastPageFreed(nsnull),
mLastPageFreedSize(0),
mLastPageTemp(nsnull),
mLastPageTempSize(0),
#ifdef NS_PAGEMGR_DEBUG
mLastPageAllocTries(0),
mLastPageAllocHits(0),
mLastPageFreeTries(0),
mLastPageFreeHits(0),
#endif
#endif
#if defined(XP_MAC)
mSegMap(nsnull),
mSegTable(nsnull),
mSegTableCount(0),
#endif
mPageCount(0)
{
NS_INIT_REFCNT();
}
nsresult
nsPageMgr::Init(nsPageCount minPages, nsPageCount maxPages)
{
PRStatus status;
mMonitor = PR_NewMonitor();
if (mMonitor == NULL)
return PR_FAILURE;
status = InitPages(minPages, maxPages);
if (status != PR_SUCCESS)
return status;
/* make sure these got set */
PR_ASSERT(mMemoryBase);
PR_ASSERT(mBoundary);
mFreeClusters = NULL;
mInUseClusters = NULL;
return status == PR_SUCCESS ? NS_OK : NS_ERROR_FAILURE;
}
nsPageMgr::~nsPageMgr()
{
#if defined(XP_PC) && defined(NS_PAGEMGR_DEBUG)
if (stderr) {
fprintf(stderr, "Page Manager Cache: alloc hits: %u/%u %u%%, free hits: %u/%u %u%%\n",
mLastPageAllocHits, mLastPageAllocTries,
(mLastPageAllocHits * 100 / mLastPageAllocTries),
mLastPageFreeHits, mLastPageFreeTries,
(mLastPageFreeHits * 100 / mLastPageFreeTries));
}
#endif
FinalizePages();
nsClusterDesc* chain = mUnusedClusterDescs;
while (chain) {
nsClusterDesc* desc = chain;
chain = chain->mNext;
PR_Free(desc);
}
}
NS_IMPL_ADDREF(nsPageMgr);
NS_IMPL_RELEASE(nsPageMgr);
NS_IMETHODIMP
nsPageMgr::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
NS_ASSERTION(aInstancePtr != nsnull, "null ptr");
static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID);
if (aIID.Equals(nsIPageManager::GetIID()) ||
aIID.Equals(kISupportsIID)) {
*aInstancePtr = NS_STATIC_CAST(nsIPageManager*, this);
NS_ADDREF_THIS();
return NS_OK;
}
if (aIID.Equals(nsIAllocator::GetIID())) {
*aInstancePtr = NS_STATIC_CAST(nsIAllocator*, this);
NS_ADDREF_THIS();
return NS_OK;
}
return NS_NOINTERFACE;
}
/******************************************************************************/
#ifdef XP_PC
#ifdef NS_PAGEMGR_PAGE_HYSTERESIS
#ifdef NS_PAGEMGR_DEBUG
void*
nsPageMgr::NS_PAGEMGR_COMMIT_CLUSTER(void* addr, PRUword size)
{
mLastPageAllocTries++;
if (mLastPageFreed == (void*)(addr) && mLastPageFreedSize == (size)) {
#ifdef NS_PAGEMGR_COMMIT_TRACE
char buf[64];
PR_snprintf(buf, sizeof(buf), "lalloc %p %u\n",
mLastPageFreed, mLastPageFreedSize);
OutputDebugString(buf);
#endif
DBG_MEMSET(mLastPageFreed, NS_PAGEMGR_PAGE_ALLOC_PATTERN, mLastPageFreedSize);
mLastPageTemp = mLastPageFreed;
mLastPageFreed = NULL;
mLastPageFreedSize = 0;
mLastPageAllocHits++;
return mLastPageTemp;
}
else {
/* If the cached pages intersect the current request, we lose.
Just free the cached request instead of trying to split it up. */
if (mLastPageFreed &&
nsOverlapping((char*)mLastPageFreed, ((char*)mLastPageFreed + mLastPageFreedSize),
(char*)(addr), ((char*)(addr) + (size)))
// ((char*)mLastPageFreed < ((char*)(addr) + (size))
// && ((char*)mLastPageFreed + mLastPageFreedSize) > (char*)(addr))
) {
#ifdef NS_PAGEMGR_COMMIT_TRACE
char buf[64];
PR_snprintf(buf, sizeof(buf), "valloc %p %u (vfree %p %u last=%u:%u req=%u:%u)\n",
addr, size,
mLastPageFreed, mLastPageFreedSize,
(char*)mLastPageFreed, ((char*)mLastPageFreed + mLastPageFreedSize),
(char*)(addr), ((char*)(addr) + (size)));
OutputDebugString(buf);
#endif
VirtualFree(mLastPageFreed, mLastPageFreedSize, MEM_DECOMMIT);
mLastPageFreed = NULL;
mLastPageFreedSize = 0;
mLastPageFreeHits--; /* lost after all */
}
else {
#ifdef NS_PAGEMGR_COMMIT_TRACE
char buf[64];
PR_snprintf(buf, sizeof(buf), "valloc %p %u (skipping %p %u)\n",
addr, size,
mLastPageFreed, mLastPageFreedSize);
OutputDebugString(buf);
#endif
}
return VirtualAlloc((void*)(addr), (size), MEM_COMMIT, PAGE_READWRITE);
}
}
int
nsPageMgr::NS_PAGEMGR_DECOMMIT_CLUSTER(void* addr, PRUword size)
{
mLastPageFreeTries++;
PR_ASSERT(mLastPageFreed != (void*)(addr));
if (mLastPageFreed) {
/* If we've already got a cached page, just keep it. Heuristically,
this tends to give us a higher hit rate because of the order in
which pages are decommitted. */
#ifdef NS_PAGEMGR_COMMIT_TRACE
char buf[64];
PR_snprintf(buf, sizeof(buf), "vfree %p %u (cached %p %u)\n",
addr, size, mLastPageFreed, mLastPageFreedSize);
OutputDebugString(buf);
#endif
return VirtualFree(addr, size, MEM_DECOMMIT);
}
mLastPageFreed = (void*)(addr);
mLastPageFreedSize = (size);
DBG_MEMSET(mLastPageFreed, NS_PAGEMGR_PAGE_FREE_PATTERN, mLastPageFreedSize);
#ifdef NS_PAGEMGR_COMMIT_TRACE
{
char buf[64];
PR_snprintf(buf, sizeof(buf), "lfree %p %u\n",
mLastPageFreed, mLastPageFreedSize);
OutputDebugString(buf);
}
#endif
mLastPageFreeHits++;
return 1;
}
#else /* !NS_PAGEMGR_DEBUG */
#define NS_PAGEMGR_COMMIT_CLUSTER(addr, size) \
(PR_ASSERT((void*)(addr) != NULL), \
((mLastPageFreed == (void*)(addr) && mLastPageFreedSize == (size)) \
? (DBG_MEMSET(mLastPageFreed, NS_PAGEMGR_PAGE_ALLOC_PATTERN, mLastPageFreedSize), \
mLastPageTemp = mLastPageFreed, \
mLastPageFreed = NULL, \
mLastPageFreedSize = 0, \
mLastPageTemp) \
: (((mLastPageFreed && \
((char*)mLastPageFreed < ((char*)(addr) + (size)) \
&& ((char*)mLastPageFreed + mLastPageFreedSize) > (char*)(addr))) \
? (VirtualFree(mLastPageFreed, mLastPageFreedSize, MEM_DECOMMIT), \
mLastPageFreed = NULL, \
mLastPageFreedSize = 0) \
: ((void)0)), \
VirtualAlloc((void*)(addr), (size), MEM_COMMIT, PAGE_READWRITE)))) \
#define NS_PAGEMGR_DECOMMIT_CLUSTER(addr, size) \
(PR_ASSERT(mLastPageFreed != (void*)(addr)), \
(mLastPageFreed \
? (VirtualFree(addr, size, MEM_DECOMMIT)) \
: (mLastPageFreed = (addr), \
mLastPageFreedSize = (size), \
DBG_MEMSET(mLastPageFreed, NS_PAGEMGR_PAGE_FREE_PATTERN, mLastPageFreedSize), \
1))) \
#endif /* !NS_PAGEMGR_DEBUG */
#else /* !NS_PAGEMGR_PAGE_HYSTERESIS */
#define NS_PAGEMGR_COMMIT_CLUSTER(addr, size) \
VirtualAlloc((void*)(addr), (size), MEM_COMMIT, PAGE_READWRITE)
#define NS_PAGEMGR_DECOMMIT_CLUSTER(addr, size) \
VirtualFree((void*)(addr), (size), MEM_DECOMMIT)
#endif /* !NS_PAGEMGR_PAGE_HYSTERESIS */
#else /* !XP_PC */
#define NS_PAGEMGR_COMMIT_CLUSTER(addr, size) (addr)
#define NS_PAGEMGR_DECOMMIT_CLUSTER(addr, size) 1
#endif /* !XP_PC */
nsPage*
nsPageMgr::NewCluster(nsPageCount nPages)
{
nsAutoMonitor mon(mMonitor);
nsPage* addr;
PR_ASSERT(nPages > 0);
addr = AllocClusterFromFreeList(nPages);
if (!addr && mBoundary + nPages <= mMemoryBase + mPageCount) {
addr = mBoundary;
mBoundary += nPages;
}
if (addr) {
/* Extend the mapping */
nsPage* vaddr;
PRUword size = nPages << NS_PAGEMGR_PAGE_BITS;
PR_ASSERT(NS_PAGEMGR_IS_ALIGNED(addr, NS_PAGEMGR_PAGE_BITS));
vaddr = (nsPage*)NS_PAGEMGR_COMMIT_CLUSTER((void*)addr, size);
#ifdef NS_PAGEMGR_VERIFYCLUSTERS
VerifyClusters(nPages);
#endif
if (addr) {
PR_ASSERT(vaddr == addr);
}
else {
DestroyCluster(addr, nPages);
}
DBG_MEMSET(addr, NS_PAGEMGR_PAGE_ALLOC_PATTERN, size);
}
return (nsPage*)addr;
}
void
nsPageMgr::DestroyCluster(nsPage* basePage, nsPageCount nPages)
{
nsAutoMonitor mon(mMonitor);
int freeResult;
PRUword size = nPages << NS_PAGEMGR_PAGE_BITS;
PR_ASSERT(nPages > 0);
PR_ASSERT(NS_PAGEMGR_IS_ALIGNED(basePage, NS_PAGEMGR_PAGE_BITS));
PR_ASSERT(mMemoryBase <= basePage);
PR_ASSERT(basePage + nPages <= mMemoryBase + mPageCount);
DBG_MEMSET(basePage, NS_PAGEMGR_PAGE_FREE_PATTERN, size);
freeResult = NS_PAGEMGR_DECOMMIT_CLUSTER((void*)basePage, size);
PR_ASSERT(freeResult);
if (basePage + nPages == mBoundary) {
nsClusterDesc **p;
nsClusterDesc *desc;
/* We deallocated the last set of clusters. Move the mBoundary lower. */
mBoundary = basePage;
/* The last free cluster might now be adjacent to the mBoundary; if so,
move the mBoundary before that cluster and delete that cluster
altogether. */
p = &mFreeClusters;
while ((desc = *p) != NULL) {
if (!desc->mNext && desc->mAddr + desc->mPageCount == mBoundary) {
*p = 0;
mBoundary = desc->mAddr;
DeleteFreeClusterDesc(desc);
}
else {
p = &desc->mNext;
}
}
}
else {
AddClusterToFreeList(basePage, nPages);
}
#ifdef NS_PAGEMGR_VERIFYCLUSTERS
VerifyClusters(-(PRWord)nPages);
#endif
}
////////////////////////////////////////////////////////////////////////////////
// nsIPageManager methods:
NS_IMETHODIMP
nsPageMgr::AllocPages(PRUint32 pageCount, void* *result)
{
nsPage* page = NewCluster(NS_STATIC_CAST(nsPageCount, pageCount));
if (page == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
*result = page;
return NS_OK;
}
NS_IMETHODIMP
nsPageMgr::DeallocPages(PRUint32 pageCount, void* pages)
{
DestroyCluster(NS_STATIC_CAST(nsPage*, pages),
NS_STATIC_CAST(nsPageCount, pageCount));
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIAllocator methods:
//
// Note: nsIAllocator needs to keep track of the size of the blocks it allocates
// whereas, nsIPageManager doesn't. That means that there's a little extra
// overhead for users of this interface. It also means that things allocated
// with the nsIPageManager interface can't be freed with the nsIAllocator
// interface and vice versa.
NS_IMETHODIMP_(void*)
nsPageMgr::Alloc(PRUint32 size)
{
nsAutoMonitor mon(mMonitor);
nsresult rv;
void* page = nsnull;
PRUint32 pageCount = NS_PAGEMGR_PAGE_COUNT(size);
rv = AllocPages(pageCount, &page);
if (NS_FAILED(rv))
return nsnull;
// Add this cluster to the mInUseClusters list:
nsClusterDesc* desc = NewFreeClusterDesc();
if (desc == nsnull) {
rv = DeallocPages(pageCount, page);
NS_ASSERTION(NS_SUCCEEDED(rv), "DeallocPages failed");
return nsnull;
}
desc->mAddr = (nsPage*)page;
desc->mPageCount = pageCount;
desc->mNext = mInUseClusters;
mInUseClusters = desc;
return page;
}
NS_IMETHODIMP_(void*)
nsPageMgr::Realloc(void* ptr, PRUint32 size)
{
// XXX This realloc implementation could be made smarter by trying to
// append to the current block, but I don't think we really care right now.
nsresult rv;
rv = Free(ptr);
if (NS_FAILED(rv)) return nsnull;
void* newPtr = Alloc(size);
return newPtr;
}
NS_IMETHODIMP
nsPageMgr::Free(void* ptr)
{
nsAutoMonitor mon(mMonitor);
PR_ASSERT(NS_PAGEMGR_IS_ALIGNED(ptr, NS_PAGEMGR_PAGE_BITS));
// Remove the cluster from the mInUseClusters list:
nsClusterDesc** list = &mInUseClusters;
nsClusterDesc* desc;
while ((desc = *list) != nsnull) {
if (desc->mAddr == ptr) {
// found -- unlink the desc and free it
*list = desc->mNext;
nsresult rv = DeallocPages(desc->mPageCount, ptr);
DeleteFreeClusterDesc(desc);
return rv;
}
list = &desc->mNext;
}
NS_ASSERTION(0, "memory not allocated with nsPageMgr::Alloc");
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsPageMgr::HeapMinimize(void)
{
// can't compact this heap
return NS_ERROR_FAILURE;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,185 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsPageMgr_h__
#define nsPageMgr_h__
#include "nsIPageManager.h"
#include "nsIAllocator.h"
#include "nscore.h"
#include "nsAutoLock.h"
#include "prlog.h"
#ifdef XP_MAC
#include <Types.h>
#include <Memory.h>
#endif
/*******************************************************************************
* Configuration/Debugging parameters:
******************************************************************************/
#ifdef NS_DEBUG
//#define NS_PAGEMGR_DEBUG
#endif
#define NS_PAGEMGR_PAGE_HYSTERESIS /* undef if you want to compare */
//#define NS_PAGEMGR_COMMIT_TRACE
#ifdef NS_PAGEMGR_DEBUG
#define NS_PAGEMGR_VERIFYCLUSTERS
#define NS_PAGEMGR_DBG_MEMSET
#endif
#define NS_PAGEMGR_MIN_PAGES 32 // XXX bogus -- this should be a runtime parameter
/******************************************************************************/
#ifdef NS_PAGEMGR_DBG_MEMSET
#include <string.h> /* for memset */
#include <stdio.h>
#define DBG_MEMSET(dest, pattern, size) memset(dest, pattern, size)
#define NS_PAGEMGR_PAGE_ALLOC_PATTERN 0xCB
#define NS_PAGEMGR_PAGE_FREE_PATTERN 0xCD
#else
#define DBG_MEMSET(dest, pattern, size) ((void)0)
#endif
#define NS_PAGEMGR_ALIGN(p, nBits) ((PRWord)(p) & ~((1 << nBits) - 1))
#define NS_PAGEMGR_IS_ALIGNED(p, nBits) ((PRWord)(p) == NS_PAGEMGR_ALIGN(p, nBits))
/*******************************************************************************
* Test for overlapping (one-dimensional) regions
******************************************************************************/
inline PRBool nsOverlapping(char* min1, char* max1, char* min2, char* max2)
{
PR_ASSERT(min1 < max1);
PR_ASSERT(min2 < max2);
return (min1 < max2 && max1 > min2);
}
/*******************************************************************************
* Types
******************************************************************************/
typedef PRUint8 nsPage[NS_PAGEMGR_PAGE_SIZE];
typedef PRUword nsPageCount; /* int big enough to count pages */
/*******************************************************************************
* Macros
******************************************************************************/
#define NS_PAGEMGR_PAGE_ROUNDDN(addr) ((nsPage*)NS_PAGEMGR_ALIGN((PRUword)(addr), NS_PAGEMGR_PAGE_BITS))
#define NS_PAGEMGR_PAGE_ROUNDUP(addr) NS_PAGEMGR_PAGE_ROUNDDN((PRUword)(addr) + NS_PAGEMGR_PAGE_SIZE)
/*******************************************************************************
* Page Manager
******************************************************************************/
class nsPageMgr : public nsIPageManager, public nsIAllocator {
public:
NS_DECL_ISUPPORTS
// nsIPageManager methods:
NS_IMETHOD AllocPages(PRUint32 pageCount, void* *result);
NS_IMETHOD DeallocPages(PRUint32 pageCount, void* pages);
// nsIAllocator methods:
NS_IMETHOD_(void*) Alloc(PRUint32 size);
NS_IMETHOD_(void*) Realloc(void* ptr, PRUint32 size);
NS_IMETHOD Free(void* ptr);
NS_IMETHOD HeapMinimize(void);
// nsPageMgr methods:
nsPageMgr();
virtual ~nsPageMgr();
nsresult Init(nsPageCount minPages = NS_PAGEMGR_MIN_PAGES,
nsPageCount maxPages = NS_PAGEMGR_MIN_PAGES);
struct nsClusterDesc {
nsClusterDesc* mNext; /* Link to next cluster of free pages */
nsPage* mAddr; /* First page in cluster of free pages */
nsPageCount mPageCount; /* Total size of cluster of free pages in bytes */
};
void DeleteFreeClusterDesc(nsClusterDesc *desc);
nsClusterDesc* NewFreeClusterDesc(void);
nsPage* AllocClusterFromFreeList(PRUword nPages);
void AddClusterToFreeList(nsPage* addr, PRWord nPages);
#ifdef NS_PAGEMGR_VERIFYCLUSTERS
void VerifyClusters(PRWord nPagesDelta);
#endif
#if defined(XP_PC) && defined(NS_PAGEMGR_DEBUG)
void* NS_PAGEMGR_COMMIT_CLUSTER(void* addr, PRUword size);
int NS_PAGEMGR_DECOMMIT_CLUSTER(void* addr, PRUword size);
#endif
// Managing Pages:
PRStatus InitPages(nsPageCount minPages, nsPageCount maxPages);
void FinalizePages();
nsPage* NewCluster(nsPageCount nPages);
void DestroyCluster(nsPage* basePage, nsPageCount nPages);
protected:
nsClusterDesc* mUnusedClusterDescs;
nsClusterDesc* mFreeClusters;
nsClusterDesc* mInUseClusters; // used by nsIAllocator methods
PRMonitor* mMonitor;
nsPage* mMemoryBase;
nsPage* mBoundary;
nsPageCount mPageCount;
#ifdef XP_PC
/* one-page hysteresis */
void* mLastPageFreed;
PRUword mLastPageFreedSize;
void* mLastPageTemp;
PRUword mLastPageTempSize;
# ifdef NS_PAGEMGR_DEBUG
PRUword mLastPageAllocTries;
PRUword mLastPageAllocHits;
PRUword mLastPageFreeTries;
PRUword mLastPageFreeHits;
# endif
#endif
#if defined(XP_MAC)
struct nsSegmentDesc {
Handle mHandle;
nsPage* mFirstPage;
nsPage* mLastPage;
};
PRUint8* mSegMap;
nsSegmentDesc* mSegTable;
PRWord mSegTableCount;
#endif
};
/******************************************************************************/
#endif /* nsPageMgr_h__ */

View File

@@ -1,424 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsIBuffer.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsAutoLock.h"
class nsBufferInputStream;
////////////////////////////////////////////////////////////////////////////////
class nsBufferInputStream : public nsIInputStream
{
public:
NS_DECL_ISUPPORTS
// nsIBaseStream methods:
NS_IMETHOD Close(void);
// nsIInputStream methods:
NS_IMETHOD GetLength(PRUint32 *aLength);
NS_IMETHOD Read(char* aBuf, PRUint32 aCount, PRUint32 *aReadCount);
// nsBufferInputStream methods:
nsBufferInputStream(nsIBuffer* buf, PRBool blocking);
virtual ~nsBufferInputStream();
PRUint32 ReadableAmount() {
nsresult rv;
PRUint32 amt;
char* buf;
rv = mBuffer->GetReadBuffer(&amt, &buf); // should never fail
NS_ASSERTION(NS_SUCCEEDED(rv), "GetInputBuffer failed");
return amt;
}
nsresult SetEOF();
nsresult Fill();
protected:
nsIBuffer* mBuffer;
PRBool mBlocking;
};
////////////////////////////////////////////////////////////////////////////////
class nsBufferOutputStream : public nsIOutputStream
{
public:
NS_DECL_ISUPPORTS
// nsIBaseStream methods:
NS_IMETHOD Close(void);
// nsIOutputStream methods:
NS_IMETHOD Write(const char* aBuf, PRUint32 aCount, PRUint32 *aWriteCount);
NS_IMETHOD Write(nsIInputStream* fromStream, PRUint32 *aWriteCount);
NS_IMETHOD Flush(void);
// nsBufferOutputStream methods:
nsBufferOutputStream(nsIBuffer* buf, PRBool blocking);
virtual ~nsBufferOutputStream();
protected:
nsIBuffer* mBuffer;
PRBool mBlocking;
};
////////////////////////////////////////////////////////////////////////////////
// nsBufferInputStream methods:
////////////////////////////////////////////////////////////////////////////////
nsBufferInputStream::nsBufferInputStream(nsIBuffer* buf, PRBool blocking)
: mBuffer(buf), mBlocking(blocking)
{
NS_INIT_REFCNT();
NS_ADDREF(mBuffer);
}
nsBufferInputStream::~nsBufferInputStream()
{
(void)Close();
}
NS_IMPL_ADDREF(nsBufferInputStream);
NS_IMPL_RELEASE(nsBufferInputStream);
NS_IMETHODIMP
nsBufferInputStream::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (aInstancePtr == nsnull)
return NS_ERROR_NULL_POINTER;
if (aIID.Equals(nsIInputStream::GetIID()) ||
aIID.Equals(nsIBaseStream::GetIID()) ||
aIID.Equals(nsISupports::GetIID())) {
*aInstancePtr = this;
NS_ADDREF_THIS();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMETHODIMP
nsBufferInputStream::Close(void)
{
if (mBuffer == nsnull)
return NS_BASE_STREAM_CLOSED;
if (mBlocking) {
nsAutoMonitor mon(mBuffer);
NS_RELEASE(mBuffer);
mBuffer = nsnull;
nsresult rv = mon.Notify(); // wake up the writer
if (NS_FAILED(rv)) return rv;
}
else {
NS_RELEASE(mBuffer);
mBuffer = nsnull;
}
return NS_OK;
}
NS_IMETHODIMP
nsBufferInputStream::GetLength(PRUint32 *aLength)
{
if (mBuffer == nsnull)
return NS_BASE_STREAM_CLOSED;
char* buf;
return mBuffer->GetReadBuffer(aLength, &buf);
}
NS_IMETHODIMP
nsBufferInputStream::Read(char* aBuf, PRUint32 aCount, PRUint32 *aReadCount)
{
if (mBuffer == nsnull)
return NS_BASE_STREAM_CLOSED;
nsresult rv = NS_OK;
*aReadCount = 0;
while (aCount > 0) {
PRUint32 amt;
rv = mBuffer->Read(aBuf, aCount, &amt);
if (rv == NS_BASE_STREAM_EOF)
return *aReadCount > 0 ? NS_OK : rv;
if (NS_FAILED(rv)) return rv;
if (amt == 0) {
rv = Fill();
if (NS_FAILED(rv)) return rv;
}
else {
*aReadCount += amt;
aBuf += amt;
aCount -= amt;
}
}
return rv;
}
nsresult
nsBufferInputStream::SetEOF()
{
if (mBuffer == nsnull)
return NS_BASE_STREAM_CLOSED;
if (mBlocking) {
nsAutoMonitor mon(mBuffer);
mBuffer->SetEOF();
nsresult rv = mon.Notify(); // wake up the writer
if (NS_FAILED(rv)) return rv;
}
else {
mBuffer->SetEOF();
}
return NS_OK;
}
nsresult
nsBufferInputStream::Fill()
{
if (mBuffer == nsnull)
return NS_BASE_STREAM_CLOSED;
if (mBlocking) {
nsAutoMonitor mon(mBuffer);
while (PR_TRUE) {
nsresult rv;
// check read buffer again while in the monitor
PRUint32 amt;
char* buf;
rv = mBuffer->GetReadBuffer(&amt, &buf);
if (rv == NS_BASE_STREAM_EOF) return rv;
if (NS_SUCCEEDED(rv) && amt > 0) return NS_OK;
// else notify the writer and wait
rv = mon.Notify();
if (NS_FAILED(rv)) return rv; // interrupted
rv = mon.Wait();
if (NS_FAILED(rv)) return rv; // interrupted
}
}
else {
return NS_BASE_STREAM_WOULD_BLOCK;
}
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
NS_BASE nsresult
NS_NewBufferInputStream(nsIInputStream* *result, nsIBuffer* buffer, PRBool blocking)
{
nsBufferInputStream* str = new nsBufferInputStream(buffer, blocking);
if (str == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(str);
*result = str;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsBufferOutputStream methods:
////////////////////////////////////////////////////////////////////////////////
nsBufferOutputStream::nsBufferOutputStream(nsIBuffer* buf, PRBool blocking)
: mBuffer(buf), mBlocking(blocking)
{
NS_INIT_REFCNT();
NS_ADDREF(mBuffer);
}
nsBufferOutputStream::~nsBufferOutputStream()
{
(void)Close();
}
NS_IMPL_ADDREF(nsBufferOutputStream);
NS_IMPL_RELEASE(nsBufferOutputStream);
NS_IMETHODIMP
nsBufferOutputStream::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (aInstancePtr == nsnull)
return NS_ERROR_NULL_POINTER;
if (aIID.Equals(nsIOutputStream::GetIID()) ||
aIID.Equals(nsIBaseStream::GetIID()) ||
aIID.Equals(nsISupports::GetIID())) {
*aInstancePtr = this;
NS_ADDREF_THIS();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMETHODIMP
nsBufferOutputStream::Close(void)
{
if (mBuffer == nsnull)
return NS_BASE_STREAM_CLOSED;
if (mBlocking) {
nsAutoMonitor mon(mBuffer);
mBuffer->SetEOF();
NS_RELEASE(mBuffer);
mBuffer = nsnull;
nsresult rv = mon.Notify(); // wake up the writer
if (NS_FAILED(rv)) return rv;
}
else {
NS_RELEASE(mBuffer);
mBuffer = nsnull;
}
return NS_OK;
}
NS_IMETHODIMP
nsBufferOutputStream::Write(const char* aBuf, PRUint32 aCount, PRUint32 *aWriteCount)
{
if (mBuffer == nsnull)
return NS_BASE_STREAM_CLOSED;
nsresult rv = NS_OK;
*aWriteCount = 0;
while (aCount > 0) {
PRUint32 amt;
rv = mBuffer->Write(aBuf, aCount, &amt);
if (rv == NS_BASE_STREAM_EOF)
return *aWriteCount > 0 ? NS_OK : rv;
if (NS_FAILED(rv)) return rv;
if (amt == 0) {
rv = Flush();
if (NS_FAILED(rv)) return rv;
}
else {
aBuf += amt;
aCount -= amt;
*aWriteCount += amt;
}
}
return rv;
}
NS_IMETHODIMP
nsBufferOutputStream::Write(nsIInputStream* fromStream, PRUint32 *aWriteCount)
{
if (mBuffer == nsnull)
return NS_BASE_STREAM_CLOSED;
nsresult rv = NS_OK;
*aWriteCount = 0;
while (PR_TRUE) { // write until fromStream gets EOF
PRUint32 amt;
rv = mBuffer->Write(fromStream, &amt);
if (rv == NS_BASE_STREAM_EOF)
return *aWriteCount > 0 ? NS_OK : rv;
if (NS_FAILED(rv)) return rv;
if (amt == 0) {
rv = Flush();
if (NS_FAILED(rv)) return rv;
}
else {
*aWriteCount += amt;
}
}
return rv;
}
NS_IMETHODIMP
nsBufferOutputStream::Flush(void)
{
if (mBuffer == nsnull)
return NS_BASE_STREAM_CLOSED;
if (mBlocking) {
nsresult rv;
nsAutoMonitor mon(mBuffer);
// check write buffer again while in the monitor
PRUint32 amt;
char* buf;
rv = mBuffer->GetWriteBuffer(&amt, &buf);
if (rv == NS_BASE_STREAM_EOF) return rv;
if (NS_SUCCEEDED(rv) && amt > 0) return NS_OK;
// else notify the reader and wait
rv = mon.Notify();
if (NS_FAILED(rv)) return rv; // interrupted
rv = mon.Wait();
if (NS_FAILED(rv)) return rv; // interrupted
}
else {
return NS_BASE_STREAM_WOULD_BLOCK;
}
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
NS_BASE nsresult
NS_NewBufferOutputStream(nsIOutputStream* *result, nsIBuffer* buffer, PRBool blocking)
{
nsBufferOutputStream* ostr = new nsBufferOutputStream(buffer, blocking);
if (ostr == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(ostr);
*result = ostr;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
NS_BASE nsresult
NS_NewPipe2(nsIInputStream* *inStrResult,
nsIOutputStream* *outStrResult,
PRUint32 growBySize, PRUint32 maxSize)
{
nsresult rv;
nsIInputStream* inStr = nsnull;
nsIOutputStream* outStr = nsnull;
nsIBuffer* buf = nsnull;
rv = NS_NewPageBuffer(&buf, growBySize, maxSize);
if (NS_FAILED(rv)) goto error;
rv = NS_NewBufferInputStream(&inStr, buf, PR_TRUE);
if (NS_FAILED(rv)) goto error;
rv = NS_NewBufferOutputStream(&outStr, buf, PR_TRUE);
if (NS_FAILED(rv)) goto error;
NS_RELEASE(buf);
*inStrResult = inStr;
*outStrResult = outStr;
return NS_OK;
error:
NS_IF_RELEASE(inStr);
NS_IF_RELEASE(outStr);
NS_IF_RELEASE(buf);
return rv;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -17,124 +17,47 @@
*/
#define NS_IMPL_IDS
#include "nsProperties.h"
////////////////////////////////////////////////////////////////////////////////
NS_IMPL_ISUPPORTS(nsProperties, nsIProperties::GetIID());
nsProperties::nsProperties()
{
}
PRBool
nsProperties::ReleaseValues(nsHashKey* key, void* data, void* closure)
{
nsISupports* value = (nsISupports*)data;
NS_IF_RELEASE(value);
return PR_TRUE;
}
nsProperties::~nsProperties()
{
Enumerate(ReleaseValues);
}
NS_IMETHODIMP
nsProperties::DefineProperty(const char* prop, nsISupports* initialValue)
{
nsCStringKey key(prop);
if (Exists(&key))
return NS_ERROR_FAILURE;
nsISupports* prevValue = (nsISupports*)Put(&key, initialValue);
NS_ASSERTION(prevValue == NULL, "hashtable error");
NS_IF_ADDREF(initialValue);
return NS_OK;
}
NS_IMETHODIMP
nsProperties::UndefineProperty(const char* prop)
{
nsCStringKey key(prop);
if (!Exists(&key))
return NS_ERROR_FAILURE;
nsISupports* prevValue = (nsISupports*)Remove(&key);
NS_IF_RELEASE(prevValue);
return NS_OK;
}
NS_IMETHODIMP
nsProperties::GetProperty(const char* prop, nsISupports* *result)
{
nsCStringKey key(prop);
if (!Exists(&key))
return NS_ERROR_FAILURE;
nsISupports* value = (nsISupports*)Get(&key);
NS_IF_ADDREF(value);
*result = value;
return NS_OK;
}
NS_IMETHODIMP
nsProperties::SetProperty(const char* prop, nsISupports* value)
{
nsCStringKey key(prop);
if (!Exists(&key))
return NS_ERROR_FAILURE;
nsISupports* prevValue = (nsISupports*)Put(&key, value);
NS_IF_RELEASE(prevValue);
NS_IF_ADDREF(value);
return NS_OK;
}
NS_IMETHODIMP
nsProperties::HasProperty(const char* prop, nsISupports* expectedValue)
{
nsISupports* value;
nsresult rv = GetProperty(prop, &value);
if (NS_FAILED(rv)) return NS_COMFALSE;
rv = (value == expectedValue) ? NS_OK : NS_COMFALSE;
NS_IF_RELEASE(value);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
nsresult
NS_NewIProperties(nsIProperties* *result)
{
nsProperties* props = new nsProperties();
if (props == NULL)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(props);
*result = props;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// Persistent Properties (should go in a separate file)
////////////////////////////////////////////////////////////////////////////////
#include "nsID.h"
#include "nsBaseDLL.h"
#include "nsCRT.h"
#include "nsIInputStream.h"
#include "nsIProperties.h"
#include "nsIUnicharInputStream.h"
#include "nsProperties.h"
#include "plhash.h"
#include "pratom.h"
nsPersistentProperties::nsPersistentProperties()
class nsProperties : public nsIProperties
{
public:
nsProperties();
virtual ~nsProperties();
NS_DECL_ISUPPORTS
NS_IMETHOD Load(nsIInputStream* aIn);
NS_IMETHOD GetProperty(const nsString& aKey, nsString& aValue);
NS_IMETHOD SetProperty(const nsString& aKey, nsString& aNewValue,
nsString& aOldValue);
NS_IMETHOD Save(nsIOutputStream* aOut, const nsString& aHeader);
NS_IMETHOD Subclass(nsIProperties* aSubclass);
PRInt32 Read();
PRInt32 SkipLine(PRInt32 c);
PRInt32 SkipWhiteSpace(PRInt32 c);
nsIUnicharInputStream* mIn;
nsIProperties* mSubclass;
struct PLHashTable* mTable;
};
nsProperties::nsProperties()
{
NS_INIT_REFCNT();
mIn = nsnull;
mSubclass = NS_STATIC_CAST(nsIPersistentProperties*, this);
mSubclass = NS_STATIC_CAST(nsIProperties*, this);
mTable = nsnull;
}
@@ -146,7 +69,7 @@ FreeHashEntries(PLHashEntry* he, PRIntn i, void* arg)
return HT_ENUMERATE_REMOVE;
}
nsPersistentProperties::~nsPersistentProperties()
nsProperties::~nsProperties()
{
if (mTable) {
// Free the PRUnicode* pointers contained in the hash table entries
@@ -156,34 +79,19 @@ nsPersistentProperties::~nsPersistentProperties()
}
}
NS_IMPL_ADDREF(nsPersistentProperties)
NS_IMPL_RELEASE(nsPersistentProperties)
NS_DEFINE_IID(kIPropertiesIID, NS_IPROPERTIES_IID);
NS_IMPL_ISUPPORTS(nsProperties, kIPropertiesIID)
NS_IMETHODIMP
nsPersistentProperties::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
NS_ASSERTION(aInstancePtr != nsnull, "null ptr");
if (aIID.Equals(nsIPersistentProperties::GetIID()) ||
aIID.Equals(nsIProperties::GetIID()) ||
aIID.Equals(nsISupports::GetIID())) {
*aInstancePtr = NS_STATIC_CAST(nsIPersistentProperties*, this);
NS_ADDREF_THIS();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMETHODIMP
nsPersistentProperties::Load(nsIInputStream *aIn)
nsProperties::Load(nsIInputStream *aIn)
{
PRInt32 c;
nsresult ret;
ret = NS_NewConverterStream(&mIn, nsnull, aIn);
if (ret != NS_OK) {
#ifdef NS_DEBUG
cout << "NS_NewConverterStream failed" << endl;
#endif
return NS_ERROR_FAILURE;
}
c = Read();
@@ -247,7 +155,7 @@ CompareKeys(const PRUnichar *aStr1, const PRUnichar *aStr2)
}
NS_IMETHODIMP
nsPersistentProperties::SetProperty(const nsString& aKey, nsString& aNewValue,
nsProperties::SetProperty(const nsString& aKey, nsString& aNewValue,
nsString& aOldValue)
{
// XXX The ToNewCString() calls allocate memory using "new" so this code
@@ -269,7 +177,7 @@ nsPersistentProperties::SetProperty(const nsString& aKey, nsString& aNewValue,
PRUint32 hashValue = nsCRT::HashValue(key, &len);
PLHashEntry **hep = PL_HashTableRawLookup(mTable, hashValue, key);
PLHashEntry *he = *hep;
if (he && aOldValue.GetUnicode()) {
if (he && aOldValue) {
// XXX fix me
}
PL_HashTableRawAdd(mTable, hep, hashValue, aKey.ToNewUnicode(),
@@ -279,13 +187,13 @@ nsPersistentProperties::SetProperty(const nsString& aKey, nsString& aNewValue,
}
NS_IMETHODIMP
nsPersistentProperties::Save(nsIOutputStream* aOut, const nsString& aHeader)
nsProperties::Save(nsIOutputStream* aOut, const nsString& aHeader)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsPersistentProperties::Subclass(nsIPersistentProperties* aSubclass)
nsProperties::Subclass(nsIProperties* aSubclass)
{
if (aSubclass) {
mSubclass = aSubclass;
@@ -295,9 +203,9 @@ nsPersistentProperties::Subclass(nsIPersistentProperties* aSubclass)
}
NS_IMETHODIMP
nsPersistentProperties::GetProperty(const nsString& aKey, nsString& aValue)
nsProperties::GetProperty(const nsString& aKey, nsString& aValue)
{
const PRUnichar *key = aKey.GetUnicode();
const PRUnichar *key = aKey;
PRUint32 len;
PRUint32 hashValue = nsCRT::HashValue(key, &len);
PLHashEntry **hep = PL_HashTableRawLookup(mTable, hashValue, key);
@@ -311,7 +219,7 @@ nsPersistentProperties::GetProperty(const nsString& aKey, nsString& aValue)
}
PRInt32
nsPersistentProperties::Read()
nsProperties::Read()
{
PRUnichar c;
PRUint32 nRead;
@@ -329,7 +237,7 @@ nsPersistentProperties::Read()
(((c) == ' ') || ((c) == '\t') || ((c) == '\r') || ((c) == '\n'))
PRInt32
nsPersistentProperties::SkipWhiteSpace(PRInt32 c)
nsProperties::SkipWhiteSpace(PRInt32 c)
{
while ((c >= 0) && IS_WHITE_SPACE(c)) {
c = Read();
@@ -339,7 +247,7 @@ nsPersistentProperties::SkipWhiteSpace(PRInt32 c)
}
PRInt32
nsPersistentProperties::SkipLine(PRInt32 c)
nsProperties::SkipLine(PRInt32 c)
{
while ((c >= 0) && (c != '\r') && (c != '\n')) {
c = Read();
@@ -354,36 +262,51 @@ nsPersistentProperties::SkipLine(PRInt32 c)
return c;
}
////////////////////////////////////////////////////////////////////////////////
NS_IMETHODIMP
nsPersistentProperties::DefineProperty(const char* prop, nsISupports* initialValue)
nsPropertiesFactory::nsPropertiesFactory()
{
return NS_ERROR_NOT_IMPLEMENTED;
NS_INIT_REFCNT();
}
NS_IMETHODIMP
nsPersistentProperties::UndefineProperty(const char* prop)
nsPropertiesFactory::~nsPropertiesFactory()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsPersistentProperties::GetProperty(const char* prop, nsISupports* *result)
NS_DEFINE_IID(kIFactoryIID, NS_IFACTORY_IID);
NS_IMPL_ISUPPORTS(nsPropertiesFactory, kIFactoryIID);
NS_IMETHODIMP
nsPropertiesFactory::CreateInstance(nsISupports* aOuter, REFNSIID aIID,
void** aResult)
{
return NS_ERROR_NOT_IMPLEMENTED;
if (aOuter) {
return NS_ERROR_NO_AGGREGATION;
}
if (!aResult) {
return NS_ERROR_NULL_POINTER;
}
*aResult = nsnull;
nsProperties* props = new nsProperties();
if (!props) {
return NS_ERROR_OUT_OF_MEMORY;
}
nsresult ret = props->QueryInterface(aIID, aResult);
if (NS_FAILED(ret)) {
delete props;
}
return ret;
}
NS_IMETHODIMP
nsPersistentProperties::SetProperty(const char* prop, nsISupports* value)
NS_IMETHODIMP
nsPropertiesFactory::LockFactory(PRBool aLock)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
if (aLock) {
PR_AtomicIncrement(&gLockCount);
}
else {
PR_AtomicDecrement(&gLockCount);
}
NS_IMETHODIMP
nsPersistentProperties::HasProperty(const char* prop, nsISupports* value)
{
return NS_ERROR_NOT_IMPLEMENTED;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -19,65 +19,19 @@
#ifndef nsProperties_h___
#define nsProperties_h___
#include "nsIProperties.h"
#include "nsHashtable.h"
#include "nsIFactory.h"
class nsIUnicharInputStream;
class nsProperties : public nsIProperties, public nsHashtable {
public:
NS_DECL_ISUPPORTS
// nsIProperties methods:
NS_IMETHOD DefineProperty(const char* prop, nsISupports* initialValue);
NS_IMETHOD UndefineProperty(const char* prop);
NS_IMETHOD GetProperty(const char* prop, nsISupports* *result);
NS_IMETHOD SetProperty(const char* prop, nsISupports* value);
NS_IMETHOD HasProperty(const char* prop, nsISupports* value);
// nsProperties methods:
nsProperties();
virtual ~nsProperties();
static PRBool ReleaseValues(nsHashKey* key, void* data, void* closure);
};
class nsPersistentProperties : public nsIPersistentProperties
class nsPropertiesFactory : public nsIFactory
{
public:
nsPersistentProperties();
virtual ~nsPersistentProperties();
nsPropertiesFactory();
virtual ~nsPropertiesFactory();
NS_DECL_ISUPPORTS
// nsIProperties methods:
NS_IMETHOD DefineProperty(const char* prop, nsISupports* initialValue);
NS_IMETHOD UndefineProperty(const char* prop);
NS_IMETHOD GetProperty(const char* prop, nsISupports* *result);
NS_IMETHOD SetProperty(const char* prop, nsISupports* value);
NS_IMETHOD HasProperty(const char* prop, nsISupports* value);
// nsIPersistentProperties methods:
NS_IMETHOD Load(nsIInputStream* aIn);
NS_IMETHOD Save(nsIOutputStream* aOut, const nsString& aHeader);
NS_IMETHOD Subclass(nsIPersistentProperties* aSubclass);
// XXX these 2 methods will be subsumed by the ones from
// nsIProperties once we figure this all out
NS_IMETHOD GetProperty(const nsString& aKey, nsString& aValue);
NS_IMETHOD SetProperty(const nsString& aKey, nsString& aNewValue,
nsString& aOldValue);
// nsPersistentProperties methods:
PRInt32 Read();
PRInt32 SkipLine(PRInt32 c);
PRInt32 SkipWhiteSpace(PRInt32 c);
nsIUnicharInputStream* mIn;
nsIPersistentProperties* mSubclass;
struct PLHashTable* mTable;
NS_IMETHOD CreateInstance(nsISupports* aOuter, REFNSIID aIID,
void** aResult);
NS_IMETHOD LockFactory(PRBool aLock);
};
#endif /* nsProperties_h___ */

View File

@@ -1,182 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*-
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/* We need this because Solaris' version of qsort is broken and
* causes array bounds reads.
*/
#include <stdlib.h>
#include "prtypes.h"
#include "nsQuickSort.h"
#if !defined(DEBUG) && (defined(__cplusplus) || defined(__gcc))
# ifndef INLINE
# define INLINE inline
# endif
#else
# define INLINE
#endif
typedef int cmp_t(const void *, const void *, void *);
static INLINE char *med3(char *, char *, char *, cmp_t *, void *);
static INLINE void swapfunc(char *, char *, int, int);
/*
* Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
*/
#define swapcode(TYPE, parmi, parmj, n) { \
long i = (n) / sizeof (TYPE); \
register TYPE *pi = (TYPE *) (parmi); \
register TYPE *pj = (TYPE *) (parmj); \
do { \
register TYPE t = *pi; \
*pi++ = *pj; \
*pj++ = t; \
} while (--i > 0); \
}
#define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \
es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1;
static INLINE void
swapfunc(char *a, char *b, int n, int swaptype)
{
if(swaptype <= 1)
swapcode(long, a, b, n)
else
swapcode(char, a, b, n)
}
#define swap(a, b) \
if (swaptype == 0) { \
long t = *(long *)(a); \
*(long *)(a) = *(long *)(b); \
*(long *)(b) = t; \
} else \
swapfunc((char *)a, (char*)b, (int)es, swaptype)
#define vecswap(a, b, n) if ((n) > 0) swapfunc((char *)a, (char *)b, (int)n, swaptype)
static INLINE char *
med3(char *a, char *b, char *c, cmp_t* cmp, void *data)
{
return cmp(a, b, data) < 0 ?
(cmp(b, c, data) < 0 ? b : (cmp(a, c, data) < 0 ? c : a ))
:(cmp(b, c, data) > 0 ? b : (cmp(a, c, data) < 0 ? a : c ));
}
void NS_QuickSort (
void *a,
unsigned int n,
unsigned int es,
cmp_t *cmp,
void *data
)
{
char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
int d, r, swaptype, swap_cnt;
loop: SWAPINIT(a, es);
swap_cnt = 0;
if (n < 7) {
for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
for (pl = pm; pl > (char *)a && cmp(pl - es, pl, data) > 0;
pl -= es)
swap(pl, pl - es);
return;
}
pm = (char *)a + (n / 2) * es;
if (n > 7) {
pl = (char *)a;
pn = (char *)a + (n - 1) * es;
if (n > 40) {
d = (n / 8) * es;
pl = med3(pl, pl + d, pl + 2 * d, cmp, data);
pm = med3(pm - d, pm, pm + d, cmp, data);
pn = med3(pn - 2 * d, pn - d, pn, cmp, data);
}
pm = med3(pl, pm, pn, cmp, data);
}
swap(a, pm);
pa = pb = (char *)a + es;
pc = pd = (char *)a + (n - 1) * es;
for (;;) {
while (pb <= pc && (r = cmp(pb, a, data)) <= 0) {
if (r == 0) {
swap_cnt = 1;
swap(pa, pb);
pa += es;
}
pb += es;
}
while (pb <= pc && (r = cmp(pc, a, data)) >= 0) {
if (r == 0) {
swap_cnt = 1;
swap(pc, pd);
pd -= es;
}
pc -= es;
}
if (pb > pc)
break;
swap(pb, pc);
swap_cnt = 1;
pb += es;
pc -= es;
}
if (swap_cnt == 0) { /* Switch to insertion sort */
for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
for (pl = pm; pl > (char *)a && cmp(pl - es, pl, data) > 0;
pl -= es)
swap(pl, pl - es);
return;
}
pn = (char *)a + n * es;
r = PR_MIN(pa - (char *)a, pb - pa);
vecswap(a, pb - r, r);
r = PR_MIN(pd - pc, pn - pd - es);
vecswap(pb, pn - r, r);
if ((r = pb - pa) > es)
NS_QuickSort(a, r / es, es, cmp, data);
if ((r = pd - pc) > es) {
/* Iterate rather than recurse to save stack space */
a = pn - r;
n = r / es;
goto loop;
}
/* NS_QuickSort(pn - r, r / es, es, cmp, data);*/
}

View File

@@ -1,233 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsIScriptable.h"
#include "nscore.h"
#include "xptcall.h"
#include "nsIInterfaceInfoManager.h"
class nsScriptable : public nsIScriptable {
public:
NS_DECL_ISUPPORTS
// nsIProperties methods:
NS_IMETHOD DefineProperty(const char* prop, nsISupports* initialValue);
NS_IMETHOD UndefineProperty(const char* prop);
NS_IMETHOD GetProperty(const char* prop, nsISupports* *result);
NS_IMETHOD SetProperty(const char* prop, nsISupports* value);
NS_IMETHOD HasProperty(const char* prop, nsISupports* value);
// nsIScriptable methods:
NS_IMETHOD Call(const char* command,
nsISupportsArray* arguments,
nsISupports* *result);
// nsScriptable methods:
nsScriptable(REFNSIID iid, nsISupports* object);
virtual ~nsScriptable();
nsresult Init();
// XXX should this be a method on nsIScriptable?
NS_IMETHOD QueryInterfaceScriptable(REFNSIID aIID, void** aInstancePtr);
// XXX later this will be a service
static nsIInterfaceInfoManager* gInterfaceInfoManager;
protected:
nsISupports* mObject;
nsIInterfaceInfo* mInterfaceInfo;
nsID mIID;
// nsXPCWrappedNativeClass* mClazz;
// nsXPCWrappedNative* mWrapper;
};
// XXX later this will be a service
nsIInterfaceInfoManager* nsScriptable::gInterfaceInfoManager = nsnull;
////////////////////////////////////////////////////////////////////////////////
nsScriptable::nsScriptable(REFNSIID iid, nsISupports* object)
: mObject(object), mInterfaceInfo(nsnull), mIID(iid)
// , mClazz(nsnull), mWrapper(nsnull)
{
NS_INIT_REFCNT();
NS_ADDREF(mObject);
}
nsScriptable::~nsScriptable()
{
NS_RELEASE(mObject);
}
NS_IMPL_ISUPPORTS(nsScriptable, nsIScriptable::GetIID());
nsresult
nsScriptable::Init()
{
nsresult rv;
if (gInterfaceInfoManager == nsnull) {
gInterfaceInfoManager = XPTI_GetInterfaceInfoManager();
if (gInterfaceInfoManager == nsnull)
return NS_ERROR_FAILURE;
}
// get the interface info
NS_IF_RELEASE(mInterfaceInfo);
rv = gInterfaceInfoManager->GetInfoForIID(&mIID, &mInterfaceInfo);
if (NS_FAILED(rv)) return rv;
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIProperties methods:
NS_IMETHODIMP
nsScriptable::DefineProperty(const char* prop, nsISupports* initialValue)
{
return NS_OK;
}
NS_IMETHODIMP
nsScriptable::UndefineProperty(const char* prop)
{
return NS_OK;
}
NS_IMETHODIMP
nsScriptable::GetProperty(const char* prop, nsISupports* *result)
{
return NS_OK;
}
NS_IMETHODIMP
nsScriptable::SetProperty(const char* prop, nsISupports* value)
{
return NS_OK;
}
NS_IMETHODIMP
nsScriptable::HasProperty(const char* prop, nsISupports* expectedValue)
{
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIScriptable methods:
#define PARAM_BUFFER_COUNT 16
NS_IMETHODIMP
nsScriptable::Call(const char* methodName,
nsISupportsArray* arguments,
nsISupports* *result)
{
nsresult rv;
const nsXPTMethodInfo* methodInfo;
PRUint16 vtblIndex;
PRUint8 paramCount;
rv = arguments->Count(&paramCount);
if (NS_FAILED(rv)) return rv;
nsXPTCVariant paramBuffer[PARAM_BUFFER_COUNT];
nsXPTCVariant* dispatchParams;
PRUint8 requiredArgs;
// get the method info and vtable index
rv = mInterfaceInfo->GetMethodInfoForName(methodName, &vtblIndex, &methodInfo);
if (NS_FAILED(rv)) return rv;
if (paramCount < PARAM_BUFFER_COUNT) {
dispatchParams = paramBuffer;
}
else {
dispatchParams = new nsXPTCVariant[paramCount];
if (dispatchParams == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
}
// put together the parameter list
for (PRUint8 i = 0; i < paramCount; i++) {
nsISupports* arg = (*arguments)[i];
const nsXPTParamInfo& paramInfo = methodInfo->GetParam(i);
const nsXPTType& paramType = paramInfo.GetType();
nsXPTCVariant* dp = &dispatchParams[i];
if (paramInfo.IsOut()) {
}
else {
}
switch (paramType.TagPart()) {
case nsXPTType::T_INTERFACE:
dp->flags |= nsXPTCVariant::VAL_IS_IFACE;
nsID* iid;
rv = mInterfaceInfo->GetIIDForParam(&paramInfo, &iid);
if (NS_FAILED(rv)) goto done;
break;
case nsXPTType::T_INTERFACE_IS:
break;
default:
break;
}
}
// invoke the method
rv = XPTC_InvokeByIndex(mObject, vtblIndex, paramCount, dispatchParams);
// return any out parameters
done:
if (dispatchParams != paramBuffer)
delete[] dispatchParams;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
NS_IMETHODIMP
nsScriptable::QueryInterfaceScriptable(REFNSIID aIID, void** aInstancePtr)
{
NS_PRECONDITION(aInstancePtr, "null aInstancePtr");
nsresult rv;
rv = mObject->QueryInterface(aIID, aInstancePtr);
if (NS_FAILED(rv)) return rv;
NS_RELEASE(mObject);
mObject = *(nsISupports**)aInstancePtr;
mIID = aIID;
return Init();
}
////////////////////////////////////////////////////////////////////////////////
extern nsresult
NS_NewIScriptable(REFNSIID iid, nsISupports* object, nsIScriptable* *result)
{
nsScriptable* s = new nsScriptable(iid, object);
if (s == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv = s->Init();
if (NS_FAILED(rv)) {
delete s;
return rv;
}
NS_ADDREF(s);
*result = s;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -23,7 +23,7 @@ static NS_DEFINE_IID(kISizeOfHandlerIID, NS_ISIZEOF_HANDLER_IID);
class nsSizeOfHandler : public nsISizeOfHandler {
public:
nsSizeOfHandler();
virtual ~nsSizeOfHandler();
~nsSizeOfHandler();
// nsISupports
NS_DECL_ISUPPORTS

View File

@@ -32,14 +32,12 @@
#include <Processes.h>
#elif defined(XP_PC)
#include <windows.h>
#include <shlobj.h>
#include <stdlib.h>
#include <stdio.h>
#elif defined(XP_UNIX)
#include <unistd.h>
#include <stdlib.h>
#include <sys/param.h>
#include "prenv.h"
#endif
#include "plstr.h"
@@ -57,56 +55,7 @@ static char* MakeUpperCase(char* aPath)
return aPath;
}
//----------------------------------------------------------------------------------------
static void GetWindowsFolder(int folder, nsFileSpec& outDirectory)
//----------------------------------------------------------------------------------------
{
LPMALLOC pMalloc = NULL;
LPSTR pBuffer = NULL;
LPITEMIDLIST pItemIDList = NULL;
int len;
// Get the shell's allocator.
if (!SUCCEEDED(SHGetMalloc(&pMalloc)))
return;
// Allocate a buffer
if ((pBuffer = (LPSTR) pMalloc->Alloc(MAX_PATH + 2)) == NULL)
return;
// Get the PIDL for the folder.
if (!SUCCEEDED(SHGetSpecialFolderLocation(
NULL, folder, &pItemIDList)))
goto Clean;
if (!SUCCEEDED(SHGetPathFromIDList(pItemIDList, pBuffer)))
goto Clean;
// Append the trailing slash
len = PL_strlen(pBuffer);
pBuffer[len] = '\\';
pBuffer[len + 1] = '\0';
// Assign the directory
outDirectory = MakeUpperCase(pBuffer);
Clean:
// Clean up.
if (pItemIDList)
pMalloc->Free(pItemIDList);
if (pBuffer)
pMalloc->Free(pBuffer);
} // GetWindowsFolder
#endif // XP_PC
//----------------------------------------------------------------------------------------
static void GetCurrentWorkingDirectory(nsFileSpec& aFileSpec)
//----------------------------------------------------------------------------------------
{
aFileSpec = ".";
return;
} // GetCurrentWorkingDirectory
#endif
//----------------------------------------------------------------------------------------
static void GetCurrentProcessDirectory(nsFileSpec& aFileSpec)
@@ -170,7 +119,7 @@ static void GetCurrentProcessDirectory(nsFileSpec& aFileSpec)
// - if MOZILLA_FIVE_HOME is defined, that is it
// - else give the current directory
char buf[MAXPATHLEN];
char *moz5 = PR_GetEnv("MOZILLA_FIVE_HOME");
char *moz5 = getenv("MOZILLA_FIVE_HOME");
if (moz5)
{
aFileSpec = moz5;
@@ -178,15 +127,6 @@ static void GetCurrentProcessDirectory(nsFileSpec& aFileSpec)
}
else
{
static PRBool firstWarning = PR_TRUE;
if(firstWarning) {
// Warn that MOZILLA_FIVE_HOME not set, once.
printf("Warning: MOZILLA_FIVE_HOME not set.\n");
firstWarning = PR_FALSE;
}
// Fall back to current directory.
if (getcwd(buf, sizeof(buf)))
{
aFileSpec = buf;
@@ -197,7 +137,7 @@ static void GetCurrentProcessDirectory(nsFileSpec& aFileSpec)
#endif
NS_ERROR("unable to get current process directory");
} // GetCurrentProcessDirectory()
}
//nsSpecialSystemDirectory::nsSpecialSystemDirectory()
//: nsFileSpec(nsnull)
@@ -250,11 +190,20 @@ void nsSpecialSystemDirectory::operator = (SystemDirectories aSystemSystemDirect
case OS_TemporaryDirectory:
#ifdef XP_PC
{
char path[_MAX_PATH];
DWORD len = GetTempPath(_MAX_PATH, path);
if ( GetEnvironmentVariable(TEXT("TMP"), path, _MAX_PATH) == 0 )
if (GetEnvironmentVariable(TEXT("TEMP"), path, _MAX_PATH))
{
// still not set!
PRInt32 len = GetWindowsDirectory( path, _MAX_PATH );
if (len)
{
strcat( path, "temp" );
}
}
strcat( path, "\\" );
*this = MakeUpperCase(path);
}
#elif defined(XP_MAC)
*this = kTemporaryFolderType;
@@ -267,10 +216,6 @@ void nsSpecialSystemDirectory::operator = (SystemDirectories aSystemSystemDirect
GetCurrentProcessDirectory(*this);
break;
case OS_CurrentWorkingDirectory:
GetCurrentWorkingDirectory(*this);
break;
#ifdef XP_MAC
case Mac_SystemDirectory:
*this = kSystemFolderType;
@@ -350,144 +295,7 @@ void nsSpecialSystemDirectory::operator = (SystemDirectories aSystemSystemDirect
break;
}
case Win_HomeDirectory:
{
char path[_MAX_PATH];
if (GetEnvironmentVariable(TEXT("HOMEDRIVE"), path, _MAX_PATH) >= 0)
{
char temp[_MAX_PATH];
if (GetEnvironmentVariable(TEXT("HOMEPATH"), temp, _MAX_PATH) > 0)
PL_strcatn(path, _MAX_PATH, temp);
PRInt32 len = PL_strlen(path);
// Need enough space to add the trailing backslash
if (len > _MAX_PATH - 2)
break;
path[len] = '\\';
path[len+1] = '\0';
}
*this = MakeUpperCase(path);
break;
}
case Win_Desktop:
{
GetWindowsFolder(CSIDL_DESKTOP, *this);
break;
}
case Win_Programs:
{
GetWindowsFolder(CSIDL_PROGRAMS, *this);
break;
}
case Win_Controls:
{
GetWindowsFolder(CSIDL_CONTROLS, *this);
break;
}
case Win_Printers:
{
GetWindowsFolder(CSIDL_PRINTERS, *this);
break;
}
case Win_Personal:
{
GetWindowsFolder(CSIDL_PERSONAL, *this);
break;
}
case Win_Favorites:
{
GetWindowsFolder(CSIDL_FAVORITES, *this);
break;
}
case Win_Startup:
{
GetWindowsFolder(CSIDL_STARTUP, *this);
break;
}
case Win_Recent:
{
GetWindowsFolder(CSIDL_RECENT, *this);
break;
}
case Win_Sendto:
{
GetWindowsFolder(CSIDL_SENDTO, *this);
break;
}
case Win_Bitbucket:
{
GetWindowsFolder(CSIDL_BITBUCKET, *this);
break;
}
case Win_Startmenu:
{
GetWindowsFolder(CSIDL_STARTMENU, *this);
break;
}
case Win_Desktopdirectory:
{
GetWindowsFolder(CSIDL_DESKTOPDIRECTORY, *this);
break;
}
case Win_Drives:
{
GetWindowsFolder(CSIDL_DRIVES, *this);
break;
}
case Win_Network:
{
GetWindowsFolder(CSIDL_NETWORK, *this);
break;
}
case Win_Nethood:
{
GetWindowsFolder(CSIDL_NETHOOD, *this);
break;
}
case Win_Fonts:
{
GetWindowsFolder(CSIDL_FONTS, *this);
break;
}
case Win_Templates:
{
GetWindowsFolder(CSIDL_TEMPLATES, *this);
break;
}
case Win_Common_Startmenu:
{
GetWindowsFolder(CSIDL_COMMON_STARTMENU, *this);
break;
}
case Win_Common_Programs:
{
GetWindowsFolder(CSIDL_COMMON_PROGRAMS, *this);
break;
}
case Win_Common_Startup:
{
GetWindowsFolder(CSIDL_COMMON_STARTUP, *this);
break;
}
case Win_Common_Desktopdirectory:
{
GetWindowsFolder(CSIDL_COMMON_DESKTOPDIRECTORY, *this);
break;
}
case Win_Appdata:
{
GetWindowsFolder(CSIDL_APPDATA, *this);
break;
}
case Win_Printhood:
{
GetWindowsFolder(CSIDL_PRINTHOOD, *this);
break;
}
#endif // XP_PC
#endif
#ifdef XP_UNIX
case Unix_LocalDirectory:
@@ -497,11 +305,6 @@ void nsSpecialSystemDirectory::operator = (SystemDirectories aSystemSystemDirect
case Unix_LibDirectory:
*this = "/usr/local/lib/netscape/";
break;
case Unix_HomeDirectory:
*this = PR_GetEnv("HOME");
break;
#endif
default:

View File

@@ -1,603 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
/******************************************************************************************
MODULE NOTES:
This file contains the nsStr data structure.
This general purpose buffer management class is used as the basis for our strings.
It's benefits include:
1. An efficient set of library style functions for manipulating nsStrs
2. Support for 1 and 2 byte character strings (which can easily be increased to n)
3. Unicode awareness and interoperability.
*******************************************************************************************/
#include "nsStr.h"
#include "bufferRoutines.h"
#include "stdio.h" //only used for printf
#include "nsDeque.h"
#include "nsCRT.h"
static const char* kFoolMsg = "Error: Some fool overwrote the shared buffer.";
//----------------------------------------------------------------------------------------
// The following is a memory agent who knows how to recycled (pool) freed memory...
//----------------------------------------------------------------------------------------
/**************************************************************
Define the char* (pooled) deallocator class...
**************************************************************/
class nsBufferDeallocator: public nsDequeFunctor{
public:
virtual void* operator()(void* anObject) {
char* aCString= (char*)anObject;
delete [] aCString;
return 0;
}
};
/**
*
* @update gess10/30/98
* @param
* @return
*/
class nsPoolingMemoryAgent : public nsMemoryAgent{
public:
nsPoolingMemoryAgent() {
memset(mPools,0,sizeof(mPools));
}
virtual ~nsPoolingMemoryAgent() {
nsBufferDeallocator theDeallocator;
int i=0;
for(i=0;i<10;i++){
if(mPools[i]){
mPools[i]->ForEach(theDeallocator); //now delete the buffers
}
delete mPools[i];
mPools[i]=0;
}
}
virtual PRBool Alloc(nsStr& aDest,PRInt32 aCount) {
//we're given the acount value in charunits; we have to scale up by the charsize.
int theShift=4;
PRInt32 theNewCapacity=eDefaultSize;
while(theNewCapacity<aCount){
theNewCapacity<<=1;
theShift++;
}
aDest.mCapacity=theNewCapacity++;
theShift=(theShift<<aDest.mCharSize)-4;
if((theShift<12) && (mPools[theShift])){
aDest.mStr=(char*)mPools[theShift]->Pop();
}
if(!aDest.mStr) {
//we're given the acount value in charunits; we have to scale up by the charsize.
size_t theSize=(theNewCapacity<<aDest.mCharSize);
aDest.mStr=new char[theSize];
}
aDest.mOwnsBuffer=1;
return PR_TRUE;
}
virtual PRBool Free(nsStr& aDest){
if(aDest.mStr){
if(aDest.mOwnsBuffer){
int theShift=1;
unsigned int theValue=1;
while((theValue<<=1)<aDest.mCapacity){
theShift++;
}
theShift-=4;
if(theShift<12){
if(!mPools[theShift]){
mPools[theShift]=new nsDeque(0);
}
mPools[theShift]->Push(aDest.mStr);
}
else delete [] aDest.mStr; //it's too big. Just delete it.
}
aDest.mStr=0;
aDest.mOwnsBuffer=0;
return PR_TRUE;
}
return PR_FALSE;
}
nsDeque* mPools[16];
};
static char* gCommonEmptyBuffer=0;
/**
*
* @update gess10/30/98
* @param
* @return
*/
char* GetSharedEmptyBuffer() {
if(!gCommonEmptyBuffer) {
const size_t theDfltSize=5;
gCommonEmptyBuffer=new char[theDfltSize];
if(gCommonEmptyBuffer){
nsCRT::zero(gCommonEmptyBuffer,theDfltSize);
gCommonEmptyBuffer[0]=0;
}
else {
printf("%s\n","Memory allocation error!");
}
}
return gCommonEmptyBuffer;
}
/**
*
* @update gess10/30/98
* @param
* @return
*/
void nsStr::Initialize(nsStr& aDest,eCharSize aCharSize) {
aDest.mStr=GetSharedEmptyBuffer();
aDest.mLength=0;
aDest.mCapacity=0;
aDest.mCharSize=aCharSize;
aDest.mOwnsBuffer=0;
NS_ASSERTION(gCommonEmptyBuffer[0]==0,kFoolMsg);
}
/**
*
* @update gess10/30/98
* @param
* @return
*/
void nsStr::Initialize(nsStr& aDest,char* aCString,PRUint32 aCapacity,PRUint32 aLength,eCharSize aCharSize,PRBool aOwnsBuffer){
aDest.mStr=(aCString) ? aCString : GetSharedEmptyBuffer();
aDest.mLength=aLength;
aDest.mCapacity=aCapacity;
aDest.mCharSize=aCharSize;
aDest.mOwnsBuffer=aOwnsBuffer;
NS_ASSERTION(gCommonEmptyBuffer[0]==0,kFoolMsg);
}
/**
*
* @update gess10/30/98
* @param
* @return
*/
nsIMemoryAgent* GetDefaultAgent(void){
// static nsPoolingMemoryAgent gDefaultAgent;
static nsMemoryAgent gDefaultAgent;
return (nsIMemoryAgent*)&gDefaultAgent;
}
/**
*
* @update gess10/30/98
* @param
* @return
*/
void nsStr::Destroy(nsStr& aDest,nsIMemoryAgent* anAgent) {
if((aDest.mStr) && (aDest.mStr!=GetSharedEmptyBuffer())) {
if(!anAgent)
anAgent=GetDefaultAgent();
if(anAgent) {
anAgent->Free(aDest);
}
else{
printf("%s\n","Leak occured in nsStr.");
}
}
}
/**
* This method gets called when the internal buffer needs
* to grow to a given size. The original contents are not preserved.
* @update gess 3/30/98
* @param aNewLength -- new capacity of string in charSize units
* @return void
*/
void nsStr::EnsureCapacity(nsStr& aString,PRUint32 aNewLength,nsIMemoryAgent* anAgent) {
if(aNewLength>aString.mCapacity) {
nsIMemoryAgent* theAgent=(anAgent) ? anAgent : GetDefaultAgent();
theAgent->Realloc(aString,aNewLength);
AddNullTerminator(aString);
}
NS_ASSERTION(gCommonEmptyBuffer[0]==0,kFoolMsg);
}
/**
* This method gets called when the internal buffer needs
* to grow to a given size. The original contents ARE preserved.
* @update gess 3/30/98
* @param aNewLength -- new capacity of string in charSize units
* @return void
*/
void nsStr::GrowCapacity(nsStr& aDest,PRUint32 aNewLength,nsIMemoryAgent* anAgent) {
if(aNewLength>aDest.mCapacity) {
nsStr theTempStr;
nsStr::Initialize(theTempStr,(eCharSize)aDest.mCharSize);
nsIMemoryAgent* theAgent=(anAgent) ? anAgent : GetDefaultAgent();
EnsureCapacity(theTempStr,aNewLength,theAgent);
if(aDest.mLength) {
Append(theTempStr,aDest,0,aDest.mLength,theAgent);
}
theAgent->Free(aDest);
aDest.mStr = theTempStr.mStr;
theTempStr.mStr=0; //make sure to null this out so that you don't lose the buffer you just stole...
aDest.mLength=theTempStr.mLength;
aDest.mCapacity=theTempStr.mCapacity;
aDest.mOwnsBuffer=theTempStr.mOwnsBuffer;
}
NS_ASSERTION(gCommonEmptyBuffer[0]==0,kFoolMsg);
}
/**
* Replaces the contents of aDest with aSource, up to aCount of chars.
* @update gess10/30/98
* @param aDest is the nsStr that gets changed.
* @param aSource is where chars are copied from
* @param aCount is the number of chars copied from aSource
*/
void nsStr::Assign(nsStr& aDest,const nsStr& aSource,PRUint32 anOffset,PRInt32 aCount,nsIMemoryAgent* anAgent){
Truncate(aDest,0,anAgent);
Append(aDest,aSource,anOffset,aCount,anAgent);
}
/**
* This method appends the given nsStr to this one. Note that we have to
* pay attention to the underlying char-size of both structs.
* @update gess10/30/98
* @param aDest is the nsStr to be manipulated
* @param aSource is where char are copied from
* @aCount is the number of bytes to be copied
*/
void nsStr::Append(nsStr& aDest,const nsStr& aSource,PRUint32 anOffset,PRInt32 aCount,nsIMemoryAgent* anAgent){
if(anOffset<aSource.mLength){
PRUint32 theRealLen=(aCount<0) ? aSource.mLength : MinInt(aCount,aSource.mLength);
PRUint32 theLength=(anOffset+theRealLen<aSource.mLength) ? theRealLen : (aSource.mLength-anOffset);
if(0<theLength){
if(aDest.mLength+theLength > aDest.mCapacity) {
GrowCapacity(aDest,aDest.mLength+theLength,anAgent);
}
//now append new chars, starting at offset
(*gCopyChars[aSource.mCharSize][aDest.mCharSize])(aDest.mStr,aDest.mLength,aSource.mStr,anOffset,theLength);
aDest.mLength+=theLength;
}
}
AddNullTerminator(aDest);
NS_ASSERTION(gCommonEmptyBuffer[0]==0,kFoolMsg);
}
/**
* This method inserts up to "aCount" chars from a source nsStr into a dest nsStr.
* @update gess10/30/98
* @param aDest is the nsStr that gets changed
* @param aDestOffset is where in aDest the insertion is to occur
* @param aSource is where chars are copied from
* @param aSrcOffset is where in aSource chars are copied from
* @param aCount is the number of chars from aSource to be inserted into aDest
*/
void nsStr::Insert( nsStr& aDest,PRUint32 aDestOffset,const nsStr& aSource,PRUint32 aSrcOffset,PRInt32 aCount,nsIMemoryAgent* anAgent){
//there are a few cases for insert:
// 1. You're inserting chars into an empty string (assign)
// 2. You're inserting onto the end of a string (append)
// 3. You're inserting onto the 1..n-1 pos of a string (the hard case).
if(0<aSource.mLength){
if(aDest.mLength){
if(aDestOffset<aDest.mLength){
PRInt32 theRealLen=(aCount<0) ? aSource.mLength : MinInt(aCount,aSource.mLength);
PRInt32 theLength=(aSrcOffset+theRealLen<aSource.mLength) ? theRealLen : (aSource.mLength-aSrcOffset);
if(aSrcOffset<aSource.mLength) {
//here's the only new case we have to handle.
//chars are really being inserted into our buffer...
GrowCapacity(aDest,aDest.mLength+theLength,anAgent);
//shift the chars right by theDelta...
(*gShiftChars[aDest.mCharSize][PR_TRUE])(aDest.mStr,aDest.mLength,aDestOffset,theLength);
//now insert new chars, starting at offset
(*gCopyChars[aSource.mCharSize][aDest.mCharSize])(aDest.mStr,aDestOffset,aSource.mStr,aSrcOffset,theLength);
//finally, make sure to update the string length...
aDest.mLength+=theLength;
AddNullTerminator(aDest);
}//if
//else nothing to do!
}
else Append(aDest,aSource,0,aCount,anAgent);
}
else Append(aDest,aSource,0,aCount,anAgent);
}
NS_ASSERTION(gCommonEmptyBuffer[0]==0,kFoolMsg);
}
/**
* This method deletes up to aCount chars from aDest
* @update gess10/30/98
* @param aDest is the nsStr to be manipulated
* @param aDestOffset is where in aDest deletion is to occur
* @param aCount is the number of chars to be deleted in aDest
*/
void nsStr::Delete(nsStr& aDest,PRUint32 aDestOffset,PRUint32 aCount,nsIMemoryAgent* anAgent){
if(aDestOffset<aDest.mLength){
PRUint32 theDelta=aDest.mLength-aDestOffset;
PRUint32 theLength=(theDelta<aCount) ? theDelta : aCount;
if(aDestOffset+theLength<aDest.mLength) {
//if you're here, it means we're cutting chars out of the middle of the string...
//so shift the chars left by theLength...
(*gShiftChars[aDest.mCharSize][PR_FALSE])(aDest.mStr,aDest.mLength,aDestOffset,theLength);
aDest.mLength-=theLength;
}
else Truncate(aDest,aDestOffset,anAgent);
}//if
NS_ASSERTION(gCommonEmptyBuffer[0]==0,kFoolMsg);
}
/**
* This method truncates the given nsStr at given offset
* @update gess10/30/98
* @param aDest is the nsStr to be truncated
* @param aDestOffset is where in aDest truncation is to occur
*/
void nsStr::Truncate(nsStr& aDest,PRUint32 aDestOffset,nsIMemoryAgent* anAgent){
if(aDestOffset<aDest.mLength){
aDest.mLength=aDestOffset;
AddNullTerminator(aDest);
}
NS_ASSERTION(gCommonEmptyBuffer[0]==0,kFoolMsg);
}
/**
*
* @update gess1/7/99
* @param
* @return
*/
void nsStr::ChangeCase(nsStr& aDest,PRBool aToUpper) {
// somehow UnicharUtil return failed, fallback to the old ascii only code
gCaseConverters[aDest.mCharSize](aDest.mStr,aDest.mLength,aToUpper);
NS_ASSERTION(gCommonEmptyBuffer[0]==0,kFoolMsg);
}
/**
*
* @update gess1/7/99
* @param
* @return
*/
void nsStr::StripChars(nsStr& aDest,PRUint32 aDestOffset,PRInt32 aCount,const char* aCharSet){
PRUint32 aNewLen=gStripChars[aDest.mCharSize](aDest.mStr,aDestOffset,aCount,aCharSet);
aDest.mLength=aNewLen;
NS_ASSERTION(gCommonEmptyBuffer[0]==0,kFoolMsg);
}
/**
*
* @update gess1/7/99
* @param
* @return
*/
void nsStr::Trim(nsStr& aDest,const char* aSet,PRBool aEliminateLeading,PRBool aEliminateTrailing){
PRUint32 aNewLen=gTrimChars[aDest.mCharSize](aDest.mStr,aDest.mLength,aSet,aEliminateLeading,aEliminateTrailing);
aDest.mLength=aNewLen;
NS_ASSERTION(gCommonEmptyBuffer[0]==0,kFoolMsg);
}
/**
*
* @update gess1/7/99
* @param
* @return
*/
void nsStr::CompressSet(nsStr& aDest,const char* aSet,PRUint32 aChar,PRBool aEliminateLeading,PRBool aEliminateTrailing){
PRUint32 aNewLen=gCompressChars[aDest.mCharSize](aDest.mStr,aDest.mLength,aSet,aChar,aEliminateLeading,aEliminateTrailing);
aDest.mLength=aNewLen;
NS_ASSERTION(gCommonEmptyBuffer[0]==0,kFoolMsg);
}
/**************************************************************
Searching methods...
**************************************************************/
PRInt32 nsStr::FindSubstr(const nsStr& aDest,const nsStr& aTarget, PRBool aIgnoreCase,PRUint32 anOffset) {
PRInt32 index=anOffset-1;
PRInt32 theMax=aDest.mLength-aTarget.mLength;
if((aDest.mLength>0) && (aTarget.mLength>0)){
PRInt32 theNewStartPos=-1;
PRUnichar theFirstTargetChar=GetCharAt(aTarget,0);
PRUnichar theLastTargetChar=GetCharAt(aTarget,aTarget.mLength-1);
PRInt32 theTargetMax=aTarget.mLength;
while(++index<=theMax) {
PRInt32 theSubIndex=-1;
PRBool matches=PR_TRUE;
while((++theSubIndex<theTargetMax) && (matches)){
PRUnichar theChar=GetCharAt(aDest,index+theSubIndex);
if(theSubIndex>0) {
if(theFirstTargetChar==theChar){
PRUnichar theDestJumpChar=GetCharAt(aDest,index+theTargetMax);
if(theDestJumpChar==theLastTargetChar) {
theNewStartPos=index; //this lets us jump ahead during our search where possible.
}//if
}//if
}//if
PRUnichar theTargetChar=GetCharAt(aTarget,theSubIndex);
matches=PRBool(theChar==theTargetChar);
}
if(matches)
return index;
if(-1<theNewStartPos){
index=theNewStartPos-1;
}
}
}//if
return kNotFound;
}
/**
*
* @update gess1/7/99
* @param
* @return
*/
PRInt32 nsStr::FindChar(const nsStr& aDest,PRUnichar aChar, PRBool aIgnoreCase,PRUint32 anOffset) {
PRInt32 result=gFindChars[aDest.mCharSize](aDest.mStr,aDest.mLength,anOffset,aChar,aIgnoreCase);
return result;
}
/**
*
*
* @update gess 3/25/98
* @param
* @return
*/
PRInt32 nsStr::FindCharInSet(const nsStr& aDest,const nsStr& aSet,PRBool aIgnoreCase,PRUint32 anOffset) {
PRUint32 index=anOffset-1;
PRInt32 thePos;
while(++index<aDest.mLength) {
PRUnichar theChar=GetCharAt(aDest,index);
thePos=gFindChars[aSet.mCharSize](aSet.mStr,aSet.mLength,anOffset,theChar,aIgnoreCase);
if(kNotFound!=thePos)
return index;
} //while
return kNotFound;
}
/**************************************************************
Reverse Searching methods...
**************************************************************/
PRInt32 nsStr::RFindSubstr(const nsStr& aDest,const nsStr& aTarget, PRBool aIgnoreCase,PRUint32 anOffset) {
PRInt32 index=(anOffset ? anOffset : aDest.mLength-aTarget.mLength+1);
if((aDest.mLength>0) && (aTarget.mLength>0)){
PRInt32 theNewStartPos=-1;
PRUnichar theFirstTargetChar=GetCharAt(aTarget,0);
PRUnichar theLastTargetChar=GetCharAt(aTarget,aTarget.mLength-1);
PRInt32 theTargetMax=aTarget.mLength;
while(index--) {
PRInt32 theSubIndex=-1;
PRBool matches=PR_TRUE;
if(anOffset+aTarget.mLength<=aDest.mLength) {
while((++theSubIndex<theTargetMax) && (matches)){
PRUnichar theChar=GetCharAt(aDest,index+theSubIndex);
if(theSubIndex>0) {
if(theFirstTargetChar==theChar){
PRUnichar theDestJumpChar=GetCharAt(aDest,index+theTargetMax);
if(theDestJumpChar==theLastTargetChar) {
theNewStartPos=index; //this lets us jump ahead during our search where possible.
}//if
}//if
}//if
PRUnichar theTargetChar=GetCharAt(aTarget,theSubIndex);
matches=PRBool(theChar==theTargetChar);
} //while
} //if
if(matches)
return index;
if(-1<theNewStartPos){
index=theNewStartPos-1;
}
}
}//if
return kNotFound;
}
/**
*
* @update gess1/7/99
* @param
* @return
*/
PRInt32 nsStr::RFindChar(const nsStr& aDest,PRUnichar aChar, PRBool aIgnoreCase,PRUint32 anOffset) {
PRInt32 result=gRFindChars[aDest.mCharSize](aDest.mStr,aDest.mLength,anOffset,aChar,aIgnoreCase);
return result;
}
/**
*
*
* @update gess 3/25/98
* @param
* @return
*/
PRInt32 nsStr::RFindCharInSet(const nsStr& aDest,const nsStr& aSet,PRBool aIgnoreCase,PRUint32 anOffset) {
PRUint32 offset=aDest.mLength-anOffset;
PRInt32 thePos;
while(--offset>=0) {
PRUnichar theChar=GetCharAt(aDest,offset);
thePos=gRFindChars[aSet.mCharSize](aSet.mStr,aSet.mLength,anOffset,theChar,aIgnoreCase);
if(kNotFound!=thePos)
return offset;
} //while
return kNotFound;
}
/**
*
* @update gess11/12/98
* @param
* @return aDest<aSource=-1;aDest==aSource==0;aDest>aSource=1
*/
PRInt32 nsStr::Compare(const nsStr& aDest,const nsStr& aSource,PRInt32 aCount,PRBool aIgnoreCase) {
int minlen=(aSource.mLength<aDest.mLength) ? aSource.mLength : aDest.mLength;
if(0==minlen) {
if ((aDest.mLength == 0) && (aSource.mLength == 0))
return 0;
if (aDest.mLength == 0)
return -1;
return 1;
}
int maxlen=(aSource.mLength<aDest.mLength) ? aDest.mLength : aSource.mLength;
PRInt32 result=(*gCompare[aDest.mCharSize][aSource.mCharSize])(aDest.mStr,aSource.mStr,maxlen,aIgnoreCase);
return result;
}

View File

@@ -1,333 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
/***********************************************************************
MODULE NOTES:
1. There are two philosophies to building string classes:
A. Hide the underlying buffer & offer API's allow indirect iteration
B. Reveal underlying buffer, risk corruption, but gain performance
We chose the option B for performance reasons.
2 Our internal buffer always holds capacity+1 bytes.
The nsStr struct is a simple structure (no methods) that contains
the necessary info to be described as a string. This simple struct
is manipulated by the static methods provided in this class.
(Which effectively makes this a library that works on structs).
There are also object-based versions called nsString and nsAutoString
which use nsStr but makes it look at feel like an object.
***********************************************************************/
#ifndef _nsStr
#define _nsStr
#include "nscore.h"
//----------------------------------------------------------------------------------------
enum eCharSize {eOneByte=0,eTwoByte=1};
#define kDefaultCharSize eTwoByte
const PRInt32 kNotFound = -1;
class nsIMemoryAgent;
//----------------------------------------------------------------------------------------
struct nsStr {
/**
* This method initializes an nsStr for use
*
* @update gess 01/04/99
* @param aString is the nsStr to be initialized
* @param aCharSize tells us the requested char size (1 or 2 bytes)
*/
static void Initialize(nsStr& aDest,eCharSize aCharSize);
/**
* This method initializes an nsStr for use
*
* @update gess 01/04/99
* @param aString is the nsStr to be initialized
* @param aCharSize tells us the requested char size (1 or 2 bytes)
*/
static void Initialize(nsStr& aDest,char* aCString,PRUint32 aCapacity,PRUint32 aLength,eCharSize aCharSize,PRBool aOwnsBuffer);
/**
* This method destroys the given nsStr, and *MAY*
* deallocate it's memory depending on the setting
* of the internal mOwnsBUffer flag.
*
* @update gess 01/04/99
* @param aString is the nsStr to be manipulated
* @param anAgent is the allocator to be used to the nsStr
*/
static void Destroy(nsStr& aDest,nsIMemoryAgent* anAgent=0);
/**
* These methods are where memory allocation/reallocation occur.
*
* @update gess 01/04/99
* @param aString is the nsStr to be manipulated
* @param anAgent is the allocator to be used on the nsStr
* @return
*/
static void EnsureCapacity(nsStr& aString,PRUint32 aNewLength,nsIMemoryAgent* anAgent=0);
static void GrowCapacity(nsStr& aString,PRUint32 aNewLength,nsIMemoryAgent* anAgent=0);
/**
* These methods are used to append content to the given nsStr
*
* @update gess 01/04/99
* @param aDest is the nsStr to be appended to
* @param aSource is the buffer to be copied from
* @param anOffset tells us where in source to start copying
* @param aCount tells us the (max) # of chars to copy
* @param anAgent is the allocator to be used for alloc/free operations
*/
static void Append(nsStr& aDest,const nsStr& aSource,PRUint32 anOffset,PRInt32 aCount,nsIMemoryAgent* anAgent=0);
/**
* These methods are used to assign contents of a source string to dest string
*
* @update gess 01/04/99
* @param aDest is the nsStr to be appended to
* @param aSource is the buffer to be copied from
* @param anOffset tells us where in source to start copying
* @param aCount tells us the (max) # of chars to copy
* @param anAgent is the allocator to be used for alloc/free operations
*/
static void Assign(nsStr& aDest,const nsStr& aSource,PRUint32 anOffset,PRInt32 aCount,nsIMemoryAgent* anAgent=0);
/**
* These methods are used to insert content from source string to the dest nsStr
*
* @update gess 01/04/99
* @param aDest is the nsStr to be appended to
* @param aDestOffset tells us where in dest to start insertion
* @param aSource is the buffer to be copied from
* @param aSrcOffset tells us where in source to start copying
* @param aCount tells us the (max) # of chars to insert
* @param anAgent is the allocator to be used for alloc/free operations
*/
static void Insert( nsStr& aDest,PRUint32 aDestOffset,const nsStr& aSource,PRUint32 aSrcOffset,PRInt32 aCount,nsIMemoryAgent* anAgent=0);
/**
* This method deletes chars from the given str.
* The given allocator may choose to resize the str as well.
*
* @update gess 01/04/99
* @param aDest is the nsStr to be deleted from
* @param aDestOffset tells us where in dest to start deleting
* @param aCount tells us the (max) # of chars to delete
* @param anAgent is the allocator to be used for alloc/free operations
*/
static void Delete(nsStr& aDest,PRUint32 aDestOffset,PRUint32 aCount,nsIMemoryAgent* anAgent=0);
/**
* This method is used to truncate the given string.
* The given allocator may choose to resize the str as well (but it's not likely).
*
* @update gess 01/04/99
* @param aDest is the nsStr to be appended to
* @param aDestOffset tells us where in dest to start insertion
* @param aSource is the buffer to be copied from
* @param aSrcOffset tells us where in source to start copying
* @param anAgent is the allocator to be used for alloc/free operations
*/
static void Truncate(nsStr& aDest,PRUint32 aDestOffset,nsIMemoryAgent* anAgent=0);
/**
* This method is used to perform a case conversion on the given string
*
* @update gess 01/04/99
* @param aDest is the nsStr to be case shifted
* @param toUpper tells us to go upper vs. lower
*/
static void ChangeCase(nsStr& aDest,PRBool aToUpper);
/**
* This method removes chars (given in aSet) from the given buffer
*
* @update gess 01/04/99
* @param aString is the buffer to be manipulated
* @param aDestOffset is starting pos in buffer for manipulation
* @param aCount is the number of chars to compare
* @param aSet tells us which chars to remove from given buffer
*/
static void StripChars(nsStr& aDest,PRUint32 aDestOffset,PRInt32 aCount,const char* aCharSet);
/**
* This method trims chars (given in aSet) from the edges of given buffer
*
* @update gess 01/04/99
* @param aDest is the buffer to be manipulated
* @param aSet tells us which chars to remove from given buffer
* @param aEliminateLeading tells us whether to strip chars from the start of the buffer
* @param aEliminateTrailing tells us whether to strip chars from the start of the buffer
*/
static void Trim(nsStr& aDest,const char* aSet,PRBool aEliminateLeading,PRBool aEliminateTrailing);
/**
* This method compresses duplicate runs of a given char from the given buffer
*
* @update gess 01/04/99
* @param aDest is the buffer to be manipulated
* @param aSet tells us which chars to compress from given buffer
* @param aChar is the replacement char
* @param aEliminateLeading tells us whether to strip chars from the start of the buffer
* @param aEliminateTrailing tells us whether to strip chars from the start of the buffer
*/
static void CompressSet(nsStr& aDest,const char* aSet,PRUint32 aChar,PRBool aEliminateLeading,PRBool aEliminateTrailing);
/**
* This method compares the data bewteen two nsStr's
*
* @update gess 01/04/99
* @param aStr1 is the first buffer to be compared
* @param aStr2 is the 2nd buffer to be compared
* @param aCount is the number of chars to compare
* @param aIgnorecase tells us whether to use a case-sensitive comparison
* @return -1,0,1 depending on <,==,>
*/
static PRInt32 Compare(const nsStr& aDest,const nsStr& aSource,PRInt32 aCount,PRBool aIgnoreCase);
/**
* These methods scan the given string for 1 or more chars in a given direction
*
* @update gess 01/04/99
* @param aDest is the nsStr to be searched to
* @param aSource (or aChar) is the substr we're looking to find
* @param aIgnoreCase tells us whether to search in a case-sensitive manner
* @param anOffset tells us where in the dest string to start searching
* @return the index of the source (substr) in dest, or -1 (kNotFound) if not found.
*/
static PRInt32 FindSubstr(const nsStr& aDest,const nsStr& aSource, PRBool aIgnoreCase,PRUint32 anOffset);
static PRInt32 FindChar(const nsStr& aDest,PRUnichar aChar, PRBool aIgnoreCase,PRUint32 anOffset);
static PRInt32 FindCharInSet(const nsStr& aDest,const nsStr& aSet,PRBool aIgnoreCase,PRUint32 anOffset);
static PRInt32 RFindSubstr(const nsStr& aDest,const nsStr& aSource, PRBool aIgnoreCase,PRUint32 anOffset);
static PRInt32 RFindChar(const nsStr& aDest,PRUnichar aChar, PRBool aIgnoreCase,PRUint32 anOffset);
static PRInt32 RFindCharInSet(const nsStr& aDest,const nsStr& aSet,PRBool aIgnoreCase,PRUint32 anOffset);
PRUint32 mLength;
PRUint32 mCapacity;
eCharSize mCharSize;
PRBool mOwnsBuffer;
union {
char* mStr;
PRUnichar* mUStr;
};
};
/**************************************************************
A couple of tiny helper methods used in the string classes.
**************************************************************/
inline PRInt32 MinInt(PRInt32 anInt1,PRInt32 anInt2){
return (anInt1<anInt2) ? anInt1 : anInt2;
}
inline PRInt32 MaxInt(PRInt32 anInt1,PRInt32 anInt2){
return (anInt1<anInt2) ? anInt2 : anInt1;
}
inline void AddNullTerminator(nsStr& aDest) {
if(eTwoByte==aDest.mCharSize)
aDest.mUStr[aDest.mLength]=0;
else aDest.mStr[aDest.mLength]=0;
}
/**
* This method is used to access a given char in the given string
*
* @update gess 01/04/99
* @param aDest is the nsStr to be appended to
* @param anIndex tells us where in dest to get the char from
* @return the given char, or 0 if anIndex is out of range
*/
inline PRUnichar GetCharAt(const nsStr& aDest,PRUint32 anIndex){
if(anIndex<aDest.mLength) {
return (eTwoByte==aDest.mCharSize) ? aDest.mUStr[anIndex] : aDest.mStr[anIndex];
}//if
return 0;
}
//----------------------------------------------------------------------------------------
class nsIMemoryAgent {
public:
virtual PRBool Alloc(nsStr& aString,PRUint32 aCount)=0;
virtual PRBool Realloc(nsStr& aString,PRUint32 aCount)=0;
virtual PRBool Free(nsStr& aString)=0;
};
class nsMemoryAgent : public nsIMemoryAgent {
protected:
enum eDelta{eDefaultSize=16};
public:
virtual PRBool Alloc(nsStr& aDest,PRUint32 aCount) {
//we're given the acount value in charunits; now scale up to next multiple.
PRUint32 theNewCapacity=eDefaultSize;
while(theNewCapacity<aCount){
theNewCapacity<<=1;
}
aDest.mCapacity=theNewCapacity++;
size_t theSize=(theNewCapacity<<aDest.mCharSize);
aDest.mStr=new char[theSize];
aDest.mOwnsBuffer=1;
return PR_TRUE;
}
virtual PRBool Free(nsStr& aDest){
if(aDest.mStr){
if(aDest.mOwnsBuffer){
delete [] aDest.mStr;
}
aDest.mStr=0;
aDest.mOwnsBuffer=0;
return PR_TRUE;
}
return PR_FALSE;
}
virtual PRBool Realloc(nsStr& aDest,PRUint32 aCount){
Free(aDest);
return Alloc(aDest,aCount);
}
};
char* GetSharedEmptyBuffer();
nsIMemoryAgent* GetDefaultAgent(void);
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -30,8 +30,8 @@
***********************************************************************/
#ifndef _nsString1
#define _nsString1
#ifndef _NSSTRING
#define _NSSTRING
#include "prtypes.h"
@@ -39,18 +39,9 @@
#include "nsIAtom.h"
#include <iostream.h>
#include <stdio.h>
#include "nsStr.h"
#ifndef USE_STRING2
#define nsString1 nsString
#define nsAutoString1 nsAutoString
#else
#include "nsString2.h" //get new string class
#endif
class nsISizeOfHandler;
class NS_BASE nsString1 {
class NS_BASE nsString {
public:
/**
@@ -59,30 +50,30 @@ class NS_BASE nsString1 {
* was to allow developers direct access to the underlying buffer for
* performance reasons.
*/
nsString1();
nsString();
/**
* This constructor accepts an isolatin string
* @param an ascii is a ptr to a 1-byte cstr
*/
nsString1(const char* aCString);
nsString(const char* aCString);
/**
* This is our copy constructor
* @param reference to another nsString1
* @param reference to another nsString
*/
nsString1(const nsString1&);
nsString(const nsString&);
/**
* Constructor from a unicode string
* @param anicodestr pts to a unicode string
*/
nsString1(const PRUnichar* aUnicode);
nsString(const PRUnichar* aUnicode);
/**
* Virtual Destructor
*/
virtual ~nsString1();
virtual ~nsString();
/**
@@ -152,7 +143,7 @@ operator const PRUnichar*() const;
* @param offset into string
* @return PRUnichar* to internal string
*/
//PRUnichar operator()(PRInt32 anIndex) const;
PRUnichar operator()(PRInt32 anIndex) const;
/**
* Retrieve reference to unicode char at given index
@@ -180,9 +171,6 @@ PRUnichar& First() const;
*/
PRUnichar& Last() const;
PRBool SetCharAt(PRUnichar aChar,PRInt32 anIndex);
/**********************************************************************
String creation methods...
*********************************************************************/
@@ -192,35 +180,35 @@ PRBool SetCharAt(PRUnichar aChar,PRInt32 anIndex);
* @param aString -- 2nd string to be appended
* @return new string
*/
nsString1 operator+(const nsString1& aString);
nsString operator+(const nsString& aString);
/**
* create a new string by adding this to the given buffer.
* @param aCString is a ptr to cstring to be added to this
* @return newly created string
*/
nsString1 operator+(const char* aCString);
nsString operator+(const char* aCString);
/**
* create a new string by adding this to the given char.
* @param aChar is a char to be added to this
* @return newly created string
*/
nsString1 operator+(char aChar);
nsString operator+(char aChar);
/**
* create a new string by adding this to the given buffer.
* @param aStr unichar buffer to be added to this
* @return newly created string
*/
nsString1 operator+(const PRUnichar* aBuffer);
nsString operator+(const PRUnichar* aBuffer);
/**
* create a new string by adding this to the given char.
* @param aChar is a unichar to be added to this
* @return newly created string
*/
nsString1 operator+(PRUnichar aChar);
nsString operator+(PRUnichar aChar);
/**
* Converts all chars in internal string to lower
@@ -230,7 +218,7 @@ void ToLowerCase();
/**
* Converts all chars in given string to lower
*/
void ToLowerCase(nsString1& aString) const;
void ToLowerCase(nsString& aString) const;
/**
* Converts all chars in given string to upper
@@ -246,13 +234,13 @@ void ToUCS2(PRInt32 aStartOffset);
/**
* Converts all chars in internal string to upper
*/
void ToUpperCase(nsString1& aString) const;
void ToUpperCase(nsString& aString) const;
/**
* Creates a duplicate clone (ptr) of this string.
* @return ptr to clone of this string
*/
nsString1* ToNewString() const;
nsString* ToNewString() const;
/**
* Creates an ascii clone of this string
@@ -274,7 +262,7 @@ char* ToCString(char* aBuf,PRInt32 aBufLength) const;
* @param aString to hold copy of this
* @return nada.
*/
void Copy(nsString1& aString) const;
void Copy(nsString& aString) const;
/**
* Creates an unichar clone of this string
@@ -307,72 +295,79 @@ PRInt32 ToInteger(PRInt32* aErrorCode,PRInt32 aRadix=10) const;
if you want me to determine its length
* @return this
*/
nsString1& SetString(const PRUnichar* aStr,PRInt32 aLength=-1);
nsString1& SetString(const char* aCString,PRInt32 aLength=-1);
nsString1& SetString(const nsString1& aString);
nsString& SetString(const PRUnichar* aStr,PRInt32 aLength=-1);
/**
* assign given char* to this string
* @param aCString: buffer to be assigned to this
* @param alength is the length of the given str (or -1)
if you want me to determine its length
* @return this
*/
nsString& SetString(const char* aCString,PRInt32 aLength=-1);
/**
* assign given string to this one
* @param aString: string to be added to this
* @return this
*/
nsString1& operator=(const nsString1& aString);
nsString& operator=(const nsString& aString);
/**
* assign given char* to this string
* @param aCString: buffer to be assigned to this
* @return this
*/
nsString1& operator=(const char* aCString);
nsString& operator=(const char* aCString);
/**
* assign given char to this string
* @param aChar: char to be assignd to this
* @return this
*/
nsString1& operator=(char aChar);
nsString& operator=(char aChar);
/**
* assign given unichar* to this string
* @param aBuffer: unichar buffer to be assigned to this
* @return this
*/
nsString1& operator=(const PRUnichar* aBuffer);
nsString& operator=(const PRUnichar* aBuffer);
/**
* assign given char to this string
* @param aChar: char to be assignd to this
* @return this
*/
nsString1& operator=(PRUnichar aChar);
nsString& operator=(PRUnichar aChar);
/**
* append given string to this string
* @param aString : string to be appended to this
* @return this
*/
nsString1& operator+=(const nsString1& aString);
nsString& operator+=(const nsString& aString);
/**
* append given buffer to this string
* @param aCString: buffer to be appended to this
* @return this
*/
nsString1& operator+=(const char* aCString);
nsString& operator+=(const char* aCString);
/**
* append given buffer to this string
* @param aBuffer: buffer to be appended to this
* @return this
*/
nsString1& operator+=(const PRUnichar* aBuffer);
nsString& operator+=(const PRUnichar* aBuffer);
/**
* append given char to this string
* @param aChar: char to be appended to this
* @return this
*/
nsString1& operator+=(PRUnichar aChar);
nsString& operator+=(PRUnichar aChar);
/**
* append given string to this string
@@ -381,7 +376,7 @@ nsString1& operator+=(PRUnichar aChar);
if you want me to determine its length
* @return this
*/
nsString1& Append(const nsString1& aString,PRInt32 aLength=-1);
nsString& Append(const nsString& aString,PRInt32 aLength=-1);
/**
* append given string to this string
@@ -390,14 +385,14 @@ nsString1& Append(const nsString1& aString,PRInt32 aLength=-1);
if you want me to determine its length
* @return this
*/
nsString1& Append(const char* aCString,PRInt32 aLength=-1);
nsString& Append(const char* aCString,PRInt32 aLength=-1);
/**
* append given string to this string
* @param aString : string to be appended to this
* @return this
*/
nsString1& Append(char aChar);
nsString& Append(char aChar);
/**
* append given unichar buffer to this string
@@ -406,14 +401,14 @@ nsString1& Append(char aChar);
if you want me to determine its length
* @return this
*/
nsString1& Append(const PRUnichar* aBuffer,PRInt32 aLength=-1);
nsString& Append(const PRUnichar* aBuffer,PRInt32 aLength=-1);
/**
* append given unichar character to this string
* @param aChar is the char to be appended to this
* @return this
*/
nsString1& Append(PRUnichar aChar);
nsString& Append(PRUnichar aChar);
/**
* Append an integer onto this string
@@ -421,14 +416,14 @@ nsString1& Append(PRUnichar aChar);
* @param aRadix specifies 8,10,16
* @return this
*/
nsString1& Append(PRInt32 aInteger,PRInt32 aRadix); //radix=8,10 or 16
nsString& Append(PRInt32 aInteger,PRInt32 aRadix); //radix=8,10 or 16
/**
* Append a float value onto this string
* @param aFloat is the float to be appended
* @return this
*/
nsString1& Append(float aFloat);
nsString& Append(float aFloat);
/*
* Copies n characters from this string to given string,
@@ -439,7 +434,7 @@ nsString1& Append(float aFloat);
* @param aCount -- number of chars to copy
* @return number of chars copied
*/
PRInt32 Left(nsString1& aCopy,PRInt32 aCount) const;
PRInt32 Left(nsString& aCopy,PRInt32 aCount) const;
/*
* Copies n characters from this string to given string,
@@ -451,7 +446,7 @@ PRInt32 Left(nsString1& aCopy,PRInt32 aCount) const;
* @param anOffset -- position where copying begins
* @return number of chars copied
*/
PRInt32 Mid(nsString1& aCopy,PRInt32 anOffset,PRInt32 aCount) const;
PRInt32 Mid(nsString& aCopy,PRInt32 anOffset,PRInt32 aCount) const;
/*
* Copies n characters from this string to given string,
@@ -462,7 +457,7 @@ PRInt32 Mid(nsString1& aCopy,PRInt32 anOffset,PRInt32 aCount) const;
* @param aCount -- number of chars to copy
* @return number of chars copied
*/
PRInt32 Right(nsString1& aCopy,PRInt32 aCount) const;
PRInt32 Right(nsString& aCopy,PRInt32 aCount) const;
/*
* This method inserts n chars from given string into this
@@ -473,7 +468,7 @@ PRInt32 Right(nsString1& aCopy,PRInt32 aCount) const;
* @param aCount -- number of chars to be copied from aCopy
* @return number of chars inserted into this.
*/
PRInt32 Insert(const nsString1& aCopy,PRInt32 anOffset,PRInt32 aCount=-1);
PRInt32 Insert(const nsString& aCopy,PRInt32 anOffset,PRInt32 aCount=-1);
/**
* Insert a single unicode char into this string at
@@ -493,7 +488,7 @@ PRInt32 Insert(PRUnichar aChar,PRInt32 anOffset);
* @param aCount -- number of chars to be cut
* @return *this
*/
nsString1& Cut(PRInt32 anOffset,PRInt32 aCount);
nsString& Cut(PRInt32 anOffset,PRInt32 aCount);
/**
* This method is used to remove all occurances of the
@@ -502,7 +497,7 @@ nsString1& Cut(PRInt32 anOffset,PRInt32 aCount);
* @param aSet -- characters to be cut from this
* @return *this
*/
nsString1& StripChars(const char* aSet);
nsString& StripChars(const char* aSet);
/**
* This method is used to replace all occurances of the
@@ -511,14 +506,14 @@ nsString1& StripChars(const char* aSet);
* @param
* @return *this
*/
nsString1& ReplaceChar(PRUnichar aSourceChar, PRUnichar aDestChar);
nsString& ReplaceChar(PRUnichar aSourceChar, PRUnichar aDestChar);
/**
* This method strips whitespace throughout the string
*
* @return this
*/
nsString1& StripWhitespace();
nsString& StripWhitespace();
/**
* This method trims characters found in aTrimSet from
@@ -528,7 +523,7 @@ nsString1& StripWhitespace();
* both ends
* @return this
*/
nsString1& Trim(const char* aSet,
nsString& Trim(const char* aSet,
PRBool aEliminateLeading=PR_TRUE,
PRBool aEliminateTrailing=PR_TRUE);
@@ -541,7 +536,7 @@ nsString1& Trim(const char* aSet,
* @param aEliminateTrailing controls stripping of trailing ws
* @return this
*/
nsString1& CompressWhitespace( PRBool aEliminateLeading=PR_TRUE,
nsString& CompressWhitespace( PRBool aEliminateLeading=PR_TRUE,
PRBool aEliminateTrailing=PR_TRUE);
/**
@@ -590,7 +585,7 @@ PRInt32 BinarySearch(PRUnichar aChar) const;
*/
PRInt32 Find(const char* aString) const;
PRInt32 Find(const PRUnichar* aString) const;
PRInt32 Find(const nsString1& aString) const;
PRInt32 Find(const nsString& aString) const;
/**
* Search for given char within this string
@@ -608,7 +603,7 @@ PRInt32 Find(PRUnichar aChar,PRInt32 offset=0) const;
* @return -1 if not found, else the offset in this
*/
PRInt32 FindCharInSet(const char* aString,PRInt32 anOffset=0) const;
PRInt32 FindCharInSet(nsString1& aString,PRInt32 anOffset=0) const;
PRInt32 FindCharInSet(nsString& aString,PRInt32 anOffset=0) const;
/**
* This method searches this string for the last character
@@ -618,7 +613,7 @@ PRInt32 FindCharInSet(nsString1& aString,PRInt32 anOffset=0) const;
* @return -1 if not found, else the offset in this
*/
PRInt32 RFindCharInSet(const char* aString,PRInt32 anOffset=0) const;
PRInt32 RFindCharInSet(nsString1& aString,PRInt32 anOffset=0) const;
PRInt32 RFindCharInSet(nsString& aString,PRInt32 anOffset=0) const;
/**
@@ -629,7 +624,7 @@ PRInt32 RFindCharInSet(nsString1& aString,PRInt32 anOffset=0) const;
*/
PRInt32 RFind(const char* aCString,PRBool aIgnoreCase=PR_FALSE) const;
PRInt32 RFind(const PRUnichar* aString,PRBool aIgnoreCase=PR_FALSE) const;
PRInt32 RFind(const nsString1& aString,PRBool aIgnoreCase=PR_FALSE) const;
PRInt32 RFind(const nsString& aString,PRBool aIgnoreCase=PR_FALSE) const;
/**
* This methods scans the string backwards, looking for the given char
@@ -650,7 +645,7 @@ PRInt32 RFind(PRUnichar aChar,PRBool aIgnoreCase=PR_FALSE) const;
* @param aIgnoreCase tells us how to treat case
* @return -1,0,1
*/
virtual PRInt32 Compare(const nsString1 &aString,PRBool aIgnoreCase=PR_FALSE) const;
virtual PRInt32 Compare(const nsString &aString,PRBool aIgnoreCase=PR_FALSE) const;
virtual PRInt32 Compare(const char *aString,PRBool aIgnoreCase=PR_FALSE,PRInt32 aLength=-1) const;
virtual PRInt32 Compare(const PRUnichar *aString,PRBool aIgnoreCase=PR_FALSE,PRInt32 aLength=-1) const;
@@ -659,7 +654,7 @@ virtual PRInt32 Compare(const PRUnichar *aString,PRBool aIgnoreCase=PR_FALSE,PRI
* @param aString is the string to be compared to this
* @return TRUE or FALSE
*/
PRBool operator==(const nsString1 &aString) const;
PRBool operator==(const nsString &aString) const;
PRBool operator==(const char *aString) const;
PRBool operator==(const PRUnichar* aString) const;
PRBool operator==(PRUnichar* aString) const;
@@ -669,7 +664,7 @@ PRBool operator==(PRUnichar* aString) const;
* @param aString is the string to be compared to this
* @return TRUE
*/
PRBool operator!=(const nsString1 &aString) const;
PRBool operator!=(const nsString &aString) const;
PRBool operator!=(const char *aString) const;
PRBool operator!=(const PRUnichar* aString) const;
@@ -678,7 +673,7 @@ PRBool operator!=(const PRUnichar* aString) const;
* @param aString is the string to be compared to this
* @return TRUE or FALSE
*/
PRBool operator<(const nsString1 &aString) const;
PRBool operator<(const nsString &aString) const;
PRBool operator<(const char *aString) const;
PRBool operator<(const PRUnichar* aString) const;
@@ -687,7 +682,7 @@ PRBool operator<(const PRUnichar* aString) const;
* @param aString is the string to be compared to this
* @return TRUE or FALSE
*/
PRBool operator>(const nsString1 &S) const;
PRBool operator>(const nsString &S) const;
PRBool operator>(const char *aCString) const;
PRBool operator>(const PRUnichar* aString) const;
@@ -696,7 +691,7 @@ PRBool operator>(const PRUnichar* aString) const;
* @param aString is the string to be compared to this
* @return TRUE or FALSE
*/
PRBool operator<=(const nsString1 &S) const;
PRBool operator<=(const nsString &S) const;
PRBool operator<=(const char *aCString) const;
PRBool operator<=(const PRUnichar* aString) const;
@@ -705,7 +700,7 @@ PRBool operator<=(const PRUnichar* aString) const;
* @param aString is the string to be compared to this
* @return TRUE or FALSE
*/
PRBool operator>=(const nsString1 &S) const;
PRBool operator>=(const nsString &S) const;
PRBool operator>=(const char* aCString) const;
PRBool operator>=(const PRUnichar* aString) const;
@@ -719,7 +714,7 @@ PRBool operator>=(const PRUnichar* aString) const;
* @param aLength -- optional length of given string.
* @return TRUE if equal
*/
PRBool Equals(const nsString1& aString) const;
PRBool Equals(const nsString& aString) const;
PRBool Equals(const char* aString,PRInt32 aLength=-1) const;
PRBool Equals(const nsIAtom *aAtom) const;
@@ -742,7 +737,7 @@ PRBool Equals(const PRUnichar* s1, const PRUnichar* s2) const;
* @param aLength -- optional length of given string.
* @return TRUE if equal
*/
PRBool EqualsIgnoreCase(const nsString1& aString) const;
PRBool EqualsIgnoreCase(const nsString& aString) const;
PRBool EqualsIgnoreCase(const char* aString,PRInt32 aLength=-1) const;
PRBool EqualsIgnoreCase(const nsIAtom *aAtom) const;
@@ -765,39 +760,37 @@ typedef PRUnichar chartype;
chartype* mStr;
PRInt32 mLength;
PRInt32 mCapacity;
#ifdef RICKG_DEBUG
static PRBool mSelfTested;
#endif
};
ostream& operator<<(ostream& os,nsString1& aString);
extern NS_BASE int fputs(const nsString1& aString, FILE* out);
ostream& operator<<(ostream& os,nsString& aString);
extern NS_BASE int fputs(const nsString& aString, FILE* out);
//----------------------------------------------------------------------
/**
* A version of nsString1 which is designed to be used as an automatic
* A version of nsString which is designed to be used as an automatic
* variable. It attempts to operate out of a fixed size internal
* buffer until too much data is added; then a dynamic buffer is
* allocated and grown as necessary.
*/
// XXX template this with a parameter for the size of the buffer?
class NS_BASE nsAutoString1 : public nsString1 {
class NS_BASE nsAutoString : public nsString {
public:
nsAutoString1();
nsAutoString1(const nsString1& other);
nsAutoString1(const nsAutoString1& other);
nsAutoString1(PRUnichar aChar);
nsAutoString1(const char* aCString);
nsAutoString1(const PRUnichar* us, PRInt32 uslen = -1);
virtual ~nsAutoString1();
nsAutoString();
nsAutoString(const nsString& other);
nsAutoString(const nsAutoString& other);
nsAutoString(PRUnichar aChar);
nsAutoString(const char* aCString);
nsAutoString(const PRUnichar* us, PRInt32 uslen = -1);
virtual ~nsAutoString();
nsAutoString1& operator=(const nsString1& aString) {nsString1::operator=(aString); return *this;}
nsAutoString1& operator=(const nsAutoString1& aString) {nsString1::operator=(aString); return *this;}
nsAutoString1& operator=(const char* aCString) {nsString1::operator=(aCString); return *this;}
nsAutoString1& operator=(char aChar) {nsString1::operator=(aChar); return *this;}
nsAutoString1& operator=(const PRUnichar* aBuffer) {nsString1::operator=(aBuffer); return *this;}
nsAutoString1& operator=(PRUnichar aChar) {nsString1::operator=(aChar); return *this;}
nsAutoString& operator=(const nsString& aString) {nsString::operator=(aString); return *this;}
nsAutoString& operator=(const nsAutoString& aString) {nsString::operator=(aString); return *this;}
nsAutoString& operator=(const char* aCString) {nsString::operator=(aCString); return *this;}
nsAutoString& operator=(char aChar) {nsString::operator=(aChar); return *this;}
nsAutoString& operator=(const PRUnichar* aBuffer) {nsString::operator=(aBuffer); return *this;}
nsAutoString& operator=(PRUnichar aChar) {nsString::operator=(aChar); return *this;}
virtual void SizeOf(nsISizeOfHandler* aHandler) const;
@@ -809,7 +802,7 @@ protected:
chartype mBuf[32];
};
ostream& operator<<(ostream& os,nsAutoString1& aString);
ostream& operator<<(ostream& os,nsAutoString& aString);
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,799 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
/***********************************************************************
MODULE NOTES:
This version of the nsString class offers many improvements over the
original version:
1. Wide and narrow chars
2. Allocators
3. Much smarter autostrings
4. Subsumable strings
5. Memory pools and recycling
***********************************************************************/
#ifndef _nsString2
#define _nsString2
#include "prtypes.h"
#include "nscore.h"
#include <iostream.h>
#include <stdio.h>
#include "nsCRT.h"
#include "nsStr.h"
#include <iostream.h>
#include <stdio.h>
#include "nsIAtom.h"
class nsISizeOfHandler;
#ifdef USE_STRING2
#define nsString2 nsString
#define nsAutoString2 nsAutoString
#endif
class NS_BASE nsSubsumeStr;
class NS_BASE nsString2 : public nsStr {
public:
/**
* Default constructor. Note that we actually allocate a small buffer
* to begin with. This is because the "philosophy" of the string class
* was to allow developers direct access to the underlying buffer for
* performance reasons.
*/
nsString2(eCharSize aCharSize=kDefaultCharSize,nsIMemoryAgent* anAgent=0);
/**
* This constructor accepts an isolatin string
* @param aCString is a ptr to a 1-byte cstr
*/
nsString2(const char* aCString,eCharSize aCharSize=kDefaultCharSize,nsIMemoryAgent* anAgent=0);
/**
* This constructor accepts a unichar string
* @param aCString is a ptr to a 2-byte cstr
*/
nsString2(const PRUnichar* aString,eCharSize aCharSize=kDefaultCharSize,nsIMemoryAgent* anAgent=0);
/**
* This is a copy constructor that accepts an nsStr
* @param reference to another nsString2
*/
nsString2(const nsStr&,eCharSize aCharSize=kDefaultCharSize,nsIMemoryAgent* anAgent=0);
/**
* This is our copy constructor
* @param reference to another nsString2
*/
nsString2(const nsString2& aString);
/**
* This constructor takes a subsumestr
* @param reference to subsumestr
*/
nsString2(nsSubsumeStr& aSubsumeStr);
/**
* Destructor
*
*/
virtual ~nsString2();
/**
* Retrieve the length of this string
* @return string length
*/
inline PRInt32 Length() const { return (PRInt32)mLength; }
/**
* Retrieve the size of this string
* @return string length
*/
virtual void SizeOf(nsISizeOfHandler* aHandler) const;
/**
* Call this method if you want to force a different string capacity
* @update gess7/30/98
* @param aLength -- contains new length for mStr
* @return
*/
void SetLength(PRUint32 aLength) {
SetCapacity(aLength);
}
/**
* Sets the new length of the string.
* @param aLength is new string length.
* @return nada
*/
void SetCapacity(PRUint32 aLength);
/**
* This method truncates this string to given length.
*
* @param anIndex -- new length of string
* @return nada
*/
void Truncate(PRInt32 anIndex=0);
/**
* Determine whether or not the characters in this
* string are in sorted order.
*
* @return TRUE if ordered.
*/
PRBool IsOrdered(void) const;
/**
* Determine whether or not the characters in this
* string are in store as 1 or 2 byte (unicode) strings.
*
* @return TRUE if ordered.
*/
PRBool IsUnicode(void) const {
PRBool result=PRBool(mCharSize==eTwoByte);
return result;
}
/**
* Determine whether or not this string has a length of 0
*
* @return TRUE if empty.
*/
PRBool IsEmpty(void) const {
return PRBool(0==mLength);
}
/**********************************************************************
Accessor methods...
*********************************************************************/
const char* GetBuffer(void) const;
const PRUnichar* GetUnicode(void) const;
/**
* Get nth character.
*/
PRUnichar operator[](PRUint32 anIndex) const;
PRUnichar CharAt(PRUint32 anIndex) const;
PRUnichar First(void) const;
PRUnichar Last(void) const;
PRBool SetCharAt(PRUnichar aChar,PRUint32 anIndex);
/**********************************************************************
String creation methods...
*********************************************************************/
/**
* Create a new string by appending given string to this
* @param aString -- 2nd string to be appended
* @return new string
*/
nsSubsumeStr operator+(const nsStr& aString);
/**
* Create a new string by appending given string to this
* @param aString -- 2nd string to be appended
* @return new string
*/
nsSubsumeStr operator+(const nsString2& aString);
/**
* create a new string by adding this to the given buffer.
* @param aCString is a ptr to cstring to be added to this
* @return newly created string
*/
nsSubsumeStr operator+(const char* aCString);
/**
* create a new string by adding this to the given wide buffer.
* @param aString is a ptr to UC-string to be added to this
* @return newly created string
*/
nsSubsumeStr operator+(const PRUnichar* aString);
/**
* create a new string by adding this to the given char.
* @param aChar is a char to be added to this
* @return newly created string
*/
nsSubsumeStr operator+(char aChar);
/**
* create a new string by adding this to the given char.
* @param aChar is a unichar to be added to this
* @return newly created string
*/
nsSubsumeStr operator+(PRUnichar aChar);
/**********************************************************************
Lexomorphic transforms...
*********************************************************************/
/**
* Converts all chars in given string to UCS2
* which ensure that the lower 256 chars are correct.
*/
void ToUCS2(PRUint32 aStartOffset);
/**
* Converts chars in this to lowercase
* @update gess 7/27/98
*/
void ToLowerCase();
/**
* Converts chars in this to lowercase, and
* stores them in aOut
* @update gess 7/27/98
* @param aOut is a string to contain result
*/
void ToLowerCase(nsString2& aString) const;
/**
* Converts chars in this to uppercase
* @update gess 7/27/98
*/
void ToUpperCase();
/**
* Converts chars in this to lowercase, and
* stores them in a given output string
* @update gess 7/27/98
* @param aOut is a string to contain result
*/
void ToUpperCase(nsString2& aString) const;
/**
* This method is used to remove all occurances of the
* characters found in aSet from this string.
*
* @param aSet -- characters to be cut from this
* @return *this
*/
nsString2& StripChars(const char* aSet);
/**
* This method strips whitespace throughout the string
*
* @return this
*/
nsString2& StripWhitespace();
/**
* swaps occurence of 1 string for another
*
* @return this
*/
nsString2& ReplaceChar(PRUnichar aSourceChar,PRUnichar aDestChar);
/**
* This method trims characters found in aTrimSet from
* either end of the underlying string.
*
* @param aTrimSet -- contains chars to be trimmed from
* both ends
* @return this
*/
nsString2& Trim(const char* aSet,PRBool aEliminateLeading=PR_TRUE,PRBool aEliminateTrailing=PR_TRUE);
/**
* This method strips whitespace from string.
* You can control whether whitespace is yanked from
* start and end of string as well.
*
* @param aEliminateLeading controls stripping of leading ws
* @param aEliminateTrailing controls stripping of trailing ws
* @return this
*/
nsString2& CompressSet(const char* aSet, char aChar, PRBool aEliminateLeading=PR_TRUE,PRBool aEliminateTrailing=PR_TRUE);
/**
* This method strips whitespace from string.
* You can control whether whitespace is yanked from
* start and end of string as well.
*
* @param aEliminateLeading controls stripping of leading ws
* @param aEliminateTrailing controls stripping of trailing ws
* @return this
*/
nsString2& CompressWhitespace( PRBool aEliminateLeading=PR_TRUE,PRBool aEliminateTrailing=PR_TRUE);
/**********************************************************************
string conversion methods...
*********************************************************************/
/**
* This method constructs a new nsString2 on the stack that is a copy
* of this string.
*
*/
nsString2* ToNewString() const;
/**
* Creates an ISOLatin1 clone of this string
* @return ptr to new isolatin1 string
*/
char* ToNewCString() const;
/**
* Creates a unicode clone of this string
* @return ptr to new unicode string
*/
PRUnichar* ToNewUnicode() const;
/**
* Copies data from internal buffer onto given char* buffer
* @param aBuf is the buffer where data is stored
* @param aBuflength is the max # of chars to move to buffer
* @return ptr to given buffer
*/
char* ToCString(char* aBuf,PRUint32 aBufLength) const;
/**
* Perform string to float conversion.
* @param aErrorCode will contain error if one occurs
* @return float rep of string value
*/
float ToFloat(PRInt32* aErrorCode) const;
/**
* Perform string to int conversion.
* @param aErrorCode will contain error if one occurs
* @return int rep of string value
*/
PRInt32 ToInteger(PRInt32* aErrorCode,PRUint32 aRadix=10) const;
/**********************************************************************
String manipulation methods...
*********************************************************************/
/**
* Functionally equivalent to assign or operator=
*
*/
nsString2& SetString(const char* aString,PRInt32 aLength=-1) {return Assign(aString,aLength);}
nsString2& SetString(const PRUnichar* aString,PRInt32 aLength=-1) {return Assign(aString,aLength);}
nsString2& SetString(const nsString2& aString,PRInt32 aLength=-1) {return Assign(aString,aLength);}
/**
* assign given string to this string
* @param aStr: buffer to be assigned to this
* @param alength is the length of the given str (or -1)
if you want me to determine its length
* @return this
*/
nsString2& Assign(const nsString2& aString,PRInt32 aCount=-1);
nsString2& Assign(const nsStr& aString,PRInt32 aCount=-1);
nsString2& Assign(const char* aString,PRInt32 aCount=-1);
nsString2& Assign(const PRUnichar* aString,PRInt32 aCount=-1);
nsString2& Assign(char aChar);
nsString2& Assign(PRUnichar aChar);
/**
* here come a bunch of assignment operators...
* @param aString: string to be added to this
* @return this
*/
nsString2& operator=(const nsString2& aString) {return Assign(aString);}
nsString2& operator=(const nsStr& aString) {return Assign(aString);}
nsString2& operator=(char aChar) {return Assign(aChar);}
nsString2& operator=(PRUnichar aChar) {return Assign(aChar);}
nsString2& operator=(const char* aCString) {return Assign(aCString);}
nsString2& operator=(const PRUnichar* aString) {return Assign(aString);}
nsString2& operator=(nsSubsumeStr& aSubsumeString);
/**
* Here's a bunch of append mehtods for varying types...
* @param aString : string to be appended to this
* @return this
*/
nsString2& operator+=(const nsStr& aString){return Append(aString,aString.mLength);}
nsString2& operator+=(const nsString2& aString){return Append(aString,aString.mLength);}
nsString2& operator+=(const char* aCString) {return Append(aCString);}
//nsString2& operator+=(char aChar){return Append(aChar);}
nsString2& operator+=(const PRUnichar* aUCString) {return Append(aUCString);}
nsString2& operator+=(PRUnichar aChar){return Append(aChar);}
/*
* Appends n characters from given string to this,
* This version computes the length of your given string
*
* @param aString is the source to be appended to this
* @return number of chars copied
*/
nsString2& Append(const nsStr& aString) {return Append(aString,aString.mLength);}
nsString2& Append(const nsString2& aString) {return Append(aString,aString.mLength);}
/*
* Appends n characters from given string to this,
*
* @param aString is the source to be appended to this
* @param aCount -- number of chars to copy
* @return number of chars copied
*/
nsString2& Append(const nsStr& aString,PRInt32 aCount);
nsString2& Append(const nsString2& aString,PRInt32 aCount);
nsString2& Append(const char* aString,PRInt32 aCount=-1);
nsString2& Append(const PRUnichar* aString,PRInt32 aCount=-1);
nsString2& Append(char aChar);
nsString2& Append(PRUnichar aChar);
nsString2& Append(PRInt32 aInteger,PRInt32 aRadix=10); //radix=8,10 or 16
nsString2& Append(float aFloat);
/*
* Copies n characters from this string to given string,
* starting at the leftmost offset.
*
*
* @param aCopy -- Receiving string
* @param aCount -- number of chars to copy
* @return number of chars copied
*/
PRUint32 Left(nsString2& aCopy,PRInt32 aCount) const;
/*
* Copies n characters from this string to given string,
* starting at the given offset.
*
*
* @param aCopy -- Receiving string
* @param aCount -- number of chars to copy
* @param anOffset -- position where copying begins
* @return number of chars copied
*/
PRUint32 Mid(nsString2& aCopy,PRUint32 anOffset,PRInt32 aCount) const;
/*
* Copies n characters from this string to given string,
* starting at rightmost char.
*
*
* @param aCopy -- Receiving string
* @param aCount -- number of chars to copy
* @return number of chars copied
*/
PRUint32 Right(nsString2& aCopy,PRInt32 aCount) const;
/*
* This method inserts n chars from given string into this
* string at str[anOffset].
*
* @param aCopy -- String to be inserted into this
* @param anOffset -- insertion position within this str
* @param aCount -- number of chars to be copied from aCopy
* @return number of chars inserted into this.
*/
nsString2& Insert(const nsString2& aCopy,PRUint32 anOffset,PRInt32 aCount=-1);
/**
* Insert a given string into this string at
* a specified offset.
*
* @param aString* to be inserted into this string
* @param anOffset is insert pos in str
* @return the number of chars inserted into this string
*/
nsString2& Insert(const char* aChar,PRUint32 anOffset,PRInt32 aCount=-1);
nsString2& Insert(const PRUnichar* aChar,PRUint32 anOffset,PRInt32 aCount=-1);
/**
* Insert a single char into this string at
* a specified offset.
*
* @param character to be inserted into this string
* @param anOffset is insert pos in str
* @return the number of chars inserted into this string
*/
//nsString2& Insert(char aChar,PRUint32 anOffset);
nsString2& Insert(PRUnichar aChar,PRUint32 anOffset);
/*
* This method is used to cut characters in this string
* starting at anOffset, continuing for aCount chars.
*
* @param anOffset -- start pos for cut operation
* @param aCount -- number of chars to be cut
* @return *this
*/
nsString2& Cut(PRUint32 anOffset,PRInt32 aCount);
/**********************************************************************
Searching methods...
*********************************************************************/
/**
* Search for given character within this string.
* This method does so by using a binary search,
* so your string HAD BETTER BE ORDERED!
*
* @param aChar is the unicode char to be found
* @return offset in string, or -1 (kNotFound)
*/
PRInt32 BinarySearch(PRUnichar aChar) const;
/**
* Search for given substring within this string
*
* @param aString is substring to be sought in this
* @return offset in string, or -1 (kNotFound)
*/
PRInt32 Find(const nsString2& aString,PRBool aIgnoreCase=PR_FALSE) const;
PRInt32 Find(const nsStr& aString,PRBool aIgnoreCase=PR_FALSE) const;
PRInt32 Find(const char* aString,PRBool aIgnoreCase=PR_FALSE) const;
PRInt32 Find(const PRUnichar* aString,PRBool aIgnoreCase=PR_FALSE) const;
PRInt32 Find(PRUnichar aChar,PRUint32 offset=0,PRBool aIgnoreCase=PR_FALSE) const;
/**
* This method searches this string for the first character
* found in the given string
* @param aString contains set of chars to be found
* @param anOffset tells us where to start searching in this
* @return -1 if not found, else the offset in this
*/
PRInt32 FindCharInSet(const char* aString,PRUint32 anOffset=0) const;
PRInt32 FindCharInSet(const PRUnichar* aString,PRUint32 anOffset=0) const;
PRInt32 FindCharInSet(const nsString2& aString,PRUint32 anOffset=0) const;
/**
* This method searches this string for the last character
* found in the given string
* @param aString contains set of chars to be found
* @param anOffset tells us where to start searching in this
* @return -1 if not found, else the offset in this
*/
PRInt32 RFindCharInSet(const char* aString,PRUint32 anOffset=0) const;
PRInt32 RFindCharInSet(const PRUnichar* aString,PRUint32 anOffset=0) const;
PRInt32 RFindCharInSet(const nsString2& aString,PRUint32 anOffset=0) const;
/**
* This methods scans the string backwards, looking for the given string
* @param aString is substring to be sought in this
* @param aIgnoreCase tells us whether or not to do caseless compare
* @return offset in string, or -1 (kNotFound)
*/
PRInt32 RFind(const char* aCString,PRBool aIgnoreCase=PR_FALSE) const;
PRInt32 RFind(const nsString2& aString,PRBool aIgnoreCase=PR_FALSE) const;
PRInt32 RFind(const nsStr& aString,PRBool aIgnoreCase=PR_FALSE) const;
PRInt32 RFind(const PRUnichar* aString,PRBool aIgnoreCase=PR_FALSE) const;
PRInt32 RFind(PRUnichar aChar,PRUint32 offset=0,PRBool aIgnoreCase=PR_FALSE) const;
/**********************************************************************
Comparison methods...
*********************************************************************/
/**
* Compares a given string type to this string.
* @update gess 7/27/98
* @param S is the string to be compared
* @param aIgnoreCase tells us how to treat case
* @return -1,0,1
*/
virtual PRInt32 Compare(const nsString2& aString,PRBool aIgnoreCase=PR_FALSE,PRInt32 aLength=-1) const;
virtual PRInt32 Compare(const nsStr &aString,PRBool aIgnoreCase=PR_FALSE,PRInt32 aLength=-1) const;
virtual PRInt32 Compare(const char* aString,PRBool aIgnoreCase=PR_FALSE,PRInt32 aLength=-1) const;
virtual PRInt32 Compare(const PRUnichar* aString,PRBool aIgnoreCase=PR_FALSE,PRInt32 aLength=-1) const;
/**
* These methods compare a given string type to this one
* @param aString is the string to be compared to this
* @return TRUE or FALSE
*/
PRBool operator==(const nsString2 &aString) const;
PRBool operator==(const nsStr &aString) const;
PRBool operator==(const char *aString) const;
PRBool operator==(const PRUnichar* aString) const;
/**
* These methods perform a !compare of a given string type to this
* @param aString is the string to be compared to this
* @return TRUE
*/
PRBool operator!=(const nsString2 &aString) const;
PRBool operator!=(const nsStr &aString) const;
PRBool operator!=(const char* aString) const;
PRBool operator!=(const PRUnichar* aString) const;
/**
* These methods test if a given string is < than this
* @param aString is the string to be compared to this
* @return TRUE or FALSE
*/
PRBool operator<(const nsString2 &aString) const;
PRBool operator<(const nsStr &aString) const;
PRBool operator<(const char* aString) const;
PRBool operator<(const PRUnichar* aString) const;
/**
* These methods test if a given string is > than this
* @param aString is the string to be compared to this
* @return TRUE or FALSE
*/
PRBool operator>(const nsString2 &aString) const;
PRBool operator>(const nsStr &S) const;
PRBool operator>(const char* aString) const;
PRBool operator>(const PRUnichar* aString) const;
/**
* These methods test if a given string is <= than this
* @param aString is the string to be compared to this
* @return TRUE or FALSE
*/
PRBool operator<=(const nsString2 &aString) const;
PRBool operator<=(const nsStr &S) const;
PRBool operator<=(const char* aString) const;
PRBool operator<=(const PRUnichar* aString) const;
/**
* These methods test if a given string is >= than this
* @param aString is the string to be compared to this
* @return TRUE or FALSE
*/
PRBool operator>=(const nsString2 &aString) const;
PRBool operator>=(const nsStr &S) const;
PRBool operator>=(const char* aString) const;
PRBool operator>=(const PRUnichar* aString) const;
/**
* Compare this to given string; note that we compare full strings here.
* The optional length argument just lets us know how long the given string is.
* If you provide a length, it is compared to length of this string as an
* optimization.
*
* @param aString -- the string to compare to this
* @param aLength -- optional length of given string.
* @return TRUE if equal
*/
PRBool Equals(const nsString2 &aString,PRBool aIgnoreCase=PR_FALSE) const;
PRBool Equals(const nsStr& aString,PRBool aIgnoreCase=PR_FALSE) const;
PRBool Equals(const char* aString,PRBool aIgnoreCase=PR_FALSE) const;
PRBool Equals(const char* aString,PRUint32 aCount,PRBool aIgnoreCase) const;
PRBool Equals(const PRUnichar* aString,PRBool aIgnoreCase=PR_FALSE) const;
PRBool Equals(const PRUnichar* aString,PRUint32 aCount,PRBool aIgnoreCase) const;
PRBool Equals(const nsIAtom* anAtom,PRBool aIgnoreCase) const;
PRBool Equals(const PRUnichar* s1, const PRUnichar* s2,PRBool aIgnoreCase=PR_FALSE) const;
PRBool EqualsIgnoreCase(const nsString2& aString) const;
PRBool EqualsIgnoreCase(const char* aString,PRInt32 aLength=-1) const;
PRBool EqualsIgnoreCase(const nsIAtom *aAtom) const;
PRBool EqualsIgnoreCase(const PRUnichar* s1, const PRUnichar* s2) const;
/**
* Determine if given char is a valid space character
*
* @param aChar is character to be tested
* @return TRUE if is valid space char
*/
static PRBool IsSpace(PRUnichar ch);
/**
* Determine if given char in valid alpha range
*
* @param aChar is character to be tested
* @return TRUE if in alpha range
*/
static PRBool IsAlpha(PRUnichar ch);
/**
* Determine if given char is valid digit
*
* @param aChar is character to be tested
* @return TRUE if char is a valid digit
*/
static PRBool IsDigit(PRUnichar ch);
static void Recycle(nsString2* aString);
static nsString2* CreateString(eCharSize aCharSize=eTwoByte);
virtual void DebugDump(ostream& aStream) const;
nsIMemoryAgent* mAgent;
};
extern NS_BASE int fputs(const nsString2& aString, FILE* out);
ostream& operator<<(ostream& os,nsString2& aString);
/**************************************************************
Here comes the AutoString class which uses internal memory
(typically found on the stack) for its default buffer.
If the buffer needs to grow, it gets reallocated on the heap.
**************************************************************/
class NS_BASE nsAutoString2 : public nsString2 {
public:
nsAutoString2(eCharSize aCharSize=kDefaultCharSize);
nsAutoString2(nsStr& anExtBuffer,const char* aCString);
nsAutoString2(const char* aCString,eCharSize aCharSize=kDefaultCharSize);
nsAutoString2(char* aCString,PRUint32 aLength,eCharSize aCharSize=kDefaultCharSize,PRBool assumeOwnership=PR_FALSE);
nsAutoString2(const PRUnichar* aString,eCharSize aCharSize=kDefaultCharSize);
nsAutoString2(PRUnichar* aString,PRUint32 aLength,eCharSize aCharSize=kDefaultCharSize,PRBool assumeOwnership=PR_FALSE);
nsAutoString2(const nsStr& aString,eCharSize aCharSize=kDefaultCharSize);
nsAutoString2(const nsString2& aString,eCharSize aCharSize=kDefaultCharSize);
nsAutoString2(const nsAutoString2& aString,eCharSize aCharSize=kDefaultCharSize);
nsAutoString2(nsSubsumeStr& aSubsumeStr);
nsAutoString2(PRUnichar aChar,eCharSize aCharSize=kDefaultCharSize);
virtual ~nsAutoString2();
nsAutoString2& operator=(const nsString2& aString) {nsString2::operator=(aString); return *this;}
nsAutoString2& operator=(const nsStr& aString) {nsString2::Assign(aString); return *this;}
nsAutoString2& operator=(const nsAutoString2& aString) {nsString2::operator=(aString); return *this;}
nsAutoString2& operator=(const char* aCString) {nsString2::operator=(aCString); return *this;}
nsAutoString2& operator=(char aChar) {nsString2::operator=(aChar); return *this;}
nsAutoString2& operator=(const PRUnichar* aBuffer) {nsString2::operator=(aBuffer); return *this;}
nsAutoString2& operator=(PRUnichar aChar) {nsString2::operator=(aChar); return *this;}
/**
* Retrieve the size of this string
* @return string length
*/
virtual void SizeOf(nsISizeOfHandler* aHandler) const;
char mBuffer[32];
};
/***************************************************************
The subsumestr class is very unusual.
It differs from a normal string in that it doesn't use normal
copy semantics when another string is assign to this.
Instead, it "steals" the contents of the source string.
This is very handy for returning nsString classes as part of
an operator+(...) for example, in that it cuts down the number
of copy operations that must occur.
You should probably not use this class unless you really know
what you're doing.
***************************************************************/
class NS_BASE nsSubsumeStr : public nsString2 {
public:
nsSubsumeStr(nsString2& aString);
nsSubsumeStr(nsStr& aString);
nsSubsumeStr(const PRUnichar* aString);
nsSubsumeStr(const char* aString);
};
#endif

View File

@@ -1,137 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
/*
The default implementation for nsIString.
*/
#include "nsIString.h"
#include "nsStr.h"
////////////////////////////////////////////////////////////////////////
static NS_DEFINE_IID(kIStringIID, NS_ISTRING_IID);
////////////////////////////////////////////////////////////////////////
class nsStringImpl : public nsIString
{
protected:
nsStr mStr;
public:
nsStringImpl();
virtual ~nsStringImpl();
// nsISupports interface
NS_DECL_ISUPPORTS
// nsIString interface
NS_IMETHOD Init(eCharSize aCharSize);
NS_IMETHOD SetStr(nsStr* aStr);
NS_IMETHOD GetStr(nsStr* aStr);
NS_IMETHOD GetImmutableStr(const nsStr** aStr);
};
////////////////////////////////////////////////////////////////////////
nsStringImpl::nsStringImpl()
{
NS_INIT_REFCNT();
nsStr::Initialize(mStr, kDefaultCharSize);
}
nsStringImpl::~nsStringImpl()
{
nsStr::Destroy(mStr);
}
PR_IMPLEMENT(nsresult)
NS_NewString(nsIString** aString)
{
NS_PRECONDITION(aString != nsnull, "null ptr");
if (! aString)
return NS_ERROR_NULL_POINTER;
nsStringImpl* s = new nsStringImpl();
if (! s)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(s);
*aString = s;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////
// nsISupports interface
NS_IMPL_ADDREF(nsStringImpl);
NS_IMPL_RELEASE(nsStringImpl);
NS_IMPL_QUERY_INTERFACE(nsStringImpl, kIStringIID);
////////////////////////////////////////////////////////////////////////
NS_IMETHODIMP
nsStringImpl::Init(eCharSize aCharSize)
{
nsStr::Initialize(mStr, aCharSize);
return NS_OK;
}
NS_IMETHODIMP
nsStringImpl::SetStr(nsStr* aStr)
{
NS_PRECONDITION(aStr != nsnull, "null ptr");
if (! aStr)
return NS_ERROR_NULL_POINTER;
nsStr::Assign(mStr, *aStr, 0, aStr->mLength);
return NS_OK;
}
NS_IMETHODIMP
nsStringImpl::GetStr(nsStr* aStr)
{
NS_PRECONDITION(aStr != nsnull, "null ptr");
if (! aStr)
return NS_ERROR_NULL_POINTER;
nsStr::Assign(*aStr, mStr, 0, mStr.mLength);
return NS_OK;
}
NS_IMETHODIMP
nsStringImpl::GetImmutableStr(const nsStr** aImmutableStr)
{
NS_PRECONDITION(aImmutableStr != nsnull, "null ptr");
if (! aImmutableStr)
return NS_ERROR_NULL_POINTER;
*aImmutableStr = &mStr;
return NS_OK;
}

View File

@@ -1,489 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsThread.h"
#include "prmem.h"
//#include <stdio.h>
PRUintn nsThread::kIThreadSelfIndex = 0;
////////////////////////////////////////////////////////////////////////////////
nsThread::nsThread()
: mThread(nsnull), mRunnable(nsnull), mDead(PR_FALSE)
{
NS_INIT_REFCNT();
}
nsresult
nsThread::Init(nsIRunnable* runnable,
PRUint32 stackSize,
PRThreadPriority priority,
PRThreadScope scope,
PRThreadState state)
{
mRunnable = runnable;
NS_ADDREF(mRunnable);
NS_ADDREF_THIS(); // released in nsThread::Exit
if (state == PR_JOINABLE_THREAD)
NS_ADDREF_THIS(); // released in nsThread::Join
mThread = PR_CreateThread(PR_USER_THREAD, Main, this,
priority, scope, state, stackSize);
// printf("%x %x (%d) create\n", this, mThread, mRefCnt);
if (mThread == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
nsThread::~nsThread()
{
// printf("%x %x (%d) destroy\n", this, mThread, mRefCnt);
NS_IF_RELEASE(mRunnable);
}
void
nsThread::Main(void* arg)
{
nsThread* self = (nsThread*)arg;
nsresult rv = NS_OK;
rv = self->RegisterThreadSelf();
NS_ASSERTION(rv == NS_OK, "failed to set thread self");
// printf("%x %x (%d) start run\n", self, self->mThread, self->mRefCnt);
rv = self->mRunnable->Run();
NS_ASSERTION(NS_SUCCEEDED(rv), "runnable failed");
PRThreadState state;
rv = self->GetState(&state);
// printf("%x %x (%d) end run\n", self, self->mThread, self->mRefCnt);
}
void
nsThread::Exit(void* arg)
{
nsThread* self = (nsThread*)arg;
nsresult rv = NS_OK;
self->mDead = PR_TRUE;
// printf("%x %x (%d) exit\n", self, self->mThread, self->mRefCnt - 1);
NS_RELEASE(self);
}
NS_IMPL_ISUPPORTS(nsThread, nsIThread::GetIID());
NS_IMETHODIMP
nsThread::Join()
{
// don't check for mDead here because nspr calls Exit (cleaning up
// thread-local storage) before they let us join with the thread
// printf("%x %x (%d) start join\n", this, mThread, mRefCnt);
PRStatus status = PR_JoinThread(mThread);
// XXX can't use NS_RELEASE here because the macro wants to set
// this to null (bad c++)
// printf("%x %x (%d) end join\n", this, mThread, mRefCnt);
if (status == PR_SUCCESS) {
this->Release(); // most likely the final release of this thread
return NS_OK;
}
else
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsThread::GetPriority(PRThreadPriority *result)
{
if (mDead)
return NS_ERROR_FAILURE;
*result = PR_GetThreadPriority(mThread);
return NS_OK;
}
NS_IMETHODIMP
nsThread::SetPriority(PRThreadPriority value)
{
if (mDead)
return NS_ERROR_FAILURE;
PR_SetThreadPriority(mThread, value);
return NS_OK;
}
NS_IMETHODIMP
nsThread::Interrupt()
{
if (mDead)
return NS_ERROR_FAILURE;
PRStatus status = PR_Interrupt(mThread);
return status == PR_SUCCESS ? NS_OK : NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsThread::GetScope(PRThreadScope *result)
{
if (mDead)
return NS_ERROR_FAILURE;
*result = PR_GetThreadScope(mThread);
return NS_OK;
}
NS_IMETHODIMP
nsThread::GetState(PRThreadState *result)
{
if (mDead)
return NS_ERROR_FAILURE;
*result = PR_GetThreadState(mThread);
return NS_OK;
}
NS_IMETHODIMP
nsThread::GetPRThread(PRThread* *result)
{
if (mDead)
return NS_ERROR_FAILURE;
*result = mThread;
return NS_OK;
}
NS_BASE nsresult
NS_NewThread(nsIThread* *result,
nsIRunnable* runnable,
PRUint32 stackSize,
PRThreadPriority priority,
PRThreadScope scope,
PRThreadState state)
{
nsresult rv;
nsThread* thread = new nsThread();
if (thread == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
rv = thread->Init(runnable, stackSize, priority, scope, state);
if (NS_FAILED(rv)) {
delete thread;
return rv;
}
NS_ADDREF(thread);
*result = thread;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
nsresult
nsThread::RegisterThreadSelf()
{
PRStatus status;
if (kIThreadSelfIndex == 0) {
status = PR_NewThreadPrivateIndex(&kIThreadSelfIndex, Exit);
if (status != PR_SUCCESS) return NS_ERROR_FAILURE;
NS_ASSERTION(kIThreadSelfIndex != 0, "couldn't get thread private index");
}
status = PR_SetThreadPrivate(kIThreadSelfIndex, this);
if (status != PR_SUCCESS) return NS_ERROR_FAILURE;
return NS_OK;
}
NS_BASE nsresult
nsIThread::GetCurrent(nsIThread* *result)
{
return GetIThread(PR_CurrentThread(), result);
}
NS_BASE nsresult
nsIThread::GetIThread(PRThread* prthread, nsIThread* *result)
{
PRStatus status;
nsThread* thread;
if (nsThread::kIThreadSelfIndex == 0) {
status = PR_NewThreadPrivateIndex(&nsThread::kIThreadSelfIndex, nsThread::Exit);
if (status != PR_SUCCESS) return NS_ERROR_FAILURE;
NS_ASSERTION(nsThread::kIThreadSelfIndex != 0, "couldn't get thread private index");
}
thread = (nsThread*)PR_GetThreadPrivate(nsThread::kIThreadSelfIndex);
if (thread == nsnull) {
// if the current thread doesn't have an nsIThread associated
// with it, make one
thread = new nsThread();
if (thread == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(thread);
thread->SetPRThread(prthread);
nsresult rv = thread->RegisterThreadSelf();
if (NS_FAILED(rv)) return rv;
}
NS_ADDREF(thread);
*result = thread;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
nsThreadPool::nsThreadPool(PRUint32 minThreads, PRUint32 maxThreads)
: mThreads(nsnull), mRequests(nsnull),
mMinThreads(minThreads), mMaxThreads(maxThreads), mShuttingDown(PR_FALSE)
{
NS_INIT_REFCNT();
}
nsresult
nsThreadPool::Init(PRUint32 stackSize,
PRThreadPriority priority,
PRThreadScope scope)
{
nsresult rv;
rv = NS_NewISupportsArray(&mThreads);
if (NS_FAILED(rv)) return rv;
rv = NS_NewISupportsArray(&mRequests);
if (NS_FAILED(rv)) return rv;
mRequestMonitor = PR_NewMonitor();
if (mRequestMonitor == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
PR_CEnterMonitor(this);
for (PRUint32 i = 0; i < mMinThreads; i++) {
nsThreadPoolRunnable* runnable =
new nsThreadPoolRunnable(this);
if (runnable == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(runnable);
nsIThread* thread;
rv = NS_NewThread(&thread, runnable, stackSize, priority, scope,
PR_JOINABLE_THREAD); // needed for Shutdown
NS_RELEASE(runnable);
if (NS_FAILED(rv)) goto exit;
rv = mThreads->AppendElement(thread) ? NS_OK : NS_ERROR_FAILURE;
NS_RELEASE(thread);
if (NS_FAILED(rv)) goto exit;
}
// wait for some worker thread to be ready
PR_CWait(this, PR_INTERVAL_NO_TIMEOUT);
exit:
PR_CExitMonitor(this);
return rv;
}
nsThreadPool::~nsThreadPool()
{
if (mThreads) {
Shutdown();
NS_RELEASE(mThreads);
}
NS_IF_RELEASE(mRequests);
if (mRequestMonitor) {
PR_DestroyMonitor(mRequestMonitor);
}
}
NS_IMPL_ISUPPORTS(nsThreadPool, nsIThreadPool::GetIID());
NS_IMETHODIMP
nsThreadPool::DispatchRequest(nsIRunnable* runnable)
{
nsresult rv;
PR_EnterMonitor(mRequestMonitor);
if (mShuttingDown) {
rv = NS_ERROR_FAILURE;
}
else {
// XXX for now AppendElement returns a PRBool
rv = ((PRBool) mRequests->AppendElement(runnable)) ? NS_OK : NS_ERROR_FAILURE;
if (NS_SUCCEEDED(rv))
PR_Notify(mRequestMonitor);
}
PR_ExitMonitor(mRequestMonitor);
return rv;
}
nsIRunnable*
nsThreadPool::GetRequest()
{
nsresult rv = NS_OK;
nsIRunnable* request = nsnull;
PR_EnterMonitor(mRequestMonitor);
PRUint32 cnt;
while (PR_TRUE) {
rv = mRequests->Count(&cnt);
if (NS_FAILED(rv) || cnt != 0)
break;
if (mShuttingDown) {
rv = NS_ERROR_FAILURE;
break;
}
// printf("thread %x waiting\n", PR_CurrentThread());
PRStatus status = PR_Wait(mRequestMonitor, PR_INTERVAL_NO_TIMEOUT);
if (status != PR_SUCCESS || mShuttingDown) {
rv = NS_ERROR_FAILURE;
break;
}
}
if (NS_SUCCEEDED(rv)) {
NS_ASSERTION((NS_SUCCEEDED(mRequests->Count(&cnt)) && cnt > 0),
"request queue out of sync");
request = (nsIRunnable*)(*mRequests)[0];
NS_ASSERTION(request != nsnull, "null runnable");
PRBool removed = mRequests->RemoveElementAt(0);
NS_ASSERTION(removed, "nsISupportsArray broken");
}
PR_ExitMonitor(mRequestMonitor);
return request;
}
NS_IMETHODIMP
nsThreadPool::ProcessPendingRequests()
{
nsresult rv;
PR_CEnterMonitor(this);
while (PR_TRUE) {
PRUint32 cnt;
rv = mRequests->Count(&cnt);
if (NS_FAILED(rv) || cnt == 0)
break;
PRStatus status = PR_CWait(this, PR_INTERVAL_NO_TIMEOUT);
if (status != PR_SUCCESS) {
rv = NS_ERROR_FAILURE; // our thread was interrupted!
break;
}
}
PR_CExitMonitor(this);
return rv;
}
NS_IMETHODIMP
nsThreadPool::Shutdown()
{
nsresult rv = NS_OK;
PRUint32 count = 0;
PRUint32 i;
mShuttingDown = PR_TRUE;
ProcessPendingRequests();
// then interrupt the threads and join them
rv = mThreads->Count(&count);
NS_ASSERTION(NS_SUCCEEDED(rv), "Count failed");
for (i = 0; i < count; i++) {
nsIThread* thread = (nsIThread*)((*mThreads)[0]);
// we don't care about the error from Interrupt, because the
// thread may have already terminated its event loop
(void)thread->Interrupt();
rv = thread->Join();
// don't break out of the loop because of an error here
NS_ASSERTION(NS_SUCCEEDED(rv), "Join failed");
NS_RELEASE(thread);
rv = mThreads->RemoveElementAt(0);
// don't break out of the loop because of an error here
NS_ASSERTION(NS_SUCCEEDED(rv), "RemoveElementAt failed");
}
return rv;
}
NS_BASE nsresult
NS_NewThreadPool(nsIThreadPool* *result,
PRUint32 minThreads, PRUint32 maxThreads,
PRUint32 stackSize,
PRThreadPriority priority,
PRThreadScope scope)
{
nsresult rv;
nsThreadPool* pool = new nsThreadPool(minThreads, maxThreads);
if (pool == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
rv = pool->Init(stackSize, priority, scope);
if (NS_FAILED(rv)) {
delete pool;
return rv;
}
NS_ADDREF(pool);
*result = pool;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
nsThreadPoolRunnable::nsThreadPoolRunnable(nsThreadPool* pool)
: mPool(pool)
{
NS_INIT_REFCNT();
NS_ADDREF(mPool);
}
nsThreadPoolRunnable::~nsThreadPoolRunnable()
{
NS_RELEASE(mPool);
}
NS_IMPL_ISUPPORTS(nsThreadPoolRunnable, nsIRunnable::GetIID());
NS_IMETHODIMP
nsThreadPoolRunnable::Run()
{
nsresult rv = NS_OK;
nsIRunnable* request;
// let the thread pool know we're ready
PR_CEnterMonitor(mPool);
PR_CNotify(mPool);
PR_CExitMonitor(mPool);
while ((request = mPool->GetRequest()) != nsnull) {
// printf("running %x, thread %x\n", this, PR_CurrentThread());
rv = request->Run();
NS_ASSERTION(NS_SUCCEEDED(rv), "runnable failed");
// let the thread pool know we're finished a run
PR_CEnterMonitor(mPool);
PR_CNotify(mPool);
PR_CExitMonitor(mPool);
}
// printf("quitting %x, thread %x\n", this, PR_CurrentThread());
return rv;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,114 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsThread_h__
#define nsThread_h__
#include "nsIThread.h"
#include "nsISupportsArray.h"
#include "prcmon.h"
class nsThread : public nsIThread
{
public:
NS_DECL_ISUPPORTS
// nsIThread methods:
NS_IMETHOD Join();
NS_IMETHOD GetPriority(PRThreadPriority *result);
NS_IMETHOD SetPriority(PRThreadPriority value);
NS_IMETHOD Interrupt();
NS_IMETHOD GetScope(PRThreadScope *result);
NS_IMETHOD GetState(PRThreadState *result);
NS_IMETHOD GetPRThread(PRThread* *result);
// nsThread methods:
nsThread();
virtual ~nsThread();
nsresult Init(nsIRunnable* runnable,
PRUint32 stackSize,
PRThreadPriority priority,
PRThreadScope scope,
PRThreadState state);
nsresult RegisterThreadSelf();
void SetPRThread(PRThread* thread) { mThread = thread; }
static void Main(void* arg);
static void Exit(void* arg);
static PRUintn kIThreadSelfIndex;
protected:
PRThread* mThread;
nsIRunnable* mRunnable;
PRBool mDead;
};
////////////////////////////////////////////////////////////////////////////////
class nsThreadPool : public nsIThreadPool
{
public:
NS_DECL_ISUPPORTS
// nsIThreadPool methods:
NS_IMETHOD DispatchRequest(nsIRunnable* runnable);
NS_IMETHOD ProcessPendingRequests();
NS_IMETHOD Shutdown();
// nsThreadPool methods:
nsThreadPool(PRUint32 minThreads, PRUint32 maxThreads);
virtual ~nsThreadPool();
nsresult Init(PRUint32 stackSize,
PRThreadPriority priority,
PRThreadScope scope);
nsIRunnable* GetRequest();
protected:
nsISupportsArray* mThreads;
nsISupportsArray* mRequests;
PRMonitor* mRequestMonitor;
PRUint32 mMinThreads;
PRUint32 mMaxThreads;
PRBool mShuttingDown;
};
////////////////////////////////////////////////////////////////////////////////
class nsThreadPoolRunnable : public nsIRunnable
{
public:
NS_DECL_ISUPPORTS
// nsIRunnable methods:
NS_IMETHOD Run();
// nsThreadPoolRunnable methods:
nsThreadPoolRunnable(nsThreadPool* pool);
virtual ~nsThreadPoolRunnable();
protected:
nsThreadPool* mPool;
};
////////////////////////////////////////////////////////////////////////////////
#endif // nsThread_h__

View File

@@ -24,7 +24,7 @@
class UnicharBufferImpl : public nsIUnicharBuffer {
public:
UnicharBufferImpl(PRUint32 aBufferSize);
virtual ~UnicharBufferImpl();
~UnicharBufferImpl();
NS_DECL_ISUPPORTS
virtual PRInt32 GetLength() const;

View File

@@ -37,7 +37,7 @@ static NS_DEFINE_IID(kIUnicharInputStreamIID, NS_IUNICHAR_INPUT_STREAM_IID);
class StringUnicharInputStream : public nsIUnicharInputStream {
public:
StringUnicharInputStream(nsString* aString);
virtual ~StringUnicharInputStream();
~StringUnicharInputStream();
NS_DECL_ISUPPORTS
@@ -159,7 +159,7 @@ public:
ConverterInputStream(nsIInputStream* aStream,
nsIUnicodeDecoder* aConverter,
PRUint32 aBufSize);
virtual ~ConverterInputStream();
~ConverterInputStream();
NS_DECL_ISUPPORTS
NS_IMETHOD Read(PRUnichar* aBuf,

View File

@@ -1,233 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsIVariant.h"
#include "nsCRT.h"
#ifdef NS_DEBUG
#include "prprf.h"
#endif
class nsVariant : public nsIVariant {
public:
NS_DECL_ISUPPORTS
// nsIVariant methods:
NS_IMETHOD GetValue(nsVariantType *type, nsVariantValue *value);
NS_IMETHOD GetValue(nsVariantType expectedType, nsVariantValue *value);
NS_IMETHOD SetValue(nsVariantType type, nsVariantValue& value);
NS_IMETHOD Equals(nsISupports* other);
#ifdef NS_DEBUG
NS_IMETHOD GetDescription(char* *result);
#endif
// nsVariant methods:
nsVariant(nsVariantType type, nsVariantValue& value);
virtual ~nsVariant();
protected:
nsVariantType mType;
nsVariantValue mValue;
};
NS_IMPL_ISUPPORTS(nsVariant, nsIVariant::GetIID());
nsVariant::nsVariant(nsVariantType type, nsVariantValue& value)
: mType(type), mValue(value)
{
NS_INIT_REFCNT();
}
nsVariant::~nsVariant()
{
switch (mType) {
case nsVariantType_voidPtr:
/* XXX: Per comments from Warren, commenting this out.
This code isn't done (or used), and is a violation
of ANSI C++ to boot. -- Bruce */
/* delete (void *)mValue; */
break;
case nsVariantType_charPtr:
nsCRT::free(mValue.mUnion._charPtr);
break;
case nsVariantType_PRUnicharPtr:
nsCRT::free(mValue.mUnion._PRUnicharPtr);
break;
default:
break;
}
}
NS_IMETHODIMP
nsVariant::GetValue(nsVariantType *type, nsVariantValue *value)
{
NS_PRECONDITION(type && value, "no place to put the result");
*type = mType;
*value = mValue;
return NS_OK;
}
NS_IMETHODIMP
nsVariant::GetValue(nsVariantType expectedType, nsVariantValue *value)
{
NS_PRECONDITION(value, "no place to put the result");
if (mType != expectedType)
return NS_ERROR_FAILURE;
*value = mValue;
return NS_OK;
}
NS_IMETHODIMP
nsVariant::SetValue(nsVariantType type, nsVariantValue& value)
{
mType = type;
mValue = value;
return NS_OK;
}
NS_IMETHODIMP
nsVariant::Equals(nsISupports* other)
{
nsIVariant* otherVariant;
nsresult rv = other->QueryInterface(nsIVariant::GetIID(), (void**)&otherVariant);
if (NS_FAILED(rv)) return NS_COMFALSE;
nsVariantType otherType;
nsVariantValue otherValue;
rv = otherVariant->GetValue(&otherType, &otherValue);
if (NS_FAILED(rv)) return rv;
if (mType != otherType)
return NS_COMFALSE;
PRBool eq = PR_FALSE;
// this is gross, but I think it's the only way to compare unions:
switch (mType) {
case nsVariantType_PRBool:
eq = (PRBool)mValue == (PRBool)otherValue;
break;
case nsVariantType_PRInt16:
eq = (PRInt16)mValue == (PRInt16)otherValue;
break;
case nsVariantType_PRUint16:
eq = (PRUint16)mValue == (PRUint16)otherValue;
break;
case nsVariantType_PRInt32:
eq = (PRInt32)mValue == (PRInt32)otherValue;
break;
case nsVariantType_PRUint32:
eq = (PRUint32)mValue == (PRUint32)otherValue;
break;
case nsVariantType_PRInt64:
eq = LL_EQ((PRInt64)mValue, (PRInt64)otherValue);
break;
case nsVariantType_PRUint64:
eq = LL_EQ((PRUint64)mValue, (PRUint64)otherValue);
break;
case nsVariantType_float:
eq = (float)mValue == (float)otherValue;
break;
case nsVariantType_PRFloat64:
eq = (PRFloat64)mValue == (PRFloat64)otherValue;
break;
case nsVariantType_PRTime:
eq = LL_EQ((PRTime)mValue, (PRTime)otherValue);
break;
case nsVariantType_voidPtr:
eq = (void*)mValue == (void*)otherValue;
break;
case nsVariantType_charPtr:
// I hope this shouldn't be comparing pointers:
eq = nsCRT::strcmp((const char*)mValue, (const char*)otherValue) == 0;
break;
case nsVariantType_PRUnicharPtr:
// I hope this shouldn't be comparing pointers:
eq = nsCRT::strcmp((const PRUnichar*)mValue, (const PRUnichar*)otherValue) == 0;
break;
default:
NS_ERROR("unknown variant type");
}
return eq ? NS_OK : NS_COMFALSE;
}
#ifdef NS_DEBUG
NS_IMETHODIMP
nsVariant::GetDescription(char* *result)
{
char* desc;
switch (mType) {
case nsVariantType_PRBool:
desc = nsCRT::strdup((PRBool)mValue ? "true" : "false");
break;
case nsVariantType_PRInt16:
desc = PR_smprintf("%d", (PRInt16)mValue);
break;
case nsVariantType_PRUint16:
desc = PR_smprintf("%u", (PRUint16)mValue);
break;
case nsVariantType_PRInt32:
desc = PR_smprintf("%l", (PRInt32)mValue);
break;
case nsVariantType_PRUint32:
desc = PR_smprintf("%u", (PRUint32)mValue);
break;
case nsVariantType_PRInt64:
desc = PR_smprintf("%ll", (PRInt64)mValue);
break;
case nsVariantType_PRUint64:
desc = PR_smprintf("%ll", (PRUint64)mValue);
break;
case nsVariantType_float:
desc = PR_smprintf("%g", (float)mValue);
break;
case nsVariantType_PRFloat64:
desc = PR_smprintf("%lg", (PRFloat64)mValue);
break;
case nsVariantType_PRTime:
desc = PR_smprintf("%l", (PRTime)mValue);
break;
case nsVariantType_voidPtr:
desc = PR_smprintf("0x%x", (void*)mValue);
break;
case nsVariantType_charPtr:
desc = PR_smprintf("'%s'", (const char*)mValue);
break;
case nsVariantType_PRUnicharPtr:
desc = PR_smprintf("\"%s\"", (const PRUnichar*)mValue);
break;
default:
desc = PR_smprintf("<Variant 0x%x>", this);
}
*result = desc;
return NS_OK;
}
#endif
////////////////////////////////////////////////////////////////////////////////
NS_BASE nsresult
NS_NewIVariant(nsVariantType initialType, nsVariantValue& initialValue,
nsIVariant* *result)
{
nsVariant* v = new nsVariant(initialType, initialValue);
if (v == NULL)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(v);
*result = v;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -29,7 +29,7 @@ class NS_BASE nsVoidArray {
public:
nsVoidArray();
nsVoidArray(PRInt32 aCount); // initial count of aCount elements set to nsnull
virtual ~nsVoidArray();
~nsVoidArray();
nsVoidArray& operator=(const nsVoidArray& other);
@@ -80,7 +80,7 @@ class NS_BASE nsStringArray: protected nsVoidArray
{
public:
nsStringArray(void);
virtual ~nsStringArray(void);
~nsStringArray(void);
nsStringArray& operator=(const nsStringArray& other);

View File

@@ -27,14 +27,18 @@
#endif
#include "prtypes.h"
#ifdef __cplusplus
#include "nsDebug.h"
#endif
#ifndef __PRUNICHAR__
#define __PRUNICHAR__
typedef PRUint16 PRUnichar;
/** ucs2 datatype for 2 byte unicode characters */
typedef PRUint16 PRUcs2;
/** ucs4 datatype for 4 byte unicode characters */
typedef PRUint32 PRUcs4;
#ifdef NS_UCS4
typedef PRUcs4 PRUnichar;
#else
typedef PRUcs2 PRUnichar;
#endif
/// The preferred symbol for null.
@@ -70,7 +74,7 @@ typedef PRUint16 PRUnichar;
#undef NS_EXPORT_
#define NS_EXPORT __declspec(export)
#define NS_EXPORT_(type) __declspec(export) type
#define NS_EXPORT_(type) type __declspec(export)
#else
/* XXX do something useful? */

View File

@@ -1,42 +0,0 @@
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (the "NPL"); you may not use this file except in
# compliance with the NPL. You may obtain a copy of the NPL at
# http://www.mozilla.org/NPL/
#
# Software distributed under the NPL is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
# for the specific language governing rights and limitations under the
# NPL.
#
# The Initial Developer of this code under the NPL is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All Rights
# Reserved.
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
LIBRARY_NAME = gmbasephoton
MODULE=base
REQUIRES = xpcom raptor
DEFINES += -D_IMPL_NS_WIDGET
CPPSRCS = \
nsTimer.cpp \
nsCaretProperties.cpp \
$(NULL)
include $(topsrcdir)/config/config.mk
CXXFLAGS += $(TK_CFLAGS)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,40 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nscore.h"
#include "nsCaretProperties.h"
//-----------------------------------------------------------------------------
nsCaretProperties::nsCaretProperties()
: mCaretWidth(eDefaultCaretWidth)
, mBlinkRate(eDefaulBlinkRate)
{
// in your platform-specific class, get data from the OS in your constructor
//mBlinkRate = 0; // don't blink the caret
}
//-----------------------------------------------------------------------------
nsCaretProperties* NewCaretProperties()
{
return new nsCaretProperties();
}

View File

@@ -1,261 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsITimer.h"
#include "nsITimerCallback.h"
#include "nsCRT.h"
#include "prlog.h"
#include <stdio.h>
#include <limits.h>
#include <time.h>
#include <signal.h>
#include <errno.h>
static NS_DEFINE_IID(kITimerIID, NS_ITIMER_IID);
extern "C" int nsTimerExpired(void *aCallData);
/*
* Implementation of timers QNX/Neutrino timers.
*/
class TimerImpl : public nsITimer {
public:
public:
TimerImpl();
virtual ~TimerImpl();
virtual nsresult Init(nsTimerCallbackFunc aFunc,
void *aClosure,
PRUint32 aDelay);
virtual nsresult Init(nsITimerCallback *aCallback,
PRUint32 aDelay);
NS_DECL_ISUPPORTS
virtual void Cancel();
virtual PRUint32 GetDelay() { return mDelay; }
virtual void SetDelay(PRUint32 aDelay) { mDelay=aDelay; };
virtual void* GetClosure() { return mClosure; }
void FireTimeout();
private:
nsresult Init(PRUint32 aDelay);
nsresult SetupTimer(PRUint32 aDelay);
PRUint32 mDelay;
nsTimerCallbackFunc mFunc;
void *mClosure;
nsITimerCallback *mCallback;
TimerImpl *mNext;
timer_t mTimerId;
};
/*
* This method is called when the Delay/Duration expires
*/
void TimerImpl::FireTimeout()
{
printf("TimerImpl::FireTimeout called for %p. mFunc=<%p> and mCallback=<%p>\n", this, mFunc, mCallback);
if (mFunc != NULL)
{
(*mFunc)(this, mClosure);
}
else if (mCallback != NULL)
{
mCallback->Notify(this); // Fire the timer
}
}
TimerImpl::TimerImpl()
{
printf("TimerImpl::TimerImpl called for %p\n", this);
NS_INIT_REFCNT();
mFunc = NULL;
mCallback = NULL;
mNext = NULL;
mTimerId = 0;
mDelay = 0;
mClosure = NULL;
}
TimerImpl::~TimerImpl()
{
printf("TimerImpl::~TimerImpl called for %p\n", this);
Cancel();
NS_IF_RELEASE(mCallback);
}
nsresult
TimerImpl::SetupTimer(PRUint32 aDelay)
{
struct sigevent event;
struct itimerspec tv;
int err;
printf("TimerImpl::SetupTimer called with func %p\n", this);
event.sigev_notify=SIGEV_PULSE;
event.sigev_coid=0; /* REVISIT: Get the global Photon channel ID */
event.sigev_priority=0;
event.sigev_code=0;
event.sigev_value.sival_int=0;
err = timer_create(CLOCK_SOFTTIME,&event,&mTimerId);
if (err!=0)
{
printf ("Timer::SetupTimer() timer_create error:%d\n",errno);
return NS_ERROR_FAILURE;
}
printf ("Timer::Init() timer id: %d\n",mTimerId);
tv.it_interval.tv_sec=0;
tv.it_interval.tv_nsec=0;
tv.it_value.tv_sec=aDelay;
tv.it_value.tv_nsec=0;
err=timer_settime(mTimerId,0,&tv,0);
if (err!=0)
{
printf ("Timer::Init() timer_settime error:%d\n",errno);
return NS_ERROR_FAILURE;
}
return NS_OK;
}
nsresult
TimerImpl::Init(nsTimerCallbackFunc aFunc,
void *aClosure,
PRUint32 aDelay)
{
nsresult err;
printf("TimerImpl::Init called with func + closure for %p\n", this);
mFunc = aFunc;
mClosure = aClosure;
if ((aDelay > 10000) || (aDelay < 0))
{
printf("Timer::Init() called with bogus value \"%d\"! Not enabling timer.\n", aDelay);
return Init(aDelay);
}
#if 0
mTimerId = gtk_timeout_add(aDelay, nsTimerExpired, this);
#else
err = SetupTimer(aDelay);
if (err != NS_OK)
{
printf ("Timer::Init() timer_create error:%d\n",errno);
return NS_ERROR_FAILURE;
}
#endif
return Init(aDelay);
}
nsresult
TimerImpl::Init(nsITimerCallback *aCallback,
PRUint32 aDelay)
{
nsresult err;
printf("TimerImpl::Init called with callback only for %p\n", this);
mCallback = aCallback;
if ((aDelay > 10000) || (aDelay < 0))
{
printf("Timer::Init() called with bogus value \"%d\"! Not enabling timer.\n",
aDelay);
return Init(aDelay);
}
#if 0
mTimerId = gtk_timeout_add(aDelay, nsTimerExpired, this);
#else
err = SetupTimer(aDelay);
if (err != NS_OK)
{
printf ("Timer::Init() timer_create error:%d\n",errno);
return NS_ERROR_FAILURE;
}
#endif
return Init(aDelay);
}
nsresult
TimerImpl::Init(PRUint32 aDelay)
{
printf("TimerImpl::Init called with delay %d only for %p\n", aDelay, this);
mDelay = aDelay;
NS_ADDREF(this);
return NS_OK;
}
NS_IMPL_ISUPPORTS(TimerImpl, kITimerIID)
void
TimerImpl::Cancel()
{
int err;
printf("TimerImpl::Cancel called for %p\n", this);
TimerImpl *me = this;
if (mTimerId)
{
#if 0
gtk_timeout_remove(mTimerId);
#else
err = timer_delete(mTimerId);
#endif
}
}
NS_BASE nsresult NS_NewTimer(nsITimer** aInstancePtrResult)
{
NS_PRECONDITION(nsnull != aInstancePtrResult, "null ptr");
if (nsnull == aInstancePtrResult)
{
return NS_ERROR_NULL_POINTER;
}
TimerImpl *timer = new TimerImpl();
if (nsnull == timer)
{
return NS_ERROR_OUT_OF_MEMORY;
}
return timer->QueryInterface(kITimerIID, (void **) aInstancePtrResult);
}
int nsTimerExpired(void *aCallData)
{
printf("nsTimerExpired for %p\n", aCallData);
TimerImpl* timer = (TimerImpl *)aCallData;
timer->FireTimeout();
return 0;
}

View File

@@ -27,81 +27,75 @@
#include <stdlib.h>
#include <limits.h>
#include "nsError.h"
#include "prio.h" /* for PR_Rename */
#if defined(SCO_SV)
#define _SVID3 /* for statvfs.h */
#endif
#ifdef HAVE_SYS_STATVFS_H
#include <sys/statvfs.h>
#endif
#ifdef HAVE_SYS_VFS_H
#include <sys/vfs.h>
#endif
#ifdef HAVE_SYS_STATFS_H
#include <sys/statfs.h>
#endif
#ifdef HAVE_SYS_MOUNT_H
#include <sys/mount.h>
#endif
#ifdef HAVE_STATVFS
#define STATFS statvfs
#else
#define STATFS statfs
#endif
#if defined(SUNOS4)
#if defined(IRIX) || defined(OSF1) || defined(SOLARIS) || defined(UNIXWARE) || defined(SNI) || defined(NCR) || defined(NEC) || defined(DGUX)
#include <sys/statvfs.h> /* for statvfs() */
#define STATFS statvfs
#elif defined(SCO_SV)
#define _SVID3/* for statvfs.h */
#include <sys/statvfs.h> /* for statvfs() */
#define STATFS statvfs
#elif defined(HPUX)
#include <sys/vfs.h> /* for statfs() */
#define STATFS statfs
#elif defined(LINUX)
#include <sys/vfs.h> /* for statfs() */
#define STATFS statfs
#elif defined(SUNOS4)
#include <sys/vfs.h> /* for statfs() */
extern "C" int statfs(char *, struct statfs *);
#define STATFS statfs
#else
#if defined(BSDI) || defined(NETBSD) || defined(OPENBSD) || defined(RHAPSODY) || defined(FREEBSD)
#include <sys/mount.h>/* for statfs() */
#define STATFS statfs
#else
#include <sys/statfs.h> /* for statfs() */
#define STATFS statfs
extern "C" int statfs(char *, struct statfs *);
#endif
#endif
#if defined(OSF1)
extern "C" int statvfs(const char *, struct statvfs *);
#endif
//----------------------------------------------------------------------------------------
void nsFileSpecHelpers::Canonify(nsSimpleCharString& ioPath, PRBool inMakeDirs)
//----------------------------------------------------------------------------------------
void nsFileSpecHelpers::Canonify(char*& ioPath, PRBool inMakeDirs)
// Canonify, make absolute, and check whether directories exist
//----------------------------------------------------------------------------------------
{
if (ioPath.IsEmpty())
if (!ioPath)
return;
if (inMakeDirs)
{
const mode_t mode = 0700;
nsFileSpecHelpers::MakeAllDirectories((const char*)ioPath, mode);
nsFileSpecHelpers::MakeAllDirectories(ioPath, mode);
}
char buffer[MAXPATHLEN];
errno = 0;
#if defined(SOLARIS)
memset(buffer, '\0', sizeof(buffer)); // realpath reads it all, initialized or not.
#else
*buffer = '\0';
#endif
char* canonicalPath = realpath((const char*)ioPath, buffer);
char* canonicalPath = realpath(ioPath, buffer);
if (!canonicalPath)
{
// Linux's realpath() is pathetically buggy. If the reason for the nil
// result is just that the leaf does not exist, strip the leaf off,
// process that, and then add the leaf back.
nsSimpleCharString allButLeaf(ioPath);
if (allButLeaf.IsEmpty())
char* allButLeaf = nsFileSpecHelpers::StringDup(ioPath);
if (!allButLeaf)
return;
char* lastSeparator = strrchr((char*)allButLeaf, '/');
char* lastSeparator = strrchr(allButLeaf, '/');
if (lastSeparator)
{
*lastSeparator = '\0';
canonicalPath = realpath((const char*)allButLeaf, buffer);
canonicalPath = realpath(allButLeaf, buffer);
strcat(buffer, "/");
// Add back the leaf
strcat(buffer, ++lastSeparator);
}
delete [] allButLeaf;
}
if (!canonicalPath && ioPath[0] != '/' && !inMakeDirs)
if (!canonicalPath && *ioPath != '/' && !inMakeDirs)
{
// Well, if it's a relative path, hack it ourselves.
canonicalPath = realpath(".", buffer);
@@ -112,21 +106,21 @@ void nsFileSpecHelpers::Canonify(nsSimpleCharString& ioPath, PRBool inMakeDirs)
}
}
if (canonicalPath)
ioPath = canonicalPath;
nsFileSpecHelpers::StringAssign(ioPath, canonicalPath);
} // nsFileSpecHelpers::Canonify
//----------------------------------------------------------------------------------------
void nsFileSpec::SetLeafName(const char* inLeafName)
//----------------------------------------------------------------------------------------
{
mPath.LeafReplace('/', inLeafName);
nsFileSpecHelpers::LeafReplace(mPath, '/', inLeafName);
} // nsFileSpec::SetLeafName
//----------------------------------------------------------------------------------------
char* nsFileSpec::GetLeafName() const
//----------------------------------------------------------------------------------------
{
return mPath.GetLeaf('/');
return nsFileSpecHelpers::GetLeaf(mPath, '/');
} // nsFileSpec::GetLeafName
//----------------------------------------------------------------------------------------
@@ -134,7 +128,7 @@ PRBool nsFileSpec::Exists() const
//----------------------------------------------------------------------------------------
{
struct stat st;
return !mPath.IsEmpty() && 0 == stat(mPath, &st);
return 0 == stat(mPath, &st);
} // nsFileSpec::Exists
//----------------------------------------------------------------------------------------
@@ -142,7 +136,7 @@ void nsFileSpec::GetModDate(TimeStamp& outStamp) const
//----------------------------------------------------------------------------------------
{
struct stat st;
if (!mPath.IsEmpty() && stat(mPath, &st) == 0)
if (stat(mPath, &st) == 0)
outStamp = st.st_mtime;
else
outStamp = 0;
@@ -153,7 +147,7 @@ PRUint32 nsFileSpec::GetFileSize() const
//----------------------------------------------------------------------------------------
{
struct stat st;
if (!mPath.IsEmpty() && stat(mPath, &st) == 0)
if (stat(mPath, &st) == 0)
return (PRUint32)st.st_size;
return 0;
} // nsFileSpec::GetFileSize
@@ -163,7 +157,7 @@ PRBool nsFileSpec::IsFile() const
//----------------------------------------------------------------------------------------
{
struct stat st;
return !mPath.IsEmpty() && stat(mPath, &st) == 0 && S_ISREG(st.st_mode);
return 0 == stat(mPath, &st) && S_ISREG(st.st_mode);
} // nsFileSpec::IsFile
//----------------------------------------------------------------------------------------
@@ -171,33 +165,31 @@ PRBool nsFileSpec::IsDirectory() const
//----------------------------------------------------------------------------------------
{
struct stat st;
return !mPath.IsEmpty() && 0 == stat(mPath, &st) && S_ISDIR(st.st_mode);
return 0 == stat(mPath, &st) && S_ISDIR(st.st_mode);
} // nsFileSpec::IsDirectory
//----------------------------------------------------------------------------------------
void nsFileSpec::GetParent(nsFileSpec& outSpec) const
//----------------------------------------------------------------------------------------
{
outSpec.mPath = mPath;
char* chars = (char*)outSpec.mPath;
chars[outSpec.mPath.Length() - 1] = '\0'; // avoid trailing separator, if any
char* cp = strrchr(chars, '/');
if (cp++)
outSpec.mPath.SetLength(cp - chars); // truncate.
nsFileSpecHelpers::StringAssign(outSpec.mPath, mPath);
char* cp = strrchr(outSpec.mPath, '/');
if (cp)
*cp = '\0';
} // nsFileSpec::GetParent
//----------------------------------------------------------------------------------------
void nsFileSpec::operator += (const char* inRelativePath)
//----------------------------------------------------------------------------------------
{
if (!inRelativePath || mPath.IsEmpty())
if (!inRelativePath || !mPath)
return;
char endChar = mPath[(int)(strlen(mPath) - 1)];
char endChar = mPath[strlen(mPath) - 1];
if (endChar == '/')
mPath += "x";
nsFileSpecHelpers::ReallocCat(mPath, "x");
else
mPath += "/x";
nsFileSpecHelpers::ReallocCat(mPath, "/x");
SetLeafName(inRelativePath);
} // nsFileSpec::operator +=
@@ -206,8 +198,6 @@ void nsFileSpec::CreateDirectory(int mode)
//----------------------------------------------------------------------------------------
{
// Note that mPath is canonical!
if (mPath.IsEmpty())
return;
mkdir(mPath, mode);
} // nsFileSpec::CreateDirectory
@@ -228,31 +218,25 @@ void nsFileSpec::Delete(PRBool inRecursive) const
}
rmdir(mPath);
}
else if (!mPath.IsEmpty())
else
remove(mPath);
} // nsFileSpec::Delete
//----------------------------------------------------------------------------------------
nsresult nsFileSpec::Rename(const char* inNewName)
//----------------------------------------------------------------------------------------
{
// This function should not be used to move a file on disk.
if (mPath.IsEmpty() || strchr(inNewName, '/'))
if (strchr(inNewName, '/'))
return NS_FILE_FAILURE;
char* oldPath = nsCRT::strdup(mPath);
SetLeafName(inNewName);
if (PR_Rename(oldPath, mPath) != NS_OK)
if (PR_Rename(mPath, inNewName) != 0)
{
// Could not rename, set back to the original.
mPath = oldPath;
return NS_FILE_FAILURE;
}
nsCRT::free(oldPath);
SetLeafName(inNewName);
return NS_OK;
} // nsFileSpec::Rename
@@ -303,7 +287,9 @@ static int CrudeFileCopy(const char* in, const char* out)
fclose (ifp);
if (stat_result == 0)
{
chmod (out, in_stat.st_mode & 0777);
}
return 0;
} // nsFileSpec::Rename
@@ -318,38 +304,45 @@ nsresult nsFileSpec::Copy(const nsFileSpec& inParentDirectory) const
if (inParentDirectory.IsDirectory() && (! IsDirectory() ) )
{
char *leafname = GetLeafName();
nsSimpleCharString destPath(inParentDirectory.GetCString());
destPath += "/";
destPath += leafname;
nsCRT::free(leafname);
char* destPath = nsFileSpecHelpers::StringDup(
inParentDirectory.GetCString(),
strlen(inParentDirectory.GetCString()) + 1 + strlen(leafname));
strcat(destPath, "/");
strcat(destPath, leafname);
delete [] leafname;
result = NS_FILE_RESULT(CrudeFileCopy(GetCString(), destPath));
delete [] destPath;
}
return result;
} // nsFileSpec::Copy
//----------------------------------------------------------------------------------------
nsresult nsFileSpec::Move(const nsFileSpec& inNewParentDirectory)
nsresult nsFileSpec::Move(const nsFileSpec& inNewParentDirectory) const
//----------------------------------------------------------------------------------------
{
// We can only copy into a directory, and (for now) can not copy entire directories
nsresult result = NS_FILE_FAILURE;
if (inNewParentDirectory.IsDirectory() && !IsDirectory())
if (inNewParentDirectory.IsDirectory() && (! IsDirectory() ) )
{
char *leafname = GetLeafName();
nsSimpleCharString destPath(inNewParentDirectory.GetCString());
destPath += "/";
destPath += leafname;
nsCRT::free(leafname);
char* destPath
= nsFileSpecHelpers::StringDup(
inNewParentDirectory.GetCString(),
strlen(inNewParentDirectory.GetCString()) + 1 + strlen(leafname));
strcat(destPath, "/");
strcat(destPath, leafname);
delete [] leafname;
result = NS_FILE_RESULT(CrudeFileCopy(GetCString(), (const char*)destPath));
result = NS_FILE_RESULT(CrudeFileCopy(GetCString(), destPath));
if (result == NS_OK)
{
// cast to fix const-ness
((nsFileSpec*)this)->Delete(PR_FALSE);
*this = inNewParentDirectory + GetLeafName();
}
{
// cast to fix const-ness
((nsFileSpec*)this)->Delete(PR_FALSE);
}
delete [] destPath;
}
return result;
}
@@ -360,10 +353,15 @@ nsresult nsFileSpec::Execute(const char* inArgs ) const
{
nsresult result = NS_FILE_FAILURE;
if (!mPath.IsEmpty() && !IsDirectory())
if (! IsDirectory())
{
nsSimpleCharString fileNameWithArgs = mPath + " " + inArgs;
char* fileNameWithArgs
= nsFileSpecHelpers::StringDup(mPath, strlen(mPath) + 1 + strlen(inArgs));
strcat(fileNameWithArgs, " ");
strcat(fileNameWithArgs, inArgs);
result = NS_FILE_RESULT(system(fileNameWithArgs));
delete [] fileNameWithArgs;
}
return result;
@@ -375,14 +373,14 @@ PRUint32 nsFileSpec::GetDiskSpaceAvailable() const
//----------------------------------------------------------------------------------------
{
char curdir [MAXPATHLEN];
if (mPath.IsEmpty())
if (!mPath || !*mPath)
{
(void) getcwd(curdir, MAXPATHLEN);
if (!curdir)
return ULONG_MAX; /* hope for the best as we did in cheddar */
}
else
sprintf(curdir, "%.200s", (const char*)mPath);
sprintf(curdir, "%.200s", mPath);
struct STATFS fs_buf;
if (STATFS(curdir, &fs_buf) < 0)

View File

@@ -35,39 +35,37 @@
#endif
//----------------------------------------------------------------------------------------
void nsFileSpecHelpers::Canonify(nsSimpleCharString& ioPath, PRBool inMakeDirs)
void nsFileSpecHelpers::Canonify(char*& ioPath, PRBool inMakeDirs)
// Canonify, make absolute, and check whether directories exist. This
// takes a (possibly relative) native path and converts it into a
// fully qualified native path.
//----------------------------------------------------------------------------------------
{
if (ioPath.IsEmpty())
return;
if (!ioPath)
return;
NS_ASSERTION(strchr((const char*)ioPath, '/') == 0,
"This smells like a Unix path. Native path expected! "
"Please fix.");
if (inMakeDirs)
{
const int mode = 0700;
nsSimpleCharString unixStylePath = ioPath;
nsFileSpecHelpers::NativeToUnix(unixStylePath);
nsFileSpecHelpers::MakeAllDirectories((const char*)unixStylePath, mode);
}
char buffer[_MAX_PATH];
errno = 0;
*buffer = '\0';
char* canonicalPath = _fullpath(buffer, ioPath, _MAX_PATH);
if (inMakeDirs)
{
const int mode = 0700;
char* unixStylePath = nsFileSpecHelpers::StringDup(ioPath);
nsFileSpecHelpers::NativeToUnix(unixStylePath);
nsFileSpecHelpers::MakeAllDirectories(unixStylePath, mode);
delete[] unixStylePath;
}
char buffer[_MAX_PATH];
errno = 0;
*buffer = '\0';
char* canonicalPath = _fullpath(buffer, ioPath, _MAX_PATH);
NS_ASSERTION( canonicalPath[0] != '\0', "Uh oh...couldn't convert" );
if (canonicalPath[0] == '\0')
return;
NS_ASSERTION( canonicalPath[0] != '\0', "Uh oh...couldn't convert" );
if (canonicalPath[0] == '\0')
return;
ioPath = canonicalPath;
} // nsFileSpecHelpers::Canonify
nsFileSpecHelpers::StringAssign(ioPath, canonicalPath);
}
//----------------------------------------------------------------------------------------
void nsFileSpecHelpers::UnixToNative(nsSimpleCharString& ioPath)
void nsFileSpecHelpers::UnixToNative(char*& ioPath)
// This just does string manipulation. It doesn't check reality, or canonify, or
// anything
//----------------------------------------------------------------------------------------
@@ -75,49 +73,55 @@ void nsFileSpecHelpers::UnixToNative(nsSimpleCharString& ioPath)
// Allow for relative or absolute. We can do this in place, because the
// native path is never longer.
if (ioPath.IsEmpty())
if (!ioPath || !*ioPath)
return;
// Strip initial slash for an absolute path
char* src = (char*)ioPath;
if (*src == '/')
{
// Since it was an absolute path, check for the drive letter
char* colonPointer = src + 2;
if (strstr(src, "|/") == colonPointer)
*colonPointer = ':';
// allocate new string by copying from ioPath[1]
nsSimpleCharString temp = src + 1;
ioPath = temp;
}
src = (char*)ioPath;
// Convert '/' to '\'.
while (*++src)
char* src = ioPath;
if (*ioPath == '/')
{
if (*src == '/')
*src = '\\';
// Strip initial slash for an absolute path
src++;
}
} // nsFileSpecHelpers::UnixToNative
// Convert the vertical slash to a colon
char* cp = src + 1;
// If it was an absolute path, check for the drive letter
if (*ioPath == '/' && strstr(cp, "|/") == cp)
*cp = ':';
// Convert '/' to '\'.
while (*++cp)
{
if (*cp == '/')
*cp = '\\';
}
if (*ioPath == '/') {
for (cp = ioPath; *cp; ++cp)
*cp = *(cp + 1);
}
}
//----------------------------------------------------------------------------------------
void nsFileSpecHelpers::NativeToUnix(nsSimpleCharString& ioPath)
void nsFileSpecHelpers::NativeToUnix(char*& ioPath)
// This just does string manipulation. It doesn't check reality, or canonify, or
// anything. The unix path is longer, so we can't do it in place.
//----------------------------------------------------------------------------------------
{
if (ioPath.IsEmpty())
if (!ioPath || !*ioPath)
return;
// Convert the drive-letter separator, if present
nsSimpleCharString temp("/");
char* temp = nsFileSpecHelpers::StringDup("/", 1 + strlen(ioPath));
char* cp = (char*)ioPath + 1;
if (strstr(cp, ":\\") == cp)
char* cp = ioPath + 1;
if (strstr(cp, ":\\") == cp) {
*cp = '|'; // absolute path
else
temp[0] = '\0'; // relative path
}
else {
*temp = '\0'; // relative path
}
// Convert '\' to '/'
for (; *cp; cp++)
@@ -125,14 +129,17 @@ void nsFileSpecHelpers::NativeToUnix(nsSimpleCharString& ioPath)
if (*cp == '\\')
*cp = '/';
}
// Add the slash in front.
temp += ioPath;
ioPath = temp;
strcat(temp, ioPath);
StringAssign(ioPath, temp);
delete [] temp;
}
//----------------------------------------------------------------------------------------
nsFileSpec::nsFileSpec(const nsFilePath& inPath)
//----------------------------------------------------------------------------------------
: mPath(NULL)
{
*this = inPath;
}
@@ -141,7 +148,7 @@ nsFileSpec::nsFileSpec(const nsFilePath& inPath)
void nsFileSpec::operator = (const nsFilePath& inPath)
//----------------------------------------------------------------------------------------
{
mPath = (const char*)inPath;
nsFileSpecHelpers::StringAssign(mPath, (const char*)inPath);
nsFileSpecHelpers::UnixToNative(mPath);
mError = NS_OK;
} // nsFileSpec::operator =
@@ -149,6 +156,7 @@ void nsFileSpec::operator = (const nsFilePath& inPath)
//----------------------------------------------------------------------------------------
nsFilePath::nsFilePath(const nsFileSpec& inSpec)
//----------------------------------------------------------------------------------------
: mPath(NULL)
{
*this = inSpec;
} // nsFilePath::nsFilePath
@@ -157,7 +165,7 @@ nsFilePath::nsFilePath(const nsFileSpec& inSpec)
void nsFilePath::operator = (const nsFileSpec& inSpec)
//----------------------------------------------------------------------------------------
{
mPath = inSpec.mPath;
nsFileSpecHelpers::StringAssign(mPath, inSpec.mPath);
nsFileSpecHelpers::NativeToUnix(mPath);
} // nsFilePath::operator =
@@ -165,14 +173,14 @@ void nsFilePath::operator = (const nsFileSpec& inSpec)
void nsFileSpec::SetLeafName(const char* inLeafName)
//----------------------------------------------------------------------------------------
{
mPath.LeafReplace('\\', inLeafName);
nsFileSpecHelpers::LeafReplace(mPath, '\\', inLeafName);
} // nsFileSpec::SetLeafName
//----------------------------------------------------------------------------------------
char* nsFileSpec::GetLeafName() const
//----------------------------------------------------------------------------------------
{
return mPath.GetLeaf('\\');
return nsFileSpecHelpers::GetLeaf(mPath, '\\');
} // nsFileSpec::GetLeafName
//----------------------------------------------------------------------------------------
@@ -180,7 +188,7 @@ PRBool nsFileSpec::Exists() const
//----------------------------------------------------------------------------------------
{
struct stat st;
return !mPath.IsEmpty() && 0 == stat(nsNSPRPath(*this), &st);
return 0 == stat(mPath, &st);
} // nsFileSpec::Exists
//----------------------------------------------------------------------------------------
@@ -188,7 +196,7 @@ void nsFileSpec::GetModDate(TimeStamp& outStamp) const
//----------------------------------------------------------------------------------------
{
struct stat st;
if (!mPath.IsEmpty() && stat(nsNSPRPath(*this), &st) == 0)
if (stat(mPath, &st) == 0)
outStamp = st.st_mtime;
else
outStamp = 0;
@@ -199,7 +207,7 @@ PRUint32 nsFileSpec::GetFileSize() const
//----------------------------------------------------------------------------------------
{
struct stat st;
if (!mPath.IsEmpty() && stat(nsNSPRPath(*this), &st) == 0)
if (stat(mPath, &st) == 0)
return (PRUint32)st.st_size;
return 0;
} // nsFileSpec::GetFileSize
@@ -209,7 +217,7 @@ PRBool nsFileSpec::IsFile() const
//----------------------------------------------------------------------------------------
{
struct stat st;
return !mPath.IsEmpty() && 0 == stat(nsNSPRPath(*this), &st) && (_S_IFREG & st.st_mode);
return 0 == stat(mPath, &st) && (_S_IFREG & st.st_mode);
} // nsFileSpec::IsFile
//----------------------------------------------------------------------------------------
@@ -217,37 +225,36 @@ PRBool nsFileSpec::IsDirectory() const
//----------------------------------------------------------------------------------------
{
struct stat st;
return !mPath.IsEmpty() && 0 == stat(nsNSPRPath(*this), &st) && (_S_IFDIR & st.st_mode);
return 0 == stat(mPath, &st) && (_S_IFDIR & st.st_mode);
} // nsFileSpec::IsDirectory
//----------------------------------------------------------------------------------------
void nsFileSpec::GetParent(nsFileSpec& outSpec) const
//----------------------------------------------------------------------------------------
{
outSpec.mPath = mPath;
char* chars = (char*)outSpec.mPath;
chars[outSpec.mPath.Length() - 1] = '\0'; // avoid trailing separator, if any
char* cp = strrchr(chars, '\\');
if (cp++)
outSpec.mPath.SetLength(cp - chars); // truncate.
nsFileSpecHelpers::StringAssign(outSpec.mPath, mPath);
char* cp = strrchr(outSpec.mPath, '\\');
if (cp)
*cp = '\0';
} // nsFileSpec::GetParent
//----------------------------------------------------------------------------------------
void nsFileSpec::operator += (const char* inRelativePath)
//----------------------------------------------------------------------------------------
{
if (!inRelativePath || mPath.IsEmpty())
if (!inRelativePath || !mPath)
return;
if (mPath[mPath.Length() - 1] == '\\')
mPath += "x";
if (mPath[strlen(mPath) - 1] == '\\')
nsFileSpecHelpers::ReallocCat(mPath, "x");
else
mPath += "\\x";
nsFileSpecHelpers::ReallocCat(mPath, "\\x");
// If it's a (unix) relative path, make it native
nsSimpleCharString dosPath = inRelativePath;
char* dosPath = nsFileSpecHelpers::StringDup(inRelativePath);
nsFileSpecHelpers::UnixToNative(dosPath);
SetLeafName(dosPath);
delete [] dosPath;
} // nsFileSpec::operator +=
//----------------------------------------------------------------------------------------
@@ -255,8 +262,7 @@ void nsFileSpec::CreateDirectory(int /*mode*/)
//----------------------------------------------------------------------------------------
{
// Note that mPath is canonical!
if (!mPath.IsEmpty())
mkdir(nsNSPRPath(*this));
mkdir(mPath);
} // nsFileSpec::CreateDirectory
//----------------------------------------------------------------------------------------
@@ -273,11 +279,11 @@ void nsFileSpec::Delete(PRBool inRecursive) const
child.Delete(inRecursive);
}
}
rmdir(nsNSPRPath(*this));
rmdir(mPath);
}
else if (!mPath.IsEmpty())
else
{
remove(nsNSPRPath(*this));
remove(mPath);
}
} // nsFileSpec::Delete
@@ -290,19 +296,11 @@ nsresult nsFileSpec::Rename(const char* inNewName)
if (strchr(inNewName, '/'))
return NS_FILE_FAILURE;
char* oldPath = nsCRT::strdup(mPath);
SetLeafName(inNewName);
if (PR_Rename(oldPath, mPath) != NS_OK)
if (PR_Rename(*this, inNewName) != NS_OK)
{
// Could not rename, set back to the original.
mPath = oldPath;
return NS_FILE_FAILURE;
}
nsCRT::free(oldPath);
SetLeafName(inNewName);
return NS_OK;
} // nsFileSpec::Rename
@@ -311,60 +309,80 @@ nsresult nsFileSpec::Copy(const nsFileSpec& inParentDirectory) const
//----------------------------------------------------------------------------------------
{
// We can only copy into a directory, and (for now) can not copy entire directories
if (inParentDirectory.IsDirectory() && (! IsDirectory() ) )
{
char *leafname = GetLeafName();
nsSimpleCharString destPath(inParentDirectory.GetCString());
destPath += "\\";
destPath += leafname;
nsCRT::free(leafname);
char* destPath = nsFileSpecHelpers::StringDup(inParentDirectory, ( strlen(inParentDirectory) + 1 + strlen(leafname) ) );
strcat(destPath, "\\");
strcat(destPath, leafname);
delete [] leafname;
// CopyFile returns non-zero if succeeds
int copyOK = CopyFile(GetCString(), destPath, PR_TRUE);
int copyOK = CopyFile(*this, destPath, true);
delete[] destPath;
if (copyOK)
{
return NS_OK;
}
}
return NS_FILE_FAILURE;
} // nsFileSpec::Copy
//----------------------------------------------------------------------------------------
nsresult nsFileSpec::Move(const nsFileSpec& inNewParentDirectory)
nsresult nsFileSpec::Move(const nsFileSpec& nsNewParentDirectory) const
//----------------------------------------------------------------------------------------
{
// We can only copy into a directory, and (for now) can not copy entire directories
if (inNewParentDirectory.IsDirectory() && (! IsDirectory() ) )
if (nsNewParentDirectory.IsDirectory() && (! IsDirectory() ) )
{
char *leafname = GetLeafName();
nsSimpleCharString destPath(inNewParentDirectory.GetCString());
destPath += "\\";
destPath += leafname;
nsCRT::free(leafname);
char *destPath = nsFileSpecHelpers::StringDup(nsNewParentDirectory, ( strlen(nsNewParentDirectory) + 1 + strlen(leafname) ));
strcat(destPath, "\\");
strcat(destPath, leafname);
delete [] leafname;
// MoveFile returns non-zero if succeeds
int copyOK = MoveFile(GetCString(), destPath);
int copyOK = MoveFile(*this, destPath);
delete [] destPath;
if (copyOK)
{
*this = inNewParentDirectory + GetLeafName();
return NS_OK;
}
delete [] destPath;
}
return NS_FILE_FAILURE;
} // nsFileSpec::Move
//----------------------------------------------------------------------------------------
nsresult nsFileSpec::Execute(const char* inArgs ) const
//----------------------------------------------------------------------------------------
{
if (!IsDirectory())
{
if (! IsDirectory())
{
nsSimpleCharString fileNameWithArgs = mPath + " " + inArgs;
int execResult = WinExec( fileNameWithArgs, SW_NORMAL );
char* fileNameWithArgs = NULL;
fileNameWithArgs = nsFileSpecHelpers::StringDup(mPath, ( strlen(mPath) + 1 + strlen(inArgs) ) );
strcat(fileNameWithArgs, " ");
strcat(fileNameWithArgs, inArgs);
int execResult = WinExec( fileNameWithArgs, SW_NORMAL );
delete [] fileNameWithArgs;
if (execResult > 31)
{
return NS_OK;
}
}
return NS_FILE_FAILURE;
} // nsFileSpec::Execute
@@ -373,13 +391,13 @@ PRUint32 nsFileSpec::GetDiskSpaceAvailable() const
//----------------------------------------------------------------------------------------
{
char aDrive[_MAX_DRIVE + 2];
_splitpath( (const char*)mPath, aDrive, NULL, NULL, NULL);
_splitpath( mPath, aDrive, NULL, NULL, NULL);
if (aDrive[0] == '\0')
{
// The back end is always trying to pass us paths that look
// like /c|/netscape/mail. See if we've got one of them
if (mPath.Length() > 2 && mPath[0] == '/' && mPath[2] == '|')
if (strlen(mPath) > 2 && mPath[0] == '/' && mPath[2] == '|')
{
aDrive[0] = mPath[1];
aDrive[1] = ':';

View File

@@ -1,40 +0,0 @@
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (the "NPL"); you may not use this file except in
# compliance with the NPL. You may obtain a copy of the NPL at
# http://www.mozilla.org/NPL/
#
# Software distributed under the NPL is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
# for the specific language governing rights and limitations under the
# NPL.
#
# The Initial Developer of this code under the NPL is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All Rights
# Reserved.
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
LIBRARY_NAME = gmbasexlib
MODULE=base
REQUIRES = xpcom raptor
DEFINES += -D_IMPL_NS_WIDGET
CPPSRCS = nsTimerXlib.cpp \
nsCaretProperties.cpp
include $(topsrcdir)/config/config.mk
CXXFLAGS += $(TK_CFLAGS)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,33 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nscore.h"
#include "nsCaretProperties.h"
nsCaretProperties::nsCaretProperties()
:mCaretWidth(eDefaultCaretWidth),
mBlinkRate(eDefaulBlinkRate)
{
}
nsCaretProperties* NewCaretProperties()
{
return new nsCaretProperties();
}

View File

@@ -1,295 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include "nsITimer.h"
#include "nsITimerCallback.h"
#include "prlog.h"
static NS_DEFINE_IID(kITimerIID, NS_ITIMER_IID);
extern "C" int NS_TimeToNextTimeout(struct timeval *aTimer);
extern "C" void NS_ProcessTimeouts(void);
class TimerImpl : public nsITimer
{
public:
static TimerImpl *gTimerList;
static struct timeval gTimer;
static struct timeval gNextFire;
static void ProcessTimeouts(struct timeval *aNow);
TimerImpl();
~TimerImpl();
virtual nsresult Init(nsTimerCallbackFunc aFunc,
void *aClosure,
PRUint32 aDelay);
virtual nsresult Init(nsITimerCallback *aCallback,
PRUint32 aDelay);
NS_DECL_ISUPPORTS
virtual void Cancel();
void Fire(struct timeval *aNow);
virtual PRUint32 GetDelay() { return 0; };
virtual void SetDelay(PRUint32 aDelay) {};
virtual void *GetClosure() { return mClosure; }
// this needs to be public so that the mainloop can
// find the next fire time...
struct timeval mFireTime;
TimerImpl *mNext;
private:
nsresult Init(PRUint32 aDelay);
nsTimerCallbackFunc mFunc;
void *mClosure;
PRUint32 mDelay;
nsITimerCallback *mCallback;
};
TimerImpl *TimerImpl::gTimerList = NULL;
struct timeval TimerImpl::gTimer = {0, 0};
struct timeval TimerImpl::gNextFire = {0, 0};
TimerImpl::TimerImpl()
{
//printf("TimerImpl::TimerImpl (%p) called.\n",
//this);
NS_INIT_REFCNT();
mFunc = NULL;
mCallback = NULL;
mNext = NULL;
mClosure = NULL;
}
TimerImpl::~TimerImpl()
{
//printf("TimerImpl::~TimerImpl (%p) called.\n",
// this);
Cancel();
NS_IF_RELEASE(mCallback);
}
NS_IMPL_ISUPPORTS(TimerImpl, kITimerIID)
nsresult
TimerImpl::Init(nsTimerCallbackFunc aFunc,
void *aClosure,
PRUint32 aDelay)
{
mFunc = aFunc;
mClosure = aClosure;
return Init(aDelay);
}
nsresult
TimerImpl::Init(nsITimerCallback *aCallback,
PRUint32 aDelay)
{
mCallback = aCallback;
NS_ADDREF(mCallback);
return Init(aDelay);
}
nsresult
TimerImpl::Init(PRUint32 aDelay)
{
struct timeval Now;
// printf("TimerImpl::Init (%p) called with delay %d\n",
//this, aDelay);
// get the cuurent time
gettimeofday(&Now, NULL);
mFireTime.tv_sec = Now.tv_sec + (aDelay / 1000);
mFireTime.tv_usec = Now.tv_usec + (aDelay * 1000);
//printf("fire set to %ld / %ld\n",
//mFireTime.tv_sec, mFireTime.tv_usec);
// set the next pointer to nothing.
mNext = NULL;
// add ourself to the list
if (!gTimerList) {
// no list here. I'm the start!
//printf("This is the beginning of the list..\n");
gTimerList = this;
}
else {
// is it before everything else on the list?
if ((mFireTime.tv_sec < gTimerList->mFireTime.tv_sec) &&
(mFireTime.tv_usec < gTimerList->mFireTime.tv_usec)) {
// printf("This is before the head of the list...\n");
mNext = gTimerList;
gTimerList = this;
}
else {
TimerImpl *pPrev = gTimerList;
TimerImpl *pCurrent = gTimerList;
while (pCurrent && ((pCurrent->mFireTime.tv_sec <= mFireTime.tv_sec) &&
(pCurrent->mFireTime.tv_usec <= mFireTime.tv_usec))) {
pPrev = pCurrent;
pCurrent = pCurrent->mNext;
}
PR_ASSERT(pPrev);
// isnert it after pPrev ( this could be at the end of the list)
mNext = pPrev->mNext;
pPrev->mNext = this;
}
}
NS_ADDREF(this);
return NS_OK;
}
void
TimerImpl::Fire(struct timeval *aNow)
{
// printf("TimerImpl::Fire (%p) called at %ld / %ld\n",
// this,
//aNow->tv_sec, aNow->tv_usec);
if (mFunc != NULL) {
(*mFunc)(this, mClosure);
}
else if (mCallback != NULL) {
mCallback->Notify(this);
}
}
void
TimerImpl::Cancel()
{
TimerImpl *me = this;
TimerImpl *p;
// printf("TimerImpl::Cancel (%p) called.\n",
// this);
if (gTimerList == this) {
// first element in the list lossage...
gTimerList = mNext;
}
else {
// walk until there's no next pointer
for (p = gTimerList; p && p->mNext && (p->mNext != this); p = p->mNext)
;
// if we found something valid pull it out of the list
if (p && p->mNext && p->mNext == this) {
p->mNext = mNext;
}
else {
// get out before we delete something that looks bogus
return;
}
}
// if we got here it must have been a valid element so trash it
NS_RELEASE(me);
}
void
TimerImpl::ProcessTimeouts(struct timeval *aNow)
{
TimerImpl *p = gTimerList;
if (aNow->tv_sec == 0 &&
aNow->tv_usec == 0) {
gettimeofday(aNow, NULL);
}
// printf("TimerImpl::ProcessTimeouts called at %ld / %ld\n",
// aNow->tv_sec, aNow->tv_usec);
while (p) {
if ((p->mFireTime.tv_sec < aNow->tv_sec) ||
((p->mFireTime.tv_sec == aNow->tv_sec) &&
(p->mFireTime.tv_usec <= aNow->tv_usec))) {
// Make sure that the timer cannot be deleted during the
// Fire(...) call which may release *all* other references
// to p...
//printf("Firing timeout for (%p)\n",
// p);
NS_ADDREF(p);
p->Fire(aNow);
// Clear the timer.
// Period synced.
p->Cancel();
NS_RELEASE(p);
// Reset the loop (can't look at p->pNext now, and called
// code may have added/cleared timers).
// (could do this by going recursive and returning).
p = gTimerList;
}
else {
p = p->mNext;
}
}
}
NS_BASE nsresult NS_NewTimer(nsITimer **aInstancePtrResult)
{
NS_PRECONDITION(nsnull != aInstancePtrResult, "null ptr");
if (nsnull == aInstancePtrResult) {
return NS_ERROR_NULL_POINTER;
}
TimerImpl *timer = new TimerImpl();
if (nsnull == timer) {
return NS_ERROR_OUT_OF_MEMORY;
}
return timer->QueryInterface(kITimerIID, (void **) aInstancePtrResult);
}
int NS_TimeToNextTimeout(struct timeval *aTimer) {
TimerImpl *timer;
timer = TimerImpl::gTimerList;
if (timer) {
if ((timer->mFireTime.tv_sec < aTimer->tv_sec) ||
((timer->mFireTime.tv_sec == aTimer->tv_sec) &&
(timer->mFireTime.tv_usec <= aTimer->tv_usec))) {
aTimer->tv_sec = 0;
aTimer->tv_usec = 0;
return 1;
}
else {
aTimer->tv_sec -= timer->mFireTime.tv_sec;
// handle the overflow case
if (aTimer->tv_usec < timer->mFireTime.tv_usec) {
aTimer->tv_usec = timer->mFireTime.tv_usec - aTimer->tv_usec;
// make sure we don't go past zero when we decrement
if (aTimer->tv_sec)
aTimer->tv_sec--;
}
else {
aTimer->tv_usec -= timer->mFireTime.tv_usec;
}
return 1;
}
}
else {
return 0;
}
}
void NS_ProcessTimeouts(void) {
struct timeval now;
now.tv_sec = 0;
now.tv_usec = 0;
TimerImpl::ProcessTimeouts(&now);
}

View File

@@ -43,21 +43,18 @@ struct FilesTest
int CanonicalPath(const char* relativePath);
int Persistence(const char* relativePath);
int FileSpecEquality(const char *aFile, const char *bFile);
int FileSpecAppend(nsFileSpec& parent, const char* relativePath);
int Copy(const char* sourceFile, const char* targDir);
int Move(const char* sourceFile, const char* targDir);
int Rename(const char* sourceFile, const char* newName);
int Execute(const char* appName, const char* args);
int SpecialSystemDirectories();
int NSPRCompatibility(const char* sourceFile);
void Banner(const char* bannerString);
int Passed();
int Failed(const char* explanation = nsnull);
int Inspect();
void Inspect();
nsOutputConsoleStream mConsole;
};
@@ -93,11 +90,10 @@ int FilesTest::Failed(const char* explanation)
}
//----------------------------------------------------------------------------------------
int FilesTest::Inspect()
void FilesTest::Inspect()
//----------------------------------------------------------------------------------------
{
mConsole << nsEndl << "^^^^^^^^^^ PLEASE INSPECT OUTPUT FOR ERRORS" << nsEndl;
return 0; // for convenience
}
//----------------------------------------------------------------------------------------
@@ -114,15 +110,15 @@ void FilesTest::WriteStuff(nsOutputStream& s)
// Initialize a native file spec from a URL
nsFileSpec fileSpec(fileURL);
s << "As a file spec: " << fileSpec.GetNativePathCString() << nsEndl;
s << "As a file spec: " << fileSpec << nsEndl;
// Make the spec unique (this one has no suffix).
fileSpec.MakeUnique();
s << "Unique file spec: " << fileSpec.GetNativePathCString() << nsEndl;
s << "Unique file spec: " << fileSpec << nsEndl;
// Assign the spec to a URL
fileURL = fileSpec;
s << "File URL assigned from spec: \"" << fileURL.GetURLString() << "\""<< nsEndl;
s << "File URL assigned from spec: \"" << fileURL << "\""<< nsEndl;
// Assign a unix path using a string with a suffix.
filePath = "/Development/MPW/SysErrs.err";
@@ -130,20 +126,20 @@ void FilesTest::WriteStuff(nsOutputStream& s)
// Assign to a file spec using a unix path.
fileSpec = filePath;
s << "File spec reassigned to: " << fileSpec.GetNativePathCString() << nsEndl;
s << "File spec reassigned to: " << fileSpec << nsEndl;
// Make this unique (this one has a suffix).
fileSpec.MakeUnique();
s << "File spec made unique: " << fileSpec.GetNativePathCString() << nsEndl;
s << "File spec made unique: " << fileSpec << nsEndl;
} // WriteStuff
//----------------------------------------------------------------------------------------
int FilesTest::OutputStream(const char* relativeUnixPath)
int FilesTest::OutputStream(const char* relativePath)
//----------------------------------------------------------------------------------------
{
nsFilePath myTextFilePath(relativeUnixPath, PR_TRUE); // convert to full path.
nsFilePath myTextFilePath(relativePath, PR_TRUE); // relative path.
const char* pathAsString = (const char*)myTextFilePath;
nsFileSpec mySpec(myTextFilePath);
const char* pathAsString = (const char*)mySpec;
{
mConsole << "WRITING IDENTICAL OUTPUT TO " << pathAsString << nsEndl << nsEndl;
nsOutputFileStream testStream(mySpec);
@@ -168,7 +164,7 @@ int FilesTest::OutputStream(const char* relativeUnixPath)
<< nsEndl;
return -1;
}
FileSizeAndDate(relativeUnixPath);
FileSizeAndDate(relativePath);
return Passed();
}
@@ -312,7 +308,8 @@ int FilesTest::InputStream(const char* relativePath)
testStream2.readline(line, sizeof(line));
mConsole << line << nsEndl;
}
return Inspect();
Inspect();
return 0;
}
//----------------------------------------------------------------------------------------
@@ -348,16 +345,14 @@ int FilesTest::Parent(
mySpec.GetParent(outParent);
nsFilePath parentPath(outParent);
nsFileURL url(parentPath);
mConsole
<< "GetParent() on "
<< "\n\t" << pathAsString
<< "\n yields "
<< "\n\t" << (const char*)parentPath
<< "\n or as a URL"
<< "\n\t" << (const char*)url
<< nsEndl;
return Inspect();
Inspect();
return 0;
}
//----------------------------------------------------------------------------------------
@@ -429,18 +424,17 @@ int FilesTest::CreateDirectory(nsFileSpec& dirSpec)
int FilesTest::CreateDirectoryRecursive(const char* aPath)
//----------------------------------------------------------------------------------------
{
nsFilePath dirPath(aPath, PR_TRUE);
nsFileSpec dirSpec(aPath, PR_TRUE);
mConsole
<< "Testing nsFilePath(X, PR_TRUE) using"
<< "\n\t" << (const char*)aPath
<< nsEndl;
nsFileSpec spec(dirPath);
if (spec.Valid())
return Passed();
return Failed();
return Passed();
}
//----------------------------------------------------------------------------------------
int FilesTest::IterateDirectoryChildren(nsFileSpec& startChild)
//----------------------------------------------------------------------------------------
@@ -456,7 +450,7 @@ int FilesTest::IterateDirectoryChildren(nsFileSpec& startChild)
{
char* itemName = ((nsFileSpec&)i).GetLeafName();
mConsole << '\t' << itemName << nsEndl;
nsCRT::free(itemName);
delete [] itemName;
}
mConsole << "Backwards listing of " << (const char*)grandparentPath << ":" << nsEndl;
@@ -464,9 +458,10 @@ int FilesTest::IterateDirectoryChildren(nsFileSpec& startChild)
{
char* itemName = ((nsFileSpec&)j).GetLeafName();
mConsole << '\t' << itemName << nsEndl;
nsCRT::free(itemName);
delete [] itemName;
}
return Inspect();
Inspect();
return 0;
}
//----------------------------------------------------------------------------------------
@@ -478,7 +473,6 @@ int FilesTest::CanonicalPath(
const char* pathAsString = (const char*)myTextFilePath;
if (*pathAsString != '/')
{
#ifndef XP_PC
mConsole
<< "ERROR: after initializing the path object with a relative path,"
<< "\n the path consisted of the string "
@@ -486,43 +480,17 @@ int FilesTest::CanonicalPath(
<< "\n which is not a canonical full path!"
<< nsEndl;
return -1;
#endif
}
return Passed();
}
//----------------------------------------------------------------------------------------
int FilesTest::FileSpecAppend(nsFileSpec& parent, const char* relativePath)
//----------------------------------------------------------------------------------------
{
nsFilePath initialPath(parent);
const char* initialPathString = (const char*)initialPath;
mConsole << "Initial nsFileSpec:\n\t\"" << initialPathString << "\"" << nsEndl;
nsFileSpec fileSpec(initialPath);
mConsole << "Appending:\t\"" << relativePath << "\"" << nsEndl;
fileSpec += relativePath;
nsFilePath resultPath(fileSpec);
const char* resultPathString = (const char*)resultPath;
mConsole << "Result:\n\t\"" << resultPathString << "\"" << nsEndl;
return Inspect();
} // FilesTest::FileSpecAppend
//----------------------------------------------------------------------------------------
int FilesTest::FileSpecEquality(const char *aFile, const char *bFile)
//----------------------------------------------------------------------------------------
{
nsFilePath aFilePath(aFile, PR_TRUE);
nsFilePath bFilePath(bFile, PR_TRUE);
nsFileSpec aFileSpec(aFilePath);
nsFileSpec bFileSpec(bFilePath);
nsFileSpec cFileSpec(bFilePath); // this should == bFile
nsFileSpec aFileSpec(aFile, PR_FALSE);
nsFileSpec bFileSpec(bFile, PR_FALSE);
nsFileSpec cFileSpec(bFile, PR_FALSE); // this should == bFile
if (aFileSpec != bFileSpec &&
bFileSpec == cFileSpec )
@@ -531,35 +499,32 @@ int FilesTest::FileSpecEquality(const char *aFile, const char *bFile)
}
return Failed();
} // FilesTest::FileSpecEquality
}
//----------------------------------------------------------------------------------------
int FilesTest::Copy(const char* file, const char* dir)
//----------------------------------------------------------------------------------------
{
nsFileSpec dirPath(nsFilePath(dir, PR_TRUE));
nsFileSpec dirPath(dir, PR_TRUE);
dirPath.CreateDirectory();
if (! dirPath.Exists())
return Failed();
nsFileSpec mySpec(nsFilePath(file, PR_TRUE)); // relative path.
nsFileSpec mySpec(file, PR_TRUE); // relative path.
{
nsIOFileStream testStream(mySpec); // creates the file
// Scope ends here, file gets closed
}
nsFileSpec filePath(nsFilePath(file, PR_TRUE));
nsFileSpec filePath(file);
if (! filePath.Exists())
return Failed();
nsresult error = filePath.Copy(dirPath);
char* leafName = filePath.GetLeafName();
dirPath += leafName;
nsCRT::free(leafName);
dirPath += filePath.GetLeafName();
if (! dirPath.Exists() || ! filePath.Exists() || NS_FAILED(error))
return Failed();
@@ -570,14 +535,14 @@ int FilesTest::Copy(const char* file, const char* dir)
int FilesTest::Move(const char* file, const char* dir)
//----------------------------------------------------------------------------------------
{
nsFileSpec dirPath(nsFilePath(dir, PR_TRUE));
nsFileSpec dirPath(dir, PR_TRUE);
dirPath.CreateDirectory();
if (! dirPath.Exists())
return Failed();
nsFileSpec srcSpec(nsFilePath(file, PR_TRUE)); // relative path.
nsFileSpec srcSpec(file, PR_TRUE); // relative path.
{
nsIOFileStream testStream(srcSpec); // creates the file
// file gets closed here because scope ends here.
@@ -588,10 +553,9 @@ int FilesTest::Move(const char* file, const char* dir)
nsresult error = srcSpec.Move(dirPath);
char* leafName = srcSpec.GetLeafName();
dirPath += leafName;
nsCRT::free(leafName);
if (! dirPath.Exists() || ! srcSpec.Exists() || NS_FAILED(error))
dirPath += srcSpec.GetLeafName();
if (! dirPath.Exists() || srcSpec.Exists() || NS_FAILED(error))
return Failed();
return Passed();
@@ -601,80 +565,17 @@ int FilesTest::Move(const char* file, const char* dir)
int FilesTest::Execute(const char* appName, const char* args)
//----------------------------------------------------------------------------------------
{
mConsole << "Attempting to execute " << appName << nsEndl;
nsFileSpec appSpec(appName, PR_FALSE);
if (!appSpec.Exists())
nsFileSpec appPath(appName, PR_FALSE);
if (!appPath.Exists())
return Failed();
nsresult error = appSpec.Execute(args);
nsresult error = appPath.Execute(args);
if (NS_FAILED(error))
return Failed();
return Passed();
}
//----------------------------------------------------------------------------------------
int FilesTest::NSPRCompatibility(const char* relativeUnixFilePath)
//----------------------------------------------------------------------------------------
{
nsFilePath filePath(relativeUnixFilePath, PR_TRUE); // relative path
nsFileSpec createTheFileSpec(filePath);
{
nsIOFileStream testStream(createTheFileSpec); // creates the file
// file gets closed here because scope ends here.
};
PRFileDesc* fOut = NULL;
// From an nsFilePath
fOut = PR_Open( nsNSPRPath(filePath), PR_RDONLY, 0 );
if ( fOut == NULL )
{
return Failed();
}
else
{
PR_Close( fOut );
fOut = NULL;
}
// From an nsFileSpec
nsFileSpec fileSpec(filePath);
fOut = PR_Open( nsNSPRPath(fileSpec), PR_RDONLY, 0 );
if ( fOut == NULL )
{
return Failed();
}
else
{
PR_Close( fOut );
fOut = NULL;
}
// From an nsFileURL
nsFileURL fileURL(fileSpec);
fOut = PR_Open( nsNSPRPath(fileURL), PR_RDONLY, 0 );
if ( fOut == NULL )
{
return Failed();
}
else
{
PR_Close( fOut );
fOut = NULL;
}
return Passed();
}
//----------------------------------------------------------------------------------------
int FilesTest::SpecialSystemDirectories()
//----------------------------------------------------------------------------------------
@@ -689,7 +590,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "OS_DriveDirectory yields \t";
if (systemDir.Valid())
{
(nsOutputStream&)mConsole << systemDir.GetNativePathCString() << nsEndl;
(nsOutputStream)mConsole << systemDir << nsEndl;
}
else
{
@@ -701,7 +602,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "OS_TemporaryDirectory yields \t";
if (systemDir.Valid())
{
(nsOutputStream&)mConsole << systemDir.GetNativePathCString() << nsEndl;
(nsOutputStream)mConsole << systemDir << nsEndl;
}
else
{
@@ -713,7 +614,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "OS_CurrentProcessDirectory yields \t";
if (systemDir.Valid())
{
(nsOutputStream&)mConsole << systemDir.GetNativePathCString() << nsEndl;
(nsOutputStream)mConsole << systemDir << nsEndl;
}
else
{
@@ -726,7 +627,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "Mac_SystemDirectory yields \t";
if (systemDir.Valid())
{
mConsole << systemDir.GetNativePathCString() << nsEndl;
mConsole << systemDir << nsEndl;
}
else
{
@@ -738,7 +639,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "Mac_DesktopDirectory yields \t";
if (systemDir.Valid())
{
mConsole << systemDir.GetNativePathCString() << nsEndl;
mConsole << systemDir << nsEndl;
}
else
{
@@ -750,7 +651,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "Mac_TrashDirectory yields \t";
if (systemDir.Valid())
{
mConsole << systemDir.GetNativePathCString() << nsEndl;
mConsole << systemDir << nsEndl;
}
else
{
@@ -762,7 +663,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "Mac_StartupDirectory yields \t";
if (systemDir.Valid())
{
mConsole << systemDir.GetNativePathCString() << nsEndl;
mConsole << systemDir << nsEndl;
}
else
{
@@ -774,7 +675,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "Mac_ShutdownDirectory yields \t";
if (systemDir.Valid())
{
mConsole << systemDir.GetNativePathCString() << nsEndl;
mConsole << systemDir << nsEndl;
}
else
{
@@ -786,7 +687,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "Mac_AppleMenuDirectory yields \t";
if (systemDir.Valid())
{
mConsole << systemDir.GetNativePathCString() << nsEndl;
mConsole << systemDir << nsEndl;
}
else
{
@@ -798,7 +699,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "Mac_ControlPanelDirectory yields \t";
if (systemDir.Valid())
{
mConsole << systemDir.GetNativePathCString() << nsEndl;
mConsole << systemDir << nsEndl;
}
else
{
@@ -810,7 +711,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "Mac_ExtensionDirectory yields \t";
if (systemDir.Valid())
{
mConsole << systemDir.GetNativePathCString() << nsEndl;
mConsole << systemDir << nsEndl;
}
else
{
@@ -822,7 +723,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "Mac_FontsDirectory yields \t";
if (systemDir.Valid())
{
mConsole << systemDir.GetNativePathCString() << nsEndl;
mConsole << systemDir << nsEndl;
}
else
{
@@ -835,7 +736,7 @@ int FilesTest::SpecialSystemDirectories()
if (systemDir.Valid())
{
mConsole << systemDir.GetNativePathCString() << nsEndl;
mConsole << systemDir << nsEndl;
}
else
{
@@ -848,7 +749,7 @@ int FilesTest::SpecialSystemDirectories()
if (systemDir.Valid())
{
mConsole << systemDir.GetNativePathCString() << nsEndl;
mConsole << systemDir << nsEndl;
}
else
{
@@ -861,7 +762,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "Win_SystemDirectory yields \t";
if (systemDir.Valid())
{
(nsOutputStream&)mConsole << systemDir.GetNativePathCString() << nsEndl;
(nsOutputStream)mConsole << systemDir << nsEndl;
}
else
{
@@ -873,7 +774,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "Win_WindowsDirectory yields \t";
if (systemDir.Valid())
{
(nsOutputStream&)mConsole << systemDir.GetNativePathCString() << nsEndl;
(nsOutputStream)mConsole << systemDir << nsEndl;
}
else
{
@@ -886,7 +787,7 @@ int FilesTest::SpecialSystemDirectories()
mConsole << "Unix_LocalDirectory yields \t";
if (systemDir.Valid())
{
(nsOutputStream&)mConsole << systemDir.GetNativePathCString() << nsEndl;
(nsOutputStream)mConsole << systemDir << nsEndl;
}
else
{
@@ -899,7 +800,7 @@ int FilesTest::SpecialSystemDirectories()
if (systemDir.Valid())
{
(nsOutputStream&)mConsole << systemDir.GetNativePathCString() << nsEndl;
(nsOutputStream)mConsole << systemDir << nsEndl;
}
else
{
@@ -917,118 +818,84 @@ int FilesTest::RunAllTests()
// For use with DEBUG defined.
//----------------------------------------------------------------------------------------
{
int rv = 0;
// Test of mConsole output
// Test of mConsole output
mConsole << "WRITING TEST OUTPUT TO CONSOLE" << nsEndl << nsEndl;
// Test of nsFileSpec
Banner("Interconversion");
WriteStuff(mConsole);
rv = Inspect();
if (rv)
return rv;
Inspect();
Banner("Canonical Path");
rv = CanonicalPath("mumble/iotest.txt");
if (rv)
return rv;
if (CanonicalPath("mumble/iotest.txt") != 0)
return -1;
Banner("OutputStream");
rv = OutputStream("mumble/iotest.txt");
if (rv)
return rv;
if (OutputStream("mumble/iotest.txt") != 0)
return -1;
Banner("InputStream");
rv = InputStream("mumble/iotest.txt");
if (rv)
return rv;
if (InputStream("mumble/iotest.txt") != 0)
return -1;
Banner("IOStream");
rv = IOStream("mumble/iotest.txt");
if (rv)
return rv;
if (IOStream("mumble/iotest.txt") != 0)
return -1;
FileSizeAndDate("mumble/iotest.txt");
rv = InputStream("mumble/iotest.txt");
if (rv)
return rv;
if (InputStream("mumble/iotest.txt") != 0)
return -1;
Banner("StringStream");
rv = StringStream();
if (rv)
return rv;
if (StringStream() != 0)
return -1;
Banner("Parent");
nsFileSpec parent;
rv = Parent("mumble/iotest.txt", parent);
if (rv)
goto Clean;
if (Parent("mumble/iotest.txt", parent) != 0)
return -1;
Banner("FileSpec Append using Unix relative path");
rv = FileSpecAppend(parent, "nested/unix/file.txt");
if (rv)
goto Clean;
Banner("FileSpec Append using Native relative path");
#ifdef XP_PC
rv = FileSpecAppend(parent, "nested\\windows\\file.txt");
#elif defined(XP_MAC)
rv = FileSpecAppend(parent, ":nested:mac:file.txt");
#else
rv = Passed();
#endif // XP_MAC
if (rv)
goto Clean;
Banner("Delete");
rv = Delete(parent);
if (rv)
goto Clean;
if (Delete(parent) != 0)
return -1;
Banner("CreateDirectory");
rv = CreateDirectory(parent);
if (rv)
goto Clean;
if (CreateDirectory(parent) != 0)
return -1;
Banner("CreateDirectoryRecursive Relative (using nsFileSpec)");
rv = CreateDirectoryRecursive("mumble/dir1/dir2/dir3/");
if (rv)
goto Clean;
if (CreateDirectoryRecursive("mumble/dir1/dir2/dir3/") != 0)
return -1;
#ifdef XP_PC
Banner("CreateDirectoryRecursive Absolute (using nsFileSpec)");
rv = CreateDirectoryRecursive("c:\\temp\\dir1\\dir2\\dir3\\");
if (rv)
goto Clean;
if (CreateDirectoryRecursive("c:\\temp\\dir1\\dir2\\dir3\\") != 0)
return -1;
#endif
Banner("IterateDirectoryChildren");
rv = IterateDirectoryChildren(parent);
if (rv)
goto Clean;
if (IterateDirectoryChildren(parent) != 0)
return -1;
Banner("nsFileSpec equality");
rv = FileSpecEquality("mumble/a", "mumble/b");
if (rv)
goto Clean;
if (FileSpecEquality("mumble/a", "mumble/b") != 0)
return -1;
Banner("Copy");
rv = Copy("mumble/copyfile.txt", "mumble/copy");
if (rv)
goto Clean;
if (Copy("mumble/copyfile.txt", "mumble/copy") != 0)
return -1;
Banner("Move");
rv = Move("mumble/moveFile.txt", "mumble/move");
if (rv)
goto Clean;
if (Move("mumble/moveFile.txt", "mumble/move") != 0)
return -1;
Banner("Execute");
#ifdef XP_MAC
// This path is hard-coded to test on jrm's machine. Finding an app
// on an arbitrary Macintosh would cost more trouble than it's worth.
// Change path to suit. This is currently a native path, as you can see.
if NS_FAILED(Execute("Projects:Nav45_BRANCH:ns:cmd:macfe:"\
"projects:client45:Client45PPC", ""))
// Change path to suit.
if NS_FAILED(Execute("/Projects/Nav45_BRANCH/ns/cmd/macfe/"\
"projects/client45/Client45PPC", ""))
#elif XP_PC
if NS_FAILED(Execute("c:\\windows\\notepad.exe", ""))
#else
@@ -1036,26 +903,19 @@ int FilesTest::RunAllTests()
#endif
return -1;
Banner("NSPR Compatibility");
rv = NSPRCompatibility("mumble/aFile.txt");
if (rv)
goto Clean;
Banner("Special System Directories");
rv = SpecialSystemDirectories();
if (rv)
goto Clean;
if (SpecialSystemDirectories() != 0)
return -1;
Banner("Persistence");
rv = Persistence("mumble/filedesc.dat");
if (rv)
goto Clean;
if (Persistence("mumble/filedesc.dat") != 0)
return -1;
Clean:
Banner("Delete again (to clean up our mess)");
Delete(parent);
if (Delete(parent) != 0)
return -1;
return rv;
return 0;
} // FilesTest::RunAllTests
//----------------------------------------------------------------------------------------

View File

@@ -21,16 +21,7 @@ VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
CPPSRCS =\
TestAtoms.cpp \
TestCRT.cpp \
CvtURL.cpp \
FilesTest.cpp \
PropertiesTest.cpp \
TestAutoLock.cpp \
TestObserverService.cpp \
TestGtkTimers.cpp \
$(NULL)
CPPSRCS = TestAtoms.cpp TestCRT.cpp CvtURL.cpp FilesTest.cpp PropertiesTest.cpp TestAutoLock.cpp
LIBS = \
-lnetlib \
@@ -45,6 +36,7 @@ LIBS = \
-lpwcac \
-lhttpurl \
-lnetwork \
-lnetutil \
-lnetcache \
-lgmbase$(MOZ_TOOLKIT) \
$(TK_LIBS) \
@@ -63,7 +55,7 @@ SIMPLE_PROGRAMS = $(CPPSRCS:.cpp=)
include $(topsrcdir)/config/rules.mk
INCLUDES += -I$(srcdir)/../src $(TK_CFLAGS)
INCLUDES += -I$(srcdir)/../src
# needed for mac linux
ifeq ($(OS_ARCH),Linux)

View File

@@ -29,7 +29,7 @@
#include "plevent.h"
#endif
#define TEST_URL "resource:/res/test.PersistentProperties"
#define TEST_URL "resource:/res/test.properties"
#ifdef XP_PC
#define NETLIB_DLL "netlib.dll"
@@ -43,13 +43,13 @@
#else
#define NETLIB_DLL "libnetlib.so"
#define RAPTORBASE_DLL "libraptorbase.so"
#define XPCOM_DLL "libxpcom.so"
#define XPCOM_DLL "libxpcom32.so"
#endif
#endif
static NS_DEFINE_IID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID);
static NS_DEFINE_IID(kIEventQueueServiceIID, NS_IEVENTQUEUESERVICE_IID);
static NS_DEFINE_IID(kINetServiceIID, NS_INETSERVICE_IID);
static NS_DEFINE_IID(kIPersistentPropertiesIID, NS_IPERSISTENTPROPERTIES_IID);
static NS_DEFINE_IID(kIPropertiesIID, NS_IPROPERTIES_IID);
static NS_DEFINE_IID(kNetServiceCID, NS_NETSERVICE_CID);
@@ -101,11 +101,11 @@ main(int argc, char *argv[])
printf("cannot open stream\n");
return 1;
}
nsIPersistentProperties *props = nsnull;
ret = nsComponentManager::CreateInstance(kPersistentPropertiesCID, NULL,
kIPersistentPropertiesIID, (void**) &props);
nsIProperties *props = nsnull;
ret = nsComponentManager::CreateInstance(kPropertiesCID, NULL,
kIPropertiesIID, (void**) &props);
if (NS_FAILED(ret)) {
printf("create nsIPersistentProperties failed\n");
printf("create nsIProperties failed\n");
return 1;
}
props->Load(in);
@@ -120,7 +120,6 @@ main(int argc, char *argv[])
}
char *value = v.ToNewCString();
cout << "\"" << i << "\"=\"" << value << "\"" << endl;
delete[] value;
i++;
}

View File

@@ -1,240 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsIBuffer.h"
#include "nsIThread.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsAutoLock.h"
#include "nsPageMgr.h"
#include "nsCRT.h"
#include "prprf.h"
#include "prmem.h"
#include "prinrval.h"
#include <stdio.h>
class Reader : public nsIRunnable {
public:
NS_DECL_ISUPPORTS
NS_IMETHOD Run() {
nsresult rv;
nsAutoMonitor mon(this);
char buf[100];
PRUint32 readCnt;
char* readBuf;
rv = mReadBuffer->GetReadBuffer(&readCnt, &readBuf);
if (NS_FAILED(rv)) return rv;
while (!(mDone && readCnt == 0)) {
rv = mReadBuffer->Read(buf, 99, &readCnt);
if (NS_FAILED(rv)) {
printf("read failed\n");
return rv;
}
if (readCnt == 0) {
if (mDone)
break;
mon.Notify(); // wake up writer
mon.Wait(); // wait for more
rv = mReadBuffer->GetReadBuffer(&readCnt, &readBuf);
if (NS_FAILED(rv)) return rv;
}
else {
// buf[readCnt] = 0;
// printf(buf);
mBytesRead += readCnt;
}
}
// printf("reader done\n");
return rv;
}
Reader(nsIBuffer* readBuffer)
: mReadBuffer(readBuffer), mBytesRead(0), mDone(PR_FALSE) {
NS_INIT_REFCNT();
NS_ADDREF(mReadBuffer);
}
virtual ~Reader() {
NS_RELEASE(mReadBuffer);
printf("bytes read = %d\n", mBytesRead);
}
void SetEOF() {
mDone = PR_TRUE;
}
PRUint32 GetBytesRead() { return mBytesRead; }
protected:
nsIBuffer* mReadBuffer;
PRUint32 mBytesRead;
PRBool mDone;
};
NS_IMPL_ISUPPORTS(Reader, nsIRunnable::GetIID());
////////////////////////////////////////////////////////////////////////////////
#define ITERATIONS 20000
nsresult
WriteMessages(nsIBuffer* buffer)
{
nsresult rv;
nsIThread* thread;
Reader* reader = new Reader(buffer);
NS_ADDREF(reader);
rv = NS_NewThread(&thread, reader);
if (NS_FAILED(rv)) {
printf("failed to create thread\n");
return rv;
}
char* mem = nsnull;
char* buf = nsnull;
PRUint32 total = 0;
PRUint32 cnt = 0;
PRUint32 bufLen = 0;
PRIntervalTime start = PR_IntervalNow();
for (PRUint32 i = 0; i < ITERATIONS;) {
if (bufLen == 0) {
PR_FREEIF(mem);
mem = PR_smprintf("%d. My hovercraft is full of eels.\n", i);
buf = mem;
NS_ASSERTION(buf, "out of memory");
bufLen = nsCRT::strlen(buf);
i++;
}
rv = buffer->Write(buf, bufLen, &cnt);
if (NS_FAILED(rv)) {
printf("failed to write %d\n", i);
return rv;
}
if (cnt == 0) {
nsAutoMonitor mon(reader);
mon.Notify(); // wake up reader
mon.Wait(); // and wait for reader to read all
}
else {
total += cnt;
buf += cnt;
bufLen -= cnt;
}
}
PR_FREEIF(mem);
{
reader->SetEOF();
nsAutoMonitor mon(reader);
mon.Notify(); // wake up reader
}
if (NS_FAILED(rv)) return rv;
rv = thread->Join();
PRIntervalTime end = PR_IntervalNow();
if (NS_FAILED(rv)) return rv;
printf("writer done: %d bytes %d ms\n", total,
PR_IntervalToMilliseconds(end - start));
NS_ASSERTION(reader->GetBytesRead() == total, "didn't read everything");
NS_RELEASE(reader);
NS_RELEASE(thread);
NS_RELEASE(buffer);
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
nsresult
TestMallocBuffers(PRUint32 growByPages, PRUint32 pageCount)
{
nsresult rv;
nsIBuffer* buffer;
printf("Malloc Buffer Test: %d pages, grow by %d pages\n",
pageCount, growByPages);
rv = NS_NewBuffer(&buffer,
NS_PAGEMGR_PAGE_SIZE * growByPages,
NS_PAGEMGR_PAGE_SIZE * pageCount);
if (NS_FAILED(rv)) {
printf("failed to create buffer\n");
return rv;
}
rv = WriteMessages(buffer);
return rv;
}
nsresult
TestPageBuffers(PRUint32 growByPages, PRUint32 pageCount)
{
nsresult rv;
nsIBuffer* buffer;
printf("Page Buffer Test: %d pages, grow by %d pages\n",
pageCount, growByPages);
rv = NS_NewPageBuffer(&buffer,
NS_PAGEMGR_PAGE_SIZE * growByPages,
NS_PAGEMGR_PAGE_SIZE * pageCount);
if (NS_FAILED(rv)) {
printf("failed to create buffer\n");
return rv;
}
rv = WriteMessages(buffer);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
int
main()
{
nsresult rv;
nsIServiceManager* servMgr;
rv = NS_InitXPCOM(&servMgr);
if (NS_FAILED(rv)) return rv;
// XXX why do I have to do this?!
rv = nsComponentManager::AutoRegister(nsIComponentManager::NS_Startup,
"components");
if (NS_FAILED(rv)) return rv;
rv = TestMallocBuffers(1, 1);
NS_ASSERTION(NS_SUCCEEDED(rv), "TestMallocBuffers failed");
rv = TestPageBuffers(1, 1);
NS_ASSERTION(NS_SUCCEEDED(rv), "TestPageBuffers failed");
rv = TestMallocBuffers(1, 10);
NS_ASSERTION(NS_SUCCEEDED(rv), "TestMallocBuffers failed");
rv = TestPageBuffers(1, 10);
NS_ASSERTION(NS_SUCCEEDED(rv), "TestPageBuffers failed");
rv = TestMallocBuffers(5, 10);
NS_ASSERTION(NS_SUCCEEDED(rv), "TestMallocBuffers failed");
rv = TestPageBuffers(5, 10);
NS_ASSERTION(NS_SUCCEEDED(rv), "TestPageBuffers failed");
return 0;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,206 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "prtypes.h"
#include "nsVoidArray.h"
#include "nsITimer.h"
#include "nsITimerCallback.h"
#include <stdio.h>
#include <stdlib.h>
#include "resources.h"
#include <gtk/gtk.h>
static char* class1Name = "TimerTest";
static GtkWidget *gInstance, *gPrevInstance;
static nsVoidArray *gTimeouts = NULL;
static void CreateRepeat(PRUint32 aDelay);
void
MyCallback (nsITimer *aTimer, void *aClosure)
{
printf("Timer executed with delay %d\n", (int)aClosure);
if (gTimeouts->RemoveElement(aTimer) == PR_TRUE) {
NS_RELEASE(aTimer);
}
}
void
MyRepeatCallback (nsITimer *aTimer, void *aClosure)
{
printf("Timer executed with delay %d\n", (int)aClosure);
if (gTimeouts->RemoveElement(aTimer) == PR_TRUE) {
NS_RELEASE(aTimer);
}
CreateRepeat((PRUint32)aClosure);
}
static void
CreateOneShot(PRUint32 aDelay)
{
nsITimer *timer;
NS_NewTimer(&timer);
timer->Init(MyCallback, (void *)aDelay, aDelay);
gTimeouts->AppendElement(timer);
}
static void
CreateRepeat(PRUint32 aDelay)
{
nsITimer *timer;
NS_NewTimer(&timer);
timer->Init(MyRepeatCallback, (void *)aDelay, aDelay);
gTimeouts->AppendElement(timer);
}
static void
CancelAll()
{
int i, count = gTimeouts->Count();
for (i=0; i < count; i++) {
nsITimer *timer = (nsITimer *)gTimeouts->ElementAt(i);
if (timer != NULL) {
timer->Cancel();
NS_RELEASE(timer);
}
}
gTimeouts->Clear();
}
// Port this to gtk
#if 0
long PASCAL
WndProc(HWND hWnd, UINT msg, WPARAM param, LPARAM lparam)
{
HMENU hMenu;
switch (msg) {
case WM_COMMAND:
hMenu = GetMenu(hWnd);
switch (LOWORD(param)) {
case TIMER_EXIT:
::DestroyWindow(hWnd);
exit(0);
case TIMER_1SECOND:
CreateOneShot(1000);
break;
case TIMER_5SECOND:
CreateOneShot(5000);
break;
case TIMER_10SECOND:
CreateOneShot(10000);
break;
case TIMER_1REPEAT:
CreateRepeat(1000);
break;
case TIMER_5REPEAT:
CreateRepeat(5000);
break;
case TIMER_10REPEAT:
CreateRepeat(10000);
break;
case TIMER_CANCEL:
CancelAll();
break;
default:
break;
}
default:
break;
}
return DefWindowProc(hWnd, msg, param, lparam);
}
static HWND CreateTopLevel(const char* clazz, const char* title,
int aWidth, int aHeight)
{
// Create a simple top level window
HWND window = ::CreateWindowEx(WS_EX_CLIENTEDGE,
clazz, title,
WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN,
CW_USEDEFAULT, CW_USEDEFAULT,
aWidth, aHeight,
HWND_DESKTOP,
NULL,
gInstance,
NULL);
::ShowWindow(window, SW_SHOW);
::UpdateWindow(window);
return window;
}
int PASCAL
WinMain(HINSTANCE instance, HINSTANCE prevInstance,
LPSTR cmdParam, int nCmdShow)
{
gInstance = instance;
if (!prevInstance) {
WNDCLASS wndClass;
wndClass.style = 0;
wndClass.lpfnWndProc = WndProc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = gInstance;
wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = (HBRUSH) GetStockObject(LTGRAY_BRUSH);
wndClass.lpszMenuName = class1Name;
wndClass.lpszClassName = class1Name;
RegisterClass(&wndClass);
}
// Create our first top level window
HWND window = CreateTopLevel(class1Name, "Raptor HTML Viewer", 620, 400);
gTimeouts = new nsVoidArray();
// Process messages
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
#endif
void main(int argc, char **argv)
{
//WinMain(GetModuleHandle(NULL), NULL, 0, SW_SHOW);
}

View File

@@ -1,86 +0,0 @@
#define NS_IMPL_IDS
#include "nsISupports.h"
#include "nsRepository.h"
#include "nsIObserverService.h"
#include "nsIObserver.h"
#include "nsString.h"
static NS_DEFINE_IID(kIObserverServiceIID, NS_IOBSERVERSERVICE_IID);
static NS_DEFINE_IID(kObserverServiceCID, NS_OBSERVERSERVICE_CID);
static NS_DEFINE_IID(kIObserverIID, NS_IOBSERVER_IID);
static NS_DEFINE_IID(kObserverCID, NS_OBSERVER_CID);
#define BASE_DLL "raptorbase.dll"
int main(int argc, char *argv[])
{
nsIObserverService *anObserverService = NULL;
nsresult rv;
nsComponentManager::RegisterComponent(kObserverServiceCID,
"ObserverService",
NS_OBSERVERSERVICE_PROGID,
BASE_DLL,PR_FALSE, PR_FALSE);
nsresult res = nsRepository::CreateInstance(kObserverServiceCID,
NULL,
kIObserverServiceIID,
(void **) &anObserverService);
if (res == NS_OK) {
nsString aTopic("htmlparser");
nsIObserver *anObserver;
nsIObserver *aObserver = nsnull;
nsIObserver *bObserver = nsnull;
nsresult res = nsRepository::CreateInstance(kObserverCID,
NULL,
kIObserverIID,
(void **) &anObserver);
rv = NS_NewObserver(&aObserver);
if (NS_FAILED(rv)) return rv;
rv = anObserverService->AddObserver(&aObserver, &aTopic);
if (NS_FAILED(rv)) return rv;
rv = NS_NewObserver(&bObserver);
if (NS_FAILED(rv)) return rv;
rv = anObserverService->AddObserver(&bObserver, &aTopic);
if (NS_FAILED(rv)) return rv;
nsIEnumerator* e;
rv = anObserverService->EnumerateObserverList(&e, &aTopic);
if (NS_FAILED(rv)) return rv;
nsISupports *inst;
for (e->First(); e->IsDone() != NS_OK; e->Next()) {
rv = e->CurrentItem(&inst);
if (NS_SUCCEEDED(rv)) {
rv = inst->QueryInterface(nsIObserver::GetIID(), (void**)&anObserver);
}
rv = anObserver->Notify(nsnull);
}
rv = anObserverService->RemoveObserver(&aObserver, &aTopic);
if (NS_FAILED(rv)) return rv;
rv = anObserverService->RemoveObserver(&bObserver, &aTopic);
if (NS_FAILED(rv)) return rv;
}
return NS_OK;
}

View File

@@ -1,182 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsIThread.h"
#include "nsIByteBufferInputStream.h"
#include "nsIBuffer.h"
#include "nsIServiceManager.h"
#include "prprf.h"
#include "prinrval.h"
#include "plstr.h"
#include "nsCRT.h"
#include <stdio.h>
#define KEY 0xa7
#define ITERATIONS 33333
char kTestPattern[] = "My hovercraft is full of eels.\n";
PRBool gTrace = PR_FALSE;
class nsReceiver : public nsIRunnable {
public:
NS_DECL_ISUPPORTS
NS_IMETHOD Run() {
nsresult rv;
char buf[101];
PRUint32 count;
PRIntervalTime start = PR_IntervalNow();
while (PR_TRUE) {
rv = mIn->Read(buf, 100, &count);
if (rv == NS_BASE_STREAM_EOF) {
// printf("EOF count = %d\n", mCount);
rv = NS_OK;
break;
}
if (NS_FAILED(rv)) {
printf("read failed\n");
break;
}
if (gTrace) {
printf("read: ");
buf[count] = '\0';
printf(buf);
printf("\n");
}
mCount += count;
}
PRIntervalTime end = PR_IntervalNow();
printf("read %d bytes, time = %dms\n", mCount,
PR_IntervalToMilliseconds(end - start));
return rv;
}
nsReceiver(nsIInputStream* in) : mIn(in), mCount(0) {
NS_INIT_REFCNT();
NS_ADDREF(in);
}
virtual ~nsReceiver() {
NS_RELEASE(mIn);
}
PRUint32 GetBytesRead() { return mCount; }
protected:
nsIInputStream* mIn;
PRUint32 mCount;
};
NS_IMPL_ISUPPORTS(nsReceiver, nsIRunnable::GetIID());
nsresult
TestPipe(nsIInputStream* in, nsIOutputStream* out)
{
nsresult rv;
nsIThread* thread;
nsReceiver* receiver = new nsReceiver(in);
if (receiver == nsnull) return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(receiver);
rv = NS_NewThread(&thread, receiver);
if (NS_FAILED(rv)) return rv;
PRUint32 total = 0;
PRIntervalTime start = PR_IntervalNow();
for (PRUint32 i = 0; i < ITERATIONS; i++) {
PRUint32 writeCount;
char* buf = PR_smprintf("%d %s", i, kTestPattern);
rv = out->Write(buf, nsCRT::strlen(buf), &writeCount);
if (gTrace) {
printf("wrote: ");
for (PRUint32 j = 0; j < writeCount; j++) {
putc(buf[j], stdout);
}
printf("\n");
}
PR_smprintf_free(buf);
if (NS_FAILED(rv)) return rv;
total += writeCount;
}
rv = out->Close();
if (NS_FAILED(rv)) return rv;
PRIntervalTime end = PR_IntervalNow();
thread->Join();
printf("write %d bytes, time = %dms\n", total,
PR_IntervalToMilliseconds(end - start));
NS_ASSERTION(receiver->GetBytesRead() == total, "didn't read everything");
NS_RELEASE(thread);
NS_RELEASE(receiver);
return NS_OK;
}
int
main(int argc, char* argv[])
{
nsresult rv;
nsIInputStream* in;
nsIOutputStream* out;
nsIServiceManager* servMgr;
rv = NS_InitXPCOM(&servMgr);
if (NS_FAILED(rv)) return rv;
// XXX why do I have to do this?!
rv = nsComponentManager::AutoRegister(nsIComponentManager::NS_Startup,
"components");
if (NS_FAILED(rv)) return rv;
if (argc > 1 && nsCRT::strcmp(argv[1], "-trace") == 0)
gTrace = PR_TRUE;
rv = NS_NewPipe(&in, &out, PR_TRUE, 4096 * 4);
if (NS_FAILED(rv)) {
printf("NewPipe failed\n");
return -1;
}
rv = TestPipe(in, out);
NS_RELEASE(in);
NS_RELEASE(out);
if (NS_FAILED(rv)) {
printf("TestPipe failed\n");
return -1;
}
rv = NS_NewPipe2(&in, &out, 4096, 4096 * 4);
if (NS_FAILED(rv)) {
printf("NewPipe failed\n");
return -1;
}
rv = TestPipe(in, out);
NS_RELEASE(in);
NS_RELEASE(out);
if (NS_FAILED(rv)) {
printf("TestPipe failed\n");
return -1;
}
return 0;
}

View File

@@ -1,141 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsIThread.h"
#include <stdio.h>
class nsRunner : public nsIRunnable {
public:
NS_DECL_ISUPPORTS
NS_IMETHOD Run() {
printf("running %d\n", mNum);
nsIThread* thread;
nsresult rv = nsIThread::GetCurrent(&thread);
if (NS_FAILED(rv)) {
printf("failed to get current thread\n");
return rv;
}
NS_RELEASE(thread);
// if we don't do something slow, we'll never see the other
// worker threads run
PR_Sleep(100);
return rv;
}
nsRunner(int num) : mNum(num) {
NS_INIT_REFCNT();
}
protected:
int mNum;
};
NS_IMPL_ISUPPORTS(nsRunner, nsIRunnable::GetIID());
nsresult
TestThreads()
{
nsresult rv;
nsIThread* runner;
rv = NS_NewThread(&runner, new nsRunner(0));
if (NS_FAILED(rv)) {
printf("failed to create thread\n");
return rv;
}
nsIThread* thread;
rv = nsIThread::GetCurrent(&thread);
if (NS_FAILED(rv)) {
printf("failed to get current thread\n");
return rv;
}
PRThreadScope scope;
rv = runner->GetScope(&scope);
if (NS_FAILED(rv)) {
printf("runner already exited\n");
}
rv = runner->Join(); // wait for the runner to die before quitting
if (NS_FAILED(rv)) {
printf("join failed\n");
}
rv = runner->GetScope(&scope); // this should fail after Join
if (NS_SUCCEEDED(rv)) {
printf("get scope failed\n");
}
rv = runner->Interrupt(); // this should fail after Join
if (NS_SUCCEEDED(rv)) {
printf("interrupt failed\n");
}
NS_RELEASE(runner);
NS_RELEASE(thread);
////////////////////////////////////////////////////////////////////////////
// try an unjoinable thread
rv = NS_NewThread(&runner, new nsRunner(1), 0,
PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD);
if (NS_FAILED(rv)) {
printf("failed to create thread\n");
return rv;
}
rv = runner->Join(); // wait for the runner to die before quitting
if (NS_SUCCEEDED(rv)) {
printf("shouldn't have been able to join an unjoinable thread\n");
}
NS_RELEASE(runner);
return NS_OK;
}
nsresult
TestThreadPools()
{
nsIThreadPool* pool;
nsresult rv = NS_NewThreadPool(&pool, 4, 4);
if (NS_FAILED(rv)) {
printf("failed to create thead pool\n");
return rv;
}
for (PRUint32 i = 0; i < 100; i++) {
rv = pool->DispatchRequest(new nsRunner(i+2));
}
rv = pool->Shutdown();
return rv;
}
int
main()
{
nsresult rv = TestThreads();
if (NS_FAILED(rv)) return -1;
rv = TestThreadPools();
if (NS_FAILED(rv)) return -1;
return 0;
}

Some files were not shown because too many files have changed in this diff Show More