re PR libgcj/37636 (java tools are unable to find resource files)

libjava/ChangeLog:

2008-10-21  Andrew John Hughes  <gnu_andrew@member.fsf.org>

        * sources.am, Makfile.in: Regenerate.

2008-10-17  Matthias Klose  <doko@ubuntu.com>

	* configure.ac: Fix bashisms.
	* configure: Regenerate.

2008-10-15  Matthias Klose  <doko@ubuntu.com>

	* configure.ac: Disable build of gjdoc, if configured without
	--with-antlr-jar or if no antlr.jar found.
	* configure: Regenerate.

2008-10-09  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* classpath/configure.ac,
	* classpath/m4/ac_prog_antlr.m4,
	* classpath/m4/ac_prog_java.m4,
	* classpath/tools/Makefile.am:
	Ported --regen-gjdoc-parser patch and
	cantlr support from GNU Classpath.

2008-10-06  Andrew Haley  <aph@redhat.com>

	* java/lang/Thread.java (Thread): Always create the ThreadLocalMap
	when creating a thread.
	(getThreadLocals) Don't lazily create the ThreadLocalMap.

2008-09-28  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* classpath/java/lang/ThreadLocalMap.java,
	* java/lang/ThreadLocalMap$Entry.h,
	* java/lang/ThreadLocalMap.h,
	* lib/java/lang/ThreadLocalMap.class,
	* lib/java/lang/ThreadLocalMap$Entry.class:
	Add the new files for the ThreadLocal patch.

2008-09-28  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* classpath/ChangeLog,
	* classpath/java/lang/InheritableThreadLocal.java,
	* classpath/java/lang/Thread.java,
	* classpath/java/lang/ThreadLocal.java:
	Merge Daniel Frampton's ThreadLocal patch.
	* gcj/javaprims.h: Updated.
	* java/lang/Thread.h: Regenerated.
	* java/lang/Thread.java:
	Replace WeakIdentityHashMap with ThreadLocalMap.
	(getThreadLocals()): Likewise.
	* java/lang/ThreadLocal.h: Regenerated.
	* java/lang/ThreadLocal.java:
	(computeNextHash()): New method.
	(ThreadLocal()): Initialise fastHash.
	(internalGet()): Updated to match Classpath's get().
	(internalSet(Object)): Likewise for set(Object).
	(internalRemove()): Likewise for remove().
	
2008-09-25  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* classpath/configure,
	* classpath/configure.ac:
	Resynchronise with Classpath's configure.
	* classpath/examples/Makefile.in:
	Add equivalent support for building as in
	tools/Makefile.in.
	* classpath/java/nio/Buffer.java,
	* classpath/java/nio/ByteBuffer.java,
	* classpath/java/nio/ByteBufferImpl.java,
	* classpath/java/nio/CharBuffer.java,
	* classpath/java/nio/CharBufferImpl.java,
	* classpath/java/nio/CharSequenceBuffer.java,
	* classpath/java/nio/CharViewBufferImpl.java,
	* classpath/java/nio/DirectByteBufferImpl.java,
	* classpath/java/nio/DoubleBuffer.java,
	* classpath/java/nio/DoubleBufferImpl.java,
	* classpath/java/nio/DoubleViewBufferImpl.java,
	* classpath/java/nio/FloatBuffer.java,
	* classpath/java/nio/FloatBufferImpl.java,
	* classpath/java/nio/FloatViewBufferImpl.java,
	* classpath/java/nio/IntBuffer.java,
	* classpath/java/nio/IntBufferImpl.java,
	* classpath/java/nio/IntViewBufferImpl.java,
	* classpath/java/nio/LongBuffer.java,
	* classpath/java/nio/LongBufferImpl.java,
	* classpath/java/nio/LongViewBufferImpl.java,
	* classpath/java/nio/MappedByteBuffer.java,
	* classpath/java/nio/MappedByteBufferImpl.java,
	* classpath/java/nio/ShortBuffer.java,
	* classpath/java/nio/ShortBufferImpl.java,
	* classpath/java/nio/ShortViewBufferImpl.java:
	Replace use of gnu.classpath.Pointer with gnu.gcj.RawData,
	and fix some formatting issues.
	* classpath/tools/gnu/classpath/tools/gjdoc/expr/JavaLexer.java,
	* classpath/tools/gnu/classpath/tools/gjdoc/expr/JavaLexer.smap,
	* classpath/tools/gnu/classpath/tools/gjdoc/expr/JavaRecognizer.java,
	* classpath/tools/gnu/classpath/tools/gjdoc/expr/JavaRecognizer.smap,
	* classpath/tools/gnu/classpath/tools/gjdoc/expr/JavaTokenTypes.java,
	* classpath/tools/gnu/classpath/tools/gjdoc/expr/JavaTokenTypes.txt:
	Regenerated (later version of antlr).
	* java/nio/Buffer.h: Regenerated.
	* java/nio/Buffer.java: Ported changes from Classpath.
	* java/nio/ByteBuffer.h,
	* java/nio/CharBuffer.h: Regenerated.
	* java/nio/DirectByteBufferImpl.java: Ported changes from
	Classpath.
	* java/nio/DoubleBuffer.h,
	* java/nio/FloatBuffer.h,
	* java/nio/IntBuffer.h,
	* java/nio/LongBuffer.h,
	* java/nio/MappedByteBuffer.h,
	* java/nio/MappedByteBufferImpl.h: Regenerated.
	* java/nio/MappedByteBufferImpl.java: Ported changes from
	Classpath.
	* java/nio/ShortBuffer.h: Regenerated.

2008-09-24  Matthias Klose  <doko@ubuntu.com>

	* configure.ac: Search for antlr.jar, if not configured.
	* configure: Regenerate.

2008-09-24  Matthias Klose  <doko@ubuntu.com>

	* Makefile.am: Build a gjdoc binary, if enabled.
	* configure.ac: Add options --disable-gjdoc, --with-antlr-jar=file.
	* Makefile.in, */Makefile.in, configure: Regenerate.

2008-09-22  Andrew Haley  <aph@redhat.com>

	* java/lang/String.java (toString(char[], int, int)): New method.

2008-09-14  Matthias Klose  <doko@ubuntu.com>

	Import GNU Classpath (libgcj-import-20080914).

	* Regenerate class and header files.
	* Regenerate auto* files.
	* configure.ac: Don't pass --disable-gjdoc to classpath.
	* sources.am: Regenerated.
	* HACKING: Mention to build gjdoc in maintainer builds.
	* gnu/classpath/Configuration.java: Update classpath version.
	* gcj/javaprims.h: Update.

2008-09-08  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* Makefile.am: Replace natStringBuffer.cc
	and natStringBuilder.cc with natAbstractStringBuffer.cc.
	* Makefile.in: Regenerated.
	* java/lang/AbstractStringBuffer.java:
	(append(int)): Made native.
	(regionMatches(int,String)): Likewise.
	* java/lang/StringBuffer.h: Regenerated.
	* java/lang/StringBuffer.java: Remerged with GNU Classpath.
	* java/lang/StringBuilder.h: Regenerated.
	* java/lang/StringBuilder.java: Remerged with GNU Classpath.
	* java/lang/natAbstractStringBuffer.cc: Provide common
	native methods for StringBuffer and StringBuilder.
	* java/lang/natStringBuffer.cc,
	* java/lang/natStringBuilder.cc: Removed.

2008-09-04  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* Makefile.in,
	* classpath/configure: Regenerated.
	* gnu/gcj/util/natDebug.cc,
	* gnu/gcj/xlib/natColormap.cc,
	* gnu/gcj/xlib/natDisplay.cc,
	* gnu/gcj/xlib/natDrawable.cc,
	* gnu/gcj/xlib/natFont.cc,
	* gnu/gcj/xlib/natWMSizeHints.cc,
	* gnu/gcj/xlib/natWindow.cc,
	* gnu/gcj/xlib/natXImage.cc:
	Add :: prefix to namespaces.
	* java/io/CharArrayWriter.h,
	* java/lang/StringBuffer.h:
	Regenerated using patched gjavah.
	* java/lang/natStringBuffer.cc:
	Fix naming of append(jint).
	* java/sql/Timestamp.h: Regenerated
	using patched gjavah.
	* jni.cc: Rename p to functions
	to match change in GNU Classpath.
	* scripts/makemake.tcl: Switch
	gnu.java.math to BC compilation.
	* sources.am: Regenerated.

2008-08-21  Andrew John Hughes  <gnu_andrew@member.fsf.org>
	
	* Makefile.in: Updated location of Configuration.java.
	* classpath/lib/gnu/java/locale/LocaleData.class: Regenerated.

2008-08-18  Andrew John Hughes  <gnu_andrew@member.fsf.org>
	
	* Makefile.in: Updated with new Java files.
	* classpath/configure: Regenerated.
	* classpath/tools/Makefile.am: Add missing
	use of GJDOC_EX so --disable-gjdoc works.
	* classpath/tools/Makefile.in: Regenerated.

2008-08-15  Matthias Klose  <doko@ubuntu.com>

	Import GNU Classpath (libgcj-import-20080811).

	* Regenerate class and header files.
	* Regenerate auto* files.
	* configure.ac: Don't pass --with-fastjar to classpath, substitute new
	dummy value in classpath/gnu/classpath/Configuration.java.in, pass
	--disable-gjdoc to classpath.
	* scripts/makemake.tcl:
	* sources.am: Regenerated.
	* java/lang/AbstractStringBuffer.java, gnu/java/lang/VMCPStringBuilder.java:
	New, copied from classpath, use System instead of VMSystem.
	* java/lang/StringBuffer.java: Merge from classpath.
	* java/lang/ClassLoader.java: Merge from classpath.
	* gcj/javaprims.h: Update class definitions,
	remove _Jv_jobjectRefType, jobjectRefType definitions.

libjava/classpath/ChangeLog.gcj:

2008-10-21  Matthias Klose  <doko@ubuntu.com>

        * classpath/tools/gnu/classpath/tools/gjdoc/expr/Java*: Move from ...
        * classpath/tools/generated/gnu/classpath/tools/gjdoc/expr/ ... here.
        * Update .class files.
        
2008-10-21  Andrew John Hughes  <gnu_andrew@member.fsf.org>

        * tools/Makefile.am:
        Always generate parser in the srcdir.

2008-10-21  Matthias Klose  <doko@ubuntu.com>

        * doc/Makefile.am (MAINTAINERCLEANFILES): Add gjdoc.1.
        * doc/Makefile.in: Regenerate.

2008-10-20  Matthias Klose  <doko@ubuntu.com>

	* configure.ac: Don't check for working java, if not configured
        with --enable-java-maintainer-mode.
	* configure: Regenerate.

2008-10-19  Matthias Klose  <doko@ubuntu.com>

	* m4/ac_prog_java.m4: Revert previous change.
	* m4/ac_prog_javac.m4: Apply it here.
	* configure: Regenerate.

2008-10-19  Matthias Klose  <doko@ubuntu.com>

	* m4/ac_prog_javac.m4: Don't check for working javac, if not configured
	with --enable-java-maintainer-mode.
	* configure: Regenerate.
	* Makefile.in, */Makefile.in: Regenerate.

2008-09-30  Matthias Klose  <doko@ubuntu.com>

	* m4/ac_prog_antlr.m4: Check for cantlr binary as well.

2008-09-29  Matthias Klose  <doko@ubuntu.com>

	* m4/ac_prog_antlr.m4: Check for antlr binary as well.

2008-09-28  Matthias Klose  <doko@ubuntu.com>

	* PR libgcj/37636. Revert:
	2008-02-20  Matthias Klose  <doko@ubuntu.com>

	* tools/Makefile.am ($(TOOLS_ZIP)): Revert part of previous change,
	Do copy resource files in JAVA_MAINTAINER_MODE only.
	* tools/Makefile.in: Regenerate.

2008-09-14  Matthias Klose  <doko@ubuntu.com>

	* m4/ac_prog_javac_works.m4, m4/ac_prog_javac.m4, m4/acinclude.m4:
	Revert local changes.
	* m4/ac_prog_antlr.m4: Check for an runantlr binary.
	* tools/Makefile.am, lib/Makefile.am: Revert local changes (JCOMPILER).
	* tools/Makefile.am: Remove USE_JAVAC_FLAGS, pass ANTLR_JAR in
	GLIBJ_CLASSPATH.

2008-09-14  Matthias Klose  <doko@ubuntu.com>

	Revert:
	Daniel Frampton  <zyridium at zyridium.net>

	* AUTHORS: Added.
	* java/lang/InheritableThreadLocal.java,
	* java/lang/Thread.java,
	* java/lang/ThreadLocal.java:
	Modified to use java.lang.ThreadLocalMap.
	* java/lang/ThreadLocalMap.java:
	New cheaper ThreadLocal-specific WeakHashMap.

2008-08-15  Matthias Klose  <doko@ubuntu.com>

	* m4/acinclude.m4 (CLASSPATH_JAVAC_MEM_CHECK): Remove unknown
	args for javac.

libjava/classpath/ChangeLog:

2008-10-20  Andrew John Hughes  <gnu_andrew@member.fsf.org>

        * m4/ac_prog_antlr.m4:
        Remove redundant checks.
        * tools/Makefile.am:
        Use gjdoc_gendir when calling antlr.

2008-10-15  Andrew John Hughes  <gnu_andrew@member.fsf.org>

        * configure.ac:
        Remove superfluous AC_PROG_JAVA call.

2008-10-06  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* m4/ac_prog_antlr:
	Check for cantlr as well.
	* tools/Makefile.am:
	Only build GJDoc parser when both
	CREATE_GJDOC and CREATE_GJDOC_PARSER
	are on.
	
2008-10-02  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* configure.ac:
	Add regen-gjdoc-parser option,
	and separate antlr tests.
	* m4/ac_prog_antlr.m4:
	Turn single test into AC_LIB_ANTLR
	and AC_PROG_ANTLR.
	* m4/ac_prog_java.m4:
	Quote tests.
	* tools/Makefile.am:
	Support CREATE_GJDOC_PARSER option.

2008-09-14  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* examples/Makefile.am:
        Check lib directly as well as glibj.zip
        for boot classes.
	* m4/acinclude.m4:
        Only require the class files to be built
        to allow the tools and examples to be built,
        not the installation of glibj.zip.
	* tools/Makefile.am:
	Check lib directly as well as glibj.zip
	for boot classes.

2008-09-13  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* examples/Makefile.am,
	* lib/Makefile.am:
	Add GCJ rules.
	* m4/ac_prog_javac.m4:
	Check whether JAVAC is gcj.
	* m4/ac_prog_javac_works.m4:
	Add GCJ rules.
	* m4/acinclude.m4:
	Don't bother checking for -J
	if using GCJ.
	* tools/Makefile.am:
	Add GCJ rules.

2007-08-23  Daniel Frampton  <zyridium@zyridium.net>

	* AUTHORS: Added.
	* java/lang/InheritableThreadLocal.java,
	* java/lang/Thread.java,
	* java/lang/ThreadLocal.java:
	Modified to use java.lang.ThreadLocalMap.
	* java/lang/ThreadLocalMap.java:
	New cheaper ThreadLocal-specific WeakHashMap.

2008-02-07  Ian Rogers  <ian.rogers@manchester.ac.uk>

	* java/util/zip/ZipEntry.java:
	Use byte fields instead of integer fields,
	store the time as well as the DOS time and
	don't retain a global Calendar instance.
	(setDOSTime(int)): Set KNOWN_DOSTIME instead
	of KNOWN_TIME, and unset KNOWN_TIME.
	(getDOSTime()): Compute DOS time from UNIX time
	only when needed.
	(clone()): Provide cloning via the ZipEntry constructor
	where possible.
	(setTime(long)): Don't compute DOS time at this point.
	(getCalendar()): Removed.
	
2008-09-09  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* tools/gnu/classpath/tools/getopt/Parser.java:
	(setHeader(String)): Make synchronized.
	(setFooter(String)): Likewise.
	* tools/gnu/classpath/tools/rmic/SourceGiopRmicCompiler.java,
	(reset()): Make synchronized.
	(name(Class)): Likewise.
	
2008-09-04  Robert Schuster  <robertschuster@fsfe.org>

	* gnu/java/nio/charset/ByteDecodeLoopHelper:
	(arrayDecodeLoop): Added new break label, escape to that label.
	* gnu/java/nio/charset/ByteEncodeLoopHelper:
	(arrayDecodeLoop): Added new break label, escape to that label.

2008-09-04  Robert Schuster  <robertschuster@fsfe.org>

	* java/text/DecimalFormat.java:
	(scanFix): Use 'i + 1' when looking at following character.
	(scanNegativePattern): Dito.

2008-09-02  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* tools/gnu/classpath/tools/javah/ClassWrapper.java:
	(makeVtable()): Populate methodNameMap.
	(printMethods(CniPrintStream)): Always use pre-populated
	methodNameMap for bridge targets.

2008-09-01  Mario Torre  <neugens@aicas.com>

	* gnu/java/awt/peer/x/XImage.java (XImageProducer): remove @Override
	annotation to allow compilation on javac < 1.6 and ecj < 3.4.

2008-09-01  Mario Torre  <neugens@aicas.com>

	* gnu/java/awt/peer/x/XGraphicsDevice.java (getDisplay): fix to support
	new Escher API.
	* gnu/java/awt/peer/x/XImage.java (getSource): method implemented.
	* gnu/java/awt/peer/x/XImage.java (XImageProducer): implement ImageProducer
	for getSource.
	 
2008-09-01  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* gnu/java/util/regex/BacktrackStack.java,
	* gnu/java/util/regex/CharIndexed.java,
	* gnu/java/util/regex/CharIndexedCharArray.java,
	* gnu/java/util/regex/CharIndexedCharSequence.java,
	* gnu/java/util/regex/CharIndexedInputStream.java,
	* gnu/java/util/regex/CharIndexedString.java,
	* gnu/java/util/regex/CharIndexedStringBuffer.java,
	* gnu/java/util/regex/RE.java,
	* gnu/java/util/regex/REException.java,
	* gnu/java/util/regex/REFilterInputStream.java,
	* gnu/java/util/regex/REMatch.java,
	* gnu/java/util/regex/REMatchEnumeration.java,
	* gnu/java/util/regex/RESyntax.java,
	* gnu/java/util/regex/REToken.java,
	* gnu/java/util/regex/RETokenAny.java,
	* gnu/java/util/regex/RETokenBackRef.java,
	* gnu/java/util/regex/RETokenChar.java,
	* gnu/java/util/regex/RETokenEnd.java,
	* gnu/java/util/regex/RETokenEndOfPreviousMatch.java,
	* gnu/java/util/regex/RETokenEndSub.java,
	* gnu/java/util/regex/RETokenIndependent.java,
	* gnu/java/util/regex/RETokenLookAhead.java,
	* gnu/java/util/regex/RETokenLookBehind.java,
	* gnu/java/util/regex/RETokenNamedProperty.java,
	* gnu/java/util/regex/RETokenOneOf.java,
	* gnu/java/util/regex/RETokenPOSIX.java,
	* gnu/java/util/regex/RETokenRange.java,
	* gnu/java/util/regex/RETokenRepeated.java,
	* gnu/java/util/regex/RETokenStart.java,
	* gnu/java/util/regex/RETokenWordBoundary.java,
	* gnu/java/util/regex/UncheckedRE.java:
	Fix indentation.

2008-09-01  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* gnu/java/util/regex/RETokenStart.java:
	(getMaximumLength()): Add Override annotation.
	(matchThis(CharIndexed, REMatch)): Likewise.
	(returnsFixedLengthMatches()): Renamed from
	returnsFixedLengthmatches and added Override
	annotation.
	(findFixedLengthMatches(CharIndexed,REMatch,int)):
	Add Override annotation.
	(dump(CPStringBuilder)): Likewise.
	* gnu/javax/print/ipp/IppRequest.java:
	(RequestWriter.writeOperationAttributes(AttributeSet)):
	Throw exception, don't just create and drop it.
	* javax/management/MBeanServerPermission.java:
	(MBeanServerPermissionCollection.add(Permission)): Compare
	against individual Strings not the entire array, and
	store the result of replace.
	* javax/swing/text/html/StyleSheet.java:
	(setBaseFontSize(size)): Store result of trim().

2008-09-01  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* javax/tools/FileObject.java:
	(openReader(boolean)): Document new parameter.
	
2008-03-27  Michael Franz  <mvfranz@gmail.com>

	PR classpath/35690:
	* javax/tools/FileObject.java:
	(toUri()): Fix case from toURI.
	(openReader(boolean)): Add missing boolean argument.
	
2008-08-26  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	PR classpath/35487:
	* gnu/javax/management/Server.java:
	(beans): Change to ConcurrentHashMap.
	(defaultDomain): Make final.
	(outer): Likewise.
	(LazyListenersHolder): Added to wrap
	listeners, also now a ConcurrentHashMap,
	providing lazy initialisation safely.
	(sequenceNumber): Documented.
	(getBean(ObjectName)): Remove redundant cast.
	(addNotificationListener(ObjectName,NotificationListener,
	NotificationFilter,Object)): Remove map initialisation
	and use holder.
	(getObjectInstance(ObjectName)): Remove redundant cast.
	(registerMBean(Object,ObjectName)): Add bean atomically.
	(removeNotificationListener(ObjectName,NotificationListener)):
	Simplified.
	(removeNotificationListener(ObjectName,NotificationListener,
	NotificationFilter,Object)): Likewise.
	(notify(ObjectName,String)): Documented.
	
2008-08-26  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* gnu/javax/management/Server.java:
	Genericised.

2008-08-26  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* gnu/javax/management/Translator.java:
	Genericised.

2008-08-26  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* javax/management/DefaultLoaderRepository.java,
	* javax/management/JMX.java,
	* javax/management/MBeanAttributeInfo.java,
	* javax/management/MBeanConstructorInfo.java,
	* javax/management/MBeanOperationInfo.java,
	* javax/management/MBeanServerDelegate.java:
	Fix warnings due to generics.

2008-08-25  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* javax/management/MBeanPermission.java,
	* javax/management/MBeanServerDelegate.java,
	* javax/management/MBeanServerFactory.java,
	* javax/management/MBeanServerInvocationHandler.java,
	* javax/management/MBeanServerPermission.java:
	Fix warnings due to use of non-generic collections.

2008-08-25  Mario Torre  <neugens@aicas.com>

	* gnu/javax/rmi/CORBA/RmiUtilities.java (readValue): check if sender is
	null to avoid NPE.
	
2008-08-22  Mario Torre  <neugens@aicas.com>
 
	* gnu/CORBA/OrbFunctional.java (set_parameters): Fix
	NullPointerException checking when param is null. 

2008-08-23  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* java/util/regex/Matcher.java:
	(reset()): Reset append position so
	we don't try and append to the end of
	the old input.
	
2008-08-22  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	PR classpath/32028:
	* m4/acinclude.m4:
	Also allow versions of GJDoc from 0.8* on, as
	CVS is 0.8.0-pre.
	
2008-08-21  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	PR classpath/32028:
	* m4/acinclude.m4:
	(CLASSPATH_WITH_GJDOC): Ensure version 0.7.9 is
	being used.
	
2008-08-20  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* tools/Makefile.am:
	Add taglets subdirectory to list of excluded
	paths when GJDoc is not compiled.
	
2008-08-19  David P Grove  <groved@us.ibm.com>

	* scripts/check_jni_methods.sh.in:
	Fix build issue on AIX by splitting generation
	of method list.
	
2008-08-18  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* native/jni/gstreamer-peer/gst_native_pipeline.c:
	(get_free_space(int)): Use #else not #elif when
	there is no condition.

2008-08-17  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	PR classpath/31895:
	* java/text/DecimalFormat.java:
	(setCurrency(Currency)): Update prefixes and
	suffixes when currency changes.
	* java/text/DecimalFormatSymbols.java:
	(DecimalFormatSymbols(Locale)): Set locale earlier
	so it can be used by setCurrency(Currency).
	(setCurrency(Currency)): Set the symbol correctly using
	the locale of the instance.
	* java/util/Currency.java:
	Throw error instead of just printing a message.

2008-08-17  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* javax/activation/ActivationDataFlavor.java:
	Suppress warnings from public API.
	(mimeType): Made final.
	(representationClass): Added generic type and
	made final.
	(normalizeMimeTypeParameter(String,String)):
	Use CPStringBuilder.
	* javax/activation/CommandInfo.java:
	(verb): Made final.
	(className): Made final.
	* javax/activation/DataHandler.java:
	(dataSource): Made final.
	* javax/activation/FileDataSource.java:
	(file): Made final.
	* javax/activation/MailcapCommandMap.java:
	Use generics on collections and CPStringBuilder
	instead of StringBuffer.
	* javax/activation/MimeType.java:
	(toString()): Use CPStringBuilder.
	(getBaseType()): Likewise.
	* javax/activation/MimeTypeParameterList.java:
	Use generics on collections and CPStringBuilder
	instead of StringBuffer.
	* javax/activation/MimeTypeParseException.java:
	(MimeTypeParseException(String,String)): Use
	CPStringBuilder.
	* javax/activation/MimetypesFileTypeMap.java:
	Use generics on collections and CPStringBuilder
	instead of StringBuffer.	
	* javax/activation/URLDataSource.java:
	(url): Made final.

2008-08-17  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* gnu/javax/activation/viewers/ImageViewer.java,
	* gnu/javax/activation/viewers/TextEditor.java,
	* gnu/javax/activation/viewers/TextViewer.java,
	* javax/activation/ActivationDataFlavor.java,
	* javax/activation/CommandInfo.java,
	* javax/activation/CommandMap.java,
	* javax/activation/CommandObject.java,
	* javax/activation/DataContentHandler.java,
	* javax/activation/DataContentHandlerFactory.java,
	* javax/activation/DataHandler.java,
	* javax/activation/DataHandlerDataSource.java,
	* javax/activation/DataSource.java,
	* javax/activation/DataSourceDataContentHandler.java,
	* javax/activation/FileDataSource.java,
	* javax/activation/FileTypeMap.java,
	* javax/activation/MailcapCommandMap.java,
	* javax/activation/MimeType.java,
	* javax/activation/MimeTypeParameterList.java,
	* javax/activation/MimeTypeParseException.java,
	* javax/activation/MimetypesFileTypeMap.java,
	* javax/activation/ObjectDataContentHandler.java,
	* javax/activation/URLDataSource.java,
	* javax/activation/UnsupportedDataTypeException.java,
	* javax/activation/package.html,
	* resource/META-INF/mailcap.default,
	* resource/META-INF/mimetypes.default:
	Import GNU JAF CVS as of 17/08/2008.

2006-04-25  Archit Shah  <ashah@redhat.com>

	* javax/activation/MimeTypeParameterList.java:
	Insert ';' separator before parameter list.

2005-06-29  Xavier Poinsard  <xpoinsard@openpricer.com>

	* javax/activation/ObjectDataContentHandler.java:
	Fixed typo.

2005-05-28  Chris Burdess  <dog@bluezoo.org>

	* javax/activation/CommandMap.java, 
	* javax/activation/MailcapCommandMap.java:
	Updated to JAF 1.1.

2004-06-09  Chris Burdess  <dog@bluezoo.org>

	* javax/activation/MailcapCommandMap.java:
	Fixed bug whereby x-java prefix was not
	attempted.

2008-08-17  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* AUTHORS: Added Laszlo.

2008-04-20  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	PR classpath/30436:
	* java/util/Scanner.java:
	Fix package to be java.util and correct
	indentation.

2007-07-25  Laszlo Andras Hernadi  <e0327023@student.tuwien.ac.at>

	PR classpath/30436:
	* java/util/Scanner.java:
	Initial implementation.

2008-08-17  Andrew John Hughes  <gnu_andrew@member.fsf.org>

	* java/util/regex/Matcher.java:
	(toMatchResult()): Implemented.
	
2008-08-13  Joshua Sumali  <jsumali@redhat.com>

	* doc/Makefile.am (gjdoc.pod): Generate gjdoc pod from cp-tools.texinfo
	instead of invoke.texi. Remove invoke.texi from EXTRA_DIST.
	* doc/invoke.texi: Removed and merged into ...
	* doc/cp-tools.texinfo: Here

2008-08-12  Robert Schuster  <robertschuster@fsfe.org>

	* native/jni/java-net/local.c
	(local_bind): Removed fprintf call, fixed access outside
	of array bounds.

From-SVN: r141271
This commit is contained in:
Matthias Klose 2008-10-21 17:55:01 +00:00
parent d9cc481a35
commit cd6d4007aa
2325 changed files with 121399 additions and 23635 deletions

View file

@ -158,18 +158,53 @@ public final class AlphaComposite implements Composite
return new AlphaCompositeContext(this, srcColorModel, dstColorModel);
}
/**
* Return an <code>AlphaComposite</code> similar to <code>this</code>,
* that uses the specified rule. If <code>rule</code> is the same as
* <code>this.rule</code>, then <code>this</code> is returned.
*
* @since 1.6
*/
public AlphaComposite derive(int rule)
{
if (this.rule == rule)
return this;
else
return AlphaComposite.getInstance(rule, this.getAlpha());
}
/**
* Return an <code>AlphaComposite</code> similar to <code>this</code>,
* that uses the specified <code>alpha</code>.
*
* If <code>alph</code> is the same as <code>this.alpha</code>,
* then <code>this</code> is returned.
*
* @since 1.6
*/
public AlphaComposite derive(float alpha)
{
if (this.getAlpha() == alpha)
return this;
else
return AlphaComposite.getInstance(this.getRule(), alpha);
}
public float getAlpha()
{
return alpha;
}
public int getRule()
{
return rule;
}
public int hashCode()
{
return 31 * Float.floatToIntBits(alpha) + rule;
}
public boolean equals(Object o)
{
if (! (o instanceof AlphaComposite))

View file

@ -43,6 +43,8 @@ package java.awt;
import gnu.java.awt.ComponentReshapeEvent;
import gnu.java.lang.CPStringBuilder;
import java.awt.dnd.DropTarget;
import java.awt.event.ActionEvent;
import java.awt.event.AdjustmentEvent;
@ -175,7 +177,7 @@ public abstract class Component
/**
* Constant returned by the <code>getAlignmentY</code> and
* <code>getAlignmentX</code> methods to indicate
* that the component wishes to be aligned to the center relative to
* that the component wishes to be aligned to the centdisper relative to
* other components.
*
* @see #getAlignmentX()
@ -4991,7 +4993,7 @@ public abstract class Component
*/
protected String paramString()
{
StringBuffer param = new StringBuffer();
CPStringBuilder param = new CPStringBuilder();
String name = getName();
if (name != null)
param.append(name).append(",");

View file

@ -39,6 +39,8 @@ exception statement from your version. */
package java.awt;
import gnu.java.lang.CPStringBuilder;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.HierarchyEvent;
@ -1341,7 +1343,7 @@ public class Container extends Component
if (layoutMgr == null)
return super.paramString();
StringBuffer sb = new StringBuffer();
CPStringBuilder sb = new CPStringBuilder();
sb.append(super.paramString());
sb.append(",layout=");
sb.append(layoutMgr.getClass().getName());

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.awt;
import gnu.java.lang.CPStringBuilder;
/**
* Needs documentation...
*
@ -479,7 +481,7 @@ public final class JobAttributes implements Cloneable
public String toString()
{
StringBuffer s = new StringBuffer("copies=").append(copies)
CPStringBuilder s = new CPStringBuilder("copies=").append(copies)
.append(",defaultSelection=").append(selection).append(",destination=")
.append(destination).append(",dialog=").append(dialog)
.append(",fileName=").append(filename).append(",fromPage=")

View file

@ -50,6 +50,13 @@ public class MouseInfo
{
private static MouseInfoPeer peer;
/**
* Private constructor to prevent instance creation.
*/
private MouseInfo()
{
}
/**
* Returns a PointerInfo object containing information about the current
* location of the mouse pointer

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.awt.datatransfer;
import gnu.java.lang.CPStringBuilder;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
@ -224,7 +226,7 @@ class MimeType
*/
public String toString()
{
StringBuilder s = new StringBuilder();
CPStringBuilder s = new CPStringBuilder();
s.append(primaryType);
s.append('/');
s.append(subType);

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.awt.event;
import gnu.java.lang.CPStringBuilder;
import java.awt.AWTEvent;
import java.awt.EventQueue;
@ -202,9 +204,9 @@ public class ActionEvent extends AWTEvent
*/
public String paramString()
{
StringBuffer s = new StringBuffer(id == ACTION_PERFORMED
? "ACTION_PERFORMED,cmd="
: "unknown type,cmd=");
CPStringBuilder s = new CPStringBuilder(id == ACTION_PERFORMED
? "ACTION_PERFORMED,cmd="
: "unknown type,cmd=");
s.append(actionCommand).append(",when=").append(when).append(",modifiers");
int len = s.length();
s.setLength(len + 1);

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.awt.event;
import gnu.java.lang.CPStringBuilder;
import java.awt.AWTEvent;
import java.awt.Component;
@ -114,7 +116,7 @@ public class ComponentEvent extends AWTEvent
*/
public String paramString()
{
StringBuffer s = new StringBuffer();
CPStringBuilder s = new CPStringBuilder();
// Unlike Sun, we don't throw NullPointerException or ClassCastException
// when source was illegally changed.

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.awt.event;
import gnu.java.lang.CPStringBuilder;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Container;
@ -226,7 +228,7 @@ public class HierarchyEvent extends AWTEvent
*/
public String paramString()
{
StringBuffer r = new StringBuffer();
CPStringBuilder r = new CPStringBuilder();
switch (id)
{
case HIERARCHY_CHANGED:

View file

@ -39,6 +39,7 @@ exception statement from your version. */
package java.awt.event;
import gnu.java.awt.EventModifier;
import gnu.java.lang.CPStringBuilder;
import java.awt.Component;
@ -376,7 +377,7 @@ public abstract class InputEvent extends ComponentEvent
modifiers &= EventModifier.NEW_MASK;
if (modifiers == 0)
return "";
StringBuffer s = new StringBuffer();
CPStringBuilder s = new CPStringBuilder();
if ((modifiers & META_DOWN_MASK) != 0)
s.append("Meta+");
if ((modifiers & CTRL_DOWN_MASK) != 0)

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.awt.event;
import gnu.java.lang.CPStringBuilder;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.EventQueue;
@ -257,8 +259,8 @@ public class InputMethodEvent extends AWTEvent
*/
public String paramString()
{
StringBuffer s
= new StringBuffer(80 + (text == null ? 0
CPStringBuilder s
= new CPStringBuilder(80 + (text == null ? 0
: text.getEndIndex() - text.getBeginIndex()));
s.append(id == INPUT_METHOD_TEXT_CHANGED ? "INPUT_METHOD_TEXT_CHANGED, "
: "CARET_POSITION_CHANGED, ");

View file

@ -39,6 +39,7 @@ exception statement from your version. */
package java.awt.event;
import gnu.java.awt.EventModifier;
import gnu.java.lang.CPStringBuilder;
import java.awt.Component;
import java.io.IOException;
@ -1673,7 +1674,7 @@ public class KeyEvent extends InputEvent
*/
public String paramString()
{
StringBuffer s = new StringBuffer();
CPStringBuilder s = new CPStringBuilder();
switch (id)
{

View file

@ -39,6 +39,7 @@ exception statement from your version. */
package java.awt.event;
import gnu.java.awt.EventModifier;
import gnu.java.lang.CPStringBuilder;
import java.awt.Component;
import java.awt.Point;
@ -434,7 +435,7 @@ public class MouseEvent extends InputEvent
*/
public String paramString()
{
StringBuffer s = new StringBuffer();
CPStringBuilder s = new CPStringBuilder();
switch (id)
{
case MOUSE_CLICKED:

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.awt.event;
import gnu.java.lang.CPStringBuilder;
import java.awt.Frame;
import java.awt.Window;
@ -270,7 +272,7 @@ public class WindowEvent extends ComponentEvent
*/
public String paramString()
{
StringBuffer s = new StringBuffer();
CPStringBuilder s = new CPStringBuilder();
switch (id)
{
case WINDOW_OPENED:

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.awt.font;
import gnu.java.lang.CPStringBuilder;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Shape;
@ -362,7 +364,7 @@ public final class TextLayout implements Cloneable
private static String getText(AttributedCharacterIterator iter)
{
StringBuffer sb = new StringBuffer();
CPStringBuilder sb = new CPStringBuilder();
int idx = iter.getIndex();
for(char c = iter.first(); c != CharacterIterator.DONE; c = iter.next())
sb.append(c);

View file

@ -37,6 +37,7 @@ exception statement from your version. */
package java.awt.image;
import gnu.java.awt.Buffers;
import gnu.java.lang.CPStringBuilder;
/**
* A sample model that reads each sample value from a separate band in the
@ -742,7 +743,7 @@ public final class BandedSampleModel extends ComponentSampleModel
*/
public String toString()
{
StringBuffer result = new StringBuffer();
CPStringBuilder result = new CPStringBuilder();
result.append(getClass().getName());
result.append("[");
result.append("scanlineStride=").append(scanlineStride);

View file

@ -41,6 +41,8 @@ package java.awt.image;
import gnu.java.awt.Buffers;
import gnu.java.awt.ClasspathGraphicsEnvironment;
import gnu.java.awt.ComponentDataBlitOp;
import gnu.java.lang.CPStringBuilder;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
@ -778,9 +780,9 @@ public class BufferedImage extends Image
public String toString()
{
StringBuffer buf;
CPStringBuilder buf;
buf = new StringBuffer(/* estimated length */ 120);
buf = new CPStringBuilder(/* estimated length */ 120);
buf.append("BufferedImage@");
buf.append(Integer.toHexString(hashCode()));
buf.append(": type=");

View file

@ -631,8 +631,8 @@ public abstract class ColorModel implements Transparency
throw new UnsupportedOperationException();
}
protected void coerceDataWorker(WritableRaster raster,
boolean isAlphaPremultiplied)
void coerceDataWorker(WritableRaster raster,
boolean isAlphaPremultiplied)
{
int w = raster.getWidth();
int h = raster.getHeight();

View file

@ -312,7 +312,7 @@ public class ComponentColorModel extends ColorModel
/* TODO: provide better implementation based on the
assumptions we can make due to the specific type of the
color model. */
super.coerceDataWorker(raster, isAlphaPremultiplied);
coerceDataWorker(raster, isAlphaPremultiplied);
return new ComponentColorModel(cspace, hasAlpha, isAlphaPremultiplied,
transparency, transferType);

View file

@ -393,8 +393,8 @@ public class DirectColorModel extends PackedColorModel
return Buffers.getData(buffer);
}
public ColorModel coerceData (WritableRaster raster,
boolean isAlphaPremultiplied)
public final ColorModel coerceData (WritableRaster raster,
boolean isAlphaPremultiplied)
{
if (this.isAlphaPremultiplied == isAlphaPremultiplied || !hasAlpha())
return this;
@ -402,7 +402,7 @@ public class DirectColorModel extends PackedColorModel
/* TODO: provide better implementation based on the
assumptions we can make due to the specific type of the
color model. */
super.coerceDataWorker(raster, isAlphaPremultiplied);
coerceDataWorker(raster, isAlphaPremultiplied);
return new DirectColorModel(cspace, pixel_bits, getRedMask(),
getGreenMask(), getBlueMask(), getAlphaMask(),

View file

@ -37,6 +37,7 @@ exception statement from your version. */
package java.awt.image;
import gnu.java.awt.Buffers;
import gnu.java.lang.CPStringBuilder;
/**
* MultiPixelPackedSampleModel provides a single band model that supports
@ -587,7 +588,7 @@ public class MultiPixelPackedSampleModel extends SampleModel
*/
public String toString()
{
StringBuffer result = new StringBuffer();
CPStringBuilder result = new CPStringBuilder();
result.append(getClass().getName());
result.append("[");
result.append("scanlineStride=").append(scanlineStride);

View file

@ -37,6 +37,8 @@ exception statement from your version. */
package java.awt.image;
import gnu.java.lang.CPStringBuilder;
import java.awt.Point;
import java.awt.Rectangle;
@ -920,7 +922,7 @@ public class Raster
*/
public String toString()
{
StringBuffer result = new StringBuffer();
CPStringBuilder result = new CPStringBuilder();
result.append(getClass().getName());
result.append("[(");

View file

@ -39,6 +39,7 @@ package java.awt.image;
import java.util.Arrays;
import gnu.java.awt.BitMaskExtent;
import gnu.java.lang.CPStringBuilder;
/**
* A <code>SampleModel</code> used when all samples are stored in a single
@ -569,7 +570,7 @@ public class SinglePixelPackedSampleModel extends SampleModel
*/
public String toString()
{
StringBuffer result = new StringBuffer();
CPStringBuilder result = new CPStringBuilder();
result.append(getClass().getName());
result.append("[");
result.append("scanlineStride=").append(scanlineStride);

View file

@ -111,13 +111,8 @@ public class WritableRaster extends Raster
public WritableRaster createWritableTranslatedChild(int childMinX,
int childMinY)
{
// This mirrors the code from the super class
int tcx = sampleModelTranslateX - minX + childMinX;
int tcy = sampleModelTranslateY - minY + childMinY;
return new WritableRaster(sampleModel, dataBuffer,
new Rectangle(childMinX, childMinY, width, height),
new Point(tcx, tcy), this);
return createWritableChild(minX, minY, width, height,
childMinX, childMinY, null);
}
/**
@ -143,12 +138,14 @@ public class WritableRaster extends Raster
SampleModel sm = (bandList == null) ?
sampleModel :
sampleModel.createSubsetSampleModel(bandList);
return new WritableRaster(sm, dataBuffer,
new Rectangle(childMinX, childMinY, w, h),
new Point(sampleModelTranslateX + childMinX - parentX,
sampleModelTranslateY + childMinY - parentY),
this);
return new WritableRaster(sm, getDataBuffer(),
new Rectangle(childMinX, childMinY, w, h),
new Point(sampleModelTranslateX + childMinX -
parentX,
sampleModelTranslateY + childMinY -
parentY),
this);
}
public Raster createChild(int parentX, int parentY, int width,

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.beans;
import gnu.java.lang.CPStringBuilder;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
@ -353,7 +355,7 @@ public class Statement
*/
public String toString()
{
StringBuffer result = new StringBuffer();
CPStringBuilder result = new CPStringBuilder();
String targetName;
if (target != null)

View file

@ -86,6 +86,11 @@ public class BeanContextServicesSupport
private BeanContextServiceProvider provider;
BCSSProxyServiceProvider(BeanContextServiceProvider p)
{
provider = p;
}
public Iterator getCurrentServiceSelectors (BeanContextServices bcs,
Class serviceClass)
{

View file

@ -39,6 +39,8 @@ exception statement from your version. */
package java.io;
import gnu.java.lang.CPStringBuilder;
/* Written using "Java Class Libraries", 2nd edition, plus online
* API docs for JDK 1.2 beta from http://www.javasoft.com.
* Status: Believed complete and correct.
@ -450,7 +452,7 @@ public class BufferedReader extends Reader
pos++;
return str;
}
StringBuilder sbuf = new StringBuilder(200);
CPStringBuilder sbuf = new CPStringBuilder(200);
sbuf.append(buffer, pos, i - pos);
pos = i;
// We only want to return null when no characters were read before

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.io;
import gnu.java.lang.CPStringBuilder;
/* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
* "The Java Language Specification", ISBN 0-201-63451-1
* plus online API docs for JDK 1.2 beta from http://www.javasoft.com.
@ -350,7 +352,7 @@ public class DataInputStream extends FilterInputStream implements DataInput
*/
public final String readLine() throws IOException
{
StringBuilder strb = new StringBuilder();
CPStringBuilder strb = new CPStringBuilder();
while (true)
{
@ -747,7 +749,7 @@ public class DataInputStream extends FilterInputStream implements DataInput
{
// Give StringBuffer an initial estimated size to avoid
// enlarge buffer frequently
StringBuilder strbuf = new StringBuilder (buf.length / 2 + 2);
CPStringBuilder strbuf = new CPStringBuilder (buf.length / 2 + 2);
for (int i = 0; i < buf.length; )
{

View file

@ -41,6 +41,8 @@ package java.io;
import gnu.classpath.SystemProperties;
import gnu.java.lang.CPStringBuilder;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
@ -158,7 +160,7 @@ public class File implements Serializable, Comparable<File>
return false;
if (VMFile.isDirectory(path))
return VMFile.canWriteDirectory(this);
return VMFile.canWriteDirectory(path);
else
return VMFile.canWrite(path);
}
@ -317,7 +319,7 @@ public class File implements Serializable, Comparable<File>
return p;
}
StringBuffer newpath = new StringBuffer(plen);
CPStringBuilder newpath = new CPStringBuilder(plen);
int last = 0;
while (dupIndex != -1)
{

View file

@ -37,6 +37,8 @@ exception statement from your version. */
package java.io;
import gnu.java.lang.CPStringBuilder;
/**
* This class parses streams of characters into tokens. There are a
* million-zillion flags that can be set to control the parsing, as
@ -391,7 +393,7 @@ public class StreamTokenizer
}
}
StringBuffer tokbuf = new StringBuffer();
CPStringBuilder tokbuf = new CPStringBuilder();
tokbuf.append((char) ch);
int decCount = 0;
@ -417,7 +419,7 @@ public class StreamTokenizer
}
else if (isAlphabetic(ch))
{
StringBuffer tokbuf = new StringBuffer();
CPStringBuilder tokbuf = new CPStringBuilder();
tokbuf.append((char) ch);
while (isAlphabetic(ch = in.read()) || isNumeric(ch))
tokbuf.append((char) ch);
@ -440,7 +442,7 @@ public class StreamTokenizer
else if (isQuote(ch))
{
ttype = ch;
StringBuffer tokbuf = new StringBuffer();
CPStringBuilder tokbuf = new CPStringBuilder();
while ((ch = in.read()) != ttype && ch != '\n' && ch != '\r' &&
ch != TT_EOF)
{

File diff suppressed because it is too large Load diff

View file

@ -88,6 +88,11 @@ public final class Byte extends Number implements Comparable<Byte>
// This caches Byte values, and is used by boxing conversions via
// valueOf(). We're required to cache all possible values here.
private static Byte[] byteCache = new Byte[MAX_VALUE - MIN_VALUE + 1];
static
{
for (int i=MIN_VALUE; i <= MAX_VALUE; i++)
byteCache[i - MIN_VALUE] = new Byte((byte) i);
}
/**
@ -185,7 +190,7 @@ public final class Byte extends Number implements Comparable<Byte>
*/
public static Byte valueOf(String s, int radix)
{
return new Byte(parseByte(s, radix));
return valueOf(parseByte(s, radix));
}
/**
@ -201,7 +206,7 @@ public final class Byte extends Number implements Comparable<Byte>
*/
public static Byte valueOf(String s)
{
return new Byte(parseByte(s, 10));
return valueOf(parseByte(s, 10));
}
/**
@ -214,12 +219,7 @@ public final class Byte extends Number implements Comparable<Byte>
*/
public static Byte valueOf(byte val)
{
synchronized (byteCache)
{
if (byteCache[val - MIN_VALUE] == null)
byteCache[val - MIN_VALUE] = new Byte(val);
return byteCache[val - MIN_VALUE];
}
return byteCache[val - MIN_VALUE];
}
/**
@ -258,7 +258,7 @@ public final class Byte extends Number implements Comparable<Byte>
int i = Integer.parseInt(s, 10, true);
if ((byte) i != i)
throw new NumberFormatException();
return new Byte((byte) i);
return valueOf((byte) i);
}
/**

View file

@ -2055,6 +2055,11 @@ public final class Character implements Serializable, Comparable<Character>
// this constant controls how much we actually cache.
private static final int MAX_CACHE = 127;
private static Character[] charCache = new Character[MAX_CACHE + 1];
static
{
for (char i=0; i <= MAX_CACHE; i++)
charCache[i] = new Character(i);
}
/**
* Lu = Letter, Uppercase (Informative).
@ -4208,12 +4213,8 @@ public final class Character implements Serializable, Comparable<Character>
{
if (val > MAX_CACHE)
return new Character(val);
synchronized (charCache)
{
if (charCache[val - MIN_VALUE] == null)
charCache[val - MIN_VALUE] = new Character(val);
return charCache[val - MIN_VALUE];
}
else
return charCache[val - MIN_VALUE];
}
/**

View file

@ -659,7 +659,7 @@ public abstract class ClassLoader
*/
protected Enumeration<URL> findResources(String name) throws IOException
{
return (Enumeration<URL>) EmptyEnumeration.getInstance();
return new EmptyEnumeration<URL>();
}
/**

View file

@ -38,6 +38,7 @@ exception statement from your version. */
package java.lang;
import gnu.java.lang.CPStringBuilder;
/**
* Instances of class <code>Double</code> represent primitive
@ -102,6 +103,16 @@ public final class Double extends Number implements Comparable<Double>
*/
public static final Class<Double> TYPE = (Class<Double>) VMClassLoader.getPrimitiveClass('D');
/**
* Cache representation of 0
*/
private static final Double ZERO = new Double(0.0d);
/**
* Cache representation of 1
*/
private static final Double ONE = new Double(1.0d);
/**
* The immutable value of this Double.
*
@ -201,7 +212,7 @@ public final class Double extends Number implements Comparable<Double>
return d < 0 ? "-Infinity" : "Infinity";
long bits = doubleToLongBits(d);
StringBuilder result = new StringBuilder();
CPStringBuilder result = new CPStringBuilder();
if (bits < 0)
result.append('-');
@ -260,8 +271,12 @@ public final class Double extends Number implements Comparable<Double>
*/
public static Double valueOf(double val)
{
// We don't actually cache, but we could.
return new Double(val);
if ((val == 0.0) && (doubleToRawLongBits(val) == 0L))
return ZERO;
else if (val == 1.0)
return ONE;
else
return new Double(val);
}
/**
@ -276,7 +291,7 @@ public final class Double extends Number implements Comparable<Double>
*/
public static Double valueOf(String s)
{
return new Double(parseDouble(s));
return valueOf(parseDouble(s));
}
/**
@ -489,17 +504,13 @@ public final class Double extends Number implements Comparable<Double>
*/
public boolean equals(Object obj)
{
if (! (obj instanceof Double))
return false;
double d = ((Double) obj).value;
// Avoid call to native method. However, some implementations, like gcj,
// are better off using floatToIntBits(value) == floatToIntBits(f).
// Check common case first, then check NaN and 0.
if (value == d)
return (value != 0) || (1 / value == 1 / d);
return isNaN(value) && isNaN(d);
if (obj instanceof Double)
{
double d = ((Double) obj).value;
return (doubleToRawLongBits(value) == doubleToRawLongBits(d)) ||
(isNaN(value) && isNaN(d));
}
return false;
}
/**

View file

@ -89,7 +89,6 @@ public abstract class Enum<T extends Enum<T>>
* @exception IllegalArgumentException when there is no value s in
* the enum etype.
*/
@SuppressWarnings("unchecked")
public static <S extends Enum<S>> S valueOf(Class<S> etype, String s)
{
if (etype == null || s == null)
@ -103,7 +102,9 @@ public abstract class Enum<T extends Enum<T>>
if (! f.isEnumConstant())
throw new IllegalArgumentException(s);
Class.setAccessible(f);
return (S) f.get(null);
@SuppressWarnings("unchecked")
S val = (S) f.get(null);
return val;
}
catch (NoSuchFieldException exception)
{

View file

@ -39,6 +39,8 @@ exception statement from your version. */
package java.lang;
import gnu.java.lang.CPStringBuilder;
/**
* Instances of class <code>Float</code> represent primitive
* <code>float</code> values.
@ -101,6 +103,16 @@ public final class Float extends Number implements Comparable<Float>
*/
public static final int SIZE = 32;
/**
* Cache representation of 0
*/
private static final Float ZERO = new Float(0.0f);
/**
* Cache representation of 1
*/
private static final Float ONE = new Float(1.0f);
/**
* The immutable value of this Float.
*
@ -211,7 +223,7 @@ public final class Float extends Number implements Comparable<Float>
return f < 0 ? "-Infinity" : "Infinity";
int bits = floatToIntBits(f);
StringBuilder result = new StringBuilder();
CPStringBuilder result = new CPStringBuilder();
if (bits < 0)
result.append('-');
@ -273,7 +285,7 @@ public final class Float extends Number implements Comparable<Float>
*/
public static Float valueOf(String s)
{
return new Float(parseFloat(s));
return valueOf(parseFloat(s));
}
/**
@ -287,8 +299,12 @@ public final class Float extends Number implements Comparable<Float>
*/
public static Float valueOf(float val)
{
// We don't actually cache, but we could.
return new Float(val);
if ((val == 0.0) && (floatToRawIntBits(val) == 0))
return ZERO;
else if (val == 1.0)
return ONE;
else
return new Float(val);
}
/**
@ -498,17 +514,13 @@ public final class Float extends Number implements Comparable<Float>
*/
public boolean equals(Object obj)
{
if (! (obj instanceof Float))
return false;
float f = ((Float) obj).value;
// Avoid call to native method. However, some implementations, like gcj,
// are better off using floatToIntBits(value) == floatToIntBits(f).
// Check common case first, then check NaN and 0.
if (value == f)
return (value != 0) || (1 / value == 1 / f);
return isNaN(value) && isNaN(f);
if (obj instanceof Float)
{
float f = ((Float) obj).value;
return (floatToRawIntBits(value) == floatToRawIntBits(f)) ||
(isNaN(value) && isNaN(f));
}
return false;
}
/**

View file

@ -37,10 +37,6 @@ exception statement from your version. */
package java.lang;
import gnu.java.util.WeakIdentityHashMap;
import java.util.Iterator;
/**
* A ThreadLocal whose value is inherited by child Threads. The value of the
* InheritableThreadLocal associated with the (parent) Thread is copied to
@ -97,24 +93,6 @@ public class InheritableThreadLocal<T> extends ThreadLocal<T>
{
// The currentThread is the parent of the new thread.
Thread parentThread = Thread.currentThread();
if (parentThread.locals != null)
{
Iterator keys = parentThread.locals.keySet().iterator();
while (keys.hasNext())
{
Object key = keys.next();
if (key instanceof InheritableThreadLocal)
{
InheritableThreadLocal local = (InheritableThreadLocal)key;
Object parentValue = parentThread.locals.get(key);
Object childValue = local.childValue(parentValue == sentinel
? null : parentValue);
if (childThread.locals == null)
childThread.locals = new WeakIdentityHashMap();
childThread.locals.put(key, (childValue == null
? sentinel : childValue));
}
}
}
childThread.locals.inherit(parentThread.locals);
}
}

View file

@ -52,6 +52,7 @@ package java.lang;
* @author Eric Blake (ebb9@email.byu.edu)
* @author Tom Tromey (tromey@redhat.com)
* @author Andrew John Hughes (gnu_andrew@member.fsf.org)
* @author Ian Rogers
* @since 1.0
* @status updated to 1.5
*/
@ -92,7 +93,12 @@ public final class Integer extends Number implements Comparable<Integer>
// these constants control how much we actually cache.
private static final int MIN_CACHE = -128;
private static final int MAX_CACHE = 127;
private static Integer[] intCache = new Integer[MAX_CACHE - MIN_CACHE + 1];
private static final Integer[] intCache = new Integer[MAX_CACHE - MIN_CACHE + 1];
static
{
for (int i=MIN_CACHE; i <= MAX_CACHE; i++)
intCache[i - MIN_CACHE] = new Integer(i);
}
/**
* The immutable value of this Integer.
@ -125,6 +131,45 @@ public final class Integer extends Number implements Comparable<Integer>
value = parseInt(s, 10, false);
}
/**
* Return the size of a string large enough to hold the given number
*
* @param num the number we want the string length for (must be positive)
* @param radix the radix (base) that will be used for the string
* @return a size sufficient for a string of num
*/
private static int stringSize(int num, int radix) {
int exp;
if (radix < 4)
{
exp = 1;
}
else if (radix < 8)
{
exp = 2;
}
else if (radix < 16)
{
exp = 3;
}
else if (radix < 32)
{
exp = 4;
}
else
{
exp = 5;
}
int size=0;
do
{
num >>>= exp;
size++;
}
while(num != 0);
return size;
}
/**
* Converts the <code>int</code> to a <code>String</code> using
* the specified radix (base). If the radix exceeds
@ -142,22 +187,40 @@ public final class Integer extends Number implements Comparable<Integer>
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10;
// For negative numbers, print out the absolute value w/ a leading '-'.
// Use an array large enough for a binary number.
char[] buffer = new char[33];
int i = 33;
boolean isNeg = false;
if (num < 0)
// Is the value negative?
boolean isNeg = num < 0;
// Is the string a single character?
if (!isNeg && num < radix)
return new String(digits, num, 1, true);
// Compute string size and allocate buffer
// account for a leading '-' if the value is negative
int size;
int i;
char[] buffer;
if (isNeg)
{
isNeg = true;
num = -num;
// When the value is MIN_VALUE, it overflows when made positive
if (num < 0)
{
i = size = stringSize(MAX_VALUE, radix) + 2;
buffer = new char[size];
buffer[--i] = digits[(int) (-(num + radix) % radix)];
num = -(num / radix);
}
else
{
i = size = stringSize(num, radix) + 1;
buffer = new char[size];
}
}
else
{
i = size = stringSize(num, radix);
buffer = new char[size];
}
do
@ -171,7 +234,7 @@ public final class Integer extends Number implements Comparable<Integer>
buffer[--i] = '-';
// Package constructor avoids an array copy.
return new String(buffer, i, 33 - i, true);
return new String(buffer, i, size - i, true);
}
/**
@ -275,7 +338,7 @@ public final class Integer extends Number implements Comparable<Integer>
*/
public static Integer valueOf(String s, int radix)
{
return new Integer(parseInt(s, radix, false));
return valueOf(parseInt(s, radix, false));
}
/**
@ -291,7 +354,7 @@ public final class Integer extends Number implements Comparable<Integer>
*/
public static Integer valueOf(String s)
{
return new Integer(parseInt(s, 10, false));
return valueOf(parseInt(s, 10, false));
}
/**
@ -306,12 +369,8 @@ public final class Integer extends Number implements Comparable<Integer>
{
if (val < MIN_CACHE || val > MAX_CACHE)
return new Integer(val);
synchronized (intCache)
{
if (intCache[val - MIN_CACHE] == null)
intCache[val - MIN_CACHE] = new Integer(val);
return intCache[val - MIN_CACHE];
}
else
return intCache[val - MIN_CACHE];
}
/**
@ -440,7 +499,7 @@ public final class Integer extends Number implements Comparable<Integer>
public static Integer getInteger(String nm, int val)
{
Integer result = getInteger(nm, null);
return result == null ? new Integer(val) : result;
return result == null ? valueOf(val) : result;
}
/**
@ -506,7 +565,7 @@ public final class Integer extends Number implements Comparable<Integer>
*/
public static Integer decode(String str)
{
return new Integer(parseInt(str, 10, true));
return valueOf(parseInt(str, 10, true));
}
/**
@ -628,7 +687,14 @@ public final class Integer extends Number implements Comparable<Integer>
*/
public static int signum(int x)
{
return x < 0 ? -1 : (x > 0 ? 1 : 0);
return (x >> 31) | (-x >>> 31);
// The LHS propagates the sign bit through every bit in the word;
// if X < 0, every bit is set to 1, else 0. if X > 0, the RHS
// negates x and shifts the resulting 1 in the sign bit to the
// LSB, leaving every other bit 0.
// Hacker's Delight, Section 2-7
}
/**
@ -666,10 +732,22 @@ public final class Integer extends Number implements Comparable<Integer>
// Package visible for use by Long.
static String toUnsignedString(int num, int exp)
{
// Use an array large enough for a binary number.
// Compute string length
int size = 1;
int copy = num >>> exp;
while (copy != 0)
{
size++;
copy >>>= exp;
}
// Quick path for single character strings
if (size == 1)
return new String(digits, num, 1, true);
// Encode into buffer
int mask = (1 << exp) - 1;
char[] buffer = new char[32];
int i = 32;
char[] buffer = new char[size];
int i = size;
do
{
buffer[--i] = digits[num & mask];
@ -678,7 +756,7 @@ public final class Integer extends Number implements Comparable<Integer>
while (num != 0);
// Package constructor avoids an array copy.
return new String(buffer, i, 32 - i, true);
return new String(buffer, i, size - i, true);
}
/**

View file

@ -51,6 +51,7 @@ package java.lang;
* @author Eric Blake (ebb9@email.byu.edu)
* @author Tom Tromey (tromey@redhat.com)
* @author Andrew John Hughes (gnu_andrew@member.fsf.org)
* @author Ian Rogers
* @since 1.0
* @status updated to 1.5
*/
@ -86,6 +87,18 @@ public final class Long extends Number implements Comparable<Long>
*/
public static final int SIZE = 64;
// This caches some Long values, and is used by boxing
// conversions via valueOf(). We cache at least -128..127;
// these constants control how much we actually cache.
private static final int MIN_CACHE = -128;
private static final int MAX_CACHE = 127;
private static final Long[] longCache = new Long[MAX_CACHE - MIN_CACHE + 1];
static
{
for (int i=MIN_CACHE; i <= MAX_CACHE; i++)
longCache[i - MIN_CACHE] = new Long(i);
}
/**
* The immutable value of this Long.
*
@ -117,6 +130,45 @@ public final class Long extends Number implements Comparable<Long>
value = parseLong(s, 10, false);
}
/**
* Return the size of a string large enough to hold the given number
*
* @param num the number we want the string length for (must be positive)
* @param radix the radix (base) that will be used for the string
* @return a size sufficient for a string of num
*/
private static int stringSize(long num, int radix) {
int exp;
if (radix < 4)
{
exp = 1;
}
else if (radix < 8)
{
exp = 2;
}
else if (radix < 16)
{
exp = 3;
}
else if (radix < 32)
{
exp = 4;
}
else
{
exp = 5;
}
int size=0;
do
{
num >>>= exp;
size++;
}
while(num != 0);
return size;
}
/**
* Converts the <code>long</code> to a <code>String</code> using
* the specified radix (base). If the radix exceeds
@ -131,29 +183,43 @@ public final class Long extends Number implements Comparable<Long>
*/
public static String toString(long num, int radix)
{
// Use the Integer toString for efficiency if possible.
if ((int) num == num)
return Integer.toString((int) num, radix);
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10;
// For negative numbers, print out the absolute value w/ a leading '-'.
// Use an array large enough for a binary number.
char[] buffer = new char[65];
int i = 65;
boolean isNeg = false;
if (num < 0)
// Is the value negative?
boolean isNeg = num < 0;
// Is the string a single character?
if (!isNeg && num < radix)
return new String(digits, (int)num, 1, true);
// Compute string size and allocate buffer
// account for a leading '-' if the value is negative
int size;
int i;
char[] buffer;
if (isNeg)
{
isNeg = true;
num = -num;
// When the value is MIN_VALUE, it overflows when made positive
if (num < 0)
{
buffer[--i] = digits[(int) (-(num + radix) % radix)];
num = -(num / radix);
}
{
i = size = stringSize(MAX_VALUE, radix) + 2;
buffer = new char[size];
buffer[--i] = digits[(int) (-(num + radix) % radix)];
num = -(num / radix);
}
else
{
i = size = stringSize(num, radix) + 1;
buffer = new char[size];
}
}
else
{
i = size = stringSize(num, radix);
buffer = new char[size];
}
do
@ -167,7 +233,7 @@ public final class Long extends Number implements Comparable<Long>
buffer[--i] = '-';
// Package constructor avoids an array copy.
return new String(buffer, i, 65 - i, true);
return new String(buffer, i, size - i, true);
}
/**
@ -270,7 +336,7 @@ public final class Long extends Number implements Comparable<Long>
*/
public static Long valueOf(String s, int radix)
{
return new Long(parseLong(s, radix, false));
return valueOf(parseLong(s, radix, false));
}
/**
@ -286,7 +352,7 @@ public final class Long extends Number implements Comparable<Long>
*/
public static Long valueOf(String s)
{
return new Long(parseLong(s, 10, false));
return valueOf(parseLong(s, 10, false));
}
/**
@ -298,9 +364,10 @@ public final class Long extends Number implements Comparable<Long>
*/
public static Long valueOf(long val)
{
// We aren't required to cache here. We could, though perhaps we
// ought to consider that as an empirical question.
return new Long(val);
if (val < MIN_CACHE || val > MAX_CACHE)
return new Long(val);
else
return longCache[((int)val) - MIN_CACHE];
}
/**
@ -337,7 +404,7 @@ public final class Long extends Number implements Comparable<Long>
*/
public static Long decode(String str)
{
return new Long(parseLong(str, 10, true));
return valueOf(parseLong(str, 10, true));
}
/**
@ -467,7 +534,7 @@ public final class Long extends Number implements Comparable<Long>
public static Long getLong(String nm, long val)
{
Long result = getLong(nm, null);
return result == null ? new Long(val) : result;
return result == null ? valueOf(val) : result;
}
/**
@ -622,7 +689,14 @@ public final class Long extends Number implements Comparable<Long>
*/
public static int signum(long x)
{
return x < 0 ? -1 : (x > 0 ? 1 : 0);
return (int) ((x >> 63) | (-x >>> 63));
// The LHS propagates the sign bit through every bit in the word;
// if X < 0, every bit is set to 1, else 0. if X > 0, the RHS
// negates x and shifts the resulting 1 in the sign bit to the
// LSB, leaving every other bit 0.
// Hacker's Delight, Section 2-7
}
/**
@ -655,16 +729,22 @@ public final class Long extends Number implements Comparable<Long>
*/
private static String toUnsignedString(long num, int exp)
{
// Use the Integer toUnsignedString for efficiency if possible.
// If NUM<0 then this particular optimization doesn't work
// properly.
if (num >= 0 && (int) num == num)
return Integer.toUnsignedString((int) num, exp);
// Compute string length
int size = 1;
long copy = num >>> exp;
while (copy != 0)
{
size++;
copy >>>= exp;
}
// Quick path for single character strings
if (size == 1)
return new String(digits, (int)num, 1, true);
// Use an array large enough for a binary number.
// Encode into buffer
int mask = (1 << exp) - 1;
char[] buffer = new char[64];
int i = 64;
char[] buffer = new char[size];
int i = size;
do
{
buffer[--i] = digits[(int) num & mask];
@ -673,7 +753,7 @@ public final class Long extends Number implements Comparable<Long>
while (num != 0);
// Package constructor avoids an array copy.
return new String(buffer, i, 64 - i, true);
return new String(buffer, i, size - i, true);
}
/**

View file

@ -90,6 +90,11 @@ public final class Short extends Number implements Comparable<Short>
private static final int MIN_CACHE = -128;
private static final int MAX_CACHE = 127;
private static Short[] shortCache = new Short[MAX_CACHE - MIN_CACHE + 1];
static
{
for (short i=MIN_CACHE; i <= MAX_CACHE; i++)
shortCache[i - MIN_CACHE] = new Short(i);
}
/**
* The immutable value of this Short.
@ -184,7 +189,7 @@ public final class Short extends Number implements Comparable<Short>
*/
public static Short valueOf(String s, int radix)
{
return new Short(parseShort(s, radix));
return valueOf(parseShort(s, radix));
}
/**
@ -200,7 +205,7 @@ public final class Short extends Number implements Comparable<Short>
*/
public static Short valueOf(String s)
{
return new Short(parseShort(s, 10));
return valueOf(parseShort(s, 10));
}
/**
@ -216,12 +221,8 @@ public final class Short extends Number implements Comparable<Short>
{
if (val < MIN_CACHE || val > MAX_CACHE)
return new Short(val);
synchronized (shortCache)
{
if (shortCache[val - MIN_CACHE] == null)
shortCache[val - MIN_CACHE] = new Short(val);
return shortCache[val - MIN_CACHE];
}
else
return shortCache[val - MIN_CACHE];
}
/**
@ -260,7 +261,7 @@ public final class Short extends Number implements Comparable<Short>
int i = Integer.parseInt(s, 10, true);
if ((short) i != i)
throw new NumberFormatException();
return new Short((short) i);
return valueOf((short) i);
}
/**

View file

@ -40,6 +40,7 @@ exception statement from your version. */
package java.lang;
import gnu.java.lang.CharData;
import gnu.java.lang.CPStringBuilder;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
@ -2072,7 +2073,7 @@ public final class String
int replaceLength = replacement.length();
int startPos = this.indexOf(targetString);
StringBuilder result = new StringBuilder(this);
CPStringBuilder result = new CPStringBuilder(this);
while (startPos != -1)
{
// Replace the target with the replacement

View file

@ -1,5 +1,5 @@
/* StringBuffer.java -- Growable strings
Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2008
Free Software Foundation, Inc.
This file is part of GNU Classpath.
@ -73,6 +73,7 @@ import java.io.Serializable;
* @status updated to 1.4
*/
public final class StringBuffer
extends AbstractStringBuffer
implements Serializable, CharSequence, Appendable
{
// Implementation note: if you change this class, you usually will
@ -83,23 +84,6 @@ public final class StringBuffer
*/
private static final long serialVersionUID = 3388685877147921107L;
/**
* Index of next available character (and thus the size of the current
* string contents). Note that this has permissions set this way so that
* String can get the value.
*
* @serial the number of characters in the buffer
*/
int count;
/**
* The buffer. Note that this has permissions set this way so that String
* can get the value.
*
* @serial the buffer
*/
char[] value;
/**
* True if the buffer is shared with another object (StringBuffer or
* String); this means the buffer must be copied before writing to it again.
@ -110,17 +94,12 @@ public final class StringBuffer
*/
boolean shared;
/**
* The default capacity of a buffer.
*/
private static final int DEFAULT_CAPACITY = 16;
/**
* Create a new StringBuffer with default capacity 16.
*/
public StringBuffer()
{
this(DEFAULT_CAPACITY);
super();
}
/**
@ -132,7 +111,7 @@ public final class StringBuffer
*/
public StringBuffer(int capacity)
{
value = new char[capacity];
super(capacity);
}
/**
@ -146,9 +125,7 @@ public final class StringBuffer
public StringBuffer(String str)
{
// Unfortunately, because the size is 16 larger, we cannot share.
count = str.count;
value = new char[count + DEFAULT_CAPACITY];
str.getChars(0, count, value, 0);
super(str);
}
/**
@ -163,11 +140,7 @@ public final class StringBuffer
*/
public StringBuffer(CharSequence seq)
{
int len = seq.length();
count = len <= 0 ? 0 : len;
value = new char[count + DEFAULT_CAPACITY];
for (int i = 0; i < len; ++i)
value[i] = seq.charAt(i);
super(seq);
}
/**
@ -226,29 +199,7 @@ public final class StringBuffer
*/
public synchronized void setLength(int newLength)
{
if (newLength < 0)
throw new StringIndexOutOfBoundsException(newLength);
int valueLength = value.length;
/* Always call ensureCapacity_unsynchronized in order to preserve
copy-on-write semantics. */
ensureCapacity_unsynchronized(newLength);
if (newLength < valueLength)
{
/* If the StringBuffer's value just grew, then we know that
value is newly allocated and the region between count and
newLength is filled with '\0'. */
count = newLength;
}
else
{
/* The StringBuffer's value doesn't need to grow. However,
we should clear out any cruft that may exist. */
while (count < newLength)
value[count++] = '\0';
}
super.setLength(newLength);
}
/**
@ -257,12 +208,11 @@ public final class StringBuffer
* @param index the index of the character to get, starting at 0
* @return the character at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* (while unspecified, this is a StringIndexOutOfBoundsException)
*/
public synchronized char charAt(int index)
{
if (index < 0 || index >= count)
throw new StringIndexOutOfBoundsException(index);
return value[index];
return super.charAt(index);
}
/**
@ -277,7 +227,7 @@ public final class StringBuffer
*/
public synchronized int codePointAt(int index)
{
return Character.codePointAt(value, index, count);
return super.codePointAt(index);
}
/**
@ -291,11 +241,7 @@ public final class StringBuffer
*/
public synchronized int codePointBefore(int index)
{
// Character.codePointBefore() doesn't perform this check. We
// could use the CharSequence overload, but this is just as easy.
if (index >= count)
throw new IndexOutOfBoundsException();
return Character.codePointBefore(value, index, 1);
return super.codePointBefore(index);
}
/**
@ -316,9 +262,7 @@ public final class StringBuffer
public synchronized void getChars(int srcOffset, int srcEnd,
char[] dst, int dstOffset)
{
if (srcOffset < 0 || srcEnd > count || srcEnd < srcOffset)
throw new StringIndexOutOfBoundsException();
VMSystem.arraycopy(value, srcOffset, dst, dstOffset, srcEnd - srcOffset);
super.getChars(srcOffset, srcEnd, dst, dstOffset);
}
/**
@ -331,11 +275,7 @@ public final class StringBuffer
*/
public synchronized void setCharAt(int index, char ch)
{
if (index < 0 || index >= count)
throw new StringIndexOutOfBoundsException(index);
// Call ensureCapacity to enforce copy-on-write.
ensureCapacity_unsynchronized(count);
value[index] = ch;
super.setCharAt(index, ch);
}
/**
@ -348,9 +288,10 @@ public final class StringBuffer
* @see String#valueOf(Object)
* @see #append(String)
*/
public StringBuffer append(Object obj)
public synchronized StringBuffer append(Object obj)
{
return append(obj == null ? "null" : obj.toString());
super.append(obj);
return this;
}
/**
@ -362,12 +303,7 @@ public final class StringBuffer
*/
public synchronized StringBuffer append(String str)
{
if (str == null)
str = "null";
int len = str.count;
ensureCapacity_unsynchronized(count + len);
str.getChars(0, len, value, count);
count += len;
super.append(str);
return this;
}
@ -383,15 +319,7 @@ public final class StringBuffer
*/
public synchronized StringBuffer append(StringBuffer stringBuffer)
{
if (stringBuffer == null)
return append("null");
synchronized (stringBuffer)
{
int len = stringBuffer.count;
ensureCapacity_unsynchronized(count + len);
VMSystem.arraycopy(stringBuffer.value, 0, value, count, len);
count += len;
}
super.append(stringBuffer);
return this;
}
@ -405,9 +333,10 @@ public final class StringBuffer
* @throws NullPointerException if <code>str</code> is <code>null</code>
* @see #append(char[], int, int)
*/
public StringBuffer append(char[] data)
public synchronized StringBuffer append(char[] data)
{
return append(data, 0, data.length);
super.append(data, 0, data.length);
return this;
}
/**
@ -426,30 +355,7 @@ public final class StringBuffer
*/
public synchronized StringBuffer append(char[] data, int offset, int count)
{
if (offset < 0 || count < 0 || offset > data.length - count)
throw new StringIndexOutOfBoundsException();
ensureCapacity_unsynchronized(this.count + count);
VMSystem.arraycopy(data, offset, value, this.count, count);
this.count += count;
return this;
}
/**
* Append the code point to this <code>StringBuffer</code>.
* This is like #append(char), but will append two characters
* if a supplementary code point is given.
*
* @param code the code point to append
* @return this <code>StringBuffer</code>
* @see Character#toChars(int, char[], int)
* @since 1.5
*/
public synchronized StringBuffer appendCodePoint(int code)
{
int len = Character.charCount(code);
ensureCapacity_unsynchronized(count + len);
Character.toChars(code, value, count);
count += len;
super.append(data, offset, count);
return this;
}
@ -462,9 +368,10 @@ public final class StringBuffer
* @return this <code>StringBuffer</code>
* @see String#valueOf(boolean)
*/
public StringBuffer append(boolean bool)
public synchronized StringBuffer append(boolean bool)
{
return append(bool ? "true" : "false");
super.append(bool);
return this;
}
/**
@ -475,8 +382,7 @@ public final class StringBuffer
*/
public synchronized StringBuffer append(char ch)
{
ensureCapacity_unsynchronized(count + 1);
value[count++] = ch;
super.append(ch);
return this;
}
@ -490,7 +396,8 @@ public final class StringBuffer
*/
public synchronized StringBuffer append(CharSequence seq)
{
return append(seq, 0, seq.length());
super.append(seq, 0, seq.length());
return this;
}
/**
@ -506,14 +413,7 @@ public final class StringBuffer
*/
public synchronized StringBuffer append(CharSequence seq, int start, int end)
{
if (seq == null)
return append("null");
if (end - start > 0)
{
ensureCapacity_unsynchronized(count + end - start);
for (; start < end; ++start)
value[count++] = seq.charAt(start);
}
super.append(seq, start, end);
return this;
}
@ -527,9 +427,10 @@ public final class StringBuffer
* @see String#valueOf(int)
*/
// This is native in libgcj, for efficiency.
public StringBuffer append(int inum)
public synchronized StringBuffer append(int inum)
{
return append(String.valueOf(inum));
super.append(inum);
return this;
}
/**
@ -541,9 +442,10 @@ public final class StringBuffer
* @return this <code>StringBuffer</code>
* @see String#valueOf(long)
*/
public StringBuffer append(long lnum)
public synchronized StringBuffer append(long lnum)
{
return append(Long.toString(lnum, 10));
super.append(lnum);
return this;
}
/**
@ -555,9 +457,10 @@ public final class StringBuffer
* @return this <code>StringBuffer</code>
* @see String#valueOf(float)
*/
public StringBuffer append(float fnum)
public synchronized StringBuffer append(float fnum)
{
return append(Float.toString(fnum));
super.append(fnum);
return this;
}
/**
@ -569,9 +472,26 @@ public final class StringBuffer
* @return this <code>StringBuffer</code>
* @see String#valueOf(double)
*/
public StringBuffer append(double dnum)
public synchronized StringBuffer append(double dnum)
{
return append(Double.toString(dnum));
super.append(dnum);
return this;
}
/**
* Append the code point to this <code>StringBuffer</code>.
* This is like #append(char), but will append two characters
* if a supplementary code point is given.
*
* @param code the code point to append
* @return this <code>StringBuffer</code>
* @see Character#toChars(int, char[], int)
* @since 1.5
*/
public synchronized StringBuffer appendCodePoint(int code)
{
super.appendCodePoint(code);
return this;
}
/**
@ -587,15 +507,8 @@ public final class StringBuffer
*/
public synchronized StringBuffer delete(int start, int end)
{
if (start < 0 || start > count || start > end)
throw new StringIndexOutOfBoundsException(start);
if (end > count)
end = count;
// This will unshare if required.
ensureCapacity_unsynchronized(count);
if (count - end != 0)
VMSystem.arraycopy(value, end, value, start, count - end);
count -= end - start;
super.delete(start, end);
return this;
}
@ -607,9 +520,10 @@ public final class StringBuffer
* @throws StringIndexOutOfBoundsException if index is out of bounds
* @since 1.2
*/
public StringBuffer deleteCharAt(int index)
public synchronized StringBuffer deleteCharAt(int index)
{
return delete(index, index + 1);
super.deleteCharAt(index);
return this;
}
/**
@ -628,19 +542,7 @@ public final class StringBuffer
*/
public synchronized StringBuffer replace(int start, int end, String str)
{
if (start < 0 || start > count || start > end)
throw new StringIndexOutOfBoundsException(start);
int len = str.count;
// Calculate the difference in 'count' after the replace.
int delta = len - (end > count ? count : end) + start;
ensureCapacity_unsynchronized(count + delta);
if (delta != 0 && end < count)
VMSystem.arraycopy(value, end, value, end + delta, count - end);
str.getChars(0, len, value, start);
count += delta;
super.replace(start, end, str);
return this;
}
@ -720,13 +622,7 @@ public final class StringBuffer
public synchronized StringBuffer insert(int offset,
char[] str, int str_offset, int len)
{
if (offset < 0 || offset > count || len < 0
|| str_offset < 0 || str_offset > str.length - len)
throw new StringIndexOutOfBoundsException();
ensureCapacity_unsynchronized(count + len);
VMSystem.arraycopy(value, offset, value, offset + len, count - offset);
VMSystem.arraycopy(str, str_offset, value, offset, len);
count += len;
super.insert(offset, str, str_offset, len);
return this;
}
@ -741,9 +637,10 @@ public final class StringBuffer
* @exception StringIndexOutOfBoundsException if offset is out of bounds
* @see String#valueOf(Object)
*/
public StringBuffer insert(int offset, Object obj)
public synchronized StringBuffer insert(int offset, Object obj)
{
return insert(offset, obj == null ? "null" : obj.toString());
super.insert(offset, obj);
return this;
}
/**
@ -758,15 +655,7 @@ public final class StringBuffer
*/
public synchronized StringBuffer insert(int offset, String str)
{
if (offset < 0 || offset > count)
throw new StringIndexOutOfBoundsException(offset);
if (str == null)
str = "null";
int len = str.count;
ensureCapacity_unsynchronized(count + len);
VMSystem.arraycopy(value, offset, value, offset + len, count - offset);
str.getChars(0, len, value, offset);
count += len;
super.insert(offset, str);
return this;
}
@ -783,9 +672,8 @@ public final class StringBuffer
*/
public synchronized StringBuffer insert(int offset, CharSequence sequence)
{
if (sequence == null)
sequence = "null";
return insert(offset, sequence, 0, sequence.length());
super.insert(offset, sequence);
return this;
}
/**
@ -805,16 +693,7 @@ public final class StringBuffer
public synchronized StringBuffer insert(int offset, CharSequence sequence,
int start, int end)
{
if (sequence == null)
sequence = "null";
if (start < 0 || end < 0 || start > end || end > sequence.length())
throw new IndexOutOfBoundsException();
int len = end - start;
ensureCapacity_unsynchronized(count + len);
VMSystem.arraycopy(value, offset, value, offset + len, count - offset);
for (int i = start; i < end; ++i)
value[offset++] = sequence.charAt(i);
count += len;
super.insert(offset, sequence, start, end);
return this;
}
@ -829,9 +708,10 @@ public final class StringBuffer
* @throws StringIndexOutOfBoundsException if offset is out of bounds
* @see #insert(int, char[], int, int)
*/
public StringBuffer insert(int offset, char[] data)
public synchronized StringBuffer insert(int offset, char[] data)
{
return insert(offset, data, 0, data.length);
super.insert(offset, data, 0, data.length);
return this;
}
/**
@ -845,9 +725,10 @@ public final class StringBuffer
* @throws StringIndexOutOfBoundsException if offset is out of bounds
* @see String#valueOf(boolean)
*/
public StringBuffer insert(int offset, boolean bool)
public synchronized StringBuffer insert(int offset, boolean bool)
{
return insert(offset, bool ? "true" : "false");
super.insert(offset, bool);
return this;
}
/**
@ -860,12 +741,7 @@ public final class StringBuffer
*/
public synchronized StringBuffer insert(int offset, char ch)
{
if (offset < 0 || offset > count)
throw new StringIndexOutOfBoundsException(offset);
ensureCapacity_unsynchronized(count + 1);
VMSystem.arraycopy(value, offset, value, offset + 1, count - offset);
value[offset] = ch;
count++;
super.insert(offset, ch);
return this;
}
@ -880,9 +756,10 @@ public final class StringBuffer
* @throws StringIndexOutOfBoundsException if offset is out of bounds
* @see String#valueOf(int)
*/
public StringBuffer insert(int offset, int inum)
public synchronized StringBuffer insert(int offset, int inum)
{
return insert(offset, String.valueOf(inum));
super.insert(offset, inum);
return this;
}
/**
@ -896,9 +773,10 @@ public final class StringBuffer
* @throws StringIndexOutOfBoundsException if offset is out of bounds
* @see String#valueOf(long)
*/
public StringBuffer insert(int offset, long lnum)
public synchronized StringBuffer insert(int offset, long lnum)
{
return insert(offset, Long.toString(lnum, 10));
super.insert(offset, lnum);
return this;
}
/**
@ -912,9 +790,10 @@ public final class StringBuffer
* @throws StringIndexOutOfBoundsException if offset is out of bounds
* @see String#valueOf(float)
*/
public StringBuffer insert(int offset, float fnum)
public synchronized StringBuffer insert(int offset, float fnum)
{
return insert(offset, Float.toString(fnum));
super.insert(offset, fnum);
return this;
}
/**
@ -928,9 +807,10 @@ public final class StringBuffer
* @throws StringIndexOutOfBoundsException if offset is out of bounds
* @see String#valueOf(double)
*/
public StringBuffer insert(int offset, double dnum)
public synchronized StringBuffer insert(int offset, double dnum)
{
return insert(offset, Double.toString(dnum));
super.insert(offset, dnum);
return this;
}
/**
@ -942,9 +822,9 @@ public final class StringBuffer
* @see #indexOf(String, int)
* @since 1.4
*/
public int indexOf(String str)
public synchronized int indexOf(String str)
{
return indexOf(str, 0);
return super.indexOf(str, 0);
}
/**
@ -961,13 +841,7 @@ public final class StringBuffer
*/
public synchronized int indexOf(String str, int fromIndex)
{
if (fromIndex < 0)
fromIndex = 0;
int limit = count - str.count;
for ( ; fromIndex <= limit; fromIndex++)
if (regionMatches(fromIndex, str))
return fromIndex;
return -1;
return super.indexOf(str, fromIndex);
}
/**
@ -979,9 +853,9 @@ public final class StringBuffer
* @see #lastIndexOf(String, int)
* @since 1.4
*/
public int lastIndexOf(String str)
public synchronized int lastIndexOf(String str)
{
return lastIndexOf(str, count - str.count);
return super.lastIndexOf(str, count - str.count);
}
/**
@ -998,11 +872,7 @@ public final class StringBuffer
*/
public synchronized int lastIndexOf(String str, int fromIndex)
{
fromIndex = Math.min(fromIndex, count - str.count);
for ( ; fromIndex >= 0; fromIndex--)
if (regionMatches(fromIndex, str))
return fromIndex;
return -1;
return super.lastIndexOf(str, fromIndex);
}
/**
@ -1013,14 +883,7 @@ public final class StringBuffer
*/
public synchronized StringBuffer reverse()
{
// Call ensureCapacity to enforce copy-on-write.
ensureCapacity_unsynchronized(count);
for (int i = count >> 1, j = count - i; --i >= 0; ++j)
{
char c = value[i];
value[i] = value[j];
value[j] = c;
}
super.reverse();
return this;
}
@ -1047,19 +910,7 @@ public final class StringBuffer
*/
public synchronized void trimToSize()
{
int wouldSave = value.length - count;
// Some random heuristics: if we save less than 20 characters, who
// cares.
if (wouldSave < 20)
return;
// If we save more than 200 characters, shrink.
// If we save more than 1/4 of the buffer, shrink.
if (wouldSave > 200 || wouldSave * 4 > value.length)
{
char[] newValue = new char[count];
VMSystem.arraycopy(value, 0, newValue, 0, count);
value = newValue;
}
super.trimToSize();
}
/**
@ -1076,31 +927,7 @@ public final class StringBuffer
*/
public synchronized int codePointCount(int start, int end)
{
if (start < 0 || end >= count || start > end)
throw new StringIndexOutOfBoundsException();
int count = 0;
while (start < end)
{
char base = value[start];
if (base < Character.MIN_HIGH_SURROGATE
|| base > Character.MAX_HIGH_SURROGATE
|| start == end
|| start == count
|| value[start + 1] < Character.MIN_LOW_SURROGATE
|| value[start + 1] > Character.MAX_LOW_SURROGATE)
{
// Nothing.
}
else
{
// Surrogate pair.
++start;
}
++start;
++count;
}
return count;
return super.codePointCount(start, end);
}
/**
@ -1116,26 +943,7 @@ public final class StringBuffer
*/
public synchronized int offsetByCodePoints(int start, int codePoints)
{
while (codePoints > 0)
{
char base = value[start];
if (base < Character.MIN_HIGH_SURROGATE
|| base > Character.MAX_HIGH_SURROGATE
|| start == count
|| value[start + 1] < Character.MIN_LOW_SURROGATE
|| value[start + 1] > Character.MAX_LOW_SURROGATE)
{
// Nothing.
}
else
{
// Surrogate pair.
++start;
}
++start;
--codePoints;
}
return start;
return super.offsetByCodePoints(start, codePoints);
}
/**
@ -1147,7 +955,7 @@ public final class StringBuffer
* @param minimumCapacity the minimum capacity
* @see #ensureCapacity(int)
*/
private void ensureCapacity_unsynchronized(int minimumCapacity)
void ensureCapacity_unsynchronized(int minimumCapacity)
{
if (shared || minimumCapacity > value.length)
{
@ -1165,26 +973,4 @@ public final class StringBuffer
}
}
/**
* Predicate which determines if a substring of this matches another String
* starting at a specified offset for each String and continuing for a
* specified length. This is more efficient than creating a String to call
* indexOf on.
*
* @param toffset index to start comparison at for this String
* @param other non-null String to compare to region of this
* @return true if regions match, false otherwise
* @see #indexOf(String, int)
* @see #lastIndexOf(String, int)
* @see String#regionMatches(boolean, int, String, int, int)
*/
private boolean regionMatches(int toffset, String other)
{
int len = other.count;
int index = other.offset;
while (--len >= 0)
if (value[toffset++] != other.value[index++])
return false;
return true;
}
}

View file

@ -1,5 +1,5 @@
/* StringBuilder.java -- Unsynchronized growable strings
Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2008
Free Software Foundation, Inc.
This file is part of GNU Classpath.
@ -75,6 +75,7 @@ import java.io.Serializable;
* @since 1.5
*/
public final class StringBuilder
extends AbstractStringBuffer
implements Serializable, CharSequence, Appendable
{
// Implementation note: if you change this class, you usually will
@ -85,34 +86,12 @@ public final class StringBuilder
*/
private static final long serialVersionUID = 4383685877147921099L;
/**
* Index of next available character (and thus the size of the current
* string contents). Note that this has permissions set this way so that
* String can get the value.
*
* @serial the number of characters in the buffer
*/
int count;
/**
* The buffer. Note that this has permissions set this way so that String
* can get the value.
*
* @serial the buffer
*/
char[] value;
/**
* The default capacity of a buffer.
*/
private static final int DEFAULT_CAPACITY = 16;
/**
* Create a new StringBuilder with default capacity 16.
*/
public StringBuilder()
{
this(DEFAULT_CAPACITY);
super();
}
/**
@ -124,7 +103,7 @@ public final class StringBuilder
*/
public StringBuilder(int capacity)
{
value = new char[capacity];
super(capacity);
}
/**
@ -137,10 +116,7 @@ public final class StringBuilder
*/
public StringBuilder(String str)
{
// Unfortunately, because the size is 16 larger, we cannot share.
count = str.count;
value = new char[count + DEFAULT_CAPACITY];
str.getChars(0, count, value, 0);
super(str);
}
/**
@ -154,11 +130,7 @@ public final class StringBuilder
*/
public StringBuilder(CharSequence seq)
{
int len = seq.length();
count = len <= 0 ? 0 : len;
value = new char[count + DEFAULT_CAPACITY];
for (int i = 0; i < len; ++i)
value[i] = seq.charAt(i);
super(seq);
}
/**
@ -188,122 +160,6 @@ public final class StringBuilder
return value.length;
}
/**
* Increase the capacity of this <code>StringBuilder</code>. This will
* ensure that an expensive growing operation will not occur until
* <code>minimumCapacity</code> is reached. The buffer is grown to the
* larger of <code>minimumCapacity</code> and
* <code>capacity() * 2 + 2</code>, if it is not already large enough.
*
* @param minimumCapacity the new capacity
* @see #capacity()
*/
public void ensureCapacity(int minimumCapacity)
{
if (minimumCapacity > value.length)
{
int max = value.length * 2 + 2;
minimumCapacity = (minimumCapacity < max ? max : minimumCapacity);
char[] nb = new char[minimumCapacity];
VMSystem.arraycopy(value, 0, nb, 0, count);
value = nb;
}
}
/**
* Set the length of this StringBuilder. If the new length is greater than
* the current length, all the new characters are set to '\0'. If the new
* length is less than the current length, the first <code>newLength</code>
* characters of the old array will be preserved, and the remaining
* characters are truncated.
*
* @param newLength the new length
* @throws IndexOutOfBoundsException if the new length is negative
* (while unspecified, this is a StringIndexOutOfBoundsException)
* @see #length()
*/
public void setLength(int newLength)
{
if (newLength < 0)
throw new StringIndexOutOfBoundsException(newLength);
int valueLength = value.length;
/* Always call ensureCapacity in order to preserve copy-on-write
semantics. */
ensureCapacity(newLength);
if (newLength < valueLength)
{
/* If the StringBuilder's value just grew, then we know that
value is newly allocated and the region between count and
newLength is filled with '\0'. */
count = newLength;
}
else
{
/* The StringBuilder's value doesn't need to grow. However,
we should clear out any cruft that may exist. */
while (count < newLength)
value[count++] = '\0';
}
}
/**
* Get the character at the specified index.
*
* @param index the index of the character to get, starting at 0
* @return the character at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* (while unspecified, this is a StringIndexOutOfBoundsException)
*/
public char charAt(int index)
{
if (index < 0 || index >= count)
throw new StringIndexOutOfBoundsException(index);
return value[index];
}
/**
* Get the specified array of characters. <code>srcOffset - srcEnd</code>
* characters will be copied into the array you pass in.
*
* @param srcOffset the index to start copying from (inclusive)
* @param srcEnd the index to stop copying from (exclusive)
* @param dst the array to copy into
* @param dstOffset the index to start copying into
* @throws NullPointerException if dst is null
* @throws IndexOutOfBoundsException if any source or target indices are
* out of range (while unspecified, source problems cause a
* StringIndexOutOfBoundsException, and dest problems cause an
* ArrayIndexOutOfBoundsException)
* @see System#arraycopy(Object, int, Object, int, int)
*/
public void getChars(int srcOffset, int srcEnd,
char[] dst, int dstOffset)
{
if (srcOffset < 0 || srcEnd > count || srcEnd < srcOffset)
throw new StringIndexOutOfBoundsException();
VMSystem.arraycopy(value, srcOffset, dst, dstOffset, srcEnd - srcOffset);
}
/**
* Set the character at the specified index.
*
* @param index the index of the character to set starting at 0
* @param ch the value to set that character to
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* (while unspecified, this is a StringIndexOutOfBoundsException)
*/
public void setCharAt(int index, char ch)
{
if (index < 0 || index >= count)
throw new StringIndexOutOfBoundsException(index);
// Call ensureCapacity to enforce copy-on-write.
ensureCapacity(count);
value[index] = ch;
}
/**
* Append the <code>String</code> value of the argument to this
* <code>StringBuilder</code>. Uses <code>String.valueOf()</code> to convert
@ -316,7 +172,8 @@ public final class StringBuilder
*/
public StringBuilder append(Object obj)
{
return append(obj == null ? "null" : obj.toString());
super.append(obj);
return this;
}
/**
@ -328,12 +185,7 @@ public final class StringBuilder
*/
public StringBuilder append(String str)
{
if (str == null)
str = "null";
int len = str.count;
ensureCapacity(count + len);
str.getChars(0, len, value, count);
count += len;
super.append(str);
return this;
}
@ -348,15 +200,7 @@ public final class StringBuilder
*/
public StringBuilder append(StringBuffer stringBuffer)
{
if (stringBuffer == null)
return append("null");
synchronized (stringBuffer)
{
int len = stringBuffer.count;
ensureCapacity(count + len);
VMSystem.arraycopy(stringBuffer.value, 0, value, count, len);
count += len;
}
super.append(stringBuffer);
return this;
}
@ -372,7 +216,8 @@ public final class StringBuilder
*/
public StringBuilder append(char[] data)
{
return append(data, 0, data.length);
super.append(data, 0, data.length);
return this;
}
/**
@ -391,11 +236,7 @@ public final class StringBuilder
*/
public StringBuilder append(char[] data, int offset, int count)
{
if (offset < 0 || count < 0 || offset > data.length - count)
throw new StringIndexOutOfBoundsException();
ensureCapacity(this.count + count);
VMSystem.arraycopy(data, offset, value, this.count, count);
this.count += count;
super.append(data, offset, count);
return this;
}
@ -410,7 +251,8 @@ public final class StringBuilder
*/
public StringBuilder append(boolean bool)
{
return append(bool ? "true" : "false");
super.append(bool);
return this;
}
/**
@ -421,8 +263,7 @@ public final class StringBuilder
*/
public StringBuilder append(char ch)
{
ensureCapacity(count + 1);
value[count++] = ch;
super.append(ch);
return this;
}
@ -435,7 +276,8 @@ public final class StringBuilder
*/
public StringBuilder append(CharSequence seq)
{
return append(seq, 0, seq.length());
super.append(seq, 0, seq.length());
return this;
}
/**
@ -451,33 +293,7 @@ public final class StringBuilder
public StringBuilder append(CharSequence seq, int start,
int end)
{
if (seq == null)
return append("null");
if (end - start > 0)
{
ensureCapacity(count + end - start);
for (; start < end; ++start)
value[count++] = seq.charAt(start);
}
return this;
}
/**
* Append the code point to this <code>StringBuilder</code>.
* This is like #append(char), but will append two characters
* if a supplementary code point is given.
*
* @param code the code point to append
* @return this <code>StringBuilder</code>
* @see Character#toChars(int, char[], int)
* @since 1.5
*/
public synchronized StringBuilder appendCodePoint(int code)
{
int len = Character.charCount(code);
ensureCapacity(count + len);
Character.toChars(code, value, count);
count += len;
super.append(seq, start, end);
return this;
}
@ -493,7 +309,8 @@ public final class StringBuilder
// This is native in libgcj, for efficiency.
public StringBuilder append(int inum)
{
return append(String.valueOf(inum));
super.append(inum);
return this;
}
/**
@ -507,7 +324,8 @@ public final class StringBuilder
*/
public StringBuilder append(long lnum)
{
return append(Long.toString(lnum, 10));
super.append(lnum);
return this;
}
/**
@ -521,7 +339,8 @@ public final class StringBuilder
*/
public StringBuilder append(float fnum)
{
return append(Float.toString(fnum));
super.append(fnum);
return this;
}
/**
@ -535,7 +354,24 @@ public final class StringBuilder
*/
public StringBuilder append(double dnum)
{
return append(Double.toString(dnum));
super.append(dnum);
return this;
}
/**
* Append the code point to this <code>StringBuilder</code>.
* This is like #append(char), but will append two characters
* if a supplementary code point is given.
*
* @param code the code point to append
* @return this <code>StringBuilder</code>
* @see Character#toChars(int, char[], int)
* @since 1.5
*/
public StringBuilder appendCodePoint(int code)
{
super.appendCodePoint(code);
return this;
}
/**
@ -550,15 +386,7 @@ public final class StringBuilder
*/
public StringBuilder delete(int start, int end)
{
if (start < 0 || start > count || start > end)
throw new StringIndexOutOfBoundsException(start);
if (end > count)
end = count;
// This will unshare if required.
ensureCapacity(count);
if (count - end != 0)
VMSystem.arraycopy(value, end, value, start, count - end);
count -= end - start;
super.delete(start, end);
return this;
}
@ -571,7 +399,8 @@ public final class StringBuilder
*/
public StringBuilder deleteCharAt(int index)
{
return delete(index, index + 1);
super.deleteCharAt(index);
return this;
}
/**
@ -589,19 +418,7 @@ public final class StringBuilder
*/
public StringBuilder replace(int start, int end, String str)
{
if (start < 0 || start > count || start > end)
throw new StringIndexOutOfBoundsException(start);
int len = str.count;
// Calculate the difference in 'count' after the replace.
int delta = len - (end > count ? count : end) + start;
ensureCapacity(count + delta);
if (delta != 0 && end < count)
VMSystem.arraycopy(value, end, value, end + delta, count - end);
str.getChars(0, len, value, start);
count += delta;
super.replace(start, end, str);
return this;
}
@ -672,13 +489,7 @@ public final class StringBuilder
public StringBuilder insert(int offset,
char[] str, int str_offset, int len)
{
if (offset < 0 || offset > count || len < 0
|| str_offset < 0 || str_offset > str.length - len)
throw new StringIndexOutOfBoundsException();
ensureCapacity(count + len);
VMSystem.arraycopy(value, offset, value, offset + len, count - offset);
VMSystem.arraycopy(str, str_offset, value, offset, len);
count += len;
super.insert(offset, str, str_offset, len);
return this;
}
@ -695,7 +506,8 @@ public final class StringBuilder
*/
public StringBuilder insert(int offset, Object obj)
{
return insert(offset, obj == null ? "null" : obj.toString());
super.insert(offset, obj);
return this;
}
/**
@ -710,15 +522,7 @@ public final class StringBuilder
*/
public StringBuilder insert(int offset, String str)
{
if (offset < 0 || offset > count)
throw new StringIndexOutOfBoundsException(offset);
if (str == null)
str = "null";
int len = str.count;
ensureCapacity(count + len);
VMSystem.arraycopy(value, offset, value, offset + len, count - offset);
str.getChars(0, len, value, offset);
count += len;
super.insert(offset, str);
return this;
}
@ -732,11 +536,10 @@ public final class StringBuilder
* @return this <code>StringBuilder</code>
* @throws IndexOutOfBoundsException if offset is out of bounds
*/
public synchronized StringBuilder insert(int offset, CharSequence sequence)
public StringBuilder insert(int offset, CharSequence sequence)
{
if (sequence == null)
sequence = "null";
return insert(offset, sequence, 0, sequence.length());
super.insert(offset, sequence);
return this;
}
/**
@ -752,19 +555,10 @@ public final class StringBuilder
* @throws IndexOutOfBoundsException if offset, start,
* or end are out of bounds
*/
public synchronized StringBuilder insert(int offset, CharSequence sequence,
int start, int end)
public StringBuilder insert(int offset, CharSequence sequence,
int start, int end)
{
if (sequence == null)
sequence = "null";
if (start < 0 || end < 0 || start > end || end > sequence.length())
throw new IndexOutOfBoundsException();
int len = end - start;
ensureCapacity(count + len);
VMSystem.arraycopy(value, offset, value, offset + len, count - offset);
for (int i = start; i < end; ++i)
value[offset++] = sequence.charAt(i);
count += len;
super.insert(offset, sequence, start, end);
return this;
}
@ -781,7 +575,8 @@ public final class StringBuilder
*/
public StringBuilder insert(int offset, char[] data)
{
return insert(offset, data, 0, data.length);
super.insert(offset, data);
return this;
}
/**
@ -797,7 +592,8 @@ public final class StringBuilder
*/
public StringBuilder insert(int offset, boolean bool)
{
return insert(offset, bool ? "true" : "false");
super.insert(offset, bool);
return this;
}
/**
@ -810,12 +606,7 @@ public final class StringBuilder
*/
public StringBuilder insert(int offset, char ch)
{
if (offset < 0 || offset > count)
throw new StringIndexOutOfBoundsException(offset);
ensureCapacity(count + 1);
VMSystem.arraycopy(value, offset, value, offset + 1, count - offset);
value[offset] = ch;
count++;
super.insert(offset, ch);
return this;
}
@ -832,7 +623,8 @@ public final class StringBuilder
*/
public StringBuilder insert(int offset, int inum)
{
return insert(offset, String.valueOf(inum));
super.insert(offset, inum);
return this;
}
/**
@ -848,7 +640,8 @@ public final class StringBuilder
*/
public StringBuilder insert(int offset, long lnum)
{
return insert(offset, Long.toString(lnum, 10));
super.insert(offset, lnum);
return this;
}
/**
@ -864,7 +657,8 @@ public final class StringBuilder
*/
public StringBuilder insert(int offset, float fnum)
{
return insert(offset, Float.toString(fnum));
super.insert(offset, fnum);
return this;
}
/**
@ -880,75 +674,8 @@ public final class StringBuilder
*/
public StringBuilder insert(int offset, double dnum)
{
return insert(offset, Double.toString(dnum));
}
/**
* Finds the first instance of a substring in this StringBuilder.
*
* @param str String to find
* @return location (base 0) of the String, or -1 if not found
* @throws NullPointerException if str is null
* @see #indexOf(String, int)
*/
public int indexOf(String str)
{
return indexOf(str, 0);
}
/**
* Finds the first instance of a String in this StringBuilder, starting at
* a given index. If starting index is less than 0, the search starts at
* the beginning of this String. If the starting index is greater than the
* length of this String, or the substring is not found, -1 is returned.
*
* @param str String to find
* @param fromIndex index to start the search
* @return location (base 0) of the String, or -1 if not found
* @throws NullPointerException if str is null
*/
public int indexOf(String str, int fromIndex)
{
if (fromIndex < 0)
fromIndex = 0;
int limit = count - str.count;
for ( ; fromIndex <= limit; fromIndex++)
if (regionMatches(fromIndex, str))
return fromIndex;
return -1;
}
/**
* Finds the last instance of a substring in this StringBuilder.
*
* @param str String to find
* @return location (base 0) of the String, or -1 if not found
* @throws NullPointerException if str is null
* @see #lastIndexOf(String, int)
*/
public int lastIndexOf(String str)
{
return lastIndexOf(str, count - str.count);
}
/**
* Finds the last instance of a String in this StringBuilder, starting at a
* given index. If starting index is greater than the maximum valid index,
* then the search begins at the end of this String. If the starting index
* is less than zero, or the substring is not found, -1 is returned.
*
* @param str String to find
* @param fromIndex index to start the search
* @return location (base 0) of the String, or -1 if not found
* @throws NullPointerException if str is null
*/
public int lastIndexOf(String str, int fromIndex)
{
fromIndex = Math.min(fromIndex, count - str.count);
for ( ; fromIndex >= 0; fromIndex--)
if (regionMatches(fromIndex, str))
return fromIndex;
return -1;
super.insert(offset, dnum);
return this;
}
/**
@ -959,14 +686,7 @@ public final class StringBuilder
*/
public StringBuilder reverse()
{
// Call ensureCapacity to enforce copy-on-write.
ensureCapacity(count);
for (int i = count >> 1, j = count - i; --i >= 0; ++j)
{
char c = value[i];
value[i] = value[j];
value[j] = c;
}
super.reverse();
return this;
}
@ -983,87 +703,4 @@ public final class StringBuilder
return new String(this);
}
/**
* Predicate which determines if a substring of this matches another String
* starting at a specified offset for each String and continuing for a
* specified length. This is more efficient than creating a String to call
* indexOf on.
*
* @param toffset index to start comparison at for this String
* @param other non-null String to compare to region of this
* @return true if regions match, false otherwise
* @see #indexOf(String, int)
* @see #lastIndexOf(String, int)
* @see String#regionMatches(boolean, int, String, int, int)
*/
private boolean regionMatches(int toffset, String other)
{
int len = other.count;
int index = other.offset;
while (--len >= 0)
if (value[toffset++] != other.value[index++])
return false;
return true;
}
/**
* Get the code point at the specified index. This is like #charAt(int),
* but if the character is the start of a surrogate pair, and the
* following character completes the pair, then the corresponding
* supplementary code point is returned.
* @param index the index of the codepoint to get, starting at 0
* @return the codepoint at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* @since 1.5
*/
public int codePointAt(int index)
{
return Character.codePointAt(value, index, count);
}
/**
* Get the code point before the specified index. This is like
* #codePointAt(int), but checks the characters at <code>index-1</code> and
* <code>index-2</code> to see if they form a supplementary code point.
* @param index the index just past the codepoint to get, starting at 0
* @return the codepoint at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* @since 1.5
*/
public int codePointBefore(int index)
{
// Character.codePointBefore() doesn't perform this check. We
// could use the CharSequence overload, but this is just as easy.
if (index >= count)
throw new IndexOutOfBoundsException();
return Character.codePointBefore(value, index, 1);
}
/**
* Returns the number of Unicode code points in the specified sub sequence.
* Surrogate pairs count as one code point.
* @param beginIndex the start of the subarray
* @param endIndex the index after the last char in the subarray
* @return the number of code points
* @throws IndexOutOfBoundsException if beginIndex is less than zero or
* greater than endIndex or if endIndex is greater than the length of this
* StringBuilder
*/
public int codePointCount(int beginIndex,int endIndex)
{
if (beginIndex < 0 || beginIndex > endIndex || endIndex > count)
throw new IndexOutOfBoundsException("invalid indices: " + beginIndex
+ ", " + endIndex);
return Character.codePointCount(value, beginIndex, endIndex - beginIndex);
}
public void trimToSize()
{
if (count < value.length)
{
char[] newValue = new char[count];
VMSystem.arraycopy(value, 0, newValue, 0, count);
value = newValue;
}
}
}

View file

@ -159,7 +159,7 @@ public class Thread implements Runnable
/** Thread local storage. Package accessible for use by
* InheritableThreadLocal.
*/
WeakIdentityHashMap locals;
final ThreadLocalMap locals;
/** The uncaught exception handler. */
UncaughtExceptionHandler exceptionHandler;
@ -367,6 +367,7 @@ public class Thread implements Runnable
this.name = name.toString();
this.runnable = target;
this.stacksize = size;
this.locals = new ThreadLocalMap();
synchronized (Thread.class)
{
@ -398,6 +399,7 @@ public class Thread implements Runnable
*/
Thread(VMThread vmThread, String name, int priority, boolean daemon)
{
this.locals = new ThreadLocalMap();
this.vmThread = vmThread;
this.runnable = null;
if (name == null)
@ -1063,21 +1065,15 @@ public class Thread implements Runnable
{
group.removeThread(this);
vmThread = null;
locals = null;
locals.clear();
}
/**
* Returns the map used by ThreadLocal to store the thread local values.
*/
static Map getThreadLocals()
static ThreadLocalMap getThreadLocals()
{
Thread thread = currentThread();
Map locals = thread.locals;
if (locals == null)
{
locals = thread.locals = new WeakIdentityHashMap();
}
return locals;
return currentThread().locals;
}
/**

View file

@ -37,9 +37,6 @@ exception statement from your version. */
package java.lang;
import java.util.Map;
/**
* ThreadLocal objects have a different state associated with every
* Thread that accesses them. Every access to the ThreadLocal object
@ -93,13 +90,31 @@ public class ThreadLocal<T>
* user. Do not expose this to the public. Package visible for use by
* InheritableThreadLocal
*/
static final Object sentinel = new Object();
static final Object notFound = new Object();
/**
* The base for the computation of the next hash for a thread local.
*/
private static int nextHashBase = 1;
/**
* Allocate a new hash.
*/
private synchronized int computeNextHash() {
return nextHashBase++ * 6709;
}
/**
* Hash code computed for ThreadLocalMap
*/
final int fastHash;
/**
* Creates a ThreadLocal object without associating any value to it yet.
*/
public ThreadLocal()
{
fastHash = computeNextHash();
}
/**
@ -125,16 +140,16 @@ public class ThreadLocal<T>
*/
public T get()
{
Map<ThreadLocal<T>,T> map = (Map<ThreadLocal<T>,T>) Thread.getThreadLocals();
ThreadLocalMap map = Thread.getThreadLocals();
// Note that we don't have to synchronize, as only this thread will
// ever modify the map.
T value = map.get(this);
if (value == null)
T value = (T) map.get(this);
if (value == notFound)
{
value = initialValue();
map.put(this, (T) (value == null ? sentinel : value));
map.set(this, value);
}
return value == (T) sentinel ? null : value;
return value;
}
/**
@ -147,10 +162,10 @@ public class ThreadLocal<T>
*/
public void set(T value)
{
Map map = Thread.getThreadLocals();
ThreadLocalMap map = Thread.getThreadLocals();
// Note that we don't have to synchronize, as only this thread will
// ever modify the map.
map.put(this, value == null ? sentinel : value);
map.set(this, value);
}
/**
@ -160,7 +175,7 @@ public class ThreadLocal<T>
*/
public void remove()
{
Map map = Thread.getThreadLocals();
ThreadLocalMap map = Thread.getThreadLocals();
map.remove(this);
}
}

View file

@ -0,0 +1,325 @@
/* ThreadLocal -- a variable with a unique value per thread
Copyright (C) 2000, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.lang;
import java.lang.ref.WeakReference;
/**
* ThreadLocalMap is the basic storage for the map of ThreadLocal instance
* to a thread's current value.
*
* Some applications really work out ThreadLocals, leading to this
* optimized implementation.
*/
final class ThreadLocalMap
{
/**
* The log (base 2) of the initial size of the map
*/
private static final int LOG_INITIAL_SIZE = 3;
/**
* The maximum occupancy rate (after which we grow)
*/
private static final float MAX_OCCUPANCY = 0.7f;
/**
* The target occupancy rate.
*/
private static final float TARGET_OCCUPANCY = 0.5f;
/**
* The deleted entry sentinel value.
*/
private static final Entry deletedEntry = new Entry(null);
/**
* Constructor
*/
ThreadLocalMap()
{
/* Dummy value to ensure fast path can be optimized */
entries = new Entry[1];
hashMask = 0;
count = 0;
}
/**
* The map entries
*/
private Entry[] entries;
/**
* Used for start index computation
*/
private int hashMask;
/**
* The number of entries currently in the map
*/
private int count;
/**
* Create or grow the table to the specified size. The size must be a
* power of two for the efficient mask/hash computation.
*
* @param newSize The new table size.
*/
private void newEntryArray(int newSize)
{
int mask = newSize - 1;
Entry[] oldEntries = this.entries;
this.entries = new Entry[newSize];
this.hashMask = mask;
/* Copy old entries to new table */
count = 0;
if (oldEntries != null)
{
for(Entry e: oldEntries)
{
if (e != null)
{
ThreadLocal<?> key = e.get();
if (e != deletedEntry && key != null)
{
for(int i = key.fastHash & mask;; i = (i + 1) & mask)
{
if (entries[i] == null)
{
entries[i] = e;
count++;
break;
}
}
}
}
}
}
}
/**
* We have run out of space in our locals. We use this as the
* trigger to attempt to find unused slots as ThreadLocals have
* died. If we recover any slots this way then we do not grow.
*/
private void overflow()
{
/* First 'actual' use */
if (entries.length == 1)
{
newEntryArray(1 << LOG_INITIAL_SIZE);
return;
}
/* Attempt to recover unused slots */
int deleted = 0;
for(int i=0; i < entries.length; i++)
{
Entry e = entries[i];
if (e != null)
{
if (e == deletedEntry)
{
deleted++;
}
else if (e.get() == null)
{
entries[i] = deletedEntry;
deleted++;
}
}
}
if ((count-deleted) <= (TARGET_OCCUPANCY * entries.length))
{
/* We currently rehash by simple reallocating into a same-sized table.
* An alternative would be to implement a clever hashing algorithm but
* as this happens infrequently this seems preferred */
newEntryArray(entries.length);
return;
}
/* Double the size */
newEntryArray(entries.length << 1);
}
/**
* This is the class that is used to refer to a thread local weakly.
*
* As we want to minimize indirections we extend WeakReference.
*/
static final class Entry extends WeakReference<ThreadLocal<?>> {
/**
* The value stored in this slot
*/
Object value;
/**
* Constructor
*/
Entry(ThreadLocal<?> threadLocal) {
super(threadLocal);
}
}
/**
* Gets the value associated with the ThreadLocal object for the currently
* executing Thread. If this is the first time the current thread has called
* get(), and it has not already called set(), the sentinel value is returned.
*
* @return the value of the variable in this thread, or sentinel if not present.
*/
public Object get(ThreadLocal<?> key)
{
int mask = this.hashMask;
for(int i = key.fastHash & mask;; i = (i + 1) & mask) {
Entry e = entries[i];
if (e != null) {
if (e.get() == key) {
return e.value;
}
} else {
return ThreadLocal.sentinel;
}
}
}
/**
* Sets the value associated with the ThreadLocal object for the currently
* executing Thread. This overrides any existing value associated with the
* current Thread and prevents <code>initialValue()</code> from being
* called if this is the first access to this ThreadLocal in this Thread.
*
* @param value the value to set this thread's view of the variable to
*/
public void set(ThreadLocal<?> key, Object value)
{
/* Overflow ? */
if ((count+1) >= (MAX_OCCUPANCY * entries.length))
{
overflow();
}
/* Set the entry */
int mask = this.hashMask;
for(int i = key.fastHash & mask;; i = (i + 1) & mask)
{
Entry e = entries[i];
if (e == null || e == deletedEntry)
{
/* Create entry */
if (e == null) count++;
entries[i] = e = new Entry(key);
e.value = value;
return;
}
else
{
ThreadLocal<?> entryKey = e.get();
if (entryKey == null)
{
entries[i] = deletedEntry;
}
else if (entryKey == key)
{
/* Update entry */
e.value = value;
return;
}
}
}
}
/**
* Removes the value associated with the ThreadLocal object for the
* currently executing Thread.
* @since 1.5
*/
public void remove(ThreadLocal<?> key)
{
int mask = this.hashMask;
for(int i = key.fastHash & mask;; i = (i + 1) & mask)
{
Entry e = entries[i];
if (e != null)
{
ThreadLocal<?> entryKey = e.get();
if (entryKey != key)
{
if (entryKey == null) {
entries[i] = deletedEntry;
}
continue;
}
else
{
/* Remove from the table */
entries[i] = deletedEntry;
}
}
return;
}
}
/**
* Clear out the map. Done once during thread death.
*/
void clear() {
entries = null;
}
/**
* Inherit all the InheritableThreadLocal instances from the given parent.
*
* @param parentMap The map to inherit from.
*/
public void inherit(ThreadLocalMap parentMap) {
for(Entry e: parentMap.entries)
{
if (e != null && e != deletedEntry)
{
ThreadLocal<?> key = e.get();
if (key instanceof InheritableThreadLocal)
{
set(key, ((InheritableThreadLocal)key).childValue(e.value));
}
}
}
}
}

View file

@ -39,6 +39,8 @@ package java.lang;
import gnu.classpath.SystemProperties;
import gnu.java.lang.CPStringBuilder;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable;
@ -411,7 +413,7 @@ public class Throwable implements Serializable
// different threads to get mixed up when written to the same PrintWriter.
private String stackTraceString()
{
StringBuilder sb = new StringBuilder();
CPStringBuilder sb = new CPStringBuilder();
// Main stacktrace
StackTraceElement[] stack = getStackTrace();
@ -455,7 +457,7 @@ public class Throwable implements Serializable
// Adds to the given StringBuffer a line containing the name and
// all stacktrace elements minus the last equal ones.
private static void stackTraceStringBuffer(StringBuilder sb, String name,
private static void stackTraceStringBuffer(CPStringBuilder sb, String name,
StackTraceElement[] stack, int equal)
{
String nl = StaticData.nl;

View file

@ -160,21 +160,72 @@ public class AccessibleObject
this.flag = flag;
}
/**
* <p>
* Returns the element's annotation for the specified annotation type,
* or <code>null</code> if no such annotation exists.
* </p>
* <p>
* <strong>This method must be overridden by subclasses to provide
* appropriate behaviour.</strong>
* </p>
*
* @param annotationClass the type of annotation to look for.
* @return this element's annotation for the specified type, or
* <code>null</code> if no such annotation exists.
* @throws NullPointerException if the annotation class is <code>null</code>.
*/
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
{
throw new AssertionError("Subclass must override this method");
}
/**
* Returns all annotations associated with the element. If there are
* no annotations associated with the element, then a zero-length array
* will be returned. The returned array may be modified by the client
* code, but this will have no effect on the annotation content of the
* element, and hence no effect on the return value of this method for
* future callers.
*
* @return this element's annotations.
*/
public Annotation[] getAnnotations()
{
return getDeclaredAnnotations();
}
/**
* <p>
* Returns all annotations directly defined by the element. If there are
* no annotations directly associated with the element, then a zero-length
* array will be returned. The returned array may be modified by the client
* code, but this will have no effect on the annotation content of this
* class, and hence no effect on the return value of this method for
* future callers.
* </p>
* <p>
* <strong>This method must be overridden by subclasses to provide
* appropriate behaviour.</strong>
* </p>
*
* @return the annotations directly defined by the element.
* @since 1.5
*/
public Annotation[] getDeclaredAnnotations()
{
throw new AssertionError("Subclass must override this method");
}
/**
* Returns true if an annotation for the specified type is associated
* with the element. This is primarily a short-hand for using marker
* annotations.
*
* @param annotationClass the type of annotation to look for.
* @return true if an annotation exists for the specified type.
* @since 1.5
*/
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
{
return getAnnotation(annotationClass) != null;

View file

@ -0,0 +1,453 @@
/* java.lang.reflect.Constructor - reflection of Java constructors
Copyright (C) 1998, 2001, 2004, 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.lang.reflect;
import gnu.java.lang.ClassHelper;
import gnu.java.lang.CPStringBuilder;
import gnu.java.lang.reflect.MethodSignatureParser;
import java.lang.annotation.Annotation;
/**
* The Constructor class represents a constructor of a class. It also allows
* dynamic creation of an object, via reflection. Invocation on Constructor
* objects knows how to do widening conversions, but throws
* {@link IllegalArgumentException} if a narrowing conversion would be
* necessary. You can query for information on this Constructor regardless
* of location, but construction access may be limited by Java language
* access controls. If you can't do it in the compiler, you can't normally
* do it here either.<p>
*
* <B>Note:</B> This class returns and accepts types as Classes, even
* primitive types; there are Class types defined that represent each
* different primitive type. They are <code>java.lang.Boolean.TYPE,
* java.lang.Byte.TYPE,</code>, also available as <code>boolean.class,
* byte.class</code>, etc. These are not to be confused with the
* classes <code>java.lang.Boolean, java.lang.Byte</code>, etc., which are
* real classes.<p>
*
* Also note that this is not a serializable class. It is entirely feasible
* to make it serializable using the Externalizable interface, but this is
* on Sun, not me.
*
* @author John Keiser
* @author Eric Blake <ebb9@email.byu.edu>
* @see Member
* @see Class
* @see java.lang.Class#getConstructor(Class[])
* @see java.lang.Class#getDeclaredConstructor(Class[])
* @see java.lang.Class#getConstructors()
* @see java.lang.Class#getDeclaredConstructors()
* @since 1.1
* @status updated to 1.4
*/
public final class Constructor<T>
extends AccessibleObject
implements GenericDeclaration, Member
{
private static final int CONSTRUCTOR_MODIFIERS
= Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC;
private MethodSignatureParser p;
VMConstructor cons;
/**
* This class is uninstantiable outside this package.
*/
Constructor(VMConstructor cons)
{
this.cons = cons;
cons.cons = this;
}
private Constructor()
{
}
/**
* Gets the class that declared this constructor.
* @return the class that declared this member
*/
public Class<T> getDeclaringClass()
{
// Inescapable as the VM layer is 1.4 based.
@SuppressWarnings("unchecked")
Class<T> declClass = (Class<T>) cons.getDeclaringClass();
return declClass;
}
/**
* Gets the name of this constructor (the non-qualified name of the class
* it was declared in).
* @return the name of this constructor
*/
public String getName()
{
return cons.getDeclaringClass().getName();
}
/**
* Gets the modifiers this constructor uses. Use the <code>Modifier</code>
* class to interpret the values. A constructor can only have a subset of the
* following modifiers: public, private, protected.
*
* @return an integer representing the modifiers to this Member
* @see Modifier
*/
public int getModifiers()
{
return cons.getModifiersInternal() & CONSTRUCTOR_MODIFIERS;
}
/**
* Return true if this constructor is synthetic, false otherwise.
* A synthetic member is one which is created by the compiler,
* and which does not appear in the user's source code.
* @since 1.5
*/
public boolean isSynthetic()
{
return (cons.getModifiersInternal() & Modifier.SYNTHETIC) != 0;
}
/**
* Return true if this is a varargs constructor, that is if
* the constructor takes a variable number of arguments.
* @since 1.5
*/
public boolean isVarArgs()
{
return (cons.getModifiersInternal() & Modifier.VARARGS) != 0;
}
/**
* Get the parameter list for this constructor, in declaration order. If the
* constructor takes no parameters, returns a 0-length array (not null).
*
* @return a list of the types of the constructor's parameters
*/
public Class<?>[] getParameterTypes()
{
return (Class<?>[]) cons.getParameterTypes();
}
/**
* Get the exception types this constructor says it throws, in no particular
* order. If the constructor has no throws clause, returns a 0-length array
* (not null).
*
* @return a list of the types in the constructor's throws clause
*/
public Class<?>[] getExceptionTypes()
{
return (Class<?>[]) cons.getExceptionTypes();
}
/**
* Compare two objects to see if they are semantically equivalent.
* Two Constructors are semantically equivalent if they have the same
* declaring class and the same parameter list. This ignores different
* exception clauses, but since you can't create a Method except through the
* VM, this is just the == relation.
*
* @param o the object to compare to
* @return <code>true</code> if they are equal; <code>false</code> if not.
*/
public boolean equals(Object o)
{
return cons.equals(o);
}
/**
* Get the hash code for the Constructor. The Constructor hash code is the
* hash code of the declaring class's name.
*
* @return the hash code for the object
*/
public int hashCode()
{
return getName().hashCode();
}
/**
* Get a String representation of the Constructor. A Constructor's String
* representation is "&lt;modifier&gt; &lt;classname&gt;(&lt;paramtypes&gt;)
* throws &lt;exceptions&gt;", where everything after ')' is omitted if
* there are no exceptions.<br> Example:
* <code>public java.io.FileInputStream(java.lang.Runnable)
* throws java.io.FileNotFoundException</code>
*
* @return the String representation of the Constructor
*/
public String toString()
{
// 128 is a reasonable buffer initial size for constructor
CPStringBuilder sb = new CPStringBuilder(128);
Modifier.toString(getModifiers(), sb).append(' ');
sb.append(getDeclaringClass().getName()).append('(');
Class[] c = getParameterTypes();
if (c.length > 0)
{
sb.append(ClassHelper.getUserName(c[0]));
for (int i = 1; i < c.length; i++)
sb.append(',').append(ClassHelper.getUserName(c[i]));
}
sb.append(')');
c = getExceptionTypes();
if (c.length > 0)
{
sb.append(" throws ").append(c[0].getName());
for (int i = 1; i < c.length; i++)
sb.append(',').append(c[i].getName());
}
return sb.toString();
}
static <X extends GenericDeclaration>
void addTypeParameters(CPStringBuilder sb, TypeVariable<X>[] typeArgs)
{
if (typeArgs.length == 0)
return;
sb.append('<');
for (int i = 0; i < typeArgs.length; ++i)
{
if (i > 0)
sb.append(',');
sb.append(typeArgs[i]);
}
sb.append("> ");
}
public String toGenericString()
{
CPStringBuilder sb = new CPStringBuilder(128);
Modifier.toString(getModifiers(), sb).append(' ');
addTypeParameters(sb, getTypeParameters());
sb.append(getDeclaringClass().getName()).append('(');
Type[] types = getGenericParameterTypes();
if (types.length > 0)
{
sb.append(types[0]);
for (int i = 1; i < types.length; ++i)
sb.append(',').append(types[i]);
}
sb.append(')');
types = getGenericExceptionTypes();
if (types.length > 0)
{
sb.append(" throws ").append(types[0]);
for (int i = 1; i < types.length; i++)
sb.append(',').append(types[i]);
}
return sb.toString();
}
/**
* Create a new instance by invoking the constructor. Arguments are
* automatically unwrapped and widened, if needed.<p>
*
* If this class is abstract, you will get an
* <code>InstantiationException</code>. If the constructor takes 0
* arguments, you may use null or a 0-length array for <code>args</code>.<p>
*
* If this Constructor enforces access control, your runtime context is
* evaluated, and you may have an <code>IllegalAccessException</code> if
* you could not create this object in similar compiled code. If the class
* is uninitialized, you trigger class initialization, which may end in a
* <code>ExceptionInInitializerError</code>.<p>
*
* Then, the constructor is invoked. If it completes normally, the return
* value will be the new object. If it completes abruptly, the exception is
* wrapped in an <code>InvocationTargetException</code>.
*
* @param args the arguments to the constructor
* @return the newly created object
* @throws IllegalAccessException if the constructor could not normally be
* called by the Java code (i.e. it is not public)
* @throws IllegalArgumentException if the number of arguments is incorrect;
* or if the arguments types are wrong even with a widening
* conversion
* @throws InstantiationException if the class is abstract
* @throws InvocationTargetException if the constructor throws an exception
* @throws ExceptionInInitializerError if construction triggered class
* initialization, which then failed
*/
public T newInstance(Object... args)
throws InstantiationException, IllegalAccessException,
InvocationTargetException
{
// Inescapable as the VM layer is 1.4 based.
@SuppressWarnings("unchecked")
T ins = (T) cons.construct(args);
return ins;
}
/**
* Returns an array of <code>TypeVariable</code> objects that represents
* the type variables declared by this constructor, in declaration order.
* An array of size zero is returned if this constructor has no type
* variables.
*
* @return the type variables associated with this constructor.
* @throws GenericSignatureFormatError if the generic signature does
* not conform to the format specified in the Virtual Machine
* specification, version 3.
* @since 1.5
*/
public TypeVariable<Constructor<T>>[] getTypeParameters()
{
if (p == null)
{
String sig = cons.getSignature();
if (sig == null)
return new TypeVariable[0];
p = new MethodSignatureParser(this, sig);
}
return p.getTypeParameters();
}
/**
* Returns an array of <code>Type</code> objects that represents
* the exception types declared by this constructor, in declaration order.
* An array of size zero is returned if this constructor declares no
* exceptions.
*
* @return the exception types declared by this constructor.
* @throws GenericSignatureFormatError if the generic signature does
* not conform to the format specified in the Virtual Machine
* specification, version 3.
* @since 1.5
*/
public Type[] getGenericExceptionTypes()
{
if (p == null)
{
String sig = cons.getSignature();
if (sig == null)
return getExceptionTypes();
p = new MethodSignatureParser(this, sig);
}
return p.getGenericExceptionTypes();
}
/**
* Returns an array of <code>Type</code> objects that represents
* the parameter list for this constructor, in declaration order.
* An array of size zero is returned if this constructor takes no
* parameters.
*
* @return a list of the types of the constructor's parameters
* @throws GenericSignatureFormatError if the generic signature does
* not conform to the format specified in the Virtual Machine
* specification, version 3.
* @since 1.5
*/
public Type[] getGenericParameterTypes()
{
if (p == null)
{
String sig = cons.getSignature();
if (sig == null)
return getParameterTypes();
p = new MethodSignatureParser(this, sig);
}
return p.getGenericParameterTypes();
}
/**
* <p>
* Return an array of arrays representing the annotations on each
* of the constructor's parameters. The outer array is aligned against
* the parameters of the constructors and is thus equal in length to
* the number of parameters (thus having a length zero if there are none).
* Each array element in the outer array contains an inner array which
* holds the annotations. This array has a length of zero if the parameter
* has no annotations.
* </p>
* <p>
* The returned annotations are serialized. Changing the annotations has
* no affect on the return value of future calls to this method.
* </p>
*
* @return an array of arrays which represents the annotations used on the
* parameters of this constructor. The order of the array elements
* matches the declaration order of the parameters.
* @since 1.5
*/
public Annotation[][] getParameterAnnotations()
{
return cons.getParameterAnnotations();
}
/**
* Returns the element's annotation for the specified annotation type,
* or <code>null</code> if no such annotation exists.
*
* @param annotationClass the type of annotation to look for.
* @return this element's annotation for the specified type, or
* <code>null</code> if no such annotation exists.
* @throws NullPointerException if the annotation class is <code>null</code>.
*/
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
{
// Inescapable as the VM layer is 1.4 based.
@SuppressWarnings("unchecked")
T ann = (T) cons.getAnnotation(annotationClass);
return ann;
}
/**
* Returns all annotations directly defined by the element. If there are
* no annotations directly associated with the element, then a zero-length
* array will be returned. The returned array may be modified by the client
* code, but this will have no effect on the annotation content of this
* class, and hence no effect on the return value of this method for
* future callers.
*
* @return the annotations directly defined by the element.
* @since 1.5
*/
public Annotation[] getDeclaredAnnotations()
{
return cons.getDeclaredAnnotations();
}
}

View file

@ -0,0 +1,735 @@
/* java.lang.reflect.Field - reflection of Java fields
Copyright (C) 1998, 2001, 2005, 2008 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.lang.reflect;
import gnu.java.lang.ClassHelper;
import gnu.java.lang.CPStringBuilder;
import gnu.java.lang.reflect.FieldSignatureParser;
import java.lang.annotation.Annotation;
/**
* The Field class represents a member variable of a class. It also allows
* dynamic access to a member, via reflection. This works for both
* static and instance fields. Operations on Field objects know how to
* do widening conversions, but throw {@link IllegalArgumentException} if
* a narrowing conversion would be necessary. You can query for information
* on this Field regardless of location, but get and set access may be limited
* by Java language access controls. If you can't do it in the compiler, you
* can't normally do it here either.<p>
*
* <B>Note:</B> This class returns and accepts types as Classes, even
* primitive types; there are Class types defined that represent each
* different primitive type. They are <code>java.lang.Boolean.TYPE,
* java.lang.Byte.TYPE,</code>, also available as <code>boolean.class,
* byte.class</code>, etc. These are not to be confused with the
* classes <code>java.lang.Boolean, java.lang.Byte</code>, etc., which are
* real classes.<p>
*
* Also note that this is not a serializable class. It is entirely feasible
* to make it serializable using the Externalizable interface, but this is
* on Sun, not me.
*
* @author John Keiser
* @author Eric Blake <ebb9@email.byu.edu>
* @see Member
* @see Class
* @see Class#getField(String)
* @see Class#getDeclaredField(String)
* @see Class#getFields()
* @see Class#getDeclaredFields()
* @since 1.1
* @status updated to 1.4
*/
public final class Field
extends AccessibleObject implements Member
{
static final int FIELD_MODIFIERS
= Modifier.FINAL | Modifier.PRIVATE | Modifier.PROTECTED
| Modifier.PUBLIC | Modifier.STATIC | Modifier.TRANSIENT
| Modifier.VOLATILE;
private FieldSignatureParser p;
VMField f;
/**
* This class is uninstantiable outside the package.
*/
Field(VMField f)
{
this.f = f;
f.f = this;
}
/**
* Gets the class that declared this field, or the class where this field
* is a non-inherited member.
* @return the class that declared this member
*/
public Class<?> getDeclaringClass()
{
return (Class<?>) f.getDeclaringClass();
}
/**
* Gets the name of this field.
* @return the name of this field
*/
public String getName()
{
return f.getName();
}
/**
* Gets the modifiers this field uses. Use the <code>Modifier</code>
* class to interpret the values. A field can only have a subset of the
* following modifiers: public, private, protected, static, final,
* transient, and volatile.
*
* @return an integer representing the modifiers to this Member
* @see Modifier
*/
public int getModifiers()
{
return f.getModifiersInternal() & FIELD_MODIFIERS;
}
/**
* Return true if this field is synthetic, false otherwise.
* @since 1.5
*/
public boolean isSynthetic()
{
return (f.getModifiersInternal() & Modifier.SYNTHETIC) != 0;
}
/**
* Return true if this field represents an enum constant,
* false otherwise.
* @since 1.5
*/
public boolean isEnumConstant()
{
return (f.getModifiersInternal() & Modifier.ENUM) != 0;
}
/**
* Gets the type of this field.
* @return the type of this field
*/
public Class<?> getType()
{
return f.getType();
}
/**
* Compare two objects to see if they are semantically equivalent.
* Two Fields are semantically equivalent if they have the same declaring
* class, name, and type. Since you can't creat a Field except through
* the VM, this is just the == relation.
*
* @param o the object to compare to
* @return <code>true</code> if they are equal; <code>false</code> if not
*/
public boolean equals(Object o)
{
return f.equals(o);
}
/**
* Get the hash code for the Field. The Field hash code is the hash code
* of its name XOR'd with the hash code of its class name.
*
* @return the hash code for the object.
*/
public int hashCode()
{
return f.getDeclaringClass().getName().hashCode() ^ f.getName().hashCode();
}
/**
* Get a String representation of the Field. A Field's String
* representation is "&lt;modifiers&gt; &lt;type&gt;
* &lt;class&gt;.&lt;fieldname&gt;".<br> Example:
* <code>public transient boolean gnu.parse.Parser.parseComplete</code>
*
* @return the String representation of the Field
*/
public String toString()
{
// 64 is a reasonable buffer initial size for field
CPStringBuilder sb = new CPStringBuilder(64);
Modifier.toString(getModifiers(), sb).append(' ');
sb.append(ClassHelper.getUserName(getType())).append(' ');
sb.append(getDeclaringClass().getName()).append('.');
sb.append(getName());
return sb.toString();
}
public String toGenericString()
{
CPStringBuilder sb = new CPStringBuilder(64);
Modifier.toString(getModifiers(), sb).append(' ');
sb.append(getGenericType()).append(' ');
sb.append(getDeclaringClass().getName()).append('.');
sb.append(getName());
return sb.toString();
}
/**
* Get the value of this Field. If it is primitive, it will be wrapped
* in the appropriate wrapper type (boolean = java.lang.Boolean).<p>
*
* If the field is static, <code>o</code> will be ignored. Otherwise, if
* <code>o</code> is null, you get a <code>NullPointerException</code>,
* and if it is incompatible with the declaring class of the field, you
* get an <code>IllegalArgumentException</code>.<p>
*
* Next, if this Field enforces access control, your runtime context is
* evaluated, and you may have an <code>IllegalAccessException</code> if
* you could not access this field in similar compiled code. If the field
* is static, and its class is uninitialized, you trigger class
* initialization, which may end in a
* <code>ExceptionInInitializerError</code>.<p>
*
* Finally, the field is accessed, and primitives are wrapped (but not
* necessarily in new objects). This method accesses the field of the
* declaring class, even if the instance passed in belongs to a subclass
* which declares another field to hide this one.
*
* @param o the object to get the value of this Field from
* @return the value of the Field
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if <code>o</code> is not an instance of
* the class or interface declaring this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #getBoolean(Object)
* @see #getByte(Object)
* @see #getChar(Object)
* @see #getShort(Object)
* @see #getInt(Object)
* @see #getLong(Object)
* @see #getFloat(Object)
* @see #getDouble(Object)
*/
public Object get(Object o)
throws IllegalAccessException
{
return f.get(o);
}
/**
* Get the value of this boolean Field. If the field is static,
* <code>o</code> will be ignored.
*
* @param o the object to get the value of this Field from
* @return the value of the Field
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a boolean field of
* <code>o</code>, or if <code>o</code> is not an instance of the
* declaring class of this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #get(Object)
*/
public boolean getBoolean(Object o)
throws IllegalAccessException
{
return f.getBoolean(o);
}
/**
* Get the value of this byte Field. If the field is static,
* <code>o</code> will be ignored.
*
* @param o the object to get the value of this Field from
* @return the value of the Field
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a byte field of
* <code>o</code>, or if <code>o</code> is not an instance of the
* declaring class of this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #get(Object)
*/
public byte getByte(Object o)
throws IllegalAccessException
{
return f.getByte(o);
}
/**
* Get the value of this Field as a char. If the field is static,
* <code>o</code> will be ignored.
*
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a char field of
* <code>o</code>, or if <code>o</code> is not an instance
* of the declaring class of this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #get(Object)
*/
public char getChar(Object o)
throws IllegalAccessException
{
return f.getChar(o);
}
/**
* Get the value of this Field as a short. If the field is static,
* <code>o</code> will be ignored.
*
* @param o the object to get the value of this Field from
* @return the value of the Field
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a byte or short
* field of <code>o</code>, or if <code>o</code> is not an instance
* of the declaring class of this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #get(Object)
*/
public short getShort(Object o)
throws IllegalAccessException
{
return f.getShort(o);
}
/**
* Get the value of this Field as an int. If the field is static,
* <code>o</code> will be ignored.
*
* @param o the object to get the value of this Field from
* @return the value of the Field
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a byte, short, char, or
* int field of <code>o</code>, or if <code>o</code> is not an
* instance of the declaring class of this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #get(Object)
*/
public int getInt(Object o)
throws IllegalAccessException
{
return f.getInt(o);
}
/**
* Get the value of this Field as a long. If the field is static,
* <code>o</code> will be ignored.
*
* @param o the object to get the value of this Field from
* @return the value of the Field
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a byte, short, char, int,
* or long field of <code>o</code>, or if <code>o</code> is not an
* instance of the declaring class of this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #get(Object)
*/
public long getLong(Object o)
throws IllegalAccessException
{
return f.getLong(o);
}
/**
* Get the value of this Field as a float. If the field is static,
* <code>o</code> will be ignored.
*
* @param o the object to get the value of this Field from
* @return the value of the Field
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a byte, short, char, int,
* long, or float field of <code>o</code>, or if <code>o</code> is
* not an instance of the declaring class of this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #get(Object)
*/
public float getFloat(Object o)
throws IllegalAccessException
{
return f.getFloat(o);
}
/**
* Get the value of this Field as a double. If the field is static,
* <code>o</code> will be ignored.
*
* @param o the object to get the value of this Field from
* @return the value of the Field
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a byte, short, char, int,
* long, float, or double field of <code>o</code>, or if
* <code>o</code> is not an instance of the declaring class of this
* field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #get(Object)
*/
public double getDouble(Object o)
throws IllegalAccessException
{
return f.getDouble(o);
}
/**
* Set the value of this Field. If it is a primitive field, the value
* will be unwrapped from the passed object (boolean = java.lang.Boolean).<p>
*
* If the field is static, <code>o</code> will be ignored. Otherwise, if
* <code>o</code> is null, you get a <code>NullPointerException</code>,
* and if it is incompatible with the declaring class of the field, you
* get an <code>IllegalArgumentException</code>.<p>
*
* Next, if this Field enforces access control, your runtime context is
* evaluated, and you may have an <code>IllegalAccessException</code> if
* you could not access this field in similar compiled code. This also
* occurs whether or not there is access control if the field is final.
* If the field is primitive, and unwrapping your argument fails, you will
* get an <code>IllegalArgumentException</code>; likewise, this error
* happens if <code>value</code> cannot be cast to the correct object type.
* If the field is static, and its class is uninitialized, you trigger class
* initialization, which may end in a
* <code>ExceptionInInitializerError</code>.<p>
*
* Finally, the field is set with the widened value. This method accesses
* the field of the declaring class, even if the instance passed in belongs
* to a subclass which declares another field to hide this one.
*
* @param o the object to set this Field on
* @param value the value to set this Field to
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if <code>value</code> cannot be
* converted by a widening conversion to the underlying type of
* the Field, or if <code>o</code> is not an instance of the class
* declaring this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #setBoolean(Object, boolean)
* @see #setByte(Object, byte)
* @see #setChar(Object, char)
* @see #setShort(Object, short)
* @see #setInt(Object, int)
* @see #setLong(Object, long)
* @see #setFloat(Object, float)
* @see #setDouble(Object, double)
*/
public void set(Object o, Object value)
throws IllegalAccessException
{
f.set(o, value);
}
/**
* Set this boolean Field. If the field is static, <code>o</code> will be
* ignored.
*
* @param o the object to set this Field on
* @param value the value to set this Field to
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a boolean field, or if
* <code>o</code> is not an instance of the class declaring this
* field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #set(Object, Object)
*/
public void setBoolean(Object o, boolean value)
throws IllegalAccessException
{
f.setBoolean(o, value);
}
/**
* Set this byte Field. If the field is static, <code>o</code> will be
* ignored.
*
* @param o the object to set this Field on
* @param value the value to set this Field to
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a byte, short, int, long,
* float, or double field, or if <code>o</code> is not an instance
* of the class declaring this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #set(Object, Object)
*/
public void setByte(Object o, byte value)
throws IllegalAccessException
{
f.setByte(o, value);
}
/**
* Set this char Field. If the field is static, <code>o</code> will be
* ignored.
*
* @param o the object to set this Field on
* @param value the value to set this Field to
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a char, int, long,
* float, or double field, or if <code>o</code> is not an instance
* of the class declaring this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #set(Object, Object)
*/
public void setChar(Object o, char value)
throws IllegalAccessException
{
f.setChar(o, value);
}
/**
* Set this short Field. If the field is static, <code>o</code> will be
* ignored.
*
* @param o the object to set this Field on
* @param value the value to set this Field to
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a short, int, long,
* float, or double field, or if <code>o</code> is not an instance
* of the class declaring this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #set(Object, Object)
*/
public void setShort(Object o, short value)
throws IllegalAccessException
{
f.setShort(o, value);
}
/**
* Set this int Field. If the field is static, <code>o</code> will be
* ignored.
*
* @param o the object to set this Field on
* @param value the value to set this Field to
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not an int, long, float, or
* double field, or if <code>o</code> is not an instance of the
* class declaring this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #set(Object, Object)
*/
public void setInt(Object o, int value)
throws IllegalAccessException
{
f.setInt(o, value);
}
/**
* Set this long Field. If the field is static, <code>o</code> will be
* ignored.
*
* @param o the object to set this Field on
* @param value the value to set this Field to
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a long, float, or double
* field, or if <code>o</code> is not an instance of the class
* declaring this field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #set(Object, Object)
*/
public void setLong(Object o, long value)
throws IllegalAccessException
{
f.setLong(o, value);
}
/**
* Set this float Field. If the field is static, <code>o</code> will be
* ignored.
*
* @param o the object to set this Field on
* @param value the value to set this Field to
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a float or long field, or
* if <code>o</code> is not an instance of the class declaring this
* field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #set(Object, Object)
*/
public void setFloat(Object o, float value)
throws IllegalAccessException
{
f.setFloat(o, value);
}
/**
* Set this double Field. If the field is static, <code>o</code> will be
* ignored.
*
* @param o the object to set this Field on
* @param value the value to set this Field to
* @throws IllegalAccessException if you could not normally access this field
* (i.e. it is not public)
* @throws IllegalArgumentException if this is not a double field, or if
* <code>o</code> is not an instance of the class declaring this
* field
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static field triggered
* class initialization, which then failed
* @see #set(Object, Object)
*/
public void setDouble(Object o, double value)
throws IllegalAccessException
{
f.setDouble(o, value);
}
/**
* Return the generic type of the field. If the field type is not a generic
* type, the method returns the same as <code>getType()</code>.
*
* @throws GenericSignatureFormatError if the generic signature does
* not conform to the format specified in the Virtual Machine
* specification, version 3.
* @since 1.5
*/
public Type getGenericType()
{
if (p == null)
{
String signature = f.getSignature();
if (signature == null)
return getType();
p = new FieldSignatureParser(getDeclaringClass(),
signature);
}
return p.getFieldType();
}
/**
* Returns the element's annotation for the specified annotation type,
* or <code>null</code> if no such annotation exists.
*
* @param annotationClass the type of annotation to look for.
* @return this element's annotation for the specified type, or
* <code>null</code> if no such annotation exists.
* @throws NullPointerException if the annotation class is <code>null</code>.
*/
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
{
// Inescapable as the VM layer is 1.4 based. T will erase to Annotation anyway.
@SuppressWarnings("unchecked") T ann = (T) f.getAnnotation(annotationClass);
return ann;
}
/**
* Returns all annotations directly defined by the element. If there are
* no annotations directly associated with the element, then a zero-length
* array will be returned. The returned array may be modified by the client
* code, but this will have no effect on the annotation content of this
* class, and hence no effect on the return value of this method for
* future callers.
*
* @return the annotations directly defined by the element.
* @since 1.5
*/
public Annotation[] getDeclaredAnnotations()
{
return f.getDeclaredAnnotations();
}
}

View file

@ -0,0 +1,497 @@
/* java.lang.reflect.Method - reflection of Java methods
Copyright (C) 1998, 2001, 2002, 2005, 2007, 2008 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.lang.reflect;
import gnu.java.lang.ClassHelper;
import gnu.java.lang.CPStringBuilder;
import gnu.java.lang.reflect.MethodSignatureParser;
import java.lang.annotation.Annotation;
/**
* The Method class represents a member method of a class. It also allows
* dynamic invocation, via reflection. This works for both static and
* instance methods. Invocation on Method objects knows how to do
* widening conversions, but throws {@link IllegalArgumentException} if
* a narrowing conversion would be necessary. You can query for information
* on this Method regardless of location, but invocation access may be limited
* by Java language access controls. If you can't do it in the compiler, you
* can't normally do it here either.<p>
*
* <B>Note:</B> This class returns and accepts types as Classes, even
* primitive types; there are Class types defined that represent each
* different primitive type. They are <code>java.lang.Boolean.TYPE,
* java.lang.Byte.TYPE,</code>, also available as <code>boolean.class,
* byte.class</code>, etc. These are not to be confused with the
* classes <code>java.lang.Boolean, java.lang.Byte</code>, etc., which are
* real classes.<p>
*
* Also note that this is not a serializable class. It is entirely feasible
* to make it serializable using the Externalizable interface, but this is
* on Sun, not me.
*
* @author John Keiser
* @author Eric Blake <ebb9@email.byu.edu>
* @see Member
* @see Class
* @see java.lang.Class#getMethod(String,Class[])
* @see java.lang.Class#getDeclaredMethod(String,Class[])
* @see java.lang.Class#getMethods()
* @see java.lang.Class#getDeclaredMethods()
* @since 1.1
* @status updated to 1.4
*/
public final class Method
extends AccessibleObject implements Member, GenericDeclaration
{
private static final int METHOD_MODIFIERS
= Modifier.ABSTRACT | Modifier.FINAL | Modifier.NATIVE
| Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC
| Modifier.STATIC | Modifier.STRICT | Modifier.SYNCHRONIZED;
private MethodSignatureParser p;
VMMethod m;
/**
* This class is uninstantiable outside this package.
*/
Method(VMMethod m)
{
this.m = m;
m.m = this;
}
/**
* Gets the class that declared this method, or the class where this method
* is a non-inherited member.
* @return the class that declared this member
*/
public Class<?> getDeclaringClass()
{
return (Class<?>) m.getDeclaringClass();
}
/**
* Gets the name of this method.
* @return the name of this method
*/
public String getName()
{
return m.getName();
}
/**
* Gets the modifiers this method uses. Use the <code>Modifier</code>
* class to interpret the values. A method can only have a subset of the
* following modifiers: public, private, protected, abstract, static,
* final, synchronized, native, and strictfp.
*
* @return an integer representing the modifiers to this Member
* @see Modifier
*/
public int getModifiers()
{
return m.getModifiersInternal() & METHOD_MODIFIERS;
}
/**
* Return true if this method is a bridge method. A bridge method
* is generated by the compiler in some situations involving
* generics and inheritance.
* @since 1.5
*/
public boolean isBridge()
{
return (m.getModifiersInternal() & Modifier.BRIDGE) != 0;
}
/**
* Return true if this method is synthetic, false otherwise.
* @since 1.5
*/
public boolean isSynthetic()
{
return (m.getModifiersInternal() & Modifier.SYNTHETIC) != 0;
}
/**
* Return true if this is a varargs method, that is if
* the method takes a variable number of arguments.
* @since 1.5
*/
public boolean isVarArgs()
{
return (m.getModifiersInternal() & Modifier.VARARGS) != 0;
}
/**
* Gets the return type of this method.
* @return the type of this method
*/
public Class<?> getReturnType()
{
return (Class<?>) m.getReturnType();
}
/**
* Get the parameter list for this method, in declaration order. If the
* method takes no parameters, returns a 0-length array (not null).
*
* @return a list of the types of the method's parameters
*/
public Class<?>[] getParameterTypes()
{
return (Class<?>[]) m.getParameterTypes();
}
/**
* Get the exception types this method says it throws, in no particular
* order. If the method has no throws clause, returns a 0-length array
* (not null).
*
* @return a list of the types in the method's throws clause
*/
public Class<?>[] getExceptionTypes()
{
return (Class<?>[]) m.getExceptionTypes();
}
/**
* Compare two objects to see if they are semantically equivalent.
* Two Methods are semantically equivalent if they have the same declaring
* class, name, parameter list, and return type.
*
* @param o the object to compare to
* @return <code>true</code> if they are equal; <code>false</code> if not
*/
public boolean equals(Object o)
{
return m.equals(o);
}
/**
* Get the hash code for the Method. The Method hash code is the hash code
* of its name XOR'd with the hash code of its class name.
*
* @return the hash code for the object
*/
public int hashCode()
{
return m.getDeclaringClass().getName().hashCode() ^ m.getName().hashCode();
}
/**
* Get a String representation of the Method. A Method's String
* representation is "&lt;modifiers&gt; &lt;returntype&gt;
* &lt;methodname&gt;(&lt;paramtypes&gt;) throws &lt;exceptions&gt;", where
* everything after ')' is omitted if there are no exceptions.<br> Example:
* <code>public static int run(java.lang.Runnable,int)</code>
*
* @return the String representation of the Method
*/
public String toString()
{
// 128 is a reasonable buffer initial size for constructor
CPStringBuilder sb = new CPStringBuilder(128);
Modifier.toString(getModifiers(), sb).append(' ');
sb.append(ClassHelper.getUserName(getReturnType())).append(' ');
sb.append(getDeclaringClass().getName()).append('.');
sb.append(getName()).append('(');
Class[] c = getParameterTypes();
if (c.length > 0)
{
sb.append(ClassHelper.getUserName(c[0]));
for (int i = 1; i < c.length; i++)
sb.append(',').append(ClassHelper.getUserName(c[i]));
}
sb.append(')');
c = getExceptionTypes();
if (c.length > 0)
{
sb.append(" throws ").append(c[0].getName());
for (int i = 1; i < c.length; i++)
sb.append(',').append(c[i].getName());
}
return sb.toString();
}
public String toGenericString()
{
// 128 is a reasonable buffer initial size for constructor
CPStringBuilder sb = new CPStringBuilder(128);
Modifier.toString(getModifiers(), sb).append(' ');
Constructor.addTypeParameters(sb, getTypeParameters());
sb.append(getGenericReturnType()).append(' ');
sb.append(getDeclaringClass().getName()).append('.');
sb.append(getName()).append('(');
Type[] types = getGenericParameterTypes();
if (types.length > 0)
{
sb.append(types[0]);
for (int i = 1; i < types.length; i++)
sb.append(',').append(types[i]);
}
sb.append(')');
types = getGenericExceptionTypes();
if (types.length > 0)
{
sb.append(" throws ").append(types[0]);
for (int i = 1; i < types.length; i++)
sb.append(',').append(types[i]);
}
return sb.toString();
}
/**
* Invoke the method. Arguments are automatically unwrapped and widened,
* and the result is automatically wrapped, if needed.<p>
*
* If the method is static, <code>o</code> will be ignored. Otherwise,
* the method uses dynamic lookup as described in JLS 15.12.4.4. You cannot
* mimic the behavior of nonvirtual lookup (as in super.foo()). This means
* you will get a <code>NullPointerException</code> if <code>o</code> is
* null, and an <code>IllegalArgumentException</code> if it is incompatible
* with the declaring class of the method. If the method takes 0 arguments,
* you may use null or a 0-length array for <code>args</code>.<p>
*
* Next, if this Method enforces access control, your runtime context is
* evaluated, and you may have an <code>IllegalAccessException</code> if
* you could not acces this method in similar compiled code. If the method
* is static, and its class is uninitialized, you trigger class
* initialization, which may end in a
* <code>ExceptionInInitializerError</code>.<p>
*
* Finally, the method is invoked. If it completes normally, the return value
* will be null for a void method, a wrapped object for a primitive return
* method, or the actual return of an Object method. If it completes
* abruptly, the exception is wrapped in an
* <code>InvocationTargetException</code>.
*
* @param o the object to invoke the method on
* @param args the arguments to the method
* @return the return value of the method, wrapped in the appropriate
* wrapper if it is primitive
* @throws IllegalAccessException if the method could not normally be called
* by the Java code (i.e. it is not public)
* @throws IllegalArgumentException if the number of arguments is incorrect;
* if the arguments types are wrong even with a widening conversion;
* or if <code>o</code> is not an instance of the class or interface
* declaring this method
* @throws InvocationTargetException if the method throws an exception
* @throws NullPointerException if <code>o</code> is null and this field
* requires an instance
* @throws ExceptionInInitializerError if accessing a static method triggered
* class initialization, which then failed
*/
public Object invoke(Object o, Object... args)
throws IllegalAccessException, InvocationTargetException
{
return m.invoke(o, args);
}
/**
* Returns an array of <code>TypeVariable</code> objects that represents
* the type variables declared by this constructor, in declaration order.
* An array of size zero is returned if this class has no type
* variables.
*
* @return the type variables associated with this class.
* @throws GenericSignatureFormatError if the generic signature does
* not conform to the format specified in the Virtual Machine
* specification, version 3.
* @since 1.5
*/
public TypeVariable<Method>[] getTypeParameters()
{
if (p == null)
{
String sig = m.getSignature();
if (sig == null)
return (TypeVariable<Method>[]) new TypeVariable[0];
p = new MethodSignatureParser(this, sig);
}
return p.getTypeParameters();
}
/**
* Returns an array of <code>Type</code> objects that represents
* the exception types declared by this method, in declaration order.
* An array of size zero is returned if this method declares no
* exceptions.
*
* @return the exception types declared by this method.
* @throws GenericSignatureFormatError if the generic signature does
* not conform to the format specified in the Virtual Machine
* specification, version 3.
* @since 1.5
*/
public Type[] getGenericExceptionTypes()
{
if (p == null)
{
String sig = m.getSignature();
if (sig == null)
return getExceptionTypes();
p = new MethodSignatureParser(this, sig);
}
return p.getGenericExceptionTypes();
}
/**
* Returns an array of <code>Type</code> objects that represents
* the parameter list for this method, in declaration order.
* An array of size zero is returned if this method takes no
* parameters.
*
* @return a list of the types of the method's parameters
* @throws GenericSignatureFormatError if the generic signature does
* not conform to the format specified in the Virtual Machine
* specification, version 3.
* @since 1.5
*/
public Type[] getGenericParameterTypes()
{
if (p == null)
{
String sig = m.getSignature();
if (sig == null)
return getParameterTypes();
p = new MethodSignatureParser(this, sig);
}
return p.getGenericParameterTypes();
}
/**
* Returns the return type of this method.
*
* @return the return type of this method
* @throws GenericSignatureFormatError if the generic signature does
* not conform to the format specified in the Virtual Machine
* specification, version 3.
* @since 1.5
*/
public Type getGenericReturnType()
{
if (p == null)
{
String sig = m.getSignature();
if (sig == null)
return getReturnType();
p = new MethodSignatureParser(this, sig);
}
return p.getGenericReturnType();
}
/**
* If this method is an annotation method, returns the default
* value for the method. If there is no default value, or if the
* method is not a member of an annotation type, returns null.
* Primitive types are wrapped.
*
* @throws TypeNotPresentException if the method returns a Class,
* and the class cannot be found
*
* @since 1.5
*/
public Object getDefaultValue()
{
return m.getDefaultValue();
}
/**
* <p>
* Return an array of arrays representing the annotations on each
* of the method's parameters. The outer array is aligned against
* the parameters of the method and is thus equal in length to
* the number of parameters (thus having a length zero if there are none).
* Each array element in the outer array contains an inner array which
* holds the annotations. This array has a length of zero if the parameter
* has no annotations.
* </p>
* <p>
* The returned annotations are serialized. Changing the annotations has
* no affect on the return value of future calls to this method.
* </p>
*
* @return an array of arrays which represents the annotations used on the
* parameters of this method. The order of the array elements
* matches the declaration order of the parameters.
* @since 1.5
*/
public Annotation[][] getParameterAnnotations()
{
return m.getParameterAnnotations();
}
/**
* Returns the element's annotation for the specified annotation type,
* or <code>null</code> if no such annotation exists.
*
* @param annotationClass the type of annotation to look for.
* @return this element's annotation for the specified type, or
* <code>null</code> if no such annotation exists.
* @throws NullPointerException if the annotation class is <code>null</code>.
*/
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
{
// Inescapable as the VM layer is 1.4 based. T will erase to Annotation anyway.
@SuppressWarnings("unchecked")
T ann = (T) m.getAnnotation(annotationClass);
return ann;
}
/**
* Returns all annotations directly defined by the element. If there are
* no annotations directly associated with the element, then a zero-length
* array will be returned. The returned array may be modified by the client
* code, but this will have no effect on the annotation content of this
* class, and hence no effect on the return value of this method for
* future callers.
*
* @return the annotations directly defined by the element.
* @since 1.5
*/
public Annotation[] getDeclaredAnnotations()
{
return m.getDeclaredAnnotations();
}
}

View file

@ -1,5 +1,5 @@
/* java.lang.reflect.Modifier
Copyright (C) 1998, 1999, 2001, 2002, 2005 Free Software Foundation, Inc.
Copyright (C) 1998, 1999, 2001, 2002, 2005, 2008 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@ -38,6 +38,8 @@ exception statement from your version. */
package java.lang.reflect;
import gnu.java.lang.CPStringBuilder;
/**
* Modifier is a helper class with static methods to determine whether an
* int returned from getModifiers() represents static, public, protected,
@ -308,28 +310,16 @@ public class Modifier
*/
public static String toString(int mod)
{
return toString(mod, new StringBuilder()).toString();
return toString(mod, new CPStringBuilder()).toString();
}
/**
* Package helper method that can take a StringBuilder.
* Package helper method that can take a CPStringBuilder.
* @param mod the modifier
* @param r the StringBuilder to which the String representation is appended
* @param r the CPStringBuilder to which the String representation is appended
* @return r, with information appended
*/
static StringBuilder toString(int mod, StringBuilder r)
{
r.append(toString(mod, new StringBuffer()));
return r;
}
/**
* Package helper method that can take a StringBuffer.
* @param mod the modifier
* @param r the StringBuffer to which the String representation is appended
* @return r, with information appended
*/
static StringBuffer toString(int mod, StringBuffer r)
static CPStringBuilder toString(int mod, CPStringBuilder r)
{
if (isPublic(mod))
r.append("public ");

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.lang.reflect;
import gnu.java.lang.CPStringBuilder;
import gnu.java.lang.reflect.TypeSignature;
import java.io.Serializable;
@ -1033,7 +1035,7 @@ public class Proxy implements Serializable
code_length += 9; // new, dup_x1, swap, invokespecial, athrow
}
int handler_pc = code_length - 1;
StringBuilder signature = new StringBuilder("(");
CPStringBuilder signature = new CPStringBuilder("(");
for (int j = 0; j < paramtypes.length; j++)
signature.append(TypeSignature.getEncodingOfClass(paramtypes[j]));
signature.append(")").append(TypeSignature.getEncodingOfClass(ret_type));
@ -1492,7 +1494,7 @@ public class Proxy implements Serializable
if (i == len)
return str;
final StringBuilder sb = new StringBuilder(str);
final CPStringBuilder sb = new CPStringBuilder(str);
sb.setLength(i);
for ( ; i < len; i++)
{

View file

@ -37,6 +37,8 @@ exception statement from your version. */
package java.math;
import gnu.java.lang.CPStringBuilder;
public class BigDecimal extends Number implements Comparable<BigDecimal>
{
private BigInteger intVal;
@ -451,7 +453,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal>
// val is a StringBuilder from which we'll create a BigInteger
// which will be the unscaled value for this BigDecimal
StringBuilder val = new StringBuilder(point - start - 1);
CPStringBuilder val = new CPStringBuilder(point - start - 1);
if (dot != -1)
{
// If there was a decimal we must combine the two parts that
@ -1070,7 +1072,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal>
boolean negative = (bigStr.charAt(0) == '-');
int point = bigStr.length() - scale - (negative ? 1 : 0);
StringBuilder val = new StringBuilder();
CPStringBuilder val = new CPStringBuilder();
if (scale >= 0 && (point - 1) >= -6)
{
@ -1137,7 +1139,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal>
// This is the adjusted exponent described above.
int adjExp = point - 1;
StringBuilder val = new StringBuilder();
CPStringBuilder val = new CPStringBuilder();
if (scale >= 0 && adjExp >= -6)
{
@ -1242,8 +1244,8 @@ public class BigDecimal extends Number implements Comparable<BigDecimal>
int point = bigStr.length() - scale - (negative ? 1 : 0);
StringBuffer sb = new StringBuffer(bigStr.length() + 2
+ (point <= 0 ? (-point + 1) : 0));
CPStringBuilder sb = new CPStringBuilder(bigStr.length() + 2
+ (point <= 0 ? (-point + 1) : 0));
if (point <= 0)
{
// We have to prepend zeros and a decimal point.

View file

@ -38,12 +38,17 @@ exception statement from your version. */
package java.math;
import gnu.classpath.Configuration;
import gnu.java.lang.CPStringBuilder;
import gnu.java.math.GMP;
import gnu.java.math.MPN;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Random;
import java.util.logging.Logger;
/**
* Written using on-line Java Platform 1.2 API Specification, as well
@ -59,6 +64,8 @@ import java.util.Random;
*/
public class BigInteger extends Number implements Comparable<BigInteger>
{
private static final Logger log = Logger.getLogger(BigInteger.class.getName());
/** All integers are stored in 2's-complement form.
* If words == null, the ival is the value of this BigInteger.
* Otherwise, the first ival elements of words make the value
@ -67,9 +74,10 @@ public class BigInteger extends Number implements Comparable<BigInteger>
private transient int[] words;
// Serialization fields.
// the first three, although not used in the code, are present for
// compatibility with older RI versions of this class. DO NOT REMOVE.
private int bitCount = -1;
private int bitLength = -1;
private int firstNonzeroByteNum = -2;
private int lowestSetBit = -2;
private byte[] magnitude;
private int signum;
@ -81,31 +89,52 @@ public class BigInteger extends Number implements Comparable<BigInteger>
private static final int minFixNum = -100;
private static final int maxFixNum = 1024;
private static final int numFixNum = maxFixNum-minFixNum+1;
private static final BigInteger[] smallFixNums = new BigInteger[numFixNum];
private static final BigInteger[] smallFixNums;
/** The alter-ego GMP instance for this. */
private transient GMP mpz;
private static final boolean USING_NATIVE = Configuration.WANT_NATIVE_BIG_INTEGER
&& initializeLibrary();
static
{
for (int i = numFixNum; --i >= 0; )
smallFixNums[i] = new BigInteger(i + minFixNum);
if (USING_NATIVE)
{
smallFixNums = null;
ZERO = valueOf(0L);
ONE = valueOf(1L);
TEN = valueOf(10L);
}
else
{
smallFixNums = new BigInteger[numFixNum];
for (int i = numFixNum; --i >= 0; )
smallFixNums[i] = new BigInteger(i + minFixNum);
ZERO = smallFixNums[-minFixNum];
ONE = smallFixNums[1 - minFixNum];
TEN = smallFixNums[10 - minFixNum];
}
}
/**
* The constant zero as a BigInteger.
* @since 1.2
*/
public static final BigInteger ZERO = smallFixNums[0 - minFixNum];
public static final BigInteger ZERO;
/**
* The constant one as a BigInteger.
* @since 1.2
*/
public static final BigInteger ONE = smallFixNums[1 - minFixNum];
public static final BigInteger ONE;
/**
* The constant ten as a BigInteger.
* @since 1.5
*/
public static final BigInteger TEN = smallFixNums[10 - minFixNum];
public static final BigInteger TEN;
/* Rounding modes: */
private static final int FLOOR = 1;
@ -130,19 +159,72 @@ public class BigInteger extends Number implements Comparable<BigInteger>
private BigInteger()
{
super();
if (USING_NATIVE)
mpz = new GMP();
}
/* Create a new (non-shared) BigInteger, and initialize to an int. */
private BigInteger(int value)
{
super();
ival = value;
}
public BigInteger(String val, int radix)
public BigInteger(String s, int radix)
{
BigInteger result = valueOf(val, radix);
this.ival = result.ival;
this.words = result.words;
this();
int len = s.length();
int i, digit;
boolean negative;
byte[] bytes;
char ch = s.charAt(0);
if (ch == '-')
{
negative = true;
i = 1;
bytes = new byte[len - 1];
}
else
{
negative = false;
i = 0;
bytes = new byte[len];
}
int byte_len = 0;
for ( ; i < len; i++)
{
ch = s.charAt(i);
digit = Character.digit(ch, radix);
if (digit < 0)
throw new NumberFormatException("Invalid character at position #" + i);
bytes[byte_len++] = (byte) digit;
}
if (USING_NATIVE)
{
bytes = null;
if (mpz.fromString(s, radix) != 0)
throw new NumberFormatException("String \"" + s
+ "\" is NOT a valid number in base "
+ radix);
}
else
{
BigInteger result;
// Testing (len < MPN.chars_per_word(radix)) would be more accurate,
// but slightly more expensive, for little practical gain.
if (len <= 15 && radix <= 16)
result = valueOf(Long.parseLong(s, radix));
else
result = valueOf(bytes, byte_len, negative, radix);
this.ival = result.ival;
this.words = result.words;
}
}
public BigInteger(String val)
@ -153,17 +235,26 @@ public class BigInteger extends Number implements Comparable<BigInteger>
/* Create a new (non-shared) BigInteger, and initialize from a byte array. */
public BigInteger(byte[] val)
{
this();
if (val == null || val.length < 1)
throw new NumberFormatException();
words = byteArrayToIntArray(val, val[0] < 0 ? -1 : 0);
BigInteger result = make(words, words.length);
this.ival = result.ival;
this.words = result.words;
if (USING_NATIVE)
mpz.fromByteArray(val);
else
{
words = byteArrayToIntArray(val, val[0] < 0 ? -1 : 0);
BigInteger result = make(words, words.length);
this.ival = result.ival;
this.words = result.words;
}
}
public BigInteger(int signum, byte[] magnitude)
{
this();
if (magnitude == null || signum > 1 || signum < -1)
throw new NumberFormatException();
@ -177,18 +268,25 @@ public class BigInteger extends Number implements Comparable<BigInteger>
return;
}
// Magnitude is always positive, so don't ever pass a sign of -1.
words = byteArrayToIntArray(magnitude, 0);
BigInteger result = make(words, words.length);
this.ival = result.ival;
this.words = result.words;
if (USING_NATIVE)
mpz.fromSignedMagnitude(magnitude, signum == -1);
else
{
// Magnitude is always positive, so don't ever pass a sign of -1.
words = byteArrayToIntArray(magnitude, 0);
BigInteger result = make(words, words.length);
this.ival = result.ival;
this.words = result.words;
if (signum < 0)
setNegative();
if (signum < 0)
setNegative();
}
}
public BigInteger(int numBits, Random rnd)
{
this();
if (numBits < 0)
throw new IllegalArgumentException();
@ -197,6 +295,22 @@ public class BigInteger extends Number implements Comparable<BigInteger>
private void init(int numBits, Random rnd)
{
if (USING_NATIVE)
{
int length = (numBits + 7) / 8;
byte[] magnitude = new byte[length];
rnd.nextBytes(magnitude);
int discardedBitCount = numBits % 8;
if (discardedBitCount != 0)
{
discardedBitCount = 8 - discardedBitCount;
magnitude[0] = (byte)((magnitude[0] & 0xFF) >>> discardedBitCount);
}
mpz.fromSignedMagnitude(magnitude, false);
magnitude = null;
return;
}
int highbits = numBits & 31;
// minimum number of bytes to store the above number of bits
int highBitByteCount = (highbits + 7) / 8;
@ -235,20 +349,23 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger(int bitLength, int certainty, Random rnd)
{
this(bitLength, rnd);
this();
// Keep going until we find a probable prime.
BigInteger result;
BigInteger result = new BigInteger();
while (true)
{
// ...but first ensure that BI has bitLength bits
result = setBit(bitLength - 1);
result.init(bitLength, rnd);
result = result.setBit(bitLength - 1);
if (result.isProbablePrime(certainty))
break;
}
if (USING_NATIVE)
mpz.fromBI(result.mpz);
else
{
this.ival = result.ival;
this.words = result.words;
if (isProbablePrime(certainty))
return;
init(bitLength, rnd);
}
}
@ -272,6 +389,13 @@ public class BigInteger extends Number implements Comparable<BigInteger>
/** Return a (possibly-shared) BigInteger with a given long value. */
public static BigInteger valueOf(long val)
{
if (USING_NATIVE)
{
BigInteger result = new BigInteger();
result.mpz.fromLong(val);
return result;
}
if (val >= minFixNum && val <= maxFixNum)
return smallFixNums[(int) val - minFixNum];
int i = (int) val;
@ -284,6 +408,31 @@ public class BigInteger extends Number implements Comparable<BigInteger>
return result;
}
/**
* @return <code>true</code> if the GMP-based native implementation library
* was successfully loaded. Returns <code>false</code> otherwise.
*/
private static boolean initializeLibrary()
{
boolean result;
try
{
System.loadLibrary("javamath");
GMP.natInitializeLibrary();
result = true;
}
catch (Throwable x)
{
result = false;
if (Configuration.DEBUG)
{
log.info("Unable to use native BigInteger: " + x);
log.info("Will use a pure Java implementation instead");
}
}
return result;
}
/** Make a canonicalized BigInteger from an array of words.
* The array may be reused (without copying). */
private static BigInteger make(int[] words, int len)
@ -374,6 +523,9 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public int signum()
{
if (USING_NATIVE)
return mpz.compare(ZERO.mpz);
if (ival == 0 && words == null)
return 0;
int top = words == null ? ival : words[ival-1];
@ -382,6 +534,12 @@ public class BigInteger extends Number implements Comparable<BigInteger>
private static int compareTo(BigInteger x, BigInteger y)
{
if (USING_NATIVE)
{
int dummy = y.signum; // force NPE check
return x.mpz.compare(y.mpz);
}
if (x.words == null && y.words == null)
return x.ival < y.ival ? -1 : x.ival > y.ival ? 1 : 0;
boolean x_negative = x.isNegative();
@ -586,11 +744,27 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger add(BigInteger val)
{
if (USING_NATIVE)
{
int dummy = val.signum; // force NPE check
BigInteger result = new BigInteger();
mpz.add(val.mpz, result.mpz);
return result;
}
return add(this, val, 1);
}
public BigInteger subtract(BigInteger val)
{
if (USING_NATIVE)
{
int dummy = val.signum; // force NPE check
BigInteger result = new BigInteger();
mpz.subtract(val.mpz, result.mpz);
return result;
}
return add(this, val, -1);
}
@ -672,6 +846,14 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger multiply(BigInteger y)
{
if (USING_NATIVE)
{
int dummy = y.signum; // force NPE check
BigInteger result = new BigInteger();
mpz.multiply(y.mpz, result.mpz);
return result;
}
return times(this, y);
}
@ -947,6 +1129,16 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger divide(BigInteger val)
{
if (USING_NATIVE)
{
if (val.compareTo(ZERO) == 0)
throw new ArithmeticException("divisor is zero");
BigInteger result = new BigInteger();
mpz.quotient(val.mpz, result.mpz);
return result;
}
if (val.isZero())
throw new ArithmeticException("divisor is zero");
@ -957,6 +1149,16 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger remainder(BigInteger val)
{
if (USING_NATIVE)
{
if (val.compareTo(ZERO) == 0)
throw new ArithmeticException("divisor is zero");
BigInteger result = new BigInteger();
mpz.remainder(val.mpz, result.mpz);
return result;
}
if (val.isZero())
throw new ArithmeticException("divisor is zero");
@ -967,6 +1169,17 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger[] divideAndRemainder(BigInteger val)
{
if (USING_NATIVE)
{
if (val.compareTo(ZERO) == 0)
throw new ArithmeticException("divisor is zero");
BigInteger q = new BigInteger();
BigInteger r = new BigInteger();
mpz.quotientAndRemainder(val.mpz, q.mpz, r.mpz);
return new BigInteger[] { q, r };
}
if (val.isZero())
throw new ArithmeticException("divisor is zero");
@ -981,6 +1194,17 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger mod(BigInteger m)
{
if (USING_NATIVE)
{
int dummy = m.signum; // force NPE check
if (m.compareTo(ZERO) < 1)
throw new ArithmeticException("non-positive modulus");
BigInteger result = new BigInteger();
mpz.modulo(m.mpz, result.mpz);
return result;
}
if (m.isNegative() || m.isZero())
throw new ArithmeticException("non-positive modulus");
@ -1000,6 +1224,14 @@ public class BigInteger extends Number implements Comparable<BigInteger>
return ONE;
throw new ArithmeticException("negative exponent");
}
if (USING_NATIVE)
{
BigInteger result = new BigInteger();
mpz.pow(exponent, result.mpz);
return result;
}
if (isZero())
return this;
int plen = words == null ? 1 : ival; // Length of pow2.
@ -1097,6 +1329,17 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger modInverse(BigInteger y)
{
if (USING_NATIVE)
{
int dummy = y.signum; // force NPE check
if (mpz.compare(ZERO.mpz) < 1)
throw new ArithmeticException("non-positive modulo");
BigInteger result = new BigInteger();
mpz.modInverse(y.mpz, result.mpz);
return result;
}
if (y.isNegative() || y.isZero())
throw new ArithmeticException("non-positive modulo");
@ -1175,6 +1418,17 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger modPow(BigInteger exponent, BigInteger m)
{
if (USING_NATIVE)
{
int dummy = exponent.signum; // force NPE check
if (m.mpz.compare(ZERO.mpz) < 1)
throw new ArithmeticException("non-positive modulo");
BigInteger result = new BigInteger();
mpz.modPow(exponent.mpz, m.mpz, result.mpz);
return result;
}
if (m.isNegative() || m.isZero())
throw new ArithmeticException("non-positive modulo");
@ -1228,6 +1482,14 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger gcd(BigInteger y)
{
if (USING_NATIVE)
{
int dummy = y.signum; // force NPE check
BigInteger result = new BigInteger();
mpz.gcd(y.mpz, result.mpz);
return result;
}
int xval = ival;
int yval = y.ival;
if (words == null)
@ -1281,6 +1543,9 @@ public class BigInteger extends Number implements Comparable<BigInteger>
if (certainty < 1)
return true;
if (USING_NATIVE)
return mpz.testPrimality(certainty) != 0;
/** We'll use the Rabin-Miller algorithm for doing a probabilistic
* primality test. It is fast, easy and has faster decreasing odds of a
* composite passing than with other tests. This means that this
@ -1460,15 +1725,41 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger shiftLeft(int n)
{
if (n == 0)
return this;
if (USING_NATIVE)
{
BigInteger result = new BigInteger();
if (n < 0)
mpz.shiftRight(-n, result.mpz);
else
mpz.shiftLeft(n, result.mpz);
return result;
}
return shift(this, n);
}
public BigInteger shiftRight(int n)
{
if (n == 0)
return this;
if (USING_NATIVE)
{
BigInteger result = new BigInteger();
if (n < 0)
mpz.shiftLeft(-n, result.mpz);
else
mpz.shiftRight(n, result.mpz);
return result;
}
return shift(this, -n);
}
private void format(int radix, StringBuffer buffer)
private void format(int radix, CPStringBuilder buffer)
{
if (words == null)
buffer.append(Integer.toString(ival, radix));
@ -1537,18 +1828,27 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public String toString(int radix)
{
if (USING_NATIVE)
return mpz.toString(radix);
if (words == null)
return Integer.toString(ival, radix);
if (ival <= 2)
return Long.toString(longValue(), radix);
int buf_size = ival * (MPN.chars_per_word(radix) + 1);
StringBuffer buffer = new StringBuffer(buf_size);
CPStringBuilder buffer = new CPStringBuilder(buf_size);
format(radix, buffer);
return buffer.toString();
}
public int intValue()
{
if (USING_NATIVE)
{
int result = mpz.absIntValue();
return mpz.compare(ZERO.mpz) < 0 ? - result : result;
}
if (words == null)
return ival;
return words[0];
@ -1556,6 +1856,15 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public long longValue()
{
if (USING_NATIVE)
{
long result;
result = (abs().shiftRight(32)).mpz.absIntValue();
result <<= 32;
result |= mpz.absIntValue() & 0xFFFFFFFFL;
return this.compareTo(ZERO) < 0 ? - result : result;
}
if (words == null)
return ival;
if (ival == 1)
@ -1566,12 +1875,25 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public int hashCode()
{
// FIXME: May not match hashcode of JDK.
if (USING_NATIVE)
{
// TODO: profile to decide whether to make it native
byte[] bytes = this.toByteArray();
int result = 0;
for (int i = 0; i < bytes.length; i++)
result ^= (bytes[i] & 0xFF) << (8 * (i % 4));
return result;
}
return words == null ? ival : (words[0] + words[ival - 1]);
}
/* Assumes x and y are both canonicalized. */
private static boolean equals(BigInteger x, BigInteger y)
{
if (USING_NATIVE)
return x.mpz.compare(y.mpz) == 0;
if (x.words == null && y.words == null)
return x.ival == y.ival;
if (x.words == null || y.words == null || x.ival != y.ival)
@ -1592,43 +1914,6 @@ public class BigInteger extends Number implements Comparable<BigInteger>
return equals(this, (BigInteger) obj);
}
private static BigInteger valueOf(String s, int radix)
throws NumberFormatException
{
int len = s.length();
// Testing (len < MPN.chars_per_word(radix)) would be more accurate,
// but slightly more expensive, for little practical gain.
if (len <= 15 && radix <= 16)
return valueOf(Long.parseLong(s, radix));
int i, digit;
boolean negative;
byte[] bytes;
char ch = s.charAt(0);
if (ch == '-')
{
negative = true;
i = 1;
bytes = new byte[len - 1];
}
else
{
negative = false;
i = 0;
bytes = new byte[len];
}
int byte_len = 0;
for ( ; i < len; i++)
{
ch = s.charAt(i);
digit = Character.digit(ch, radix);
if (digit < 0)
throw new NumberFormatException();
bytes[byte_len++] = (byte) digit;
}
return valueOf(bytes, byte_len, negative, radix);
}
private static BigInteger valueOf(byte[] digits, int byte_len,
boolean negative, int radix)
{
@ -1646,6 +1931,9 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public double doubleValue()
{
if (USING_NATIVE)
return mpz.doubleValue();
if (words == null)
return (double) ival;
if (ival <= 2)
@ -1827,6 +2115,13 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger abs()
{
if (USING_NATIVE)
{
BigInteger result = new BigInteger();
mpz.abs(result.mpz);
return result;
}
return abs(this);
}
@ -1841,6 +2136,13 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public BigInteger negate()
{
if (USING_NATIVE)
{
BigInteger result = new BigInteger();
mpz.negate(result.mpz);
return result;
}
return neg(this);
}
@ -1849,6 +2151,9 @@ public class BigInteger extends Number implements Comparable<BigInteger>
*/
public int bitLength()
{
if (USING_NATIVE)
return mpz.bitLength();
if (words == null)
return MPN.intLength(ival);
return MPN.intLength(words, ival);
@ -1856,6 +2161,25 @@ public class BigInteger extends Number implements Comparable<BigInteger>
public byte[] toByteArray()
{
if (signum() == 0)
return new byte[1];
if (USING_NATIVE)
{
// the minimal number of bytes required to represent the MPI is function
// of (a) its bit-length, and (b) its sign. only when this MPI is both
// positive, and its bit-length is a multiple of 8 do we add one zero
// bit for its sign. we do this so if we construct a new MPI from the
// resulting byte array, we wouldn't mistake a positive number, whose
// bit-length is a multiple of 8, for a similar-length negative one.
int bits = bitLength();
if (bits % 8 == 0 || this.signum() == 1)
bits++;
byte[] bytes = new byte[(bits + 7) / 8];
mpz.toByteArray(bytes);
return bytes;
}
// Determine number of bytes needed. The method bitlength returns
// the size without the sign bit, so add one bit for that and then
// add 7 more to emulate the ceil function using integer math.
@ -2112,6 +2436,14 @@ public class BigInteger extends Number implements Comparable<BigInteger>
/** Return the logical (bit-wise) "and" of two BigIntegers. */
public BigInteger and(BigInteger y)
{
if (USING_NATIVE)
{
int dummy = y.signum; // force NPE check
BigInteger result = new BigInteger();
mpz.and(y.mpz, result.mpz);
return result;
}
if (y.words == null)
return and(this, y.ival);
else if (words == null)
@ -2135,23 +2467,54 @@ public class BigInteger extends Number implements Comparable<BigInteger>
/** Return the logical (bit-wise) "(inclusive) or" of two BigIntegers. */
public BigInteger or(BigInteger y)
{
if (USING_NATIVE)
{
int dummy = y.signum; // force NPE check
BigInteger result = new BigInteger();
mpz.or(y.mpz, result.mpz);
return result;
}
return bitOp(7, this, y);
}
/** Return the logical (bit-wise) "exclusive or" of two BigIntegers. */
public BigInteger xor(BigInteger y)
{
if (USING_NATIVE)
{
int dummy = y.signum; // force NPE check
BigInteger result = new BigInteger();
mpz.xor(y.mpz, result.mpz);
return result;
}
return bitOp(6, this, y);
}
/** Return the logical (bit-wise) negation of a BigInteger. */
public BigInteger not()
{
if (USING_NATIVE)
{
BigInteger result = new BigInteger();
mpz.not(result.mpz);
return result;
}
return bitOp(12, this, ZERO);
}
public BigInteger andNot(BigInteger val)
{
if (USING_NATIVE)
{
int dummy = val.signum; // force NPE check
BigInteger result = new BigInteger();
mpz.andNot(val.mpz, result.mpz);
return result;
}
return and(val.not());
}
@ -2160,6 +2523,13 @@ public class BigInteger extends Number implements Comparable<BigInteger>
if (n < 0)
throw new ArithmeticException();
if (USING_NATIVE)
{
BigInteger result = new BigInteger();
mpz.setBit(n, false, result.mpz);
return result;
}
return and(ONE.shiftLeft(n).not());
}
@ -2168,6 +2538,13 @@ public class BigInteger extends Number implements Comparable<BigInteger>
if (n < 0)
throw new ArithmeticException();
if (USING_NATIVE)
{
BigInteger result = new BigInteger();
mpz.setBit(n, true, result.mpz);
return result;
}
return or(ONE.shiftLeft(n));
}
@ -2176,6 +2553,9 @@ public class BigInteger extends Number implements Comparable<BigInteger>
if (n < 0)
throw new ArithmeticException();
if (USING_NATIVE)
return mpz.testBit(n) != 0;
return !and(ONE.shiftLeft(n)).isZero();
}
@ -2184,11 +2564,21 @@ public class BigInteger extends Number implements Comparable<BigInteger>
if (n < 0)
throw new ArithmeticException();
if (USING_NATIVE)
{
BigInteger result = new BigInteger();
mpz.flipBit(n, result.mpz);
return result;
}
return xor(ONE.shiftLeft(n));
}
public int getLowestSetBit()
{
if (USING_NATIVE)
return mpz.compare(ZERO.mpz) == 0 ? -1 : mpz.lowestSetBit();
if (isZero())
return -1;
@ -2225,6 +2615,9 @@ public class BigInteger extends Number implements Comparable<BigInteger>
* If argument is negative, count zero bits instead. */
public int bitCount()
{
if (USING_NATIVE)
return mpz.bitCount();
int i, x_len;
int[] x_words = words;
if (x_words == null)
@ -2243,19 +2636,30 @@ public class BigInteger extends Number implements Comparable<BigInteger>
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
if (magnitude.length == 0 || signum == 0)
if (USING_NATIVE)
{
this.ival = 0;
this.words = null;
mpz = new GMP();
s.defaultReadObject();
if (signum != 0)
mpz.fromByteArray(magnitude);
// else it's zero and we need to do nothing
}
else
{
words = byteArrayToIntArray(magnitude, signum < 0 ? -1 : 0);
BigInteger result = make(words, words.length);
this.ival = result.ival;
this.words = result.words;
}
s.defaultReadObject();
if (magnitude.length == 0 || signum == 0)
{
this.ival = 0;
this.words = null;
}
else
{
words = byteArrayToIntArray(magnitude, signum < 0 ? -1 : 0);
BigInteger result = make(words, words.length);
this.ival = result.ival;
this.words = result.words;
}
}
}
private void writeObject(ObjectOutputStream s)
@ -2264,5 +2668,9 @@ public class BigInteger extends Number implements Comparable<BigInteger>
signum = signum();
magnitude = signum == 0 ? new byte[0] : toByteArray();
s.defaultWriteObject();
magnitude = null; // not needed anymore
}
// inner class(es) ..........................................................
}

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.net;
import gnu.java.lang.CPStringBuilder;
import java.io.ObjectStreamException;
/*
@ -212,7 +214,7 @@ public final class Inet4Address extends InetAddress
*/
public String getHostAddress()
{
StringBuffer sb = new StringBuffer(40);
CPStringBuilder sb = new CPStringBuilder(40);
int len = addr.length;
int i = 0;

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.net;
import gnu.java.lang.CPStringBuilder;
import java.util.Arrays;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@ -317,7 +319,7 @@ public final class Inet6Address extends InetAddress
*/
public String getHostAddress()
{
StringBuffer sbuf = new StringBuffer(40);
CPStringBuilder sbuf = new CPStringBuilder(40);
for (int i = 0; i < 16; i += 2)
{

View file

@ -1,5 +1,5 @@
/* NetworkInterface.java --
Copyright (C) 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
Copyright (C) 2002, 2003, 2004, 2005, 2006, 2008 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@ -40,6 +40,8 @@ package java.net;
import gnu.classpath.SystemProperties;
import gnu.java.lang.CPStringBuilder;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
@ -247,10 +249,10 @@ public final class NetworkInterface
public String toString()
{
// FIXME: check if this is correct
StringBuffer result;
CPStringBuilder result;
String separator = SystemProperties.getProperty("line.separator");
result = new StringBuffer();
result = new CPStringBuilder();
result.append("name: ");
result.append(getDisplayName());
@ -265,4 +267,50 @@ public final class NetworkInterface
return result.toString();
}
/**
* Determines whether this interface is ready to transfer data.
*
* @return whether the interface is up
*/
public boolean isUp()
throws SocketException
{
return VMNetworkInterface.isUp(netif.name);
}
/**
* Determines whether this interface does point to point
* transmission.
*
* @return whether the interface does point to point transmission
*/
public boolean isPointToPoint()
throws SocketException
{
return VMNetworkInterface.isPointToPoint(netif.name);
}
/**
* Determines whether this interface is the loopback interface.
*
* @return whether the interface is the loopback interface
*/
public boolean isLoopback()
throws SocketException
{
return VMNetworkInterface.isLoopback(netif.name);
}
/**
* Determines whether this interface supports multicast transmission.
*
* @return whether the interface supports multicast transmission.
*/
public boolean supportsMulticast()
throws SocketException
{
return VMNetworkInterface.supportsMulticast(netif.name);
}
}

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.net;
import gnu.java.lang.CPStringBuilder;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@ -431,7 +433,7 @@ public final class SocketPermission extends Permission implements Serializable
*/
public String getActions()
{
StringBuffer sb = new StringBuffer("");
CPStringBuilder sb = new CPStringBuilder("");
for (int i = 0; i < ACTIONS.length; i++)
{

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.net;
import gnu.java.lang.CPStringBuilder;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@ -483,7 +485,7 @@ public final class URI
*/
private static String quote(String str, String legalCharacters)
{
StringBuilder sb = new StringBuilder(str.length());
CPStringBuilder sb = new CPStringBuilder(str.length());
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
@ -778,8 +780,8 @@ public final class URI
This follows the algorithm in section 5.2.4. of RFC3986,
but doesn't modify the input buffer.
*/
StringBuilder input = new StringBuilder(relativePath);
StringBuilder output = new StringBuilder();
CPStringBuilder input = new CPStringBuilder(relativePath);
CPStringBuilder output = new CPStringBuilder();
int start = 0;
while (start < input.length())
{
@ -853,7 +855,7 @@ public final class URI
*
* @param buffer the buffer containing the path.
*/
private void removeLastSegment(StringBuilder buffer)
private void removeLastSegment(CPStringBuilder buffer)
{
int lastSlash = buffer.lastIndexOf("/");
if (lastSlash == -1)
@ -899,7 +901,7 @@ public final class URI
path = "";
if (! (path.startsWith("/")))
{
StringBuilder basepath = new StringBuilder(this.path);
CPStringBuilder basepath = new CPStringBuilder(this.path);
int i = this.path.lastIndexOf('/');
if (i >= 0)
@ -1388,8 +1390,8 @@ public final class URI
{
String strRep = toString();
boolean inNonAsciiBlock = false;
StringBuilder buffer = new StringBuilder();
StringBuilder encBuffer = null;
CPStringBuilder buffer = new CPStringBuilder();
CPStringBuilder encBuffer = null;
for (int i = 0; i < strRep.length(); i++)
{
char c = strRep.charAt(i);
@ -1406,7 +1408,7 @@ public final class URI
{
if (!inNonAsciiBlock)
{
encBuffer = new StringBuilder();
encBuffer = new CPStringBuilder();
inNonAsciiBlock = true;
}
encBuffer.append(c);
@ -1428,7 +1430,7 @@ public final class URI
{
try
{
StringBuilder sb = new StringBuilder();
CPStringBuilder sb = new CPStringBuilder();
// this is far from optimal, but it works
byte[] utf8 = str.getBytes("utf-8");
for (int j = 0; j < utf8.length; j++)

View file

@ -39,6 +39,8 @@ exception statement from your version. */
package java.net;
import gnu.java.lang.CPStringBuilder;
import gnu.java.net.loader.FileURLLoader;
import gnu.java.net.loader.JarURLLoader;
import gnu.java.net.loader.RemoteURLLoader;
@ -452,7 +454,7 @@ public class URLClassLoader extends SecureClassLoader
{
// Compute the name of the package as it may appear in the
// Manifest.
StringBuilder xform = new StringBuilder(name);
CPStringBuilder xform = new CPStringBuilder(name);
for (int i = xform.length () - 1; i >= 0; --i)
if (xform.charAt(i) == '.')
xform.setCharAt(i, '/');
@ -641,7 +643,7 @@ public class URLClassLoader extends SecureClassLoader
{
if (thisString == null)
{
StringBuilder sb = new StringBuilder();
CPStringBuilder sb = new CPStringBuilder();
sb.append(this.getClass().getName());
sb.append("{urls=[" );
URL[] thisURLs = getURLs();

View file

@ -37,6 +37,8 @@ exception statement from your version. */
package java.net;
import gnu.java.lang.CPStringBuilder;
import java.io.UnsupportedEncodingException;
@ -127,7 +129,7 @@ public class URLDecoder
int start = 0;
byte[] bytes = null;
int length = str.length();
StringBuffer result = new StringBuffer(length);
CPStringBuilder result = new CPStringBuilder(length);
while ((i = str.indexOf('%', start)) >= 0)
{
// Add all non-encoded characters to the result buffer

View file

@ -37,6 +37,8 @@ exception statement from your version. */
package java.net;
import gnu.java.lang.CPStringBuilder;
import java.io.UnsupportedEncodingException;
@ -113,7 +115,7 @@ public class URLEncoder
int start = 0;
int i = 0;
StringBuilder result = new StringBuilder(length);
CPStringBuilder result = new CPStringBuilder(length);
while (true)
{
while (i < length && isSafe(s.charAt(i)))

View file

@ -37,6 +37,8 @@ exception statement from your version. */
package java.net;
import gnu.java.lang.CPStringBuilder;
import java.io.File;
import java.io.IOException;
@ -510,7 +512,7 @@ public abstract class URLStreamHandler
// Guess a reasonable size for the string buffer so we have to resize
// at most once.
int size = protocol.length() + authority.length() + file.length() + 24;
StringBuffer sb = new StringBuffer(size);
CPStringBuilder sb = new CPStringBuilder(size);
if (protocol.length() > 0)
{

View file

@ -45,19 +45,21 @@ import gnu.classpath.Pointer;
*/
public abstract class Buffer
{
int cap = 0;
int limit = 0;
int pos = 0;
int mark = -1;
Pointer address;
private final int cap;
int limit;
int pos;
int mark;
final Pointer address;
/**
* Creates a new Buffer.
*
* Should be package private.
*/
Buffer (int capacity, int limit, int position, int mark)
Buffer (int capacity, int limit, int position, int mark, Pointer address)
{
this.address = address;
if (capacity < 0)
throw new IllegalArgumentException ();
@ -72,6 +74,10 @@ public abstract class Buffer
this.mark = mark;
}
else
{
this.mark = -1;
}
}
/**

View file

@ -38,6 +38,10 @@ exception statement from your version. */
package java.nio;
// GCJ LOCAL: Change gnu.classpath.Pointer to RawData
import gnu.gcj.RawData;
import gnu.classpath.Pointer;
/**
* @since 1.4
*/
@ -45,13 +49,15 @@ public abstract class ByteBuffer extends Buffer
implements Comparable<ByteBuffer>
{
ByteOrder endian = ByteOrder.BIG_ENDIAN;
final byte[] backing_buffer;
final int array_offset;
int array_offset;
byte[] backing_buffer;
ByteBuffer (int capacity, int limit, int position, int mark)
ByteBuffer (int capacity, int limit, int position, int mark,
RawData address, byte[] backing_buffer, int array_offset)
{
super (capacity, limit, position, mark);
super (capacity, limit, position, mark, address);
this.backing_buffer = backing_buffer;
this.array_offset = array_offset;
}
/**

View file

@ -43,13 +43,12 @@ package java.nio;
*/
final class ByteBufferImpl extends ByteBuffer
{
private boolean readOnly;
private final boolean readOnly;
ByteBufferImpl (byte[] buffer, int offset, int capacity, int limit, int position, int mark, boolean readOnly)
ByteBufferImpl (byte[] buffer, int offset, int capacity, int limit,
int position, int mark, boolean readOnly)
{
super (capacity, limit, position, mark);
this.backing_buffer = buffer;
this.array_offset = offset;
super (capacity, limit, position, mark, null, buffer, offset);
this.readOnly = readOnly;
}
@ -90,17 +89,20 @@ final class ByteBufferImpl extends ByteBuffer
public ByteBuffer slice ()
{
return new ByteBufferImpl (backing_buffer, array_offset + position (), remaining (), remaining (), 0, -1, isReadOnly ());
return new ByteBufferImpl (backing_buffer, array_offset + position (),
remaining (), remaining (), 0, -1, isReadOnly ());
}
public ByteBuffer duplicate ()
{
return new ByteBufferImpl (backing_buffer, array_offset, capacity (), limit (), position (), mark, isReadOnly ());
return new ByteBufferImpl (backing_buffer, array_offset, capacity (),
limit (), position (), mark, isReadOnly ());
}
public ByteBuffer asReadOnlyBuffer ()
{
return new ByteBufferImpl (backing_buffer, array_offset, capacity (), limit (), position (), mark, true);
return new ByteBufferImpl (backing_buffer, array_offset, capacity (),
limit (), position (), mark, true);
}
void shiftDown (int dst_offset, int src_offset, int count)

View file

@ -38,6 +38,9 @@ exception statement from your version. */
package java.nio;
// GCJ LOCAL: Use RawData instead of gnu.classpath.Pointer
import gnu.gcj.RawData;
import java.io.IOException;
/**
@ -46,13 +49,15 @@ import java.io.IOException;
public abstract class CharBuffer extends Buffer
implements Comparable<CharBuffer>, CharSequence, Readable, Appendable
{
int array_offset;
char[] backing_buffer;
final int array_offset;
final char[] backing_buffer;
CharBuffer (int capacity, int limit, int position, int mark)
CharBuffer (int capacity, int limit, int position, int mark,
RawData address, char[] backing_buffer, int array_offset)
{
super (capacity, limit, position, mark);
array_offset = 0;
super (capacity, limit, position, mark, address);
this.backing_buffer = backing_buffer;
this.array_offset = array_offset;
}
/**
@ -78,7 +83,8 @@ public abstract class CharBuffer extends Buffer
*/
public static final CharBuffer wrap(char[] array, int offset, int length)
{
return new CharBufferImpl(array, 0, array.length, offset + length, offset, -1, false);
return new CharBufferImpl(array, 0, array.length, offset + length, offset,
-1, false);
}
/**

View file

@ -43,7 +43,7 @@ package java.nio;
*/
final class CharBufferImpl extends CharBuffer
{
private boolean readOnly;
private final boolean readOnly;
CharBufferImpl (int capacity)
{
@ -52,18 +52,14 @@ final class CharBufferImpl extends CharBuffer
CharBufferImpl (char[] buffer, int offset, int capacity, int limit, int position, int mark, boolean readOnly)
{
super (capacity, limit, position, mark);
this.backing_buffer = buffer;
this.array_offset = offset;
super (capacity, limit, position, mark, null, buffer, offset);
this.readOnly = readOnly;
}
public CharBufferImpl (CharBufferImpl copy)
{
super (copy.capacity (), copy.limit (), copy.position (), 0);
backing_buffer = copy.backing_buffer;
array_offset = copy.array_offset;
readOnly = copy.isReadOnly ();
super (copy.capacity (), copy.limit (), copy.position (), 0, null, copy.backing_buffer, copy.array_offset);
this.readOnly = copy.isReadOnly ();
}
public boolean isReadOnly ()

View file

@ -48,7 +48,7 @@ final class CharSequenceBuffer
/**
* The wrapped char sequence.
*/
private CharSequence charSequence;
private final CharSequence charSequence;
/**
* Creates a new CharSequenceBuffer.
@ -63,9 +63,8 @@ final class CharSequenceBuffer
CharSequenceBuffer(CharSequence charSeq, int capacity, int limit,
int position, int mark, int offs)
{
super(capacity, limit, position, mark);
charSequence = charSeq;
array_offset = offs;
super(capacity, limit, position, mark, null, null, offs);
this.charSequence = charSeq;
}
/**
@ -105,7 +104,7 @@ final class CharSequenceBuffer
*/
public CharBuffer duplicate()
{
return new CharSequenceBuffer(charSequence, cap, limit, pos, mark, 0);
return new CharSequenceBuffer(charSequence, capacity(), limit, pos, mark, 0);
}
/**

View file

@ -41,33 +41,33 @@ package java.nio;
class CharViewBufferImpl extends CharBuffer
{
/** Position in bb (i.e. a byte offset) where this buffer starts. */
private int offset;
private ByteBuffer bb;
private boolean readOnly;
private ByteOrder endian;
private final int offset;
private final ByteBuffer bb;
private final boolean readOnly;
private final ByteOrder endian;
CharViewBufferImpl (ByteBuffer bb, int capacity)
{
super (capacity, capacity, 0, -1);
super (capacity, capacity, 0, -1, bb.isDirect() ?
VMDirectByteBuffer.adjustAddress(bb.address, bb.position()) : null,
null, 0);
this.bb = bb;
this.offset = bb.position();
this.readOnly = bb.isReadOnly();
this.endian = bb.order();
if (bb.isDirect())
this.address = VMDirectByteBuffer.adjustAddress(bb.address, offset);
}
public CharViewBufferImpl (ByteBuffer bb, int offset, int capacity,
int limit, int position, int mark,
boolean readOnly, ByteOrder endian)
{
super (capacity, limit, position, mark);
super (capacity, limit, position, mark, bb.isDirect() ?
VMDirectByteBuffer.adjustAddress(bb.address, offset) : null,
null, 0);
this.bb = bb;
this.offset = offset;
this.readOnly = readOnly;
this.endian = endian;
if (bb.isDirect())
this.address = VMDirectByteBuffer.adjustAddress(bb.address, offset);
}
/**

View file

@ -104,18 +104,16 @@ abstract class DirectByteBufferImpl extends ByteBuffer
DirectByteBufferImpl(int capacity)
{
super(capacity, capacity, 0, -1);
super(capacity, capacity, 0, -1, VMDirectByteBuffer.allocate(capacity), null, 0);
this.owner = this;
this.address = VMDirectByteBuffer.allocate(capacity);
}
DirectByteBufferImpl(Object owner, Pointer address,
int capacity, int limit,
int position)
{
super(capacity, limit, position, -1);
super(capacity, limit, position, -1, address, null, 0);
this.owner = owner;
this.address = address;
}
/**

View file

@ -38,19 +38,24 @@ exception statement from your version. */
package java.nio;
// GCJ LOCAL: Change gnu.classpath.Pointer to RawData
import gnu.gcj.RawData;
/**
* @since 1.4
*/
public abstract class DoubleBuffer extends Buffer
implements Comparable<DoubleBuffer>
{
int array_offset;
double[] backing_buffer;
final int array_offset;
final double[] backing_buffer;
DoubleBuffer (int capacity, int limit, int position, int mark)
DoubleBuffer (int capacity, int limit, int position, int mark,
RawData address, double[] backing_buffer, int array_offset)
{
super (capacity, limit, position, mark);
array_offset = 0;
super (capacity, limit, position, mark, address);
this.backing_buffer = backing_buffer;
this.array_offset = array_offset;
}
/**

View file

@ -43,18 +43,17 @@ package java.nio;
*/
final class DoubleBufferImpl extends DoubleBuffer
{
private boolean readOnly;
private final boolean readOnly;
DoubleBufferImpl (int capacity)
{
this (new double [capacity], 0, capacity, capacity, 0, -1, false);
}
DoubleBufferImpl (double[] buffer, int offset, int capacity, int limit, int position, int mark, boolean readOnly)
DoubleBufferImpl (double[] buffer, int offset, int capacity, int limit,
int position, int mark, boolean readOnly)
{
super (capacity, limit, position, mark);
this.backing_buffer = buffer;
this.array_offset = offset;
super (capacity, limit, position, mark, null, buffer, offset);
this.readOnly = readOnly;
}
@ -65,17 +64,20 @@ final class DoubleBufferImpl extends DoubleBuffer
public DoubleBuffer slice ()
{
return new DoubleBufferImpl (backing_buffer, array_offset + position (), remaining (), remaining (), 0, -1, isReadOnly ());
return new DoubleBufferImpl (backing_buffer, array_offset + position (),
remaining (), remaining (), 0, -1, isReadOnly ());
}
public DoubleBuffer duplicate ()
{
return new DoubleBufferImpl (backing_buffer, array_offset, capacity (), limit (), position (), mark, isReadOnly ());
return new DoubleBufferImpl (backing_buffer, array_offset, capacity (),
limit (), position (), mark, isReadOnly ());
}
public DoubleBuffer asReadOnlyBuffer ()
{
return new DoubleBufferImpl (backing_buffer, array_offset, capacity (), limit (), position (), mark, true);
return new DoubleBufferImpl (backing_buffer, array_offset, capacity (),
limit (), position (), mark, true);
}
public DoubleBuffer compact ()

View file

@ -41,33 +41,31 @@ package java.nio;
final class DoubleViewBufferImpl extends DoubleBuffer
{
/** Position in bb (i.e. a byte offset) where this buffer starts. */
private int offset;
private ByteBuffer bb;
private boolean readOnly;
private ByteOrder endian;
private final int offset;
private final ByteBuffer bb;
private final boolean readOnly;
private final ByteOrder endian;
DoubleViewBufferImpl (ByteBuffer bb, int capacity)
{
super (capacity, capacity, 0, -1);
super (capacity, capacity, 0, -1, bb.isDirect() ?
VMDirectByteBuffer.adjustAddress(bb.address, bb.position()) : null, null, 0);
this.bb = bb;
this.offset = bb.position();
this.readOnly = bb.isReadOnly();
this.endian = bb.order();
if (bb.isDirect())
this.address = VMDirectByteBuffer.adjustAddress(bb.address, offset);
}
public DoubleViewBufferImpl (ByteBuffer bb, int offset, int capacity,
int limit, int position, int mark,
boolean readOnly, ByteOrder endian)
{
super (capacity, limit, position, mark);
super (capacity, limit, position, mark, bb.isDirect() ?
VMDirectByteBuffer.adjustAddress(bb.address, bb.position()) : null, null, 0);
this.bb = bb;
this.offset = offset;
this.readOnly = readOnly;
this.endian = endian;
if (bb.isDirect())
this.address = VMDirectByteBuffer.adjustAddress(bb.address, offset);
}
/**

View file

@ -38,19 +38,24 @@ exception statement from your version. */
package java.nio;
// GCJ LOCAL: Change gnu.classpath.Pointer to RawData
import gnu.gcj.RawData;
/**
* @since 1.4
*/
public abstract class FloatBuffer extends Buffer
implements Comparable<FloatBuffer>
{
int array_offset;
float[] backing_buffer;
final int array_offset;
final float[] backing_buffer;
FloatBuffer (int capacity, int limit, int position, int mark)
FloatBuffer (int capacity, int limit, int position, int mark,
RawData address, float[] backing_buffer, int array_offset)
{
super (capacity, limit, position, mark);
array_offset = 0;
super (capacity, limit, position, mark, address);
this.backing_buffer = backing_buffer;
this.array_offset = array_offset;
}
/**

View file

@ -43,18 +43,17 @@ package java.nio;
*/
final class FloatBufferImpl extends FloatBuffer
{
private boolean readOnly;
private final boolean readOnly;
FloatBufferImpl (int capacity)
{
this (new float [capacity], 0, capacity, capacity, 0, -1, false);
}
FloatBufferImpl (float[] buffer, int offset, int capacity, int limit, int position, int mark, boolean readOnly)
FloatBufferImpl (float[] buffer, int offset, int capacity, int limit,
int position, int mark, boolean readOnly)
{
super (capacity, limit, position, mark);
this.backing_buffer = buffer;
this.array_offset = offset;
super (capacity, limit, position, mark, null, buffer, offset);
this.readOnly = readOnly;
}

View file

@ -41,33 +41,31 @@ package java.nio;
final class FloatViewBufferImpl extends FloatBuffer
{
/** Position in bb (i.e. a byte offset) where this buffer starts. */
private int offset;
private ByteBuffer bb;
private boolean readOnly;
private ByteOrder endian;
private final int offset;
private final ByteBuffer bb;
private final boolean readOnly;
private final ByteOrder endian;
FloatViewBufferImpl (ByteBuffer bb, int capacity)
{
super (capacity, capacity, 0, -1);
super (capacity, capacity, 0, -1, bb.isDirect() ?
VMDirectByteBuffer.adjustAddress(bb.address, bb.position()):null, null, 0);
this.bb = bb;
this.offset = bb.position();
this.readOnly = bb.isReadOnly();
this.endian = bb.order();
if (bb.isDirect())
this.address = VMDirectByteBuffer.adjustAddress(bb.address, offset);
}
public FloatViewBufferImpl (ByteBuffer bb, int offset, int capacity,
int limit, int position, int mark,
boolean readOnly, ByteOrder endian)
{
super (capacity, limit, position, mark);
super (capacity, limit, position, mark, bb.isDirect() ?
VMDirectByteBuffer.adjustAddress(bb.address, offset):null, null, 0);
this.bb = bb;
this.offset = offset;
this.readOnly = readOnly;
this.endian = endian;
if (bb.isDirect())
this.address = VMDirectByteBuffer.adjustAddress(bb.address, offset);
}
/**

View file

@ -38,19 +38,24 @@ exception statement from your version. */
package java.nio;
// GCJ LOCAL: Change gnu.classpath.Pointer to RawData
import gnu.gcj.RawData;
/**
* @since 1.4
*/
public abstract class IntBuffer extends Buffer
implements Comparable<IntBuffer>
{
int array_offset;
int[] backing_buffer;
final int array_offset;
final int[] backing_buffer;
IntBuffer (int capacity, int limit, int position, int mark)
IntBuffer (int capacity, int limit, int position, int mark, RawData address,
int[] backing_buffer, int array_offset)
{
super (capacity, limit, position, mark);
array_offset = 0;
super (capacity, limit, position, mark, address);
this.backing_buffer = backing_buffer;
this.array_offset = array_offset;
}
/**
@ -70,7 +75,8 @@ public abstract class IntBuffer extends Buffer
*/
public static final IntBuffer wrap (int[] array, int offset, int length)
{
return new IntBufferImpl (array, 0, array.length, offset + length, offset, -1, false);
return new IntBufferImpl (array, 0, array.length, offset + length, offset,
-1, false);
}
/**

View file

@ -43,7 +43,7 @@ package java.nio;
*/
final class IntBufferImpl extends IntBuffer
{
private boolean readOnly;
private final boolean readOnly;
IntBufferImpl (int capacity)
{
@ -52,9 +52,7 @@ final class IntBufferImpl extends IntBuffer
IntBufferImpl (int[] buffer, int offset, int capacity, int limit, int position, int mark, boolean readOnly)
{
super (capacity, limit, position, mark);
this.backing_buffer = buffer;
this.array_offset = offset;
super (capacity, limit, position, mark, null, buffer, offset);
this.readOnly = readOnly;
}

View file

@ -41,33 +41,31 @@ package java.nio;
final class IntViewBufferImpl extends IntBuffer
{
/** Position in bb (i.e. a byte offset) where this buffer starts. */
private int offset;
private ByteBuffer bb;
private boolean readOnly;
private ByteOrder endian;
private final int offset;
private final ByteBuffer bb;
private final boolean readOnly;
private final ByteOrder endian;
IntViewBufferImpl (ByteBuffer bb, int capacity)
{
super (capacity, capacity, 0, -1);
super (capacity, capacity, 0, -1, bb.isDirect() ?
VMDirectByteBuffer.adjustAddress(bb.address, bb.position()):null, null, 0);
this.bb = bb;
this.offset = bb.position();
this.readOnly = bb.isReadOnly();
this.endian = bb.order();
if (bb.isDirect())
this.address = VMDirectByteBuffer.adjustAddress(bb.address, offset);
}
public IntViewBufferImpl (ByteBuffer bb, int offset, int capacity,
int limit, int position, int mark,
boolean readOnly, ByteOrder endian)
{
super (capacity, limit, position, mark);
super (capacity, limit, position, mark, bb.isDirect() ?
VMDirectByteBuffer.adjustAddress(bb.address, offset):null, null, 0);
this.bb = bb;
this.offset = offset;
this.readOnly = readOnly;
this.endian = endian;
if (bb.isDirect())
this.address = VMDirectByteBuffer.adjustAddress(bb.address, offset);
}
/**

View file

@ -38,19 +38,24 @@ exception statement from your version. */
package java.nio;
// GCJ LOCAL: Change gnu.classpath.Pointer to RawData
import gnu.gcj.RawData;
/**
* @since 1.4
*/
public abstract class LongBuffer extends Buffer
implements Comparable<LongBuffer>
{
int array_offset;
long[] backing_buffer;
final int array_offset;
final long[] backing_buffer;
LongBuffer (int capacity, int limit, int position, int mark)
LongBuffer (int capacity, int limit, int position, int mark,
RawData address, long[] backing_buffer, int array_offset)
{
super (capacity, limit, position, mark);
array_offset = 0;
super (capacity, limit, position, mark, address);
this.backing_buffer = backing_buffer;
this.array_offset = array_offset;
}
/**

View file

@ -43,18 +43,17 @@ package java.nio;
*/
final class LongBufferImpl extends LongBuffer
{
private boolean readOnly;
private final boolean readOnly;
LongBufferImpl (int capacity)
{
this (new long [capacity], 0, capacity, capacity, 0, -1, false);
}
LongBufferImpl (long[] buffer, int offset, int capacity, int limit, int position, int mark, boolean readOnly)
LongBufferImpl (long[] buffer, int offset, int capacity, int limit,
int position, int mark, boolean readOnly)
{
super (capacity, limit, position, mark);
this.backing_buffer = buffer;
this.array_offset = offset;
super (capacity, limit, position, mark, null, buffer, offset);
this.readOnly = readOnly;
}
@ -65,17 +64,20 @@ final class LongBufferImpl extends LongBuffer
public LongBuffer slice ()
{
return new LongBufferImpl (backing_buffer, array_offset + position (), remaining (), remaining (), 0, -1, isReadOnly ());
return new LongBufferImpl (backing_buffer, array_offset + position (),
remaining (), remaining (), 0, -1, isReadOnly ());
}
public LongBuffer duplicate ()
{
return new LongBufferImpl (backing_buffer, array_offset, capacity (), limit (), position (), mark, isReadOnly ());
return new LongBufferImpl (backing_buffer, array_offset, capacity (), limit (),
position (), mark, isReadOnly ());
}
public LongBuffer asReadOnlyBuffer ()
{
return new LongBufferImpl (backing_buffer, array_offset, capacity (), limit (), position (), mark, true);
return new LongBufferImpl (backing_buffer, array_offset, capacity (), limit (),
position (), mark, true);
}
public LongBuffer compact ()

View file

@ -41,33 +41,31 @@ package java.nio;
final class LongViewBufferImpl extends LongBuffer
{
/** Position in bb (i.e. a byte offset) where this buffer starts. */
private int offset;
private ByteBuffer bb;
private boolean readOnly;
private ByteOrder endian;
private final int offset;
private final ByteBuffer bb;
private final boolean readOnly;
private final ByteOrder endian;
LongViewBufferImpl (ByteBuffer bb, int capacity)
{
super (capacity, capacity, 0, -1);
super (capacity, capacity, 0, -1, bb.isDirect() ?
VMDirectByteBuffer.adjustAddress(bb.address, bb.position()):null, null, 0);
this.bb = bb;
this.offset = bb.position();
this.readOnly = bb.isReadOnly();
this.endian = bb.order();
if (bb.isDirect())
this.address = VMDirectByteBuffer.adjustAddress(bb.address, offset);
}
public LongViewBufferImpl (ByteBuffer bb, int offset, int capacity,
int limit, int position, int mark,
boolean readOnly, ByteOrder endian)
{
super (capacity, limit, position, mark);
super (capacity, limit, position, mark, bb.isDirect() ?
VMDirectByteBuffer.adjustAddress(bb.address, offset):null, null, 0);
this.bb = bb;
this.offset = offset;
this.readOnly = readOnly;
this.endian = endian;
if (bb.isDirect())
this.address = VMDirectByteBuffer.adjustAddress(bb.address, offset);
}
/**

View file

@ -38,15 +38,19 @@ exception statement from your version. */
package java.nio;
// GCJ LOCAL: Use RawData instead of gnu.classpath.Pointer
import gnu.gcj.RawData;
/**
* @author Michael Koch (konqueror@gmx.de)
* @since 1.4
*/
public abstract class MappedByteBuffer extends ByteBuffer
{
MappedByteBuffer (int capacity, int limit, int position, int mark)
MappedByteBuffer (int capacity, int limit, int position, int mark,
RawData address)
{
super (capacity, limit, position, mark);
super (capacity, limit, position, mark, address, null, 0);
}
void forceImpl()

View file

@ -44,7 +44,7 @@ import java.io.IOException;
final class MappedByteBufferImpl extends MappedByteBuffer
{
boolean readOnly;
private final boolean readOnly;
/** Posix uses this for the pointer returned by mmap;
* Win32 uses it for the pointer returned by MapViewOfFile. */
@ -56,8 +56,7 @@ final class MappedByteBufferImpl extends MappedByteBuffer
public MappedByteBufferImpl(Pointer address, int size, boolean readOnly)
throws IOException
{
super(size, size, 0, -1);
this.address = address;
super(size, size, 0, -1, address);
this.readOnly = readOnly;
}

View file

@ -38,19 +38,25 @@ exception statement from your version. */
package java.nio;
// GCJ LOCAL: Use RawData instead of gnu.classpath.Pointer
import gnu.gcj.RawData;
/**
* @since 1.4
*/
public abstract class ShortBuffer extends Buffer
implements Comparable<ShortBuffer>
{
int array_offset;
short[] backing_buffer;
final int array_offset;
final short[] backing_buffer;
ShortBuffer (int capacity, int limit, int position, int mark)
ShortBuffer (int capacity, int limit, int position,
int mark, RawData address, short[] backing_buffer,
int array_offset)
{
super (capacity, limit, position, mark);
array_offset = 0;
super (capacity, limit, position, mark, address);
this.backing_buffer = backing_buffer;
this.array_offset = array_offset;
}
/**

View file

@ -43,18 +43,17 @@ package java.nio;
*/
final class ShortBufferImpl extends ShortBuffer
{
private boolean readOnly;
private final boolean readOnly;
ShortBufferImpl (int capacity)
{
this (new short [capacity], 0, capacity, capacity, 0, -1, false);
}
ShortBufferImpl (short[] buffer, int offset, int capacity, int limit, int position, int mark, boolean readOnly)
ShortBufferImpl (short[] buffer, int offset, int capacity,
int limit, int position, int mark, boolean readOnly)
{
super (capacity, limit, position, mark);
this.backing_buffer = buffer;
this.array_offset = offset;
super (capacity, limit, position, mark, null, buffer, offset);
this.readOnly = readOnly;
}
@ -65,17 +64,20 @@ final class ShortBufferImpl extends ShortBuffer
public ShortBuffer slice ()
{
return new ShortBufferImpl (backing_buffer, array_offset + position (), remaining (), remaining (), 0, -1, isReadOnly ());
return new ShortBufferImpl (backing_buffer, array_offset + position (),
remaining (), remaining (), 0, -1, isReadOnly ());
}
public ShortBuffer duplicate ()
{
return new ShortBufferImpl (backing_buffer, array_offset, capacity (), limit (), position (), mark, isReadOnly ());
return new ShortBufferImpl (backing_buffer, array_offset, capacity (),
limit (), position (), mark, isReadOnly ());
}
public ShortBuffer asReadOnlyBuffer ()
{
return new ShortBufferImpl (backing_buffer, array_offset, capacity (), limit (), position (), mark, true);
return new ShortBufferImpl (backing_buffer, array_offset, capacity (), limit (),
position (), mark, true);
}
public ShortBuffer compact ()

View file

@ -41,33 +41,31 @@ package java.nio;
final class ShortViewBufferImpl extends ShortBuffer
{
/** Position in bb (i.e. a byte offset) where this buffer starts. */
private int offset;
private ByteBuffer bb;
private boolean readOnly;
private ByteOrder endian;
private final int offset;
private final ByteBuffer bb;
private final boolean readOnly;
private final ByteOrder endian;
ShortViewBufferImpl (ByteBuffer bb, int capacity)
{
super (capacity, capacity, 0, -1);
super (capacity, capacity, 0, -1, bb.isDirect() ?
VMDirectByteBuffer.adjustAddress(bb.address, bb.position()):null, null, 0);
this.bb = bb;
this.offset = bb.position();
this.readOnly = bb.isReadOnly();
this.endian = bb.order();
if (bb.isDirect())
this.address = VMDirectByteBuffer.adjustAddress(bb.address, offset);
}
public ShortViewBufferImpl (ByteBuffer bb, int offset, int capacity,
int limit, int position, int mark,
boolean readOnly, ByteOrder endian)
{
super (capacity, limit, position, mark);
super (capacity, limit, position, mark, bb.isDirect() ?
VMDirectByteBuffer.adjustAddress(bb.address, offset):null, null, 0);
this.bb = bb;
this.offset = offset;
this.readOnly = readOnly;
this.endian = endian;
if (bb.isDirect())
this.address = VMDirectByteBuffer.adjustAddress(bb.address, offset);
}
/**

View file

@ -37,8 +37,9 @@ exception statement from your version. */
package java.nio.channels;
import java.io.IOException;
import gnu.java.lang.CPStringBuilder;
import java.io.IOException;
/**
* @since 1.4
@ -132,7 +133,7 @@ public abstract class FileLock
*/
public final String toString()
{
StringBuffer buf = new StringBuffer(getClass().getName());
CPStringBuilder buf = new CPStringBuilder(getClass().getName());
buf.append("[");
buf.append(position);
buf.append(":");

View file

@ -462,8 +462,8 @@ public abstract class Activatable
* means anonymous port.
* @param serverSocketFactory the server socket factory
*/
public static Remote export(ActivationID id, Remote obj, int port,
RMIServerSocketFactory serverSocketFactory)
private static Remote export(ActivationID id, Remote obj, int port,
RMIServerSocketFactory serverSocketFactory)
throws RemoteException
{
ActivatableServerRef sref = null;
@ -479,7 +479,7 @@ public abstract class Activatable
*
* @return the object id
*/
public static ObjID makeId(ActivationID aid)
private static ObjID makeId(ActivationID aid)
{
ObjID id = new ObjID(0);

View file

@ -37,6 +37,8 @@ exception statement from your version. */
package java.rmi.dgc;
import gnu.java.lang.CPStringBuilder;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
@ -168,7 +170,7 @@ public final class VMID implements Serializable
*/
public String toString ()
{
StringBuffer buf = new StringBuffer ("[VMID: ");
CPStringBuilder buf = new CPStringBuilder ("[VMID: ");
for (int i = 0; i < addr.length; i++)
{

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.security;
import gnu.java.lang.CPStringBuilder;
import gnu.java.security.Engine;
import java.lang.reflect.InvocationTargetException;
@ -171,7 +173,7 @@ public class AlgorithmParameterGenerator
Provider provider)
throws NoSuchAlgorithmException
{
StringBuilder sb = new StringBuilder()
CPStringBuilder sb = new CPStringBuilder()
.append("AlgorithmParameterGenerator for algorithm [")
.append(algorithm).append("] from provider[")
.append(provider).append("] could not be created");

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.security;
import gnu.java.lang.CPStringBuilder;
import gnu.java.security.Engine;
import java.io.IOException;
@ -175,7 +177,7 @@ public class AlgorithmParameters
Provider provider)
throws NoSuchAlgorithmException
{
StringBuilder sb = new StringBuilder("AlgorithmParameters for algorithm [")
CPStringBuilder sb = new CPStringBuilder("AlgorithmParameters for algorithm [")
.append(algorithm).append("] from provider[")
.append(provider).append("] could not be created");
Throwable cause;

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.security;
import gnu.java.lang.CPStringBuilder;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
@ -259,7 +261,7 @@ public class CodeSource implements Serializable
*/
public String toString()
{
StringBuffer sb = new StringBuffer("(").append(location);
CPStringBuilder sb = new CPStringBuilder("(").append(location);
if (certs == null || certs.isEmpty())
sb.append(" <no certificates>");
else

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.security;
import gnu.java.lang.CPStringBuilder;
import gnu.java.security.Engine;
import java.lang.reflect.InvocationTargetException;
@ -165,7 +167,7 @@ public class KeyFactory
public static KeyFactory getInstance(String algorithm, Provider provider)
throws NoSuchAlgorithmException
{
StringBuilder sb = new StringBuilder("KeyFactory for algorithm [")
CPStringBuilder sb = new CPStringBuilder("KeyFactory for algorithm [")
.append(algorithm).append("] from provider[")
.append(provider).append("] could not be created");
Throwable cause;

View file

@ -38,6 +38,8 @@ exception statement from your version. */
package java.security;
import gnu.java.lang.CPStringBuilder;
import gnu.java.security.Engine;
import java.lang.reflect.InvocationTargetException;
@ -165,7 +167,7 @@ public abstract class KeyPairGenerator extends KeyPairGeneratorSpi
Provider provider)
throws NoSuchAlgorithmException
{
StringBuilder sb = new StringBuilder("KeyPairGenerator for algorithm [")
CPStringBuilder sb = new CPStringBuilder("KeyPairGenerator for algorithm [")
.append(algorithm).append("] from provider[")
.append(provider).append("] ");
Object o;

View file

@ -37,6 +37,8 @@ exception statement from your version. */
package java.security;
import gnu.java.lang.CPStringBuilder;
import gnu.java.security.Engine;
import java.nio.ByteBuffer;
@ -146,7 +148,7 @@ public abstract class MessageDigest extends MessageDigestSpi
public static MessageDigest getInstance(String algorithm, Provider provider)
throws NoSuchAlgorithmException
{
StringBuilder sb = new StringBuilder("MessageDigest for algorithm [")
CPStringBuilder sb = new CPStringBuilder("MessageDigest for algorithm [")
.append(algorithm).append("] from provider[")
.append(provider).append("] ");
Object o;
@ -235,7 +237,7 @@ public abstract class MessageDigest extends MessageDigestSpi
* @param input The input byte buffer.
* @since 1.5
*/
public void update (ByteBuffer input)
public final void update (ByteBuffer input)
{
engineUpdate (input);
}
@ -363,7 +365,7 @@ public abstract class MessageDigest extends MessageDigestSpi
if (digest == null)
return "incomplete";
StringBuffer buf = new StringBuffer();
CPStringBuilder buf = new CPStringBuilder();
int len = digest.length;
for (int i = 0; i < len; ++i)
{

View file

@ -37,6 +37,8 @@ exception statement from your version. */
package java.security;
import gnu.java.lang.CPStringBuilder;
import java.io.Serializable;
/**
@ -181,7 +183,7 @@ public abstract class Permission implements Guard, Serializable
*/
public String toString()
{
StringBuffer string = new StringBuffer();
CPStringBuilder string = new CPStringBuilder();
string = string.append('(');
string = string.append(getClass().getName());

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