file_id
stringlengths
4
10
content
stringlengths
91
42.8k
repo
stringlengths
7
108
path
stringlengths
7
251
token_length
int64
34
8.19k
original_comment
stringlengths
11
11.5k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
34
42.8k
2_29
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2018, 2020-2021 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Mutable IJK hexagon coordinates * * Each axis is spaced 120 degrees apart. * * References two Vec2d cartesian coordinate systems: * * 1. gnomonic: face-centered polyhedral gnomonic projection space with * traditional scaling and x-axes aligned with the face Class II * i-axes. * * 2. hex2d: local face-centered coordinate system scaled a specific H3 grid * resolution unit length and with x-axes aligned with the local * i-axes */ final class CoordIJK { /** CoordIJK unit vectors corresponding to the 7 H3 digits. */ private static final int[][] UNIT_VECS = { { 0, 0, 0 }, // direction 0 { 0, 0, 1 }, // direction 1 { 0, 1, 0 }, // direction 2 { 0, 1, 1 }, // direction 3 { 1, 0, 0 }, // direction 4 { 1, 0, 1 }, // direction 5 { 1, 1, 0 } // direction 6 }; /** H3 digit representing ijk+ axes direction. * Values will be within the lowest 3 bits of an integer. */ public enum Direction { CENTER_DIGIT(0), K_AXES_DIGIT(1), J_AXES_DIGIT(2), JK_AXES_DIGIT(J_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), I_AXES_DIGIT(4), IK_AXES_DIGIT(I_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), IJ_AXES_DIGIT(I_AXES_DIGIT.digit() | J_AXES_DIGIT.digit()), INVALID_DIGIT(7), NUM_DIGITS(INVALID_DIGIT.digit()), PENTAGON_SKIPPED_DIGIT(K_AXES_DIGIT.digit()); Direction(int digit) { this.digit = digit; } private final int digit; public int digit() { return digit; } } int i; // i component int j; // j component int k; // k component CoordIJK(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Reset the value of the IJK coordinates to the provided ones. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ void reset(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Find the center point in 2D cartesian coordinates of a hex. */ public Vec2d ijkToHex2d() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return new Vec2d(i - 0.5 * j, j * Constants.M_SQRT3_2); } /** * Find the center point in spherical coordinates of a hex on a particular icosahedral face. */ public LatLng ijkToGeo(int face, int res, boolean substrate) { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return Vec2d.hex2dToGeo(i - 0.5 * j, j * Constants.M_SQRT3_2, face, res, substrate); } /** * Add ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkAdd(int i, int j, int k) { this.i = Math.addExact(this.i, i); this.j = Math.addExact(this.j, j); this.k = Math.addExact(this.k, k); } /** * Subtract ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkSub(int i, int j, int k) { this.i = Math.subtractExact(this.i, i); this.j = Math.subtractExact(this.j, j); this.k = Math.subtractExact(this.k, k); } /** * Normalizes ijk coordinates by setting the ijk coordinates * to the smallest possible positive values. */ public void ijkNormalize() { final int min = Math.min(i, Math.min(j, k)); ijkSub(min, min, min); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 counter-clockwise resolution. */ public void downAp7() { // res r unit vectors in res r+1 // iVec (3, 0, 1) // jVec (1, 3, 0) // kVec (0, 1, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 clockwise resolution. */ public void downAp7r() { // iVec (3, 1, 0) // jVec (0, 3, 1) // kVec (1, 0, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 counter-clockwise resolution. */ public void downAp3() { // res r unit vectors in res r+1 // iVec (2, 0, 1) // jVec (1, 2, 0) // kVec (0, 1, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 clockwise resolution. */ public void downAp3r() { // res r unit vectors in res r+1 // iVec (2, 1, 0) // jVec (0, 2, 1) // kVec (1, 0, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees clockwise. * */ public void ijkRotate60cw() { // unit vector rotations // iVec (1, 0, 1) // jVec (1, 1, 0) // kVec (0, 1, 1) final int i = Math.addExact(this.i, this.j); final int j = Math.addExact(this.j, this.k); final int k = Math.addExact(this.i, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees counter-clockwise. */ public void ijkRotate60ccw() { // unit vector rotations // iVec (1, 1, 0) // jVec (0, 1, 1) // kVec (1, 0, 1) final int i = Math.addExact(this.i, this.k); final int j = Math.addExact(this.i, this.j); final int k = Math.addExact(this.j, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex in the specified digit * direction from the current ijk coordinates. * @param digit The digit direction from the original ijk coordinates. */ public void neighbor(int digit) { if (digit > Direction.CENTER_DIGIT.digit() && digit < Direction.NUM_DIGITS.digit()) { ijkAdd(UNIT_VECS[digit][0], UNIT_VECS[digit][1], UNIT_VECS[digit][2]); ijkNormalize(); } } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * clockwise aperture 7 grid. */ public void upAp7r() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.addExact(Math.multiplyExact(2, i), j)) / 7.0); this.j = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * counter-clockwise aperture 7 grid. * */ public void upAp7() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, i), j)) / 7.0); this.j = (int) Math.round((Math.addExact(Math.multiplyExact(2, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Determines the H3 digit corresponding to a unit vector in ijk coordinates. * * @return The H3 digit (0-6) corresponding to the ijk unit vector, or * INVALID_DIGIT on failure. */ public int unitIjkToDigit() { // should be call on a normalized object if (Math.min(i, Math.min(j, k)) < 0 || Math.max(i, Math.max(j, k)) > 1) { return Direction.INVALID_DIGIT.digit(); } return i << 2 | j << 1 | k; } /** * Rotates indexing digit 60 degrees clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60cw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.K_AXES_DIGIT.digit(); default -> digit; }; } /** * Rotates indexing digit 60 degrees counter-clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60ccw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.K_AXES_DIGIT.digit(); default -> digit; }; } }
elastic/elasticsearch
libs/h3/src/main/java/org/elasticsearch/h3/CoordIJK.java
3,778
/** * Rotates ijk coordinates 60 degrees clockwise. * */
block_comment
nl
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2018, 2020-2021 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Mutable IJK hexagon coordinates * * Each axis is spaced 120 degrees apart. * * References two Vec2d cartesian coordinate systems: * * 1. gnomonic: face-centered polyhedral gnomonic projection space with * traditional scaling and x-axes aligned with the face Class II * i-axes. * * 2. hex2d: local face-centered coordinate system scaled a specific H3 grid * resolution unit length and with x-axes aligned with the local * i-axes */ final class CoordIJK { /** CoordIJK unit vectors corresponding to the 7 H3 digits. */ private static final int[][] UNIT_VECS = { { 0, 0, 0 }, // direction 0 { 0, 0, 1 }, // direction 1 { 0, 1, 0 }, // direction 2 { 0, 1, 1 }, // direction 3 { 1, 0, 0 }, // direction 4 { 1, 0, 1 }, // direction 5 { 1, 1, 0 } // direction 6 }; /** H3 digit representing ijk+ axes direction. * Values will be within the lowest 3 bits of an integer. */ public enum Direction { CENTER_DIGIT(0), K_AXES_DIGIT(1), J_AXES_DIGIT(2), JK_AXES_DIGIT(J_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), I_AXES_DIGIT(4), IK_AXES_DIGIT(I_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), IJ_AXES_DIGIT(I_AXES_DIGIT.digit() | J_AXES_DIGIT.digit()), INVALID_DIGIT(7), NUM_DIGITS(INVALID_DIGIT.digit()), PENTAGON_SKIPPED_DIGIT(K_AXES_DIGIT.digit()); Direction(int digit) { this.digit = digit; } private final int digit; public int digit() { return digit; } } int i; // i component int j; // j component int k; // k component CoordIJK(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Reset the value of the IJK coordinates to the provided ones. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ void reset(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Find the center point in 2D cartesian coordinates of a hex. */ public Vec2d ijkToHex2d() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return new Vec2d(i - 0.5 * j, j * Constants.M_SQRT3_2); } /** * Find the center point in spherical coordinates of a hex on a particular icosahedral face. */ public LatLng ijkToGeo(int face, int res, boolean substrate) { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return Vec2d.hex2dToGeo(i - 0.5 * j, j * Constants.M_SQRT3_2, face, res, substrate); } /** * Add ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkAdd(int i, int j, int k) { this.i = Math.addExact(this.i, i); this.j = Math.addExact(this.j, j); this.k = Math.addExact(this.k, k); } /** * Subtract ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkSub(int i, int j, int k) { this.i = Math.subtractExact(this.i, i); this.j = Math.subtractExact(this.j, j); this.k = Math.subtractExact(this.k, k); } /** * Normalizes ijk coordinates by setting the ijk coordinates * to the smallest possible positive values. */ public void ijkNormalize() { final int min = Math.min(i, Math.min(j, k)); ijkSub(min, min, min); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 counter-clockwise resolution. */ public void downAp7() { // res r unit vectors in res r+1 // iVec (3, 0, 1) // jVec (1, 3, 0) // kVec (0, 1, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 clockwise resolution. */ public void downAp7r() { // iVec (3, 1, 0) // jVec (0, 3, 1) // kVec (1, 0, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 counter-clockwise resolution. */ public void downAp3() { // res r unit vectors in res r+1 // iVec (2, 0, 1) // jVec (1, 2, 0) // kVec (0, 1, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 clockwise resolution. */ public void downAp3r() { // res r unit vectors in res r+1 // iVec (2, 1, 0) // jVec (0, 2, 1) // kVec (1, 0, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates<SUF>*/ public void ijkRotate60cw() { // unit vector rotations // iVec (1, 0, 1) // jVec (1, 1, 0) // kVec (0, 1, 1) final int i = Math.addExact(this.i, this.j); final int j = Math.addExact(this.j, this.k); final int k = Math.addExact(this.i, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees counter-clockwise. */ public void ijkRotate60ccw() { // unit vector rotations // iVec (1, 1, 0) // jVec (0, 1, 1) // kVec (1, 0, 1) final int i = Math.addExact(this.i, this.k); final int j = Math.addExact(this.i, this.j); final int k = Math.addExact(this.j, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex in the specified digit * direction from the current ijk coordinates. * @param digit The digit direction from the original ijk coordinates. */ public void neighbor(int digit) { if (digit > Direction.CENTER_DIGIT.digit() && digit < Direction.NUM_DIGITS.digit()) { ijkAdd(UNIT_VECS[digit][0], UNIT_VECS[digit][1], UNIT_VECS[digit][2]); ijkNormalize(); } } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * clockwise aperture 7 grid. */ public void upAp7r() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.addExact(Math.multiplyExact(2, i), j)) / 7.0); this.j = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * counter-clockwise aperture 7 grid. * */ public void upAp7() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, i), j)) / 7.0); this.j = (int) Math.round((Math.addExact(Math.multiplyExact(2, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Determines the H3 digit corresponding to a unit vector in ijk coordinates. * * @return The H3 digit (0-6) corresponding to the ijk unit vector, or * INVALID_DIGIT on failure. */ public int unitIjkToDigit() { // should be call on a normalized object if (Math.min(i, Math.min(j, k)) < 0 || Math.max(i, Math.max(j, k)) > 1) { return Direction.INVALID_DIGIT.digit(); } return i << 2 | j << 1 | k; } /** * Rotates indexing digit 60 degrees clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60cw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.K_AXES_DIGIT.digit(); default -> digit; }; } /** * Rotates indexing digit 60 degrees counter-clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60ccw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.K_AXES_DIGIT.digit(); default -> digit; }; } }
2_34
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2018, 2020-2021 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Mutable IJK hexagon coordinates * * Each axis is spaced 120 degrees apart. * * References two Vec2d cartesian coordinate systems: * * 1. gnomonic: face-centered polyhedral gnomonic projection space with * traditional scaling and x-axes aligned with the face Class II * i-axes. * * 2. hex2d: local face-centered coordinate system scaled a specific H3 grid * resolution unit length and with x-axes aligned with the local * i-axes */ final class CoordIJK { /** CoordIJK unit vectors corresponding to the 7 H3 digits. */ private static final int[][] UNIT_VECS = { { 0, 0, 0 }, // direction 0 { 0, 0, 1 }, // direction 1 { 0, 1, 0 }, // direction 2 { 0, 1, 1 }, // direction 3 { 1, 0, 0 }, // direction 4 { 1, 0, 1 }, // direction 5 { 1, 1, 0 } // direction 6 }; /** H3 digit representing ijk+ axes direction. * Values will be within the lowest 3 bits of an integer. */ public enum Direction { CENTER_DIGIT(0), K_AXES_DIGIT(1), J_AXES_DIGIT(2), JK_AXES_DIGIT(J_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), I_AXES_DIGIT(4), IK_AXES_DIGIT(I_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), IJ_AXES_DIGIT(I_AXES_DIGIT.digit() | J_AXES_DIGIT.digit()), INVALID_DIGIT(7), NUM_DIGITS(INVALID_DIGIT.digit()), PENTAGON_SKIPPED_DIGIT(K_AXES_DIGIT.digit()); Direction(int digit) { this.digit = digit; } private final int digit; public int digit() { return digit; } } int i; // i component int j; // j component int k; // k component CoordIJK(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Reset the value of the IJK coordinates to the provided ones. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ void reset(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Find the center point in 2D cartesian coordinates of a hex. */ public Vec2d ijkToHex2d() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return new Vec2d(i - 0.5 * j, j * Constants.M_SQRT3_2); } /** * Find the center point in spherical coordinates of a hex on a particular icosahedral face. */ public LatLng ijkToGeo(int face, int res, boolean substrate) { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return Vec2d.hex2dToGeo(i - 0.5 * j, j * Constants.M_SQRT3_2, face, res, substrate); } /** * Add ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkAdd(int i, int j, int k) { this.i = Math.addExact(this.i, i); this.j = Math.addExact(this.j, j); this.k = Math.addExact(this.k, k); } /** * Subtract ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkSub(int i, int j, int k) { this.i = Math.subtractExact(this.i, i); this.j = Math.subtractExact(this.j, j); this.k = Math.subtractExact(this.k, k); } /** * Normalizes ijk coordinates by setting the ijk coordinates * to the smallest possible positive values. */ public void ijkNormalize() { final int min = Math.min(i, Math.min(j, k)); ijkSub(min, min, min); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 counter-clockwise resolution. */ public void downAp7() { // res r unit vectors in res r+1 // iVec (3, 0, 1) // jVec (1, 3, 0) // kVec (0, 1, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 clockwise resolution. */ public void downAp7r() { // iVec (3, 1, 0) // jVec (0, 3, 1) // kVec (1, 0, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 counter-clockwise resolution. */ public void downAp3() { // res r unit vectors in res r+1 // iVec (2, 0, 1) // jVec (1, 2, 0) // kVec (0, 1, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 clockwise resolution. */ public void downAp3r() { // res r unit vectors in res r+1 // iVec (2, 1, 0) // jVec (0, 2, 1) // kVec (1, 0, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees clockwise. * */ public void ijkRotate60cw() { // unit vector rotations // iVec (1, 0, 1) // jVec (1, 1, 0) // kVec (0, 1, 1) final int i = Math.addExact(this.i, this.j); final int j = Math.addExact(this.j, this.k); final int k = Math.addExact(this.i, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees counter-clockwise. */ public void ijkRotate60ccw() { // unit vector rotations // iVec (1, 1, 0) // jVec (0, 1, 1) // kVec (1, 0, 1) final int i = Math.addExact(this.i, this.k); final int j = Math.addExact(this.i, this.j); final int k = Math.addExact(this.j, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex in the specified digit * direction from the current ijk coordinates. * @param digit The digit direction from the original ijk coordinates. */ public void neighbor(int digit) { if (digit > Direction.CENTER_DIGIT.digit() && digit < Direction.NUM_DIGITS.digit()) { ijkAdd(UNIT_VECS[digit][0], UNIT_VECS[digit][1], UNIT_VECS[digit][2]); ijkNormalize(); } } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * clockwise aperture 7 grid. */ public void upAp7r() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.addExact(Math.multiplyExact(2, i), j)) / 7.0); this.j = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * counter-clockwise aperture 7 grid. * */ public void upAp7() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, i), j)) / 7.0); this.j = (int) Math.round((Math.addExact(Math.multiplyExact(2, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Determines the H3 digit corresponding to a unit vector in ijk coordinates. * * @return The H3 digit (0-6) corresponding to the ijk unit vector, or * INVALID_DIGIT on failure. */ public int unitIjkToDigit() { // should be call on a normalized object if (Math.min(i, Math.min(j, k)) < 0 || Math.max(i, Math.max(j, k)) > 1) { return Direction.INVALID_DIGIT.digit(); } return i << 2 | j << 1 | k; } /** * Rotates indexing digit 60 degrees clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60cw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.K_AXES_DIGIT.digit(); default -> digit; }; } /** * Rotates indexing digit 60 degrees counter-clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60ccw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.K_AXES_DIGIT.digit(); default -> digit; }; } }
elastic/elasticsearch
libs/h3/src/main/java/org/elasticsearch/h3/CoordIJK.java
3,778
/** * Rotates ijk coordinates 60 degrees counter-clockwise. */
block_comment
nl
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2018, 2020-2021 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Mutable IJK hexagon coordinates * * Each axis is spaced 120 degrees apart. * * References two Vec2d cartesian coordinate systems: * * 1. gnomonic: face-centered polyhedral gnomonic projection space with * traditional scaling and x-axes aligned with the face Class II * i-axes. * * 2. hex2d: local face-centered coordinate system scaled a specific H3 grid * resolution unit length and with x-axes aligned with the local * i-axes */ final class CoordIJK { /** CoordIJK unit vectors corresponding to the 7 H3 digits. */ private static final int[][] UNIT_VECS = { { 0, 0, 0 }, // direction 0 { 0, 0, 1 }, // direction 1 { 0, 1, 0 }, // direction 2 { 0, 1, 1 }, // direction 3 { 1, 0, 0 }, // direction 4 { 1, 0, 1 }, // direction 5 { 1, 1, 0 } // direction 6 }; /** H3 digit representing ijk+ axes direction. * Values will be within the lowest 3 bits of an integer. */ public enum Direction { CENTER_DIGIT(0), K_AXES_DIGIT(1), J_AXES_DIGIT(2), JK_AXES_DIGIT(J_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), I_AXES_DIGIT(4), IK_AXES_DIGIT(I_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), IJ_AXES_DIGIT(I_AXES_DIGIT.digit() | J_AXES_DIGIT.digit()), INVALID_DIGIT(7), NUM_DIGITS(INVALID_DIGIT.digit()), PENTAGON_SKIPPED_DIGIT(K_AXES_DIGIT.digit()); Direction(int digit) { this.digit = digit; } private final int digit; public int digit() { return digit; } } int i; // i component int j; // j component int k; // k component CoordIJK(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Reset the value of the IJK coordinates to the provided ones. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ void reset(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Find the center point in 2D cartesian coordinates of a hex. */ public Vec2d ijkToHex2d() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return new Vec2d(i - 0.5 * j, j * Constants.M_SQRT3_2); } /** * Find the center point in spherical coordinates of a hex on a particular icosahedral face. */ public LatLng ijkToGeo(int face, int res, boolean substrate) { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return Vec2d.hex2dToGeo(i - 0.5 * j, j * Constants.M_SQRT3_2, face, res, substrate); } /** * Add ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkAdd(int i, int j, int k) { this.i = Math.addExact(this.i, i); this.j = Math.addExact(this.j, j); this.k = Math.addExact(this.k, k); } /** * Subtract ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkSub(int i, int j, int k) { this.i = Math.subtractExact(this.i, i); this.j = Math.subtractExact(this.j, j); this.k = Math.subtractExact(this.k, k); } /** * Normalizes ijk coordinates by setting the ijk coordinates * to the smallest possible positive values. */ public void ijkNormalize() { final int min = Math.min(i, Math.min(j, k)); ijkSub(min, min, min); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 counter-clockwise resolution. */ public void downAp7() { // res r unit vectors in res r+1 // iVec (3, 0, 1) // jVec (1, 3, 0) // kVec (0, 1, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 clockwise resolution. */ public void downAp7r() { // iVec (3, 1, 0) // jVec (0, 3, 1) // kVec (1, 0, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 counter-clockwise resolution. */ public void downAp3() { // res r unit vectors in res r+1 // iVec (2, 0, 1) // jVec (1, 2, 0) // kVec (0, 1, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 clockwise resolution. */ public void downAp3r() { // res r unit vectors in res r+1 // iVec (2, 1, 0) // jVec (0, 2, 1) // kVec (1, 0, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees clockwise. * */ public void ijkRotate60cw() { // unit vector rotations // iVec (1, 0, 1) // jVec (1, 1, 0) // kVec (0, 1, 1) final int i = Math.addExact(this.i, this.j); final int j = Math.addExact(this.j, this.k); final int k = Math.addExact(this.i, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates<SUF>*/ public void ijkRotate60ccw() { // unit vector rotations // iVec (1, 1, 0) // jVec (0, 1, 1) // kVec (1, 0, 1) final int i = Math.addExact(this.i, this.k); final int j = Math.addExact(this.i, this.j); final int k = Math.addExact(this.j, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex in the specified digit * direction from the current ijk coordinates. * @param digit The digit direction from the original ijk coordinates. */ public void neighbor(int digit) { if (digit > Direction.CENTER_DIGIT.digit() && digit < Direction.NUM_DIGITS.digit()) { ijkAdd(UNIT_VECS[digit][0], UNIT_VECS[digit][1], UNIT_VECS[digit][2]); ijkNormalize(); } } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * clockwise aperture 7 grid. */ public void upAp7r() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.addExact(Math.multiplyExact(2, i), j)) / 7.0); this.j = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * counter-clockwise aperture 7 grid. * */ public void upAp7() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, i), j)) / 7.0); this.j = (int) Math.round((Math.addExact(Math.multiplyExact(2, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Determines the H3 digit corresponding to a unit vector in ijk coordinates. * * @return The H3 digit (0-6) corresponding to the ijk unit vector, or * INVALID_DIGIT on failure. */ public int unitIjkToDigit() { // should be call on a normalized object if (Math.min(i, Math.min(j, k)) < 0 || Math.max(i, Math.max(j, k)) > 1) { return Direction.INVALID_DIGIT.digit(); } return i << 2 | j << 1 | k; } /** * Rotates indexing digit 60 degrees clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60cw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.K_AXES_DIGIT.digit(); default -> digit; }; } /** * Rotates indexing digit 60 degrees counter-clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60ccw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.K_AXES_DIGIT.digit(); default -> digit; }; } }
28_45
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.ssl; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.internal.tcnative.Buffer; import io.netty.internal.tcnative.Library; import io.netty.internal.tcnative.SSL; import io.netty.internal.tcnative.SSLContext; import io.netty.util.CharsetUtil; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.NativeLibraryLoader; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.StringUtil; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.ByteArrayInputStream; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static io.netty.handler.ssl.SslUtils.*; /** * Tells if <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support * are available. */ public final class OpenSsl { private static final InternalLogger logger = InternalLoggerFactory.getInstance(OpenSsl.class); private static final Throwable UNAVAILABILITY_CAUSE; static final List<String> DEFAULT_CIPHERS; static final Set<String> AVAILABLE_CIPHER_SUITES; private static final Set<String> AVAILABLE_OPENSSL_CIPHER_SUITES; private static final Set<String> AVAILABLE_JAVA_CIPHER_SUITES; private static final boolean SUPPORTS_KEYMANAGER_FACTORY; private static final boolean USE_KEYMANAGER_FACTORY; private static final boolean SUPPORTS_OCSP; private static final boolean TLSV13_SUPPORTED; private static final boolean IS_BORINGSSL; private static final Set<String> CLIENT_DEFAULT_PROTOCOLS; private static final Set<String> SERVER_DEFAULT_PROTOCOLS; static final Set<String> SUPPORTED_PROTOCOLS_SET; static final String[] EXTRA_SUPPORTED_TLS_1_3_CIPHERS; static final String EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING; static final String[] NAMED_GROUPS; static final boolean JAVAX_CERTIFICATE_CREATION_SUPPORTED; // Use default that is supported in java 11 and earlier and also in OpenSSL / BoringSSL. // See https://github.com/netty/netty-tcnative/issues/567 // See https://www.java.com/en/configure_crypto.html for ordering private static final String[] DEFAULT_NAMED_GROUPS = { "x25519", "secp256r1", "secp384r1", "secp521r1" }; static { Throwable cause = null; if (SystemPropertyUtil.getBoolean("io.netty.handler.ssl.noOpenSsl", false)) { cause = new UnsupportedOperationException( "OpenSSL was explicit disabled with -Dio.netty.handler.ssl.noOpenSsl=true"); logger.debug( "netty-tcnative explicit disabled; " + OpenSslEngine.class.getSimpleName() + " will be unavailable.", cause); } else { // Test if netty-tcnative is in the classpath first. try { Class.forName("io.netty.internal.tcnative.SSLContext", false, PlatformDependent.getClassLoader(OpenSsl.class)); } catch (ClassNotFoundException t) { cause = t; logger.debug( "netty-tcnative not in the classpath; " + OpenSslEngine.class.getSimpleName() + " will be unavailable."); } // If in the classpath, try to load the native library and initialize netty-tcnative. if (cause == null) { try { // The JNI library was not already loaded. Load it now. loadTcNative(); } catch (Throwable t) { cause = t; logger.debug( "Failed to load netty-tcnative; " + OpenSslEngine.class.getSimpleName() + " will be unavailable, unless the " + "application has already loaded the symbols by some other means. " + "See https://netty.io/wiki/forked-tomcat-native.html for more information.", t); } try { String engine = SystemPropertyUtil.get("io.netty.handler.ssl.openssl.engine", null); if (engine == null) { logger.debug("Initialize netty-tcnative using engine: 'default'"); } else { logger.debug("Initialize netty-tcnative using engine: '{}'", engine); } initializeTcNative(engine); // The library was initialized successfully. If loading the library failed above, // reset the cause now since it appears that the library was loaded by some other // means. cause = null; } catch (Throwable t) { if (cause == null) { cause = t; } logger.debug( "Failed to initialize netty-tcnative; " + OpenSslEngine.class.getSimpleName() + " will be unavailable. " + "See https://netty.io/wiki/forked-tomcat-native.html for more information.", t); } } } UNAVAILABILITY_CAUSE = cause; CLIENT_DEFAULT_PROTOCOLS = defaultProtocols("jdk.tls.client.protocols"); SERVER_DEFAULT_PROTOCOLS = defaultProtocols("jdk.tls.server.protocols"); if (cause == null) { logger.debug("netty-tcnative using native library: {}", SSL.versionString()); final List<String> defaultCiphers = new ArrayList<String>(); final Set<String> availableOpenSslCipherSuites = new LinkedHashSet<String>(128); boolean supportsKeyManagerFactory = false; boolean useKeyManagerFactory = false; boolean tlsv13Supported = false; String[] namedGroups = DEFAULT_NAMED_GROUPS; String[] defaultConvertedNamedGroups = new String[namedGroups.length]; for (int i = 0; i < namedGroups.length; i++) { defaultConvertedNamedGroups[i] = GroupsConverter.toOpenSsl(namedGroups[i]); } IS_BORINGSSL = "BoringSSL".equals(versionString()); if (IS_BORINGSSL) { EXTRA_SUPPORTED_TLS_1_3_CIPHERS = new String [] { "TLS_AES_128_GCM_SHA256", "TLS_AES_256_GCM_SHA384" , "TLS_CHACHA20_POLY1305_SHA256" }; StringBuilder ciphersBuilder = new StringBuilder(128); for (String cipher: EXTRA_SUPPORTED_TLS_1_3_CIPHERS) { ciphersBuilder.append(cipher).append(":"); } ciphersBuilder.setLength(ciphersBuilder.length() - 1); EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = ciphersBuilder.toString(); } else { EXTRA_SUPPORTED_TLS_1_3_CIPHERS = EmptyArrays.EMPTY_STRINGS; EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = StringUtil.EMPTY_STRING; } try { final long sslCtx = SSLContext.make(SSL.SSL_PROTOCOL_ALL, SSL.SSL_MODE_SERVER); long certBio = 0; long keyBio = 0; long cert = 0; long key = 0; try { // As we delegate to the KeyManager / TrustManager of the JDK we need to ensure it can actually // handle TLSv13 as otherwise we may see runtime exceptions if (SslProvider.isTlsv13Supported(SslProvider.JDK)) { try { StringBuilder tlsv13Ciphers = new StringBuilder(); for (String cipher : TLSV13_CIPHERS) { String converted = CipherSuiteConverter.toOpenSsl(cipher, IS_BORINGSSL); if (converted != null) { tlsv13Ciphers.append(converted).append(':'); } } if (tlsv13Ciphers.length() == 0) { tlsv13Supported = false; } else { tlsv13Ciphers.setLength(tlsv13Ciphers.length() - 1); SSLContext.setCipherSuite(sslCtx, tlsv13Ciphers.toString(), true); tlsv13Supported = true; } } catch (Exception ignore) { tlsv13Supported = false; } } SSLContext.setCipherSuite(sslCtx, "ALL", false); final long ssl = SSL.newSSL(sslCtx, true); try { for (String c: SSL.getCiphers(ssl)) { // Filter out bad input. if (c == null || c.isEmpty() || availableOpenSslCipherSuites.contains(c) || // Filter out TLSv1.3 ciphers if not supported. !tlsv13Supported && isTLSv13Cipher(c)) { continue; } availableOpenSslCipherSuites.add(c); } if (IS_BORINGSSL) { // Currently BoringSSL does not include these when calling SSL.getCiphers() even when these // are supported. Collections.addAll(availableOpenSslCipherSuites, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); Collections.addAll(availableOpenSslCipherSuites, "AEAD-AES128-GCM-SHA256", "AEAD-AES256-GCM-SHA384", "AEAD-CHACHA20-POLY1305-SHA256"); } PemEncoded privateKey = PemPrivateKey.valueOf(PROBING_KEY.getBytes(CharsetUtil.US_ASCII)); try { // Let's check if we can set a callback, which may not work if the used OpenSSL version // is to old. SSLContext.setCertificateCallback(sslCtx, null); X509Certificate certificate = selfSignedCertificate(); certBio = ReferenceCountedOpenSslContext.toBIO(ByteBufAllocator.DEFAULT, certificate); cert = SSL.parseX509Chain(certBio); keyBio = ReferenceCountedOpenSslContext.toBIO( UnpooledByteBufAllocator.DEFAULT, privateKey.retain()); key = SSL.parsePrivateKey(keyBio, null); SSL.setKeyMaterial(ssl, cert, key); supportsKeyManagerFactory = true; try { boolean propertySet = SystemPropertyUtil.contains( "io.netty.handler.ssl.openssl.useKeyManagerFactory"); if (!IS_BORINGSSL) { useKeyManagerFactory = SystemPropertyUtil.getBoolean( "io.netty.handler.ssl.openssl.useKeyManagerFactory", true); if (propertySet) { logger.info("System property " + "'io.netty.handler.ssl.openssl.useKeyManagerFactory'" + " is deprecated and so will be ignored in the future"); } } else { useKeyManagerFactory = true; if (propertySet) { logger.info("System property " + "'io.netty.handler.ssl.openssl.useKeyManagerFactory'" + " is deprecated and will be ignored when using BoringSSL"); } } } catch (Throwable ignore) { logger.debug("Failed to get useKeyManagerFactory system property."); } } catch (Error ignore) { logger.debug("KeyManagerFactory not supported."); } finally { privateKey.release(); } } finally { SSL.freeSSL(ssl); if (certBio != 0) { SSL.freeBIO(certBio); } if (keyBio != 0) { SSL.freeBIO(keyBio); } if (cert != 0) { SSL.freeX509Chain(cert); } if (key != 0) { SSL.freePrivateKey(key); } } String groups = SystemPropertyUtil.get("jdk.tls.namedGroups", null); if (groups != null) { String[] nGroups = groups.split(","); Set<String> supportedNamedGroups = new LinkedHashSet<String>(nGroups.length); Set<String> supportedConvertedNamedGroups = new LinkedHashSet<String>(nGroups.length); Set<String> unsupportedNamedGroups = new LinkedHashSet<String>(); for (String namedGroup : nGroups) { String converted = GroupsConverter.toOpenSsl(namedGroup); if (SSLContext.setCurvesList(sslCtx, converted)) { supportedConvertedNamedGroups.add(converted); supportedNamedGroups.add(namedGroup); } else { unsupportedNamedGroups.add(namedGroup); } } if (supportedNamedGroups.isEmpty()) { namedGroups = defaultConvertedNamedGroups; logger.info("All configured namedGroups are not supported: {}. Use default: {}.", Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS)), Arrays.toString(DEFAULT_NAMED_GROUPS)); } else { String[] groupArray = supportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS); if (unsupportedNamedGroups.isEmpty()) { logger.info("Using configured namedGroups -D 'jdk.tls.namedGroup': {} ", Arrays.toString(groupArray)); } else { logger.info("Using supported configured namedGroups: {}. Unsupported namedGroups: {}. ", Arrays.toString(groupArray), Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS))); } namedGroups = supportedConvertedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS); } } else { namedGroups = defaultConvertedNamedGroups; } } finally { SSLContext.free(sslCtx); } } catch (Exception e) { logger.warn("Failed to get the list of available OpenSSL cipher suites.", e); } NAMED_GROUPS = namedGroups; AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.unmodifiableSet(availableOpenSslCipherSuites); final Set<String> availableJavaCipherSuites = new LinkedHashSet<String>( AVAILABLE_OPENSSL_CIPHER_SUITES.size() * 2); for (String cipher: AVAILABLE_OPENSSL_CIPHER_SUITES) { // Included converted but also openssl cipher name if (!isTLSv13Cipher(cipher)) { availableJavaCipherSuites.add(CipherSuiteConverter.toJava(cipher, "TLS")); availableJavaCipherSuites.add(CipherSuiteConverter.toJava(cipher, "SSL")); } else { // TLSv1.3 ciphers have the correct format. availableJavaCipherSuites.add(cipher); } } addIfSupported(availableJavaCipherSuites, defaultCiphers, DEFAULT_CIPHER_SUITES); addIfSupported(availableJavaCipherSuites, defaultCiphers, TLSV13_CIPHER_SUITES); // Also handle the extra supported ciphers as these will contain some more stuff on BoringSSL. addIfSupported(availableJavaCipherSuites, defaultCiphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); useFallbackCiphersIfDefaultIsEmpty(defaultCiphers, availableJavaCipherSuites); DEFAULT_CIPHERS = Collections.unmodifiableList(defaultCiphers); AVAILABLE_JAVA_CIPHER_SUITES = Collections.unmodifiableSet(availableJavaCipherSuites); final Set<String> availableCipherSuites = new LinkedHashSet<String>( AVAILABLE_OPENSSL_CIPHER_SUITES.size() + AVAILABLE_JAVA_CIPHER_SUITES.size()); availableCipherSuites.addAll(AVAILABLE_OPENSSL_CIPHER_SUITES); availableCipherSuites.addAll(AVAILABLE_JAVA_CIPHER_SUITES); AVAILABLE_CIPHER_SUITES = availableCipherSuites; SUPPORTS_KEYMANAGER_FACTORY = supportsKeyManagerFactory; USE_KEYMANAGER_FACTORY = useKeyManagerFactory; Set<String> protocols = new LinkedHashSet<String>(6); // Seems like there is no way to explicitly disable SSLv2Hello in openssl so it is always enabled protocols.add(SslProtocols.SSL_v2_HELLO); if (doesSupportProtocol(SSL.SSL_PROTOCOL_SSLV2, SSL.SSL_OP_NO_SSLv2)) { protocols.add(SslProtocols.SSL_v2); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_SSLV3, SSL.SSL_OP_NO_SSLv3)) { protocols.add(SslProtocols.SSL_v3); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1, SSL.SSL_OP_NO_TLSv1)) { protocols.add(SslProtocols.TLS_v1); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_1, SSL.SSL_OP_NO_TLSv1_1)) { protocols.add(SslProtocols.TLS_v1_1); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_2, SSL.SSL_OP_NO_TLSv1_2)) { protocols.add(SslProtocols.TLS_v1_2); } // This is only supported by java8u272 and later. if (tlsv13Supported && doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_3, SSL.SSL_OP_NO_TLSv1_3)) { protocols.add(SslProtocols.TLS_v1_3); TLSV13_SUPPORTED = true; } else { TLSV13_SUPPORTED = false; } SUPPORTED_PROTOCOLS_SET = Collections.unmodifiableSet(protocols); SUPPORTS_OCSP = doesSupportOcsp(); if (logger.isDebugEnabled()) { logger.debug("Supported protocols (OpenSSL): {} ", SUPPORTED_PROTOCOLS_SET); logger.debug("Default cipher suites (OpenSSL): {}", DEFAULT_CIPHERS); } // Check if we can create a javax.security.cert.X509Certificate from our cert. This might fail on // JDK17 and above. In this case we will later throw an UnsupportedOperationException if someone // tries to access these via SSLSession. See https://github.com/netty/netty/issues/13560. boolean javaxCertificateCreationSupported; try { javax.security.cert.X509Certificate.getInstance(PROBING_CERT.getBytes(CharsetUtil.US_ASCII)); javaxCertificateCreationSupported = true; } catch (javax.security.cert.CertificateException ex) { javaxCertificateCreationSupported = false; } JAVAX_CERTIFICATE_CREATION_SUPPORTED = javaxCertificateCreationSupported; } else { DEFAULT_CIPHERS = Collections.emptyList(); AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.emptySet(); AVAILABLE_JAVA_CIPHER_SUITES = Collections.emptySet(); AVAILABLE_CIPHER_SUITES = Collections.emptySet(); SUPPORTS_KEYMANAGER_FACTORY = false; USE_KEYMANAGER_FACTORY = false; SUPPORTED_PROTOCOLS_SET = Collections.emptySet(); SUPPORTS_OCSP = false; TLSV13_SUPPORTED = false; IS_BORINGSSL = false; EXTRA_SUPPORTED_TLS_1_3_CIPHERS = EmptyArrays.EMPTY_STRINGS; EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = StringUtil.EMPTY_STRING; NAMED_GROUPS = DEFAULT_NAMED_GROUPS; JAVAX_CERTIFICATE_CREATION_SUPPORTED = false; } } static String checkTls13Ciphers(InternalLogger logger, String ciphers) { if (IS_BORINGSSL && !ciphers.isEmpty()) { assert EXTRA_SUPPORTED_TLS_1_3_CIPHERS.length > 0; Set<String> boringsslTlsv13Ciphers = new HashSet<String>(EXTRA_SUPPORTED_TLS_1_3_CIPHERS.length); Collections.addAll(boringsslTlsv13Ciphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); boolean ciphersNotMatch = false; for (String cipher: ciphers.split(":")) { if (boringsslTlsv13Ciphers.isEmpty()) { ciphersNotMatch = true; break; } if (!boringsslTlsv13Ciphers.remove(cipher) && !boringsslTlsv13Ciphers.remove(CipherSuiteConverter.toJava(cipher, "TLS"))) { ciphersNotMatch = true; break; } } // Also check if there are ciphers left. ciphersNotMatch |= !boringsslTlsv13Ciphers.isEmpty(); if (ciphersNotMatch) { if (logger.isInfoEnabled()) { StringBuilder javaCiphers = new StringBuilder(128); for (String cipher : ciphers.split(":")) { javaCiphers.append(CipherSuiteConverter.toJava(cipher, "TLS")).append(":"); } javaCiphers.setLength(javaCiphers.length() - 1); logger.info( "BoringSSL doesn't allow to enable or disable TLSv1.3 ciphers explicitly." + " Provided TLSv1.3 ciphers: '{}', default TLSv1.3 ciphers that will be used: '{}'.", javaCiphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING); } return EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING; } } return ciphers; } static boolean isSessionCacheSupported() { return version() >= 0x10100000L; } /** * Returns a self-signed {@link X509Certificate} for {@code netty.io}. */ static X509Certificate selfSignedCertificate() throws CertificateException { return (X509Certificate) SslContext.X509_CERT_FACTORY.generateCertificate( new ByteArrayInputStream(PROBING_CERT.getBytes(CharsetUtil.US_ASCII)) ); } private static boolean doesSupportOcsp() { boolean supportsOcsp = false; if (version() >= 0x10002000L) { long sslCtx = -1; try { sslCtx = SSLContext.make(SSL.SSL_PROTOCOL_TLSV1_2, SSL.SSL_MODE_SERVER); SSLContext.enableOcsp(sslCtx, false); supportsOcsp = true; } catch (Exception ignore) { // ignore } finally { if (sslCtx != -1) { SSLContext.free(sslCtx); } } } return supportsOcsp; } private static boolean doesSupportProtocol(int protocol, int opt) { if (opt == 0) { // If the opt is 0 the protocol is not supported. This is for example the case with BoringSSL and SSLv2. return false; } long sslCtx = -1; try { sslCtx = SSLContext.make(protocol, SSL.SSL_MODE_COMBINED); return true; } catch (Exception ignore) { return false; } finally { if (sslCtx != -1) { SSLContext.free(sslCtx); } } } /** * Returns {@code true} if and only if * <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support * are available. */ public static boolean isAvailable() { return UNAVAILABILITY_CAUSE == null; } /** * Returns {@code true} if the used version of openssl supports * <a href="https://tools.ietf.org/html/rfc7301">ALPN</a>. * * @deprecated use {@link SslProvider#isAlpnSupported(SslProvider)} with {@link SslProvider#OPENSSL}. */ @Deprecated public static boolean isAlpnSupported() { return version() >= 0x10002000L; } /** * Returns {@code true} if the used version of OpenSSL supports OCSP stapling. */ public static boolean isOcspSupported() { return SUPPORTS_OCSP; } /** * Returns the version of the used available OpenSSL library or {@code -1} if {@link #isAvailable()} * returns {@code false}. */ public static int version() { return isAvailable() ? SSL.version() : -1; } /** * Returns the version string of the used available OpenSSL library or {@code null} if {@link #isAvailable()} * returns {@code false}. */ public static String versionString() { return isAvailable() ? SSL.versionString() : null; } /** * Ensure that <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and * its OpenSSL support are available. * * @throws UnsatisfiedLinkError if unavailable */ public static void ensureAvailability() { if (UNAVAILABILITY_CAUSE != null) { throw (Error) new UnsatisfiedLinkError( "failed to load the required native library").initCause(UNAVAILABILITY_CAUSE); } } /** * Returns the cause of unavailability of * <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support. * * @return the cause if unavailable. {@code null} if available. */ public static Throwable unavailabilityCause() { return UNAVAILABILITY_CAUSE; } /** * @deprecated use {@link #availableOpenSslCipherSuites()} */ @Deprecated public static Set<String> availableCipherSuites() { return availableOpenSslCipherSuites(); } /** * Returns all the available OpenSSL cipher suites. * Please note that the returned array may include the cipher suites that are insecure or non-functional. */ public static Set<String> availableOpenSslCipherSuites() { return AVAILABLE_OPENSSL_CIPHER_SUITES; } /** * Returns all the available cipher suites (Java-style). * Please note that the returned array may include the cipher suites that are insecure or non-functional. */ public static Set<String> availableJavaCipherSuites() { return AVAILABLE_JAVA_CIPHER_SUITES; } /** * Returns {@code true} if and only if the specified cipher suite is available in OpenSSL. * Both Java-style cipher suite and OpenSSL-style cipher suite are accepted. */ public static boolean isCipherSuiteAvailable(String cipherSuite) { String converted = CipherSuiteConverter.toOpenSsl(cipherSuite, IS_BORINGSSL); if (converted != null) { cipherSuite = converted; } return AVAILABLE_OPENSSL_CIPHER_SUITES.contains(cipherSuite); } /** * Returns {@code true} if {@link javax.net.ssl.KeyManagerFactory} is supported when using OpenSSL. */ public static boolean supportsKeyManagerFactory() { return SUPPORTS_KEYMANAGER_FACTORY; } /** * Always returns {@code true} if {@link #isAvailable()} returns {@code true}. * * @deprecated Will be removed because hostname validation is always done by a * {@link javax.net.ssl.TrustManager} implementation. */ @Deprecated public static boolean supportsHostnameValidation() { return isAvailable(); } static boolean useKeyManagerFactory() { return USE_KEYMANAGER_FACTORY; } static long memoryAddress(ByteBuf buf) { assert buf.isDirect(); return buf.hasMemoryAddress() ? buf.memoryAddress() : // Use internalNioBuffer to reduce object creation. Buffer.address(buf.internalNioBuffer(0, buf.readableBytes())); } private OpenSsl() { } private static void loadTcNative() throws Exception { String os = PlatformDependent.normalizedOs(); String arch = PlatformDependent.normalizedArch(); Set<String> libNames = new LinkedHashSet<String>(5); String staticLibName = "netty_tcnative"; // First, try loading the platform-specific library. Platform-specific // libraries will be available if using a tcnative uber jar. if ("linux".equals(os)) { Set<String> classifiers = PlatformDependent.normalizedLinuxClassifiers(); for (String classifier : classifiers) { libNames.add(staticLibName + "_" + os + '_' + arch + "_" + classifier); } // generic arch-dependent library libNames.add(staticLibName + "_" + os + '_' + arch); // Fedora SSL lib so naming (libssl.so.10 vs libssl.so.1.0.0). // note: should already be included from the classifiers but if not, we use this as an // additional fallback option here libNames.add(staticLibName + "_" + os + '_' + arch + "_fedora"); } else { libNames.add(staticLibName + "_" + os + '_' + arch); } libNames.add(staticLibName + "_" + arch); libNames.add(staticLibName); NativeLibraryLoader.loadFirstAvailable(PlatformDependent.getClassLoader(SSLContext.class), libNames.toArray(EmptyArrays.EMPTY_STRINGS)); } private static boolean initializeTcNative(String engine) throws Exception { return Library.initialize("provided", engine); } static void releaseIfNeeded(ReferenceCounted counted) { if (counted.refCnt() > 0) { ReferenceCountUtil.safeRelease(counted); } } static boolean isTlsv13Supported() { return TLSV13_SUPPORTED; } static boolean isOptionSupported(SslContextOption<?> option) { if (isAvailable()) { if (option == OpenSslContextOption.USE_TASKS) { return true; } // Check for options that are only supported by BoringSSL atm. if (isBoringSSL()) { return option == OpenSslContextOption.ASYNC_PRIVATE_KEY_METHOD || option == OpenSslContextOption.PRIVATE_KEY_METHOD || option == OpenSslContextOption.CERTIFICATE_COMPRESSION_ALGORITHMS || option == OpenSslContextOption.TLS_FALSE_START || option == OpenSslContextOption.MAX_CERTIFICATE_LIST_BYTES; } } return false; } private static Set<String> defaultProtocols(String property) { String protocolsString = SystemPropertyUtil.get(property, null); Set<String> protocols = new HashSet<String>(); if (protocolsString != null) { for (String proto : protocolsString.split(",")) { String p = proto.trim(); protocols.add(p); } } else { protocols.add(SslProtocols.TLS_v1_2); protocols.add(SslProtocols.TLS_v1_3); } return protocols; } static String[] defaultProtocols(boolean isClient) { final Collection<String> defaultProtocols = isClient ? CLIENT_DEFAULT_PROTOCOLS : SERVER_DEFAULT_PROTOCOLS; assert defaultProtocols != null; List<String> protocols = new ArrayList<String>(defaultProtocols.size()); for (String proto : defaultProtocols) { if (SUPPORTED_PROTOCOLS_SET.contains(proto)) { protocols.add(proto); } } return protocols.toArray(EmptyArrays.EMPTY_STRINGS); } static boolean isBoringSSL() { return IS_BORINGSSL; } }
netty/netty
handler/src/main/java/io/netty/handler/ssl/OpenSsl.java
8,169
// generic arch-dependent library
line_comment
nl
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.ssl; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.internal.tcnative.Buffer; import io.netty.internal.tcnative.Library; import io.netty.internal.tcnative.SSL; import io.netty.internal.tcnative.SSLContext; import io.netty.util.CharsetUtil; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.NativeLibraryLoader; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.StringUtil; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.ByteArrayInputStream; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static io.netty.handler.ssl.SslUtils.*; /** * Tells if <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support * are available. */ public final class OpenSsl { private static final InternalLogger logger = InternalLoggerFactory.getInstance(OpenSsl.class); private static final Throwable UNAVAILABILITY_CAUSE; static final List<String> DEFAULT_CIPHERS; static final Set<String> AVAILABLE_CIPHER_SUITES; private static final Set<String> AVAILABLE_OPENSSL_CIPHER_SUITES; private static final Set<String> AVAILABLE_JAVA_CIPHER_SUITES; private static final boolean SUPPORTS_KEYMANAGER_FACTORY; private static final boolean USE_KEYMANAGER_FACTORY; private static final boolean SUPPORTS_OCSP; private static final boolean TLSV13_SUPPORTED; private static final boolean IS_BORINGSSL; private static final Set<String> CLIENT_DEFAULT_PROTOCOLS; private static final Set<String> SERVER_DEFAULT_PROTOCOLS; static final Set<String> SUPPORTED_PROTOCOLS_SET; static final String[] EXTRA_SUPPORTED_TLS_1_3_CIPHERS; static final String EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING; static final String[] NAMED_GROUPS; static final boolean JAVAX_CERTIFICATE_CREATION_SUPPORTED; // Use default that is supported in java 11 and earlier and also in OpenSSL / BoringSSL. // See https://github.com/netty/netty-tcnative/issues/567 // See https://www.java.com/en/configure_crypto.html for ordering private static final String[] DEFAULT_NAMED_GROUPS = { "x25519", "secp256r1", "secp384r1", "secp521r1" }; static { Throwable cause = null; if (SystemPropertyUtil.getBoolean("io.netty.handler.ssl.noOpenSsl", false)) { cause = new UnsupportedOperationException( "OpenSSL was explicit disabled with -Dio.netty.handler.ssl.noOpenSsl=true"); logger.debug( "netty-tcnative explicit disabled; " + OpenSslEngine.class.getSimpleName() + " will be unavailable.", cause); } else { // Test if netty-tcnative is in the classpath first. try { Class.forName("io.netty.internal.tcnative.SSLContext", false, PlatformDependent.getClassLoader(OpenSsl.class)); } catch (ClassNotFoundException t) { cause = t; logger.debug( "netty-tcnative not in the classpath; " + OpenSslEngine.class.getSimpleName() + " will be unavailable."); } // If in the classpath, try to load the native library and initialize netty-tcnative. if (cause == null) { try { // The JNI library was not already loaded. Load it now. loadTcNative(); } catch (Throwable t) { cause = t; logger.debug( "Failed to load netty-tcnative; " + OpenSslEngine.class.getSimpleName() + " will be unavailable, unless the " + "application has already loaded the symbols by some other means. " + "See https://netty.io/wiki/forked-tomcat-native.html for more information.", t); } try { String engine = SystemPropertyUtil.get("io.netty.handler.ssl.openssl.engine", null); if (engine == null) { logger.debug("Initialize netty-tcnative using engine: 'default'"); } else { logger.debug("Initialize netty-tcnative using engine: '{}'", engine); } initializeTcNative(engine); // The library was initialized successfully. If loading the library failed above, // reset the cause now since it appears that the library was loaded by some other // means. cause = null; } catch (Throwable t) { if (cause == null) { cause = t; } logger.debug( "Failed to initialize netty-tcnative; " + OpenSslEngine.class.getSimpleName() + " will be unavailable. " + "See https://netty.io/wiki/forked-tomcat-native.html for more information.", t); } } } UNAVAILABILITY_CAUSE = cause; CLIENT_DEFAULT_PROTOCOLS = defaultProtocols("jdk.tls.client.protocols"); SERVER_DEFAULT_PROTOCOLS = defaultProtocols("jdk.tls.server.protocols"); if (cause == null) { logger.debug("netty-tcnative using native library: {}", SSL.versionString()); final List<String> defaultCiphers = new ArrayList<String>(); final Set<String> availableOpenSslCipherSuites = new LinkedHashSet<String>(128); boolean supportsKeyManagerFactory = false; boolean useKeyManagerFactory = false; boolean tlsv13Supported = false; String[] namedGroups = DEFAULT_NAMED_GROUPS; String[] defaultConvertedNamedGroups = new String[namedGroups.length]; for (int i = 0; i < namedGroups.length; i++) { defaultConvertedNamedGroups[i] = GroupsConverter.toOpenSsl(namedGroups[i]); } IS_BORINGSSL = "BoringSSL".equals(versionString()); if (IS_BORINGSSL) { EXTRA_SUPPORTED_TLS_1_3_CIPHERS = new String [] { "TLS_AES_128_GCM_SHA256", "TLS_AES_256_GCM_SHA384" , "TLS_CHACHA20_POLY1305_SHA256" }; StringBuilder ciphersBuilder = new StringBuilder(128); for (String cipher: EXTRA_SUPPORTED_TLS_1_3_CIPHERS) { ciphersBuilder.append(cipher).append(":"); } ciphersBuilder.setLength(ciphersBuilder.length() - 1); EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = ciphersBuilder.toString(); } else { EXTRA_SUPPORTED_TLS_1_3_CIPHERS = EmptyArrays.EMPTY_STRINGS; EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = StringUtil.EMPTY_STRING; } try { final long sslCtx = SSLContext.make(SSL.SSL_PROTOCOL_ALL, SSL.SSL_MODE_SERVER); long certBio = 0; long keyBio = 0; long cert = 0; long key = 0; try { // As we delegate to the KeyManager / TrustManager of the JDK we need to ensure it can actually // handle TLSv13 as otherwise we may see runtime exceptions if (SslProvider.isTlsv13Supported(SslProvider.JDK)) { try { StringBuilder tlsv13Ciphers = new StringBuilder(); for (String cipher : TLSV13_CIPHERS) { String converted = CipherSuiteConverter.toOpenSsl(cipher, IS_BORINGSSL); if (converted != null) { tlsv13Ciphers.append(converted).append(':'); } } if (tlsv13Ciphers.length() == 0) { tlsv13Supported = false; } else { tlsv13Ciphers.setLength(tlsv13Ciphers.length() - 1); SSLContext.setCipherSuite(sslCtx, tlsv13Ciphers.toString(), true); tlsv13Supported = true; } } catch (Exception ignore) { tlsv13Supported = false; } } SSLContext.setCipherSuite(sslCtx, "ALL", false); final long ssl = SSL.newSSL(sslCtx, true); try { for (String c: SSL.getCiphers(ssl)) { // Filter out bad input. if (c == null || c.isEmpty() || availableOpenSslCipherSuites.contains(c) || // Filter out TLSv1.3 ciphers if not supported. !tlsv13Supported && isTLSv13Cipher(c)) { continue; } availableOpenSslCipherSuites.add(c); } if (IS_BORINGSSL) { // Currently BoringSSL does not include these when calling SSL.getCiphers() even when these // are supported. Collections.addAll(availableOpenSslCipherSuites, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); Collections.addAll(availableOpenSslCipherSuites, "AEAD-AES128-GCM-SHA256", "AEAD-AES256-GCM-SHA384", "AEAD-CHACHA20-POLY1305-SHA256"); } PemEncoded privateKey = PemPrivateKey.valueOf(PROBING_KEY.getBytes(CharsetUtil.US_ASCII)); try { // Let's check if we can set a callback, which may not work if the used OpenSSL version // is to old. SSLContext.setCertificateCallback(sslCtx, null); X509Certificate certificate = selfSignedCertificate(); certBio = ReferenceCountedOpenSslContext.toBIO(ByteBufAllocator.DEFAULT, certificate); cert = SSL.parseX509Chain(certBio); keyBio = ReferenceCountedOpenSslContext.toBIO( UnpooledByteBufAllocator.DEFAULT, privateKey.retain()); key = SSL.parsePrivateKey(keyBio, null); SSL.setKeyMaterial(ssl, cert, key); supportsKeyManagerFactory = true; try { boolean propertySet = SystemPropertyUtil.contains( "io.netty.handler.ssl.openssl.useKeyManagerFactory"); if (!IS_BORINGSSL) { useKeyManagerFactory = SystemPropertyUtil.getBoolean( "io.netty.handler.ssl.openssl.useKeyManagerFactory", true); if (propertySet) { logger.info("System property " + "'io.netty.handler.ssl.openssl.useKeyManagerFactory'" + " is deprecated and so will be ignored in the future"); } } else { useKeyManagerFactory = true; if (propertySet) { logger.info("System property " + "'io.netty.handler.ssl.openssl.useKeyManagerFactory'" + " is deprecated and will be ignored when using BoringSSL"); } } } catch (Throwable ignore) { logger.debug("Failed to get useKeyManagerFactory system property."); } } catch (Error ignore) { logger.debug("KeyManagerFactory not supported."); } finally { privateKey.release(); } } finally { SSL.freeSSL(ssl); if (certBio != 0) { SSL.freeBIO(certBio); } if (keyBio != 0) { SSL.freeBIO(keyBio); } if (cert != 0) { SSL.freeX509Chain(cert); } if (key != 0) { SSL.freePrivateKey(key); } } String groups = SystemPropertyUtil.get("jdk.tls.namedGroups", null); if (groups != null) { String[] nGroups = groups.split(","); Set<String> supportedNamedGroups = new LinkedHashSet<String>(nGroups.length); Set<String> supportedConvertedNamedGroups = new LinkedHashSet<String>(nGroups.length); Set<String> unsupportedNamedGroups = new LinkedHashSet<String>(); for (String namedGroup : nGroups) { String converted = GroupsConverter.toOpenSsl(namedGroup); if (SSLContext.setCurvesList(sslCtx, converted)) { supportedConvertedNamedGroups.add(converted); supportedNamedGroups.add(namedGroup); } else { unsupportedNamedGroups.add(namedGroup); } } if (supportedNamedGroups.isEmpty()) { namedGroups = defaultConvertedNamedGroups; logger.info("All configured namedGroups are not supported: {}. Use default: {}.", Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS)), Arrays.toString(DEFAULT_NAMED_GROUPS)); } else { String[] groupArray = supportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS); if (unsupportedNamedGroups.isEmpty()) { logger.info("Using configured namedGroups -D 'jdk.tls.namedGroup': {} ", Arrays.toString(groupArray)); } else { logger.info("Using supported configured namedGroups: {}. Unsupported namedGroups: {}. ", Arrays.toString(groupArray), Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS))); } namedGroups = supportedConvertedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS); } } else { namedGroups = defaultConvertedNamedGroups; } } finally { SSLContext.free(sslCtx); } } catch (Exception e) { logger.warn("Failed to get the list of available OpenSSL cipher suites.", e); } NAMED_GROUPS = namedGroups; AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.unmodifiableSet(availableOpenSslCipherSuites); final Set<String> availableJavaCipherSuites = new LinkedHashSet<String>( AVAILABLE_OPENSSL_CIPHER_SUITES.size() * 2); for (String cipher: AVAILABLE_OPENSSL_CIPHER_SUITES) { // Included converted but also openssl cipher name if (!isTLSv13Cipher(cipher)) { availableJavaCipherSuites.add(CipherSuiteConverter.toJava(cipher, "TLS")); availableJavaCipherSuites.add(CipherSuiteConverter.toJava(cipher, "SSL")); } else { // TLSv1.3 ciphers have the correct format. availableJavaCipherSuites.add(cipher); } } addIfSupported(availableJavaCipherSuites, defaultCiphers, DEFAULT_CIPHER_SUITES); addIfSupported(availableJavaCipherSuites, defaultCiphers, TLSV13_CIPHER_SUITES); // Also handle the extra supported ciphers as these will contain some more stuff on BoringSSL. addIfSupported(availableJavaCipherSuites, defaultCiphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); useFallbackCiphersIfDefaultIsEmpty(defaultCiphers, availableJavaCipherSuites); DEFAULT_CIPHERS = Collections.unmodifiableList(defaultCiphers); AVAILABLE_JAVA_CIPHER_SUITES = Collections.unmodifiableSet(availableJavaCipherSuites); final Set<String> availableCipherSuites = new LinkedHashSet<String>( AVAILABLE_OPENSSL_CIPHER_SUITES.size() + AVAILABLE_JAVA_CIPHER_SUITES.size()); availableCipherSuites.addAll(AVAILABLE_OPENSSL_CIPHER_SUITES); availableCipherSuites.addAll(AVAILABLE_JAVA_CIPHER_SUITES); AVAILABLE_CIPHER_SUITES = availableCipherSuites; SUPPORTS_KEYMANAGER_FACTORY = supportsKeyManagerFactory; USE_KEYMANAGER_FACTORY = useKeyManagerFactory; Set<String> protocols = new LinkedHashSet<String>(6); // Seems like there is no way to explicitly disable SSLv2Hello in openssl so it is always enabled protocols.add(SslProtocols.SSL_v2_HELLO); if (doesSupportProtocol(SSL.SSL_PROTOCOL_SSLV2, SSL.SSL_OP_NO_SSLv2)) { protocols.add(SslProtocols.SSL_v2); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_SSLV3, SSL.SSL_OP_NO_SSLv3)) { protocols.add(SslProtocols.SSL_v3); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1, SSL.SSL_OP_NO_TLSv1)) { protocols.add(SslProtocols.TLS_v1); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_1, SSL.SSL_OP_NO_TLSv1_1)) { protocols.add(SslProtocols.TLS_v1_1); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_2, SSL.SSL_OP_NO_TLSv1_2)) { protocols.add(SslProtocols.TLS_v1_2); } // This is only supported by java8u272 and later. if (tlsv13Supported && doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_3, SSL.SSL_OP_NO_TLSv1_3)) { protocols.add(SslProtocols.TLS_v1_3); TLSV13_SUPPORTED = true; } else { TLSV13_SUPPORTED = false; } SUPPORTED_PROTOCOLS_SET = Collections.unmodifiableSet(protocols); SUPPORTS_OCSP = doesSupportOcsp(); if (logger.isDebugEnabled()) { logger.debug("Supported protocols (OpenSSL): {} ", SUPPORTED_PROTOCOLS_SET); logger.debug("Default cipher suites (OpenSSL): {}", DEFAULT_CIPHERS); } // Check if we can create a javax.security.cert.X509Certificate from our cert. This might fail on // JDK17 and above. In this case we will later throw an UnsupportedOperationException if someone // tries to access these via SSLSession. See https://github.com/netty/netty/issues/13560. boolean javaxCertificateCreationSupported; try { javax.security.cert.X509Certificate.getInstance(PROBING_CERT.getBytes(CharsetUtil.US_ASCII)); javaxCertificateCreationSupported = true; } catch (javax.security.cert.CertificateException ex) { javaxCertificateCreationSupported = false; } JAVAX_CERTIFICATE_CREATION_SUPPORTED = javaxCertificateCreationSupported; } else { DEFAULT_CIPHERS = Collections.emptyList(); AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.emptySet(); AVAILABLE_JAVA_CIPHER_SUITES = Collections.emptySet(); AVAILABLE_CIPHER_SUITES = Collections.emptySet(); SUPPORTS_KEYMANAGER_FACTORY = false; USE_KEYMANAGER_FACTORY = false; SUPPORTED_PROTOCOLS_SET = Collections.emptySet(); SUPPORTS_OCSP = false; TLSV13_SUPPORTED = false; IS_BORINGSSL = false; EXTRA_SUPPORTED_TLS_1_3_CIPHERS = EmptyArrays.EMPTY_STRINGS; EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = StringUtil.EMPTY_STRING; NAMED_GROUPS = DEFAULT_NAMED_GROUPS; JAVAX_CERTIFICATE_CREATION_SUPPORTED = false; } } static String checkTls13Ciphers(InternalLogger logger, String ciphers) { if (IS_BORINGSSL && !ciphers.isEmpty()) { assert EXTRA_SUPPORTED_TLS_1_3_CIPHERS.length > 0; Set<String> boringsslTlsv13Ciphers = new HashSet<String>(EXTRA_SUPPORTED_TLS_1_3_CIPHERS.length); Collections.addAll(boringsslTlsv13Ciphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); boolean ciphersNotMatch = false; for (String cipher: ciphers.split(":")) { if (boringsslTlsv13Ciphers.isEmpty()) { ciphersNotMatch = true; break; } if (!boringsslTlsv13Ciphers.remove(cipher) && !boringsslTlsv13Ciphers.remove(CipherSuiteConverter.toJava(cipher, "TLS"))) { ciphersNotMatch = true; break; } } // Also check if there are ciphers left. ciphersNotMatch |= !boringsslTlsv13Ciphers.isEmpty(); if (ciphersNotMatch) { if (logger.isInfoEnabled()) { StringBuilder javaCiphers = new StringBuilder(128); for (String cipher : ciphers.split(":")) { javaCiphers.append(CipherSuiteConverter.toJava(cipher, "TLS")).append(":"); } javaCiphers.setLength(javaCiphers.length() - 1); logger.info( "BoringSSL doesn't allow to enable or disable TLSv1.3 ciphers explicitly." + " Provided TLSv1.3 ciphers: '{}', default TLSv1.3 ciphers that will be used: '{}'.", javaCiphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING); } return EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING; } } return ciphers; } static boolean isSessionCacheSupported() { return version() >= 0x10100000L; } /** * Returns a self-signed {@link X509Certificate} for {@code netty.io}. */ static X509Certificate selfSignedCertificate() throws CertificateException { return (X509Certificate) SslContext.X509_CERT_FACTORY.generateCertificate( new ByteArrayInputStream(PROBING_CERT.getBytes(CharsetUtil.US_ASCII)) ); } private static boolean doesSupportOcsp() { boolean supportsOcsp = false; if (version() >= 0x10002000L) { long sslCtx = -1; try { sslCtx = SSLContext.make(SSL.SSL_PROTOCOL_TLSV1_2, SSL.SSL_MODE_SERVER); SSLContext.enableOcsp(sslCtx, false); supportsOcsp = true; } catch (Exception ignore) { // ignore } finally { if (sslCtx != -1) { SSLContext.free(sslCtx); } } } return supportsOcsp; } private static boolean doesSupportProtocol(int protocol, int opt) { if (opt == 0) { // If the opt is 0 the protocol is not supported. This is for example the case with BoringSSL and SSLv2. return false; } long sslCtx = -1; try { sslCtx = SSLContext.make(protocol, SSL.SSL_MODE_COMBINED); return true; } catch (Exception ignore) { return false; } finally { if (sslCtx != -1) { SSLContext.free(sslCtx); } } } /** * Returns {@code true} if and only if * <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support * are available. */ public static boolean isAvailable() { return UNAVAILABILITY_CAUSE == null; } /** * Returns {@code true} if the used version of openssl supports * <a href="https://tools.ietf.org/html/rfc7301">ALPN</a>. * * @deprecated use {@link SslProvider#isAlpnSupported(SslProvider)} with {@link SslProvider#OPENSSL}. */ @Deprecated public static boolean isAlpnSupported() { return version() >= 0x10002000L; } /** * Returns {@code true} if the used version of OpenSSL supports OCSP stapling. */ public static boolean isOcspSupported() { return SUPPORTS_OCSP; } /** * Returns the version of the used available OpenSSL library or {@code -1} if {@link #isAvailable()} * returns {@code false}. */ public static int version() { return isAvailable() ? SSL.version() : -1; } /** * Returns the version string of the used available OpenSSL library or {@code null} if {@link #isAvailable()} * returns {@code false}. */ public static String versionString() { return isAvailable() ? SSL.versionString() : null; } /** * Ensure that <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and * its OpenSSL support are available. * * @throws UnsatisfiedLinkError if unavailable */ public static void ensureAvailability() { if (UNAVAILABILITY_CAUSE != null) { throw (Error) new UnsatisfiedLinkError( "failed to load the required native library").initCause(UNAVAILABILITY_CAUSE); } } /** * Returns the cause of unavailability of * <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support. * * @return the cause if unavailable. {@code null} if available. */ public static Throwable unavailabilityCause() { return UNAVAILABILITY_CAUSE; } /** * @deprecated use {@link #availableOpenSslCipherSuites()} */ @Deprecated public static Set<String> availableCipherSuites() { return availableOpenSslCipherSuites(); } /** * Returns all the available OpenSSL cipher suites. * Please note that the returned array may include the cipher suites that are insecure or non-functional. */ public static Set<String> availableOpenSslCipherSuites() { return AVAILABLE_OPENSSL_CIPHER_SUITES; } /** * Returns all the available cipher suites (Java-style). * Please note that the returned array may include the cipher suites that are insecure or non-functional. */ public static Set<String> availableJavaCipherSuites() { return AVAILABLE_JAVA_CIPHER_SUITES; } /** * Returns {@code true} if and only if the specified cipher suite is available in OpenSSL. * Both Java-style cipher suite and OpenSSL-style cipher suite are accepted. */ public static boolean isCipherSuiteAvailable(String cipherSuite) { String converted = CipherSuiteConverter.toOpenSsl(cipherSuite, IS_BORINGSSL); if (converted != null) { cipherSuite = converted; } return AVAILABLE_OPENSSL_CIPHER_SUITES.contains(cipherSuite); } /** * Returns {@code true} if {@link javax.net.ssl.KeyManagerFactory} is supported when using OpenSSL. */ public static boolean supportsKeyManagerFactory() { return SUPPORTS_KEYMANAGER_FACTORY; } /** * Always returns {@code true} if {@link #isAvailable()} returns {@code true}. * * @deprecated Will be removed because hostname validation is always done by a * {@link javax.net.ssl.TrustManager} implementation. */ @Deprecated public static boolean supportsHostnameValidation() { return isAvailable(); } static boolean useKeyManagerFactory() { return USE_KEYMANAGER_FACTORY; } static long memoryAddress(ByteBuf buf) { assert buf.isDirect(); return buf.hasMemoryAddress() ? buf.memoryAddress() : // Use internalNioBuffer to reduce object creation. Buffer.address(buf.internalNioBuffer(0, buf.readableBytes())); } private OpenSsl() { } private static void loadTcNative() throws Exception { String os = PlatformDependent.normalizedOs(); String arch = PlatformDependent.normalizedArch(); Set<String> libNames = new LinkedHashSet<String>(5); String staticLibName = "netty_tcnative"; // First, try loading the platform-specific library. Platform-specific // libraries will be available if using a tcnative uber jar. if ("linux".equals(os)) { Set<String> classifiers = PlatformDependent.normalizedLinuxClassifiers(); for (String classifier : classifiers) { libNames.add(staticLibName + "_" + os + '_' + arch + "_" + classifier); } // generic arch-dependent<SUF> libNames.add(staticLibName + "_" + os + '_' + arch); // Fedora SSL lib so naming (libssl.so.10 vs libssl.so.1.0.0). // note: should already be included from the classifiers but if not, we use this as an // additional fallback option here libNames.add(staticLibName + "_" + os + '_' + arch + "_fedora"); } else { libNames.add(staticLibName + "_" + os + '_' + arch); } libNames.add(staticLibName + "_" + arch); libNames.add(staticLibName); NativeLibraryLoader.loadFirstAvailable(PlatformDependent.getClassLoader(SSLContext.class), libNames.toArray(EmptyArrays.EMPTY_STRINGS)); } private static boolean initializeTcNative(String engine) throws Exception { return Library.initialize("provided", engine); } static void releaseIfNeeded(ReferenceCounted counted) { if (counted.refCnt() > 0) { ReferenceCountUtil.safeRelease(counted); } } static boolean isTlsv13Supported() { return TLSV13_SUPPORTED; } static boolean isOptionSupported(SslContextOption<?> option) { if (isAvailable()) { if (option == OpenSslContextOption.USE_TASKS) { return true; } // Check for options that are only supported by BoringSSL atm. if (isBoringSSL()) { return option == OpenSslContextOption.ASYNC_PRIVATE_KEY_METHOD || option == OpenSslContextOption.PRIVATE_KEY_METHOD || option == OpenSslContextOption.CERTIFICATE_COMPRESSION_ALGORITHMS || option == OpenSslContextOption.TLS_FALSE_START || option == OpenSslContextOption.MAX_CERTIFICATE_LIST_BYTES; } } return false; } private static Set<String> defaultProtocols(String property) { String protocolsString = SystemPropertyUtil.get(property, null); Set<String> protocols = new HashSet<String>(); if (protocolsString != null) { for (String proto : protocolsString.split(",")) { String p = proto.trim(); protocols.add(p); } } else { protocols.add(SslProtocols.TLS_v1_2); protocols.add(SslProtocols.TLS_v1_3); } return protocols; } static String[] defaultProtocols(boolean isClient) { final Collection<String> defaultProtocols = isClient ? CLIENT_DEFAULT_PROTOCOLS : SERVER_DEFAULT_PROTOCOLS; assert defaultProtocols != null; List<String> protocols = new ArrayList<String>(defaultProtocols.size()); for (String proto : defaultProtocols) { if (SUPPORTED_PROTOCOLS_SET.contains(proto)) { protocols.add(proto); } } return protocols.toArray(EmptyArrays.EMPTY_STRINGS); } static boolean isBoringSSL() { return IS_BORINGSSL; } }
40_6
/* * Copyright 2020 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.buffer; import static io.netty.buffer.PoolThreadCache.*; /** * SizeClasses requires {@code pageShifts} to be defined prior to inclusion, * and it in turn defines: * <p> * LOG2_SIZE_CLASS_GROUP: Log of size class count for each size doubling. * LOG2_MAX_LOOKUP_SIZE: Log of max size class in the lookup table. * sizeClasses: Complete table of [index, log2Group, log2Delta, nDelta, isMultiPageSize, * isSubPage, log2DeltaLookup] tuples. * index: Size class index. * log2Group: Log of group base size (no deltas added). * log2Delta: Log of delta to previous size class. * nDelta: Delta multiplier. * isMultiPageSize: 'yes' if a multiple of the page size, 'no' otherwise. * isSubPage: 'yes' if a subpage size class, 'no' otherwise. * log2DeltaLookup: Same as log2Delta if a lookup table size class, 'no' * otherwise. * <p> * nSubpages: Number of subpages size classes. * nSizes: Number of size classes. * nPSizes: Number of size classes that are multiples of pageSize. * * smallMaxSizeIdx: Maximum small size class index. * * lookupMaxClass: Maximum size class included in lookup table. * log2NormalMinClass: Log of minimum normal size class. * <p> * The first size class and spacing are 1 << LOG2_QUANTUM. * Each group has 1 << LOG2_SIZE_CLASS_GROUP of size classes. * * size = 1 << log2Group + nDelta * (1 << log2Delta) * * The first size class has an unusual encoding, because the size has to be * split between group and delta*nDelta. * * If pageShift = 13, sizeClasses looks like this: * * (index, log2Group, log2Delta, nDelta, isMultiPageSize, isSubPage, log2DeltaLookup) * <p> * ( 0, 4, 4, 0, no, yes, 4) * ( 1, 4, 4, 1, no, yes, 4) * ( 2, 4, 4, 2, no, yes, 4) * ( 3, 4, 4, 3, no, yes, 4) * <p> * ( 4, 6, 4, 1, no, yes, 4) * ( 5, 6, 4, 2, no, yes, 4) * ( 6, 6, 4, 3, no, yes, 4) * ( 7, 6, 4, 4, no, yes, 4) * <p> * ( 8, 7, 5, 1, no, yes, 5) * ( 9, 7, 5, 2, no, yes, 5) * ( 10, 7, 5, 3, no, yes, 5) * ( 11, 7, 5, 4, no, yes, 5) * ... * ... * ( 72, 23, 21, 1, yes, no, no) * ( 73, 23, 21, 2, yes, no, no) * ( 74, 23, 21, 3, yes, no, no) * ( 75, 23, 21, 4, yes, no, no) * <p> * ( 76, 24, 22, 1, yes, no, no) */ final class SizeClasses implements SizeClassesMetric { static final int LOG2_QUANTUM = 4; private static final int LOG2_SIZE_CLASS_GROUP = 2; private static final int LOG2_MAX_LOOKUP_SIZE = 12; private static final int LOG2GROUP_IDX = 1; private static final int LOG2DELTA_IDX = 2; private static final int NDELTA_IDX = 3; private static final int PAGESIZE_IDX = 4; private static final int SUBPAGE_IDX = 5; private static final int LOG2_DELTA_LOOKUP_IDX = 6; private static final byte no = 0, yes = 1; final int pageSize; final int pageShifts; final int chunkSize; final int directMemoryCacheAlignment; final int nSizes; final int nSubpages; final int nPSizes; final int lookupMaxSize; final int smallMaxSizeIdx; private final int[] pageIdx2sizeTab; // lookup table for sizeIdx <= smallMaxSizeIdx private final int[] sizeIdx2sizeTab; // lookup table used for size <= lookupMaxClass // spacing is 1 << LOG2_QUANTUM, so the size of array is lookupMaxClass >> LOG2_QUANTUM private final int[] size2idxTab; SizeClasses(int pageSize, int pageShifts, int chunkSize, int directMemoryCacheAlignment) { int group = log2(chunkSize) - LOG2_QUANTUM - LOG2_SIZE_CLASS_GROUP + 1; //generate size classes //[index, log2Group, log2Delta, nDelta, isMultiPageSize, isSubPage, log2DeltaLookup] short[][] sizeClasses = new short[group << LOG2_SIZE_CLASS_GROUP][7]; int normalMaxSize = -1; int nSizes = 0; int size = 0; int log2Group = LOG2_QUANTUM; int log2Delta = LOG2_QUANTUM; int ndeltaLimit = 1 << LOG2_SIZE_CLASS_GROUP; //First small group, nDelta start at 0. //first size class is 1 << LOG2_QUANTUM for (int nDelta = 0; nDelta < ndeltaLimit; nDelta++, nSizes++) { short[] sizeClass = newSizeClass(nSizes, log2Group, log2Delta, nDelta, pageShifts); sizeClasses[nSizes] = sizeClass; size = sizeOf(sizeClass, directMemoryCacheAlignment); } log2Group += LOG2_SIZE_CLASS_GROUP; //All remaining groups, nDelta start at 1. for (; size < chunkSize; log2Group++, log2Delta++) { for (int nDelta = 1; nDelta <= ndeltaLimit && size < chunkSize; nDelta++, nSizes++) { short[] sizeClass = newSizeClass(nSizes, log2Group, log2Delta, nDelta, pageShifts); sizeClasses[nSizes] = sizeClass; size = normalMaxSize = sizeOf(sizeClass, directMemoryCacheAlignment); } } //chunkSize must be normalMaxSize assert chunkSize == normalMaxSize; int smallMaxSizeIdx = 0; int lookupMaxSize = 0; int nPSizes = 0; int nSubpages = 0; for (int idx = 0; idx < nSizes; idx++) { short[] sz = sizeClasses[idx]; if (sz[PAGESIZE_IDX] == yes) { nPSizes++; } if (sz[SUBPAGE_IDX] == yes) { nSubpages++; smallMaxSizeIdx = idx; } if (sz[LOG2_DELTA_LOOKUP_IDX] != no) { lookupMaxSize = sizeOf(sz, directMemoryCacheAlignment); } } this.smallMaxSizeIdx = smallMaxSizeIdx; this.lookupMaxSize = lookupMaxSize; this.nPSizes = nPSizes; this.nSubpages = nSubpages; this.nSizes = nSizes; this.pageSize = pageSize; this.pageShifts = pageShifts; this.chunkSize = chunkSize; this.directMemoryCacheAlignment = directMemoryCacheAlignment; //generate lookup tables this.sizeIdx2sizeTab = newIdx2SizeTab(sizeClasses, nSizes, directMemoryCacheAlignment); this.pageIdx2sizeTab = newPageIdx2sizeTab(sizeClasses, nSizes, nPSizes, directMemoryCacheAlignment); this.size2idxTab = newSize2idxTab(lookupMaxSize, sizeClasses); } //calculate size class private static short[] newSizeClass(int index, int log2Group, int log2Delta, int nDelta, int pageShifts) { short isMultiPageSize; if (log2Delta >= pageShifts) { isMultiPageSize = yes; } else { int pageSize = 1 << pageShifts; int size = calculateSize(log2Group, nDelta, log2Delta); isMultiPageSize = size == size / pageSize * pageSize? yes : no; } int log2Ndelta = nDelta == 0? 0 : log2(nDelta); byte remove = 1 << log2Ndelta < nDelta? yes : no; int log2Size = log2Delta + log2Ndelta == log2Group? log2Group + 1 : log2Group; if (log2Size == log2Group) { remove = yes; } short isSubpage = log2Size < pageShifts + LOG2_SIZE_CLASS_GROUP? yes : no; int log2DeltaLookup = log2Size < LOG2_MAX_LOOKUP_SIZE || log2Size == LOG2_MAX_LOOKUP_SIZE && remove == no ? log2Delta : no; return new short[] { (short) index, (short) log2Group, (short) log2Delta, (short) nDelta, isMultiPageSize, isSubpage, (short) log2DeltaLookup }; } private static int[] newIdx2SizeTab(short[][] sizeClasses, int nSizes, int directMemoryCacheAlignment) { int[] sizeIdx2sizeTab = new int[nSizes]; for (int i = 0; i < nSizes; i++) { short[] sizeClass = sizeClasses[i]; sizeIdx2sizeTab[i] = sizeOf(sizeClass, directMemoryCacheAlignment); } return sizeIdx2sizeTab; } private static int calculateSize(int log2Group, int nDelta, int log2Delta) { return (1 << log2Group) + (nDelta << log2Delta); } private static int sizeOf(short[] sizeClass, int directMemoryCacheAlignment) { int log2Group = sizeClass[LOG2GROUP_IDX]; int log2Delta = sizeClass[LOG2DELTA_IDX]; int nDelta = sizeClass[NDELTA_IDX]; int size = calculateSize(log2Group, nDelta, log2Delta); return alignSizeIfNeeded(size, directMemoryCacheAlignment); } private static int[] newPageIdx2sizeTab(short[][] sizeClasses, int nSizes, int nPSizes, int directMemoryCacheAlignment) { int[] pageIdx2sizeTab = new int[nPSizes]; int pageIdx = 0; for (int i = 0; i < nSizes; i++) { short[] sizeClass = sizeClasses[i]; if (sizeClass[PAGESIZE_IDX] == yes) { pageIdx2sizeTab[pageIdx++] = sizeOf(sizeClass, directMemoryCacheAlignment); } } return pageIdx2sizeTab; } private static int[] newSize2idxTab(int lookupMaxSize, short[][] sizeClasses) { int[] size2idxTab = new int[lookupMaxSize >> LOG2_QUANTUM]; int idx = 0; int size = 0; for (int i = 0; size <= lookupMaxSize; i++) { int log2Delta = sizeClasses[i][LOG2DELTA_IDX]; int times = 1 << log2Delta - LOG2_QUANTUM; while (size <= lookupMaxSize && times-- > 0) { size2idxTab[idx++] = i; size = idx + 1 << LOG2_QUANTUM; } } return size2idxTab; } @Override public int sizeIdx2size(int sizeIdx) { return sizeIdx2sizeTab[sizeIdx]; } @Override public int sizeIdx2sizeCompute(int sizeIdx) { int group = sizeIdx >> LOG2_SIZE_CLASS_GROUP; int mod = sizeIdx & (1 << LOG2_SIZE_CLASS_GROUP) - 1; int groupSize = group == 0? 0 : 1 << LOG2_QUANTUM + LOG2_SIZE_CLASS_GROUP - 1 << group; int shift = group == 0? 1 : group; int lgDelta = shift + LOG2_QUANTUM - 1; int modSize = mod + 1 << lgDelta; return groupSize + modSize; } @Override public long pageIdx2size(int pageIdx) { return pageIdx2sizeTab[pageIdx]; } @Override public long pageIdx2sizeCompute(int pageIdx) { int group = pageIdx >> LOG2_SIZE_CLASS_GROUP; int mod = pageIdx & (1 << LOG2_SIZE_CLASS_GROUP) - 1; long groupSize = group == 0? 0 : 1L << pageShifts + LOG2_SIZE_CLASS_GROUP - 1 << group; int shift = group == 0? 1 : group; int log2Delta = shift + pageShifts - 1; int modSize = mod + 1 << log2Delta; return groupSize + modSize; } @Override public int size2SizeIdx(int size) { if (size == 0) { return 0; } if (size > chunkSize) { return nSizes; } size = alignSizeIfNeeded(size, directMemoryCacheAlignment); if (size <= lookupMaxSize) { //size-1 / MIN_TINY return size2idxTab[size - 1 >> LOG2_QUANTUM]; } int x = log2((size << 1) - 1); int shift = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? 0 : x - (LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM); int group = shift << LOG2_SIZE_CLASS_GROUP; int log2Delta = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? LOG2_QUANTUM : x - LOG2_SIZE_CLASS_GROUP - 1; int mod = size - 1 >> log2Delta & (1 << LOG2_SIZE_CLASS_GROUP) - 1; return group + mod; } @Override public int pages2pageIdx(int pages) { return pages2pageIdxCompute(pages, false); } @Override public int pages2pageIdxFloor(int pages) { return pages2pageIdxCompute(pages, true); } private int pages2pageIdxCompute(int pages, boolean floor) { int pageSize = pages << pageShifts; if (pageSize > chunkSize) { return nPSizes; } int x = log2((pageSize << 1) - 1); int shift = x < LOG2_SIZE_CLASS_GROUP + pageShifts ? 0 : x - (LOG2_SIZE_CLASS_GROUP + pageShifts); int group = shift << LOG2_SIZE_CLASS_GROUP; int log2Delta = x < LOG2_SIZE_CLASS_GROUP + pageShifts + 1? pageShifts : x - LOG2_SIZE_CLASS_GROUP - 1; int mod = pageSize - 1 >> log2Delta & (1 << LOG2_SIZE_CLASS_GROUP) - 1; int pageIdx = group + mod; if (floor && pageIdx2sizeTab[pageIdx] > pages << pageShifts) { pageIdx--; } return pageIdx; } // Round size up to the nearest multiple of alignment. private static int alignSizeIfNeeded(int size, int directMemoryCacheAlignment) { if (directMemoryCacheAlignment <= 0) { return size; } int delta = size & directMemoryCacheAlignment - 1; return delta == 0? size : size + directMemoryCacheAlignment - delta; } @Override public int normalizeSize(int size) { if (size == 0) { return sizeIdx2sizeTab[0]; } size = alignSizeIfNeeded(size, directMemoryCacheAlignment); if (size <= lookupMaxSize) { int ret = sizeIdx2sizeTab[size2idxTab[size - 1 >> LOG2_QUANTUM]]; assert ret == normalizeSizeCompute(size); return ret; } return normalizeSizeCompute(size); } private static int normalizeSizeCompute(int size) { int x = log2((size << 1) - 1); int log2Delta = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? LOG2_QUANTUM : x - LOG2_SIZE_CLASS_GROUP - 1; int delta = 1 << log2Delta; int delta_mask = delta - 1; return size + delta_mask & ~delta_mask; } }
netty/netty
buffer/src/main/java/io/netty/buffer/SizeClasses.java
4,514
//[index, log2Group, log2Delta, nDelta, isMultiPageSize, isSubPage, log2DeltaLookup]
line_comment
nl
/* * Copyright 2020 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.buffer; import static io.netty.buffer.PoolThreadCache.*; /** * SizeClasses requires {@code pageShifts} to be defined prior to inclusion, * and it in turn defines: * <p> * LOG2_SIZE_CLASS_GROUP: Log of size class count for each size doubling. * LOG2_MAX_LOOKUP_SIZE: Log of max size class in the lookup table. * sizeClasses: Complete table of [index, log2Group, log2Delta, nDelta, isMultiPageSize, * isSubPage, log2DeltaLookup] tuples. * index: Size class index. * log2Group: Log of group base size (no deltas added). * log2Delta: Log of delta to previous size class. * nDelta: Delta multiplier. * isMultiPageSize: 'yes' if a multiple of the page size, 'no' otherwise. * isSubPage: 'yes' if a subpage size class, 'no' otherwise. * log2DeltaLookup: Same as log2Delta if a lookup table size class, 'no' * otherwise. * <p> * nSubpages: Number of subpages size classes. * nSizes: Number of size classes. * nPSizes: Number of size classes that are multiples of pageSize. * * smallMaxSizeIdx: Maximum small size class index. * * lookupMaxClass: Maximum size class included in lookup table. * log2NormalMinClass: Log of minimum normal size class. * <p> * The first size class and spacing are 1 << LOG2_QUANTUM. * Each group has 1 << LOG2_SIZE_CLASS_GROUP of size classes. * * size = 1 << log2Group + nDelta * (1 << log2Delta) * * The first size class has an unusual encoding, because the size has to be * split between group and delta*nDelta. * * If pageShift = 13, sizeClasses looks like this: * * (index, log2Group, log2Delta, nDelta, isMultiPageSize, isSubPage, log2DeltaLookup) * <p> * ( 0, 4, 4, 0, no, yes, 4) * ( 1, 4, 4, 1, no, yes, 4) * ( 2, 4, 4, 2, no, yes, 4) * ( 3, 4, 4, 3, no, yes, 4) * <p> * ( 4, 6, 4, 1, no, yes, 4) * ( 5, 6, 4, 2, no, yes, 4) * ( 6, 6, 4, 3, no, yes, 4) * ( 7, 6, 4, 4, no, yes, 4) * <p> * ( 8, 7, 5, 1, no, yes, 5) * ( 9, 7, 5, 2, no, yes, 5) * ( 10, 7, 5, 3, no, yes, 5) * ( 11, 7, 5, 4, no, yes, 5) * ... * ... * ( 72, 23, 21, 1, yes, no, no) * ( 73, 23, 21, 2, yes, no, no) * ( 74, 23, 21, 3, yes, no, no) * ( 75, 23, 21, 4, yes, no, no) * <p> * ( 76, 24, 22, 1, yes, no, no) */ final class SizeClasses implements SizeClassesMetric { static final int LOG2_QUANTUM = 4; private static final int LOG2_SIZE_CLASS_GROUP = 2; private static final int LOG2_MAX_LOOKUP_SIZE = 12; private static final int LOG2GROUP_IDX = 1; private static final int LOG2DELTA_IDX = 2; private static final int NDELTA_IDX = 3; private static final int PAGESIZE_IDX = 4; private static final int SUBPAGE_IDX = 5; private static final int LOG2_DELTA_LOOKUP_IDX = 6; private static final byte no = 0, yes = 1; final int pageSize; final int pageShifts; final int chunkSize; final int directMemoryCacheAlignment; final int nSizes; final int nSubpages; final int nPSizes; final int lookupMaxSize; final int smallMaxSizeIdx; private final int[] pageIdx2sizeTab; // lookup table for sizeIdx <= smallMaxSizeIdx private final int[] sizeIdx2sizeTab; // lookup table used for size <= lookupMaxClass // spacing is 1 << LOG2_QUANTUM, so the size of array is lookupMaxClass >> LOG2_QUANTUM private final int[] size2idxTab; SizeClasses(int pageSize, int pageShifts, int chunkSize, int directMemoryCacheAlignment) { int group = log2(chunkSize) - LOG2_QUANTUM - LOG2_SIZE_CLASS_GROUP + 1; //generate size classes //[index, log2Group,<SUF> short[][] sizeClasses = new short[group << LOG2_SIZE_CLASS_GROUP][7]; int normalMaxSize = -1; int nSizes = 0; int size = 0; int log2Group = LOG2_QUANTUM; int log2Delta = LOG2_QUANTUM; int ndeltaLimit = 1 << LOG2_SIZE_CLASS_GROUP; //First small group, nDelta start at 0. //first size class is 1 << LOG2_QUANTUM for (int nDelta = 0; nDelta < ndeltaLimit; nDelta++, nSizes++) { short[] sizeClass = newSizeClass(nSizes, log2Group, log2Delta, nDelta, pageShifts); sizeClasses[nSizes] = sizeClass; size = sizeOf(sizeClass, directMemoryCacheAlignment); } log2Group += LOG2_SIZE_CLASS_GROUP; //All remaining groups, nDelta start at 1. for (; size < chunkSize; log2Group++, log2Delta++) { for (int nDelta = 1; nDelta <= ndeltaLimit && size < chunkSize; nDelta++, nSizes++) { short[] sizeClass = newSizeClass(nSizes, log2Group, log2Delta, nDelta, pageShifts); sizeClasses[nSizes] = sizeClass; size = normalMaxSize = sizeOf(sizeClass, directMemoryCacheAlignment); } } //chunkSize must be normalMaxSize assert chunkSize == normalMaxSize; int smallMaxSizeIdx = 0; int lookupMaxSize = 0; int nPSizes = 0; int nSubpages = 0; for (int idx = 0; idx < nSizes; idx++) { short[] sz = sizeClasses[idx]; if (sz[PAGESIZE_IDX] == yes) { nPSizes++; } if (sz[SUBPAGE_IDX] == yes) { nSubpages++; smallMaxSizeIdx = idx; } if (sz[LOG2_DELTA_LOOKUP_IDX] != no) { lookupMaxSize = sizeOf(sz, directMemoryCacheAlignment); } } this.smallMaxSizeIdx = smallMaxSizeIdx; this.lookupMaxSize = lookupMaxSize; this.nPSizes = nPSizes; this.nSubpages = nSubpages; this.nSizes = nSizes; this.pageSize = pageSize; this.pageShifts = pageShifts; this.chunkSize = chunkSize; this.directMemoryCacheAlignment = directMemoryCacheAlignment; //generate lookup tables this.sizeIdx2sizeTab = newIdx2SizeTab(sizeClasses, nSizes, directMemoryCacheAlignment); this.pageIdx2sizeTab = newPageIdx2sizeTab(sizeClasses, nSizes, nPSizes, directMemoryCacheAlignment); this.size2idxTab = newSize2idxTab(lookupMaxSize, sizeClasses); } //calculate size class private static short[] newSizeClass(int index, int log2Group, int log2Delta, int nDelta, int pageShifts) { short isMultiPageSize; if (log2Delta >= pageShifts) { isMultiPageSize = yes; } else { int pageSize = 1 << pageShifts; int size = calculateSize(log2Group, nDelta, log2Delta); isMultiPageSize = size == size / pageSize * pageSize? yes : no; } int log2Ndelta = nDelta == 0? 0 : log2(nDelta); byte remove = 1 << log2Ndelta < nDelta? yes : no; int log2Size = log2Delta + log2Ndelta == log2Group? log2Group + 1 : log2Group; if (log2Size == log2Group) { remove = yes; } short isSubpage = log2Size < pageShifts + LOG2_SIZE_CLASS_GROUP? yes : no; int log2DeltaLookup = log2Size < LOG2_MAX_LOOKUP_SIZE || log2Size == LOG2_MAX_LOOKUP_SIZE && remove == no ? log2Delta : no; return new short[] { (short) index, (short) log2Group, (short) log2Delta, (short) nDelta, isMultiPageSize, isSubpage, (short) log2DeltaLookup }; } private static int[] newIdx2SizeTab(short[][] sizeClasses, int nSizes, int directMemoryCacheAlignment) { int[] sizeIdx2sizeTab = new int[nSizes]; for (int i = 0; i < nSizes; i++) { short[] sizeClass = sizeClasses[i]; sizeIdx2sizeTab[i] = sizeOf(sizeClass, directMemoryCacheAlignment); } return sizeIdx2sizeTab; } private static int calculateSize(int log2Group, int nDelta, int log2Delta) { return (1 << log2Group) + (nDelta << log2Delta); } private static int sizeOf(short[] sizeClass, int directMemoryCacheAlignment) { int log2Group = sizeClass[LOG2GROUP_IDX]; int log2Delta = sizeClass[LOG2DELTA_IDX]; int nDelta = sizeClass[NDELTA_IDX]; int size = calculateSize(log2Group, nDelta, log2Delta); return alignSizeIfNeeded(size, directMemoryCacheAlignment); } private static int[] newPageIdx2sizeTab(short[][] sizeClasses, int nSizes, int nPSizes, int directMemoryCacheAlignment) { int[] pageIdx2sizeTab = new int[nPSizes]; int pageIdx = 0; for (int i = 0; i < nSizes; i++) { short[] sizeClass = sizeClasses[i]; if (sizeClass[PAGESIZE_IDX] == yes) { pageIdx2sizeTab[pageIdx++] = sizeOf(sizeClass, directMemoryCacheAlignment); } } return pageIdx2sizeTab; } private static int[] newSize2idxTab(int lookupMaxSize, short[][] sizeClasses) { int[] size2idxTab = new int[lookupMaxSize >> LOG2_QUANTUM]; int idx = 0; int size = 0; for (int i = 0; size <= lookupMaxSize; i++) { int log2Delta = sizeClasses[i][LOG2DELTA_IDX]; int times = 1 << log2Delta - LOG2_QUANTUM; while (size <= lookupMaxSize && times-- > 0) { size2idxTab[idx++] = i; size = idx + 1 << LOG2_QUANTUM; } } return size2idxTab; } @Override public int sizeIdx2size(int sizeIdx) { return sizeIdx2sizeTab[sizeIdx]; } @Override public int sizeIdx2sizeCompute(int sizeIdx) { int group = sizeIdx >> LOG2_SIZE_CLASS_GROUP; int mod = sizeIdx & (1 << LOG2_SIZE_CLASS_GROUP) - 1; int groupSize = group == 0? 0 : 1 << LOG2_QUANTUM + LOG2_SIZE_CLASS_GROUP - 1 << group; int shift = group == 0? 1 : group; int lgDelta = shift + LOG2_QUANTUM - 1; int modSize = mod + 1 << lgDelta; return groupSize + modSize; } @Override public long pageIdx2size(int pageIdx) { return pageIdx2sizeTab[pageIdx]; } @Override public long pageIdx2sizeCompute(int pageIdx) { int group = pageIdx >> LOG2_SIZE_CLASS_GROUP; int mod = pageIdx & (1 << LOG2_SIZE_CLASS_GROUP) - 1; long groupSize = group == 0? 0 : 1L << pageShifts + LOG2_SIZE_CLASS_GROUP - 1 << group; int shift = group == 0? 1 : group; int log2Delta = shift + pageShifts - 1; int modSize = mod + 1 << log2Delta; return groupSize + modSize; } @Override public int size2SizeIdx(int size) { if (size == 0) { return 0; } if (size > chunkSize) { return nSizes; } size = alignSizeIfNeeded(size, directMemoryCacheAlignment); if (size <= lookupMaxSize) { //size-1 / MIN_TINY return size2idxTab[size - 1 >> LOG2_QUANTUM]; } int x = log2((size << 1) - 1); int shift = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? 0 : x - (LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM); int group = shift << LOG2_SIZE_CLASS_GROUP; int log2Delta = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? LOG2_QUANTUM : x - LOG2_SIZE_CLASS_GROUP - 1; int mod = size - 1 >> log2Delta & (1 << LOG2_SIZE_CLASS_GROUP) - 1; return group + mod; } @Override public int pages2pageIdx(int pages) { return pages2pageIdxCompute(pages, false); } @Override public int pages2pageIdxFloor(int pages) { return pages2pageIdxCompute(pages, true); } private int pages2pageIdxCompute(int pages, boolean floor) { int pageSize = pages << pageShifts; if (pageSize > chunkSize) { return nPSizes; } int x = log2((pageSize << 1) - 1); int shift = x < LOG2_SIZE_CLASS_GROUP + pageShifts ? 0 : x - (LOG2_SIZE_CLASS_GROUP + pageShifts); int group = shift << LOG2_SIZE_CLASS_GROUP; int log2Delta = x < LOG2_SIZE_CLASS_GROUP + pageShifts + 1? pageShifts : x - LOG2_SIZE_CLASS_GROUP - 1; int mod = pageSize - 1 >> log2Delta & (1 << LOG2_SIZE_CLASS_GROUP) - 1; int pageIdx = group + mod; if (floor && pageIdx2sizeTab[pageIdx] > pages << pageShifts) { pageIdx--; } return pageIdx; } // Round size up to the nearest multiple of alignment. private static int alignSizeIfNeeded(int size, int directMemoryCacheAlignment) { if (directMemoryCacheAlignment <= 0) { return size; } int delta = size & directMemoryCacheAlignment - 1; return delta == 0? size : size + directMemoryCacheAlignment - delta; } @Override public int normalizeSize(int size) { if (size == 0) { return sizeIdx2sizeTab[0]; } size = alignSizeIfNeeded(size, directMemoryCacheAlignment); if (size <= lookupMaxSize) { int ret = sizeIdx2sizeTab[size2idxTab[size - 1 >> LOG2_QUANTUM]]; assert ret == normalizeSizeCompute(size); return ret; } return normalizeSizeCompute(size); } private static int normalizeSizeCompute(int size) { int x = log2((size << 1) - 1); int log2Delta = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? LOG2_QUANTUM : x - LOG2_SIZE_CLASS_GROUP - 1; int delta = 1 << log2Delta; int delta_mask = delta - 1; return size + delta_mask & ~delta_mask; } }
89_23
// Within Settlers of Catan, the 1995 German game of the year, players attempt to dominate an island // by building roads, settlements and cities across its uncharted wilderness. // You are employed by a software company that just has decided to develop a computer version of // this game, and you are chosen to implement one of the game’s special rules: // When the game ends, the player who built the longest road gains two extra victory points. // The problem here is that the players usually build complex road networks and not just one linear // path. Therefore, determining the longest road is not trivial (although human players usually see it // immediately). // Compared to the original game, we will solve a simplified problem here: You are given a set of nodes // (cities) and a set of edges (road segments) of length 1 connecting the nodes. // The longest road is defined as the longest path within the network that doesn’t use an edge twice. // Nodes may be visited more than once, though. // Input // The input file will contain one or more test cases. // The first line of each test case contains two integers: the number of nodes n (2 ≤ n ≤ 25) and the // number of edges m (1 ≤ m ≤ 25). The next m lines describe the m edges. Each edge is given by the // numbers of the two nodes connected by it. Nodes are numbered from 0 to n − 1. Edges are undirected. // Nodes have degrees of three or less. The network is not neccessarily connected. // Input will be terminated by two values of 0 for n and m. // Output // For each test case, print the length of the longest road on a single line. // Sample Input // 3 2 // 0 1 // 1 2 // 15 16 // 0 2 // 1 2 // 2 3 // 3 4 // 3 5 // 4 6 // 5 7 // 6 8 // 7 8 // 7 9 // 8 10 // 9 11 // 10 12 // 11 12 // 10 13 // 12 14 // 0 0 // Sample Output // 2 // 12 import java.io.*; /** * Created by kdn251 on 2/20/17. */ public class TheSettlersOfCatan { public static int[][] matrix = new int[30][30]; public static int answer; public static void main(String args[]) throws Exception { //initialize buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; //iterate while current line is not equal to 0 0 while(!(line = br.readLine()).equals("0 0")) { //initialize number of nodes and edges int nodes = Integer.parseInt(line.split(" ")[0]); int edges = Integer.parseInt(line.split(" ")[1]); //iterate through all edges for(int i = 0; i < edges; i++) { //get edge between node x and node y String[] current = br.readLine().split(" "); int x = Integer.parseInt(current[0]); int y = Integer.parseInt(current[1]); //mark edge matrix[x][y] = 1; matrix[y][x] = 1; } //initialize answer to zero answer = 0; //dfs on every node for(int i = 0; i < nodes; i++) { dfs(i, 0, nodes); } //print answer System.out.println(answer); //reset graph matrix = new int[30][30]; } } public static void dfs(int nd, int l, int nodes) { //update answer if l is larger than current answer if(l > answer) { answer = l; } for(int i = 0; i < nodes; i++) { if(matrix[nd][i] > 0) { //ensure that edge is not counted twice (like marking as "visited") matrix[nd][i] = 0; matrix[i][nd] = 0; //continue traversing graph and add 1 to count dfs(i, l + 1, nodes); //set current edge again in case node further into graph can reach it matrix[nd][i] = 1; matrix[i][nd] = 1; } } } } //source: https://github.com/morris821028/UVa/blob/master/volume005/539%20-%20The%20Settlers%20of%20Catan.cpp
kdn251/interviews
uva/TheSettlersOfCatan.java
1,174
//get edge between node x and node y
line_comment
nl
// Within Settlers of Catan, the 1995 German game of the year, players attempt to dominate an island // by building roads, settlements and cities across its uncharted wilderness. // You are employed by a software company that just has decided to develop a computer version of // this game, and you are chosen to implement one of the game’s special rules: // When the game ends, the player who built the longest road gains two extra victory points. // The problem here is that the players usually build complex road networks and not just one linear // path. Therefore, determining the longest road is not trivial (although human players usually see it // immediately). // Compared to the original game, we will solve a simplified problem here: You are given a set of nodes // (cities) and a set of edges (road segments) of length 1 connecting the nodes. // The longest road is defined as the longest path within the network that doesn’t use an edge twice. // Nodes may be visited more than once, though. // Input // The input file will contain one or more test cases. // The first line of each test case contains two integers: the number of nodes n (2 ≤ n ≤ 25) and the // number of edges m (1 ≤ m ≤ 25). The next m lines describe the m edges. Each edge is given by the // numbers of the two nodes connected by it. Nodes are numbered from 0 to n − 1. Edges are undirected. // Nodes have degrees of three or less. The network is not neccessarily connected. // Input will be terminated by two values of 0 for n and m. // Output // For each test case, print the length of the longest road on a single line. // Sample Input // 3 2 // 0 1 // 1 2 // 15 16 // 0 2 // 1 2 // 2 3 // 3 4 // 3 5 // 4 6 // 5 7 // 6 8 // 7 8 // 7 9 // 8 10 // 9 11 // 10 12 // 11 12 // 10 13 // 12 14 // 0 0 // Sample Output // 2 // 12 import java.io.*; /** * Created by kdn251 on 2/20/17. */ public class TheSettlersOfCatan { public static int[][] matrix = new int[30][30]; public static int answer; public static void main(String args[]) throws Exception { //initialize buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; //iterate while current line is not equal to 0 0 while(!(line = br.readLine()).equals("0 0")) { //initialize number of nodes and edges int nodes = Integer.parseInt(line.split(" ")[0]); int edges = Integer.parseInt(line.split(" ")[1]); //iterate through all edges for(int i = 0; i < edges; i++) { //get edge<SUF> String[] current = br.readLine().split(" "); int x = Integer.parseInt(current[0]); int y = Integer.parseInt(current[1]); //mark edge matrix[x][y] = 1; matrix[y][x] = 1; } //initialize answer to zero answer = 0; //dfs on every node for(int i = 0; i < nodes; i++) { dfs(i, 0, nodes); } //print answer System.out.println(answer); //reset graph matrix = new int[30][30]; } } public static void dfs(int nd, int l, int nodes) { //update answer if l is larger than current answer if(l > answer) { answer = l; } for(int i = 0; i < nodes; i++) { if(matrix[nd][i] > 0) { //ensure that edge is not counted twice (like marking as "visited") matrix[nd][i] = 0; matrix[i][nd] = 0; //continue traversing graph and add 1 to count dfs(i, l + 1, nodes); //set current edge again in case node further into graph can reach it matrix[nd][i] = 1; matrix[i][nd] = 1; } } } } //source: https://github.com/morris821028/UVa/blob/master/volume005/539%20-%20The%20Settlers%20of%20Catan.cpp
93_1
package com.thealgorithms.sorts; /** * Comb Sort algorithm implementation * * <p> * Best-case performance O(n * log(n)) Worst-case performance O(n ^ 2) * Worst-case space complexity O(1) * * <p> * Comb sort improves on bubble sort. * * @author Sandeep Roy (https://github.com/sandeeproy99) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see BubbleSort * @see SortAlgorithm */ class CombSort implements SortAlgorithm { // To find gap between elements private int nextGap(int gap) { // Shrink gap by Shrink factor gap = (gap * 10) / 13; return Math.max(gap, 1); } /** * Function to sort arr[] using Comb * * @param arr - an array should be sorted * @return sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] arr) { int size = arr.length; // initialize gap int gap = size; // Initialize swapped as true to make sure that loop runs boolean swapped = true; // Keep running while gap is more than 1 and last iteration caused a swap while (gap != 1 || swapped) { // Find next gap gap = nextGap(gap); // Initialize swapped as false so that we can check if swap happened or not swapped = false; // Compare all elements with current gap for (int i = 0; i < size - gap; i++) { if (SortUtils.less(arr[i + gap], arr[i])) { // Swap arr[i] and arr[i+gap] SortUtils.swap(arr, i, i + gap); swapped = true; } } } return arr; } // Driver method public static void main(String[] args) { CombSort ob = new CombSort(); Integer[] arr = { 8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0, }; ob.sort(arr); System.out.println("sorted array"); SortUtils.print(arr); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/sorts/CombSort.java
632
// To find gap between elements
line_comment
nl
package com.thealgorithms.sorts; /** * Comb Sort algorithm implementation * * <p> * Best-case performance O(n * log(n)) Worst-case performance O(n ^ 2) * Worst-case space complexity O(1) * * <p> * Comb sort improves on bubble sort. * * @author Sandeep Roy (https://github.com/sandeeproy99) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see BubbleSort * @see SortAlgorithm */ class CombSort implements SortAlgorithm { // To find<SUF> private int nextGap(int gap) { // Shrink gap by Shrink factor gap = (gap * 10) / 13; return Math.max(gap, 1); } /** * Function to sort arr[] using Comb * * @param arr - an array should be sorted * @return sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] arr) { int size = arr.length; // initialize gap int gap = size; // Initialize swapped as true to make sure that loop runs boolean swapped = true; // Keep running while gap is more than 1 and last iteration caused a swap while (gap != 1 || swapped) { // Find next gap gap = nextGap(gap); // Initialize swapped as false so that we can check if swap happened or not swapped = false; // Compare all elements with current gap for (int i = 0; i < size - gap; i++) { if (SortUtils.less(arr[i + gap], arr[i])) { // Swap arr[i] and arr[i+gap] SortUtils.swap(arr, i, i + gap); swapped = true; } } } return arr; } // Driver method public static void main(String[] args) { CombSort ob = new CombSort(); Integer[] arr = { 8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0, }; ob.sort(arr); System.out.println("sorted array"); SortUtils.print(arr); } }
99_7
package com.thealgorithms.others; import java.util.Objects; /** * The Verhoeff algorithm is a checksum formula for error detection developed by * the Dutch mathematician Jacobus Verhoeff and was first published in 1969. It * was the first decimal check digit algorithm which detects all single-digit * errors, and all transposition errors involving two adjacent digits. * * <p> * The strengths of the algorithm are that it detects all transliteration and * transposition errors, and additionally most twin, twin jump, jump * transposition and phonetic errors. The main weakness of the Verhoeff * algorithm is its complexity. The calculations required cannot easily be * expressed as a formula. For easy calculation three tables are required:</p> * <ol> * <li>multiplication table</li> * <li>inverse table</li> * <li>permutation table</li> * </ol> * * @see <a href="https://en.wikipedia.org/wiki/Verhoeff_algorithm">Wiki. * Verhoeff algorithm</a> */ public final class Verhoeff { private Verhoeff() { } /** * Table {@code d}. Based on multiplication in the dihedral group D5 and is * simply the Cayley table of the group. Note that this group is not * commutative, that is, for some values of {@code j} and {@code k}, * {@code d(j,k) ≠ d(k, j)}. * * @see <a href="https://en.wikipedia.org/wiki/Dihedral_group">Wiki. * Dihedral group</a> */ private static final byte[][] MULTIPLICATION_TABLE = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, }; /** * The inverse table {@code inv}. Represents the multiplicative inverse of a * digit, that is, the value that satisfies {@code d(j, inv(j)) = 0}. */ private static final byte[] MULTIPLICATIVE_INVERSE = { 0, 4, 3, 2, 1, 5, 6, 7, 8, 9, }; /** * The permutation table {@code p}. Applies a permutation to each digit * based on its position in the number. This is actually a single * permutation {@code (1 5 8 9 4 2 7 0)(3 6)} applied iteratively; i.e. * {@code p(i+j,n) = p(i, p(j,n))}. */ private static final byte[][] PERMUTATION_TABLE = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, }; /** * Check input digits by Verhoeff algorithm. * * @param digits input to check * @return true if check was successful, false otherwise * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static boolean verhoeffCheck(String digits) { checkInput(digits); int[] numbers = toIntArray(digits); // The Verhoeff algorithm int checksum = 0; for (int i = 0; i < numbers.length; i++) { int index = numbers.length - i - 1; byte b = PERMUTATION_TABLE[i % 8][numbers[index]]; checksum = MULTIPLICATION_TABLE[checksum][b]; } return checksum == 0; } /** * Calculate check digit for initial digits and add it tho the last * position. * * @param initialDigits initial value * @return digits with the checksum in the last position * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static String addVerhoeffChecksum(String initialDigits) { checkInput(initialDigits); // Add zero to end of input value var modifiedDigits = initialDigits + "0"; int[] numbers = toIntArray(modifiedDigits); int checksum = 0; for (int i = 0; i < numbers.length; i++) { int index = numbers.length - i - 1; byte b = PERMUTATION_TABLE[i % 8][numbers[index]]; checksum = MULTIPLICATION_TABLE[checksum][b]; } checksum = MULTIPLICATIVE_INVERSE[checksum]; return initialDigits + checksum; } public static void main(String[] args) { System.out.println("Verhoeff algorithm usage examples:"); var validInput = "2363"; var invalidInput = "2364"; checkAndPrint(validInput); checkAndPrint(invalidInput); System.out.println("\nCheck digit generation example:"); var input = "236"; generateAndPrint(input); } private static void checkAndPrint(String input) { String validationResult = Verhoeff.verhoeffCheck(input) ? "valid" : "not valid"; System.out.println("Input '" + input + "' is " + validationResult); } private static void generateAndPrint(String input) { String result = addVerhoeffChecksum(input); System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); } } private static int[] toIntArray(String string) { return string.chars().map(i -> Character.digit(i, 10)).toArray(); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/Verhoeff.java
1,958
// Add zero to end of input value
line_comment
nl
package com.thealgorithms.others; import java.util.Objects; /** * The Verhoeff algorithm is a checksum formula for error detection developed by * the Dutch mathematician Jacobus Verhoeff and was first published in 1969. It * was the first decimal check digit algorithm which detects all single-digit * errors, and all transposition errors involving two adjacent digits. * * <p> * The strengths of the algorithm are that it detects all transliteration and * transposition errors, and additionally most twin, twin jump, jump * transposition and phonetic errors. The main weakness of the Verhoeff * algorithm is its complexity. The calculations required cannot easily be * expressed as a formula. For easy calculation three tables are required:</p> * <ol> * <li>multiplication table</li> * <li>inverse table</li> * <li>permutation table</li> * </ol> * * @see <a href="https://en.wikipedia.org/wiki/Verhoeff_algorithm">Wiki. * Verhoeff algorithm</a> */ public final class Verhoeff { private Verhoeff() { } /** * Table {@code d}. Based on multiplication in the dihedral group D5 and is * simply the Cayley table of the group. Note that this group is not * commutative, that is, for some values of {@code j} and {@code k}, * {@code d(j,k) ≠ d(k, j)}. * * @see <a href="https://en.wikipedia.org/wiki/Dihedral_group">Wiki. * Dihedral group</a> */ private static final byte[][] MULTIPLICATION_TABLE = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, }; /** * The inverse table {@code inv}. Represents the multiplicative inverse of a * digit, that is, the value that satisfies {@code d(j, inv(j)) = 0}. */ private static final byte[] MULTIPLICATIVE_INVERSE = { 0, 4, 3, 2, 1, 5, 6, 7, 8, 9, }; /** * The permutation table {@code p}. Applies a permutation to each digit * based on its position in the number. This is actually a single * permutation {@code (1 5 8 9 4 2 7 0)(3 6)} applied iteratively; i.e. * {@code p(i+j,n) = p(i, p(j,n))}. */ private static final byte[][] PERMUTATION_TABLE = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, }; /** * Check input digits by Verhoeff algorithm. * * @param digits input to check * @return true if check was successful, false otherwise * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static boolean verhoeffCheck(String digits) { checkInput(digits); int[] numbers = toIntArray(digits); // The Verhoeff algorithm int checksum = 0; for (int i = 0; i < numbers.length; i++) { int index = numbers.length - i - 1; byte b = PERMUTATION_TABLE[i % 8][numbers[index]]; checksum = MULTIPLICATION_TABLE[checksum][b]; } return checksum == 0; } /** * Calculate check digit for initial digits and add it tho the last * position. * * @param initialDigits initial value * @return digits with the checksum in the last position * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static String addVerhoeffChecksum(String initialDigits) { checkInput(initialDigits); // Add zero<SUF> var modifiedDigits = initialDigits + "0"; int[] numbers = toIntArray(modifiedDigits); int checksum = 0; for (int i = 0; i < numbers.length; i++) { int index = numbers.length - i - 1; byte b = PERMUTATION_TABLE[i % 8][numbers[index]]; checksum = MULTIPLICATION_TABLE[checksum][b]; } checksum = MULTIPLICATIVE_INVERSE[checksum]; return initialDigits + checksum; } public static void main(String[] args) { System.out.println("Verhoeff algorithm usage examples:"); var validInput = "2363"; var invalidInput = "2364"; checkAndPrint(validInput); checkAndPrint(invalidInput); System.out.println("\nCheck digit generation example:"); var input = "236"; generateAndPrint(input); } private static void checkAndPrint(String input) { String validationResult = Verhoeff.verhoeffCheck(input) ? "valid" : "not valid"; System.out.println("Input '" + input + "' is " + validationResult); } private static void generateAndPrint(String input) { String result = addVerhoeffChecksum(input); System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); } } private static int[] toIntArray(String string) { return string.chars().map(i -> Character.digit(i, 10)).toArray(); } }
315_124
"// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRI(...TRUNCATED)
spring-projects/spring-framework
spring-core/src/main/java/org/springframework/asm/Label.java
7,954
// Overridden Object methods
line_comment
nl
"// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRI(...TRUNCATED)
346_0
"///usr/bin/env jbang \"$0\" \"$@\" ; exit $?\n// //DEPS <dependency1> <dependency2>\n\nimport stati(...TRUNCATED)
eugenp/tutorials
jbang/hello.java
70
///usr/bin/env jbang "$0" "$@" ; exit $?
line_comment
nl
"///usr/bin/env jbang<SUF>\n// //DEPS <dependency1> <dependency2>\n\nimport static java.lang.System.(...TRUNCATED)
404_9
"/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License(...TRUNCATED)
tensorflow/tensorflow
tensorflow/lite/java/src/main/java/org/tensorflow/lite/DataType.java
544
// Boolean size is JVM-dependent.
line_comment
nl
"/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License(...TRUNCATED)
README.md exists but content is empty.
Downloads last month
30