diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..90e2fb4
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,10 @@
+# dependabot analyzing maven dependencies
+version: 2
+updates:
+ - package-ecosystem: "maven"
+ directory: "/"
+ open-pull-requests-limit: 3
+ schedule:
+ interval: "weekly"
+ labels:
+ - "dependencies"
diff --git a/.github/workflows/build_deploy.yml b/.github/workflows/build_deploy.yml
new file mode 100644
index 0000000..cde13a1
--- /dev/null
+++ b/.github/workflows/build_deploy.yml
@@ -0,0 +1,96 @@
+name: Build and Deploy with Maven
+
+on:
+ push:
+ branches:
+ - main
+ tags:
+ - '*' # Trigger on all tags
+ pull_request: { }
+
+env:
+ SONARQUBE_PROJECT: patrickfav_bytes-java
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout Code
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
+ - name: Cache SonarCloud packages
+ uses: actions/cache@v3
+ with:
+ path: ~/.sonar/cache
+ key: ${{ runner.os }}-sonar
+ restore-keys: ${{ runner.os }}-sonar
+ - name: Cache Maven
+ id: cache-primes
+ uses: actions/cache@v3
+ with:
+ path: ~/.m2
+ key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
+ restore-keys: ${{ runner.os }}-m2
+ - name: Set up JDK 11
+ uses: actions/setup-java@v3
+ with:
+ java-version: '11'
+ distribution: 'temurin'
+ - name: Build with Maven
+ run: ./mvnw -B clean verify -DcommonConfig.jarSign.skip=true
+ - name: Analyze with SonaQube
+ if: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
+ SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
+ run: mvn -B org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=$SONARQUBE_PROJECT
+
+ deploy:
+ needs: build
+ if: startsWith(github.ref, 'refs/tags/')
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v3
+ - name: Retrieve Keystore from secrets
+ env:
+ KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
+ run: |
+ echo $KEYSTORE_BASE64 | base64 --decode > keystore.jks
+ - name: Cache Maven
+ id: cache-primes
+ uses: actions/cache@v3
+ with:
+ path: ~/.m2
+ key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
+ restore-keys: ${{ runner.os }}-m2
+ - name: Set up Maven Central Repository
+ uses: actions/setup-java@v3
+ with:
+ java-version: '11'
+ distribution: 'temurin'
+ server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml
+ server-username: MAVEN_USERNAME # env variable for username in deploy
+ server-password: MAVEN_PASSWORD # env variable for token in deploy
+ gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import
+ gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase
+ - name: Publish package
+ run: |
+ ./mvnw -B verify nexus-staging:deploy -P deploy -DskipTests && \
+ ./mvnw -B nexus-staging:release -P deploy
+ env:
+ OPENSOURCE_PROJECTS_KS_PW: ${{ secrets.KEYSTORE_PASSWORD }}
+ OPENSOURCE_PROJECTS_KEY_PW: ${{ secrets.KEYSTORE_KEY_PASSWORD }}
+ MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }}
+ MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }}
+ MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
+ - name: Create and upload Github Release
+ uses: xresloader/upload-to-github-release@v1
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ with:
+ file: "target/*.jar;target/*.sha256;target/checksum-sha256.txt"
+ tags: true
+ draft: false
diff --git a/.mvn/maven.config b/.mvn/maven.config
index b9d8785..f1099e4 100644
--- a/.mvn/maven.config
+++ b/.mvn/maven.config
@@ -1 +1 @@
--DcommonConfig.compiler.profile=jdk7_w_errorprone
+-DcommonConfig.compiler.profile=jdk7
diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java
deleted file mode 100644
index b901097..0000000
--- a/.mvn/wrapper/MavenWrapperDownloader.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright 2007-present the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-import java.net.*;
-import java.io.*;
-import java.nio.channels.*;
-import java.util.Properties;
-
-public class MavenWrapperDownloader {
-
- private static final String WRAPPER_VERSION = "0.5.6";
- /**
- * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
- */
- private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
- + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
-
- /**
- * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
- * use instead of the default one.
- */
- private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
- ".mvn/wrapper/maven-wrapper.properties";
-
- /**
- * Path where the maven-wrapper.jar will be saved to.
- */
- private static final String MAVEN_WRAPPER_JAR_PATH =
- ".mvn/wrapper/maven-wrapper.jar";
-
- /**
- * Name of the property which should be used to override the default download url for the wrapper.
- */
- private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
-
- public static void main(String args[]) {
- System.out.println("- Downloader started");
- File baseDirectory = new File(args[0]);
- System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
-
- // If the maven-wrapper.properties exists, read it and check if it contains a custom
- // wrapperUrl parameter.
- File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
- String url = DEFAULT_DOWNLOAD_URL;
- if(mavenWrapperPropertyFile.exists()) {
- FileInputStream mavenWrapperPropertyFileInputStream = null;
- try {
- mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
- Properties mavenWrapperProperties = new Properties();
- mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
- url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
- } catch (IOException e) {
- System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
- } finally {
- try {
- if(mavenWrapperPropertyFileInputStream != null) {
- mavenWrapperPropertyFileInputStream.close();
- }
- } catch (IOException e) {
- // Ignore ...
- }
- }
- }
- System.out.println("- Downloading from: " + url);
-
- File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
- if(!outputFile.getParentFile().exists()) {
- if(!outputFile.getParentFile().mkdirs()) {
- System.out.println(
- "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
- }
- }
- System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
- try {
- downloadFileFromURL(url, outputFile);
- System.out.println("Done");
- System.exit(0);
- } catch (Throwable e) {
- System.out.println("- Error downloading");
- e.printStackTrace();
- System.exit(1);
- }
- }
-
- private static void downloadFileFromURL(String urlString, File destination) throws Exception {
- if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
- String username = System.getenv("MVNW_USERNAME");
- char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
- Authenticator.setDefault(new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(username, password);
- }
- });
- }
- URL website = new URL(urlString);
- ReadableByteChannel rbc;
- rbc = Channels.newChannel(website.openStream());
- FileOutputStream fos = new FileOutputStream(destination);
- fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
- fos.close();
- rbc.close();
- }
-
-}
diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar
index 2cc7d4a..bf82ff0 100644
Binary files a/.mvn/wrapper/maven-wrapper.jar and b/.mvn/wrapper/maven-wrapper.jar differ
diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties
index 642d572..ca5ab4b 100644
--- a/.mvn/wrapper/maven-wrapper.properties
+++ b/.mvn/wrapper/maven-wrapper.properties
@@ -1,2 +1,18 @@
-distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
-wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# 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.
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.7/apache-maven-3.8.7-bin.zip
+wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index f6b9abc..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,51 +0,0 @@
-# To let the CI execute the maven wrapper, use this command and push the change:
-# git update-index --chmod=+x mvnw
-
-language: java
-jdk:
- - openjdk8
-
-env:
- global:
- - secure: "eV7hLuGYyG1daQIdZ4p2EtSu0vwZSC9aVpEz1/6JWypdAJKu6uLxibHtLXHqSB8PWXDJbpNIhs7gaD8NGBz506U0V+XG1eMYhJ4qonw4Xayk5HATrGW2aWxT1t8W/ZVpb+Z9r3D6N7VvxvbzzV1yUJYc0RJCHT2MklCdjv2CVdZMErDdg3tCQihP7AWm3Z7Ab4+33STcOzNkZNyiOKu9UQBSvu2EoBBrzEbjJo+tZyn4iEC4DVLxA8tLeHi7XTD6DhzgTdyUTM1YAvwNxNrkMewG4tPV8sH+sdj80Qqt4h2Wg+LfoYUwT59HFPcoMdmPauQbaSkqMMjVpwvtWXoJgWCNYRg3Us/7vtml4YTqdj2ao38QvL/QATyOXy/0kilhp32pfyY5hbknxseLr/dShhsrofbThUfxyK8As6FfeIwOywU/TNRl2D7WfQwtAL9nv5RRkNj+EVZjE7J4pl2gL4wn6O18m04stGgkoXSjKa2Zeiy4dd5Nb7FyYSL5CWhMevPVOwUNKZkz3Ys3v/DEmelerCIfFofFlULtyFc4MVWDZpHA2EJd78DC/P3MuiL8aElICRenIpvgHShxFnrGbvomWW60EKuexkM5Hrcn8oyNx7zDPwrqw0hgM8xEZCJymVu01G/JlthjynzFvR7WBxRGwAPxTxBh5adzWZdr6gw="
- - secure: "BqaCKfW/yyBh0jzrMloCxvDECKtg8qa/AxJNlw1IInQPobN7MLH/hGaGtuArG0zfY8pu0w5nGYGkmo/RgW4kgdd/YQ1UIZNS8gBoZh5S7dtSg9EXV+oXlhOfIzictJtL1sJjCGVhzlIRWj5HTysdrAY4Lg/QrjnyX7R5vSdNPnCdDyg7dIsg6r1ROSt8bjQCWxJpNLA3BrG1hvBqP2QLNmlCz7OlFmNPok9PfMumSa8VT8WpqwghrBOCEFf32wRHAkpXjQgQ5biXL2iPgTbEvfoU1ePn9N/OaUYl5mVKcDc1YnTQeMHg7tvciSZ1DZfuiCrTsnnUq8DXVghsjt3zDASlFyTvgf1PSCTjOezNEP/LZw9BXeMo5+bETZLMCcSaSZTUjnNgMRodKPXT3T8v22+5vjvC1NjZCeYdNCt0bxu+/ETdPxh4Lo7L5SNJ/rAurAKXXWt2ARmBrm5nGIiZNyOGjec59Y4ekfDqut87YNmbeqZgxxIoz40EwoRsfT0On7xss8SQi/uKhBwt9i/RW1ihyFAQLymKuSE3ChUkCVwzy/SmTduRUDhoSy982qFMnTPmjMDizfXXP2DjtPqZOExd2/AZsPmAz0N5FjCWciTHWKmhLr358SzgJIpXL+cYkJIR8pk038NKLvzlV0LQb1nrA20iiggjFzyRbwC60oE="
-
-before_install:
- - openssl aes-256-cbc -K $encrypted_b9f5be6a7c0d_key -iv $encrypted_b9f5be6a7c0d_iv -in secrets.tar.enc -out secrets.tar -d
- - tar xvf secrets.tar
-
-script:
- - 'if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then ./mvnw clean install -Djarsigner.skip=true; fi'
- - 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then ./mvnw clean install -Djarsigner.skip=false; fi'
-
-after_success:
- - ./mvnw test jacoco:report coveralls:report
-
-deploy:
- - provider: script
- script: ./mvnw -s ci-settings.xml deploy -X
- skip_cleanup: true
- on:
- branch: master
- tags: true
- - provider: releases
- api_key:
- secure: "ozRga/xe4pNZNH59tmPK1lLpCFa4WFW674JMTBWLbf+7zjPiN8K5dtAYUkhDqngw0ifasukVCRey4F9fu479KlFciGrLBd4r/hq/rh7inVHqd1qcn4AwyDX3EkbloD5qwfas7yn5zJ7cWm7KyEkfpr+fgReaQzSRvJUpjpDBrS2xNIYOhL1tInu84/RtyB6QuJjQOkH9rulP9M8gjcEH9Iu0k40jAVYLJDL9opOWrc9qpAzL0wN4xXGbnI30WrA8nmLcrHRxODOxbYEQ5EndLFJyS3nYxL9D3QJeEYkXf9uqz46V4dgfrEirWrtin3PlSUKTD9/0Mqz4uxqrGky0vrpha7m231+ilTUJzvE0a29LdS3R4A6ssDb0oFtj4pP3O6uNDqZN20r83ughGi0GrlKL/CGpQ4fS5nOpqppx0Xg+SR78/uOqQDIOn570FILBTKiaTsCn6xKqYC4QFSlsZiXojgU4FDZpKygH932qUDE0BnzsZEtzCube2oXMktZs6keSmELMyRYVs/K9yC7+8R1Pez1Xz72zxNG1ke6588sO3wxN+Q+0ZhqmQC8Y2OY8i72b06M5SyGz5TV38SrntLU88HOMWVJtfRDcMcPnJdFgaujZCoOw5SfokzXncipldfJGpKGIb3fHBMJw0MzspT7Kp6XRzSbtJI5+NVestR4="
- file_glob: true
- file:
- - "target/*.jar"
- - "target/*.sha256"
- - "target/checksum-sha256.txt"
- skip_cleanup: true
- on:
- branch: master
- tags: true
-
-cache:
- directories:
- - $HOME/.m2
-
-notifications:
- slack:
- secure: "PiEdsZoQlBR7ce6IT9LlxWod2XqWjm8HCxs4yP8o9iI5ix7FxEV8NDGQKY1vcDG6D8bz4gcNsBxJrPKASD0G3rLaJpjA4L9MUNhyx+4VCIBBnT1fwV+as+PJmr1tZupqUnlxZJyTdiaqkV8jtjCkHUn3P6TURbNuZws74/ki2rICbi4EebD3mdeQvFtWYKTOsAgZjLecMvPU9q+b7TAwDlaZFbkG7DMFruT8i7tA/EWMOvI48kVaUEM0QPsAxNdr32YFta0s/xJyNuOp1Hp3ZZbnZgXgKc2WvGRcg+9sucnQ+eQsQKj1tbWS2YwxHcy7B3Q7YDmBL2NIJIHbuaWNlbK9fVh3gdk7Knlr8IHpLmVuHvH3HAF6JDcrARjk8ViVP2HafkkDNbQZLupz5LkJ02hj1DMGVOAyuVTt6IpOMt3WTaQ66qtyGupQXhrqvq8tDwvg6FIy1sjPZbWE/Sq1s20PYBbHkVwNvQ3bNaC44nAkcnTv+dAoazvy8G40RIPovTO1ubzriZvuY8Db4THF2ZL1mDbyHEJstA7L9qkObqZOwnFsy5pLp4NfR9C/bTAY8EUcZVGm0spIADafip2H57Hf+n3co4aqw689t+Y453AUh3W+k4ZsC/V1kzX3MVdcluRP7ET8ejtfwduMyh2/jFmUK3g246/teEssyohp6ik="
- email: false
diff --git a/CHANGELOG b/CHANGELOG
index 36ef1de..e30ed69 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,5 +1,36 @@
# Releases
+## 1.6.2
+
+* remove hashCode caching since it could introduce very subtle bugs
+
+## v1.6.1
+
+* now build by JDK 11 and removed errorprone compiler #52
+* introduce sonarqube and remove codecov
+* improve javadoc by fixing many typos #53
+* some small bugfixes
+
+## v1.6.0
+
+* migrate to github actions, codecov and maven central #49
+* add `indexOf` (thx @hlyakhovich) #48
+* add `toShortArray` (thx @hlyakhovich) #44
+* add `from()` constructor from `short` vararg or array (thx @hlyakhovich) #45
+* add an automatic module name to support the JPMS (thx @airsquared) #47
+* fix warning of junit 4.13 CVE-2020-15250
+
+## v1.5.0
+
+* fix `leftShift()` and `rightShift()` to respect byte order (thx @gfpeltier)
+* fix `bitAt()` to respect byte order (thx @gfpeltier)
+
+## v1.4.0
+
+* add `from()` constructor from `float[]`
+* add `from()` constructor from `double[]`
+* fix throwing `IllegalArgumentException` instead of `IllegalStateException` in `.toUUID()`
+
## v1.3.0
* improve hex encoder performance by factor 5
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 4a0c2d5..7404d32 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -2,13 +2,13 @@
We ❤ pull requests from everyone.
-If possible proof features and bug fixes with unit tests.
+If possible to proof features and bug fixes with unit tests.
This repo validates against checkstyle (import the xml found in the root to your IDE if possible)
To run the tests (and checkstyle):
```shell
-mvn test
+mvn verify
```
Tests are automatically run against branches and pull requests
diff --git a/README.md b/README.md
index b047dfc..eea6e4b 100644
--- a/README.md
+++ b/README.md
@@ -27,13 +27,14 @@ to blindly paste code snippets from
[o](https://stackoverflow.com/a/9670279/774398)
[m](https://stackoverflow.com/questions/1519736/random-shuffling-of-an-array)
-[](https://bintray.com/patrickfav/maven/bytes-java/_latestVersion)
-[](https://travis-ci.org/patrickfav/bytes-java)
+[](https://mvnrepository.com/artifact/at.favre.lib/bytes)
+[](https://github.com/patrickfav/bytes-java/actions)
[](https://www.javadoc.io/doc/at.favre.lib/bytes)
-[](https://coveralls.io/github/patrickfav/bytes-java?branch=master)
-[](https://codeclimate.com/github/patrickfav/bytes-java/maintainability)
+[](https://sonarcloud.io/summary/new_code?id=patrickfav_bytes-java)
+[](https://sonarcloud.io/summary/new_code?id=patrickfav_bytes-java)
+[](https://sonarcloud.io/summary/new_code?id=patrickfav_bytes-java)
-It's main features include:
+Its main features include:
* **Creation** from a wide variety of sources: multiple arrays, integers, [streams](https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html), random, strings, files, uuid, ...
* **Transformation** with many built-in: append, [xor](https://en.wikipedia.org/wiki/Exclusive_or), [and](https://en.wikipedia.org/wiki/Logical_conjunction), [hash](https://en.wikipedia.org/wiki/Cryptographic_hash_function), [shifts](https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts), shuffle, reverse, [checksum](https://en.wikipedia.org/wiki/Checksum), ...
@@ -137,6 +138,8 @@ Creating byte arrays from **primitive integer** types and arrays:
Bytes.from(8); //00000000 00000000 00000000 00001000
Bytes.from(1897621543227L);
Bytes.from(1634, 88903, 77263);
+Bytes.from(0.7336f, -87263.0f);
+Bytes.from(0.8160183296, 3984639846.0);
```
Initializing **empty arrays** of arbitrary length:
@@ -496,7 +499,7 @@ Conversion to [`InputStream`](https://docs.oracle.com/javase/7/docs/api/java/io/
```java
Bytes.wrap(array).inputStream();
-Bytes.wrap(array).byteBuffer();
+Bytes.wrap(array).buffer();
```
If you just want a duplicated instance, sharing the same array:
@@ -620,11 +623,11 @@ readOnlyBytes.inputStream();
## Download
-The artifacts are deployed to [jcenter](https://bintray.com/bintray/jcenter) and [Maven Central](https://search.maven.org/).
+The artifacts are deployed to [Maven Central](https://search.maven.org/).
### Maven
-Add the dependency of the [latest version](https://github.com/patrickfav/bytes/releases) to your `pom.xml`:
+Add the dependency of the [latest version](https://github.com/patrickfav/bytes-java/releases) to your `pom.xml`:
```xml
* Derived from Google Guava's common/io/ BaseEncoding
*
- * See: https://github.com/google/guava/blob/v26.0/guava/src/com/google/common/io/BaseEncoding.java
+ * See: BaseEncoding
*/
final class BaseEncoding implements BinaryToTextEncoding.EncoderDecoder {
private static final char ASCII_MAX = 127;
@@ -190,7 +190,7 @@ char encode(int bits) {
}
int decode(char ch) {
- return (int) decodabet[ch];
+ return decodabet[ch];
}
}
diff --git a/src/main/java/at/favre/lib/bytes/Bytes.java b/src/main/java/at/favre/lib/bytes/Bytes.java
index 1cb22c4..123eeec 100644
--- a/src/main/java/at/favre/lib/bytes/Bytes.java
+++ b/src/main/java/at/favre/lib/bytes/Bytes.java
@@ -31,7 +31,7 @@
import java.util.*;
/**
- * Bytes is wrapper class for an byte-array that allows a lot of convenience operations on it:
+ * "Bytes" is wrapper class for a byte-array that allows a lot of convenience operations on it:
*
* This class is immutable as long as the internal array is not changed from outside (which can't be assured, when
- * using using
* Example:
*
- * This is usually a number encoding, not a data encoding (ie. leading zeros are not preserved), but this implementation
+ * This is usually a number encoding, not a data encoding (i.e. leading zeros are not preserved), but this implementation
* tries to preserve the leading zeros, to keep the in/output byte length size the same, but use at your own risk!
*
* @param radixNumberString the encoded string
@@ -598,7 +628,7 @@ public static Bytes parseRadix(CharSequence radixNumberString, int radix) {
*
- * This is usually a number encoding, not a data encoding (ie. leading zeros are not preserved), but this implementation
+ * This is usually a number encoding, not a data encoding (i.e. leading zeros are not preserved), but this implementation
* tries to preserve the leading zeros, to keep the in/output byte length size the same.
*
* @param base36String the encoded string
@@ -715,7 +745,6 @@ public static Bytes random(int length, Random random) {
private final byte[] byteArray;
private final ByteOrder byteOrder;
private final BytesFactory factory;
- private transient int hashCodeCache;
Bytes(byte[] byteArray, ByteOrder byteOrder) {
this(byteArray, byteOrder, new Factory());
@@ -736,7 +765,7 @@ public static Bytes random(int length, Random random) {
/* TRANSFORMER **********************************************************************************************/
/**
- * Creates a new instance with the current array appended to the provided data (ie. append at the end).
+ * Creates a new instance with the current array appended to the provided data (i.e. append at the end).
*
* This will create a new byte array internally, so it is not suitable to use as extensive builder pattern -
* use {@link ByteBuffer} or {@link java.io.ByteArrayOutputStream} for that.
@@ -749,7 +778,7 @@ public Bytes append(Bytes bytes) {
}
/**
- * Creates a new instance with the current array appended to the provided data (ie. append at the end)
+ * Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* @param singleByte to append
* @return appended instance
@@ -759,7 +788,7 @@ public Bytes append(byte singleByte) {
}
/**
- * Creates a new instance with the current array appended to the provided data (ie. append at the end)
+ * Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* @param char2Bytes to append
* @return appended instance
@@ -769,7 +798,7 @@ public Bytes append(char char2Bytes) {
}
/**
- * Creates a new instance with the current array appended to the provided data (ie. append at the end)
+ * Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* @param short2Bytes to append
* @return appended instance
@@ -779,7 +808,7 @@ public Bytes append(short short2Bytes) {
}
/**
- * Creates a new instance with the current array appended to the provided data (ie. append at the end)
+ * Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* @param integer4Bytes to append
* @return appended instance
@@ -789,7 +818,7 @@ public Bytes append(int integer4Bytes) {
}
/**
- * Creates a new instance with the current array appended to the provided data (ie. append at the end)
+ * Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* @param long8Bytes to append
* @return appended instance
@@ -799,7 +828,7 @@ public Bytes append(long long8Bytes) {
}
/**
- * Creates a new instance with the current array appended to the provided data (ie. append at the end).
+ * Creates a new instance with the current array appended to the provided data (i.e. append at the end).
* You may use this to append multiple byte arrays without the need for chaining the {@link #append(byte[])} call
* and therefore generating intermediate copies of the byte array, making this approach use less memory.
*
@@ -811,7 +840,7 @@ public Bytes append(byte[]... arrays) {
}
/**
- * Creates a new instance with the current array appended to the provided data (ie. append at the end)
+ * Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* @param secondArray to append
* @return appended instance
@@ -821,7 +850,7 @@ public Bytes append(byte[] secondArray) {
}
/**
- * Creates a new instance with the current array appended to the provided data (ie. append at the end)
+ * Creates a new instance with the current array appended to the provided data (i.e. append at the end)
*
* If given array is null, the nothing will be appended.
*
@@ -947,7 +976,11 @@ public Bytes not() {
* @see Bit shifts
*/
public Bytes leftShift(int shiftCount) {
- return transform(new BytesTransformer.ShiftTransformer(shiftCount, BytesTransformer.ShiftTransformer.Type.LEFT_SHIFT));
+ return transform(new BytesTransformer.ShiftTransformer(
+ shiftCount,
+ BytesTransformer.ShiftTransformer.Type.LEFT_SHIFT,
+ byteOrder
+ ));
}
/**
@@ -962,11 +995,15 @@ public Bytes leftShift(int shiftCount) {
* @see Bit shifts
*/
public Bytes rightShift(int shiftCount) {
- return transform(new BytesTransformer.ShiftTransformer(shiftCount, BytesTransformer.ShiftTransformer.Type.RIGHT_SHIFT));
+ return transform(new BytesTransformer.ShiftTransformer(
+ shiftCount,
+ BytesTransformer.ShiftTransformer.Type.RIGHT_SHIFT,
+ byteOrder
+ ));
}
/**
- * Returns a Byte whose value is equivalent to this Byte with the designated bit set to newBitValue. Bits start to count from the LSB (ie. Bytes.from(0).switchBit(0,true) == 1)
+ * Returns a Byte whose value is equivalent to this Byte with the designated bit set to newBitValue. Bits start to count from the LSB (i.e. Bytes.from(0).switchBit(0,true) == 1)
*
* @param bitPosition not to confuse with byte position
* @param newBitValue if true set to 1, 0 otherwise
@@ -1025,7 +1062,7 @@ public Bytes reverse() {
* copy but not the original, the copy will contain {@code (byte)0}.
*
* Resize from LSB or length, so an array [0,1,2,3] resized to 3 will result in [1,2,3] or resized to 5 [0,0,1,2,3].
- * So when a 8 byte value resized to 4 byte will result in the same 32 bit integer value
+ * So when an 8 byte value resized to 4 byte will result in the same 32-bit integer value
*
* @param newByteLength the length of the copy to be returned
* @return a copy with the desired size or "this" instance if newByteLength == current length
@@ -1061,7 +1098,7 @@ public Bytes resize(int newByteLength, BytesTransformer.ResizeTransformer.Mode m
* Calculates md5 on the underlying byte array and returns a byte instance containing the hash.
* This hash algorithm SHOULD be supported by every JVM implementation (see
* Javadoc for MessageDigest)
- *
+ *
* Do not use this algorithm in security relevant applications.
*
* @return md5 (16 bytes) hash of internal byte array
@@ -1076,7 +1113,7 @@ public Bytes hashMd5() {
* Calculates sha1 on the underlying byte array and returns a byte instance containing the hash.
* This hash algorithm SHOULD be supported by every JVM implementation (see
* Javadoc for MessageDigest)
- *
+ *
* Do not use this algorithm in security relevant applications.
*
* @return sha1 (20 bytes) hash of internal byte array
@@ -1113,9 +1150,9 @@ public Bytes hash(String algorithm) {
/**
* Generic transformation of this instance.
*
- * This transformation might be done in-place (ie. without copying the internal array and overwriting its old state),
+ * This transformation might be done in-place (i.e. without copying the internal array and overwriting its old state),
* or on a copy of the internal data, depending on the type (e.g. {@link MutableBytes}) and if the operation can be done
- * in-place. Therefore the caller has to ensure that certain side-effects, which occur due to the changing of the internal
+ * in-place. Therefore, the caller has to ensure that certain side effects, which occur due to the changing of the internal
* data, do not create bugs in his/her code. Usually immutability is preferred, but when handling many or big byte arrays,
* mutability enables drastically better performance.
*
@@ -1161,7 +1198,7 @@ public int length() {
/**
* The bit length of the underlying byte array.
*
- * @return bit length
+ * @return the bit length
*/
public int lengthBit() {
return length() * 8;
@@ -1189,7 +1226,7 @@ public ByteOrder byteOrder() {
/**
* Checks if instance is mutable
*
- * @return true if mutable, ie. transformers will change internal array
+ * @return true if mutable, i.e. transformers will change internal array
*/
public boolean isMutable() {
return false;
@@ -1239,6 +1276,20 @@ public int indexOf(byte target, int fromIndex) {
return indexOf(new byte[]{target}, fromIndex);
}
+ /**
+ * Returns the index of the first appearance of the value {@code target} in
+ * {@code array} from given start index 'fromIndex' to given end index 'toIndex'.
+ *
+ * @param target a primitive {@code byte} value
+ * @param fromIndex search from this index
+ * @param toIndex search to this index
+ * @return the least index {@code i} for which {@code array[i] == target}, or
+ * {@code -1} if no such index exists or fromIndex is gt target length.
+ */
+ public int indexOf(byte target, int fromIndex, int toIndex) {
+ return indexOf(new byte[]{target}, fromIndex, toIndex);
+ }
+
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
@@ -1273,6 +1324,25 @@ public int indexOf(byte[] subArray, int fromIndex) {
return Util.Byte.indexOf(internalArray(), subArray, fromIndex, length());
}
+ /**
+ * Returns the start position of the first occurrence of the specified {@code
+ * target} within {@code array} from given start index 'fromIndex' to given end
+ * index 'toIndex', or {@code -1} if there is no such occurrence.
+ *
+ * More formally, returns the lowest index {@code i} such that {@code
+ * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
+ * the same elements as {@code target}.
+ *
+ * @param subArray the array to search for as a sub-sequence of {@code array}
+ * @param fromIndex search from this index
+ * @param toIndex search to this index
+ * @return the least index {@code i} for which {@code array[i] == target}, or
+ * {@code -1} if no such index exists.
+ */
+ public int indexOf(byte[] subArray, int fromIndex, int toIndex) {
+ return Util.Byte.indexOf(internalArray(), subArray, fromIndex, toIndex);
+ }
+
/**
* Checks if the given sub array is equal to the start of given array. That is, sub array must be gt or eq
* to the length of the internal array and
- * This option is important for all encoding and conversation methods.
+ * This option is important for all encoding and conversion methods.
*
* @param byteOrder new byteOrder
* @return a new instance with the same underlying array and new order, or "this" if order is the same
@@ -1531,7 +1605,7 @@ public InputStream inputStream() {
/**
* The reference of te internal byte-array. This call requires no conversation or additional memory allocation.
*
- * Modifications to this bytes's content will cause the returned
+ * Modifications to these byte's content will cause the returned
* array's content to be modified, and vice versa.
*
* @return the direct reference of the internal byte array
@@ -1587,12 +1661,12 @@ public String encodeDec() {
/**
* Encodes the internal array in given radix representation (e.g. 2 = binary, 10 = decimal, 16 = hex).
*
- * This is usually a number encoding, not a data encoding (ie. leading zeros are not preserved), but this implementation
+ * This is usually a number encoding, not a data encoding (i.e. leading zeros are not preserved), but this implementation
* tries to preserve the leading zeros, to keep the in/output byte length size the same. To preserve the length padding
* would be required, but is not supported in this implementation.
*
* But still full disclaimer:
- *
+ *
* This is NOT recommended for data encoding, only for number encoding
*
* See Radix Economy and {@link BigInteger#toString(int)}.
@@ -1793,7 +1867,7 @@ public BitSet toBitSet() {
* The internal byte array wrapped in a {@link BigInteger} instance.
*
* If the internal byte order is {@link ByteOrder#LITTLE_ENDIAN}, a copy of the internal
- * array will be reversed and used as backing array with the big integer. Otherwise the internal
+ * array will be reversed and used as backing array with the big integer. Otherwise, the internal
* array will be used directly.
*
* @return big integer
@@ -1812,11 +1886,10 @@ public BigInteger toBigInteger() {
* to a {@link UUID} constructor.
*
* @return newly created UUID
+ * @throws IllegalArgumentException if byte array has length not equal to 16
*/
public UUID toUUID() {
- if (length() != 16) {
- throw new IllegalStateException("creating UUID requires internal array to be exactly 16 bytes, was " + length());
- }
+ Util.Validation.checkExactLength(length(), 16, "UUID");
ByteBuffer byteBuffer = buffer();
return new UUID(byteBuffer.getLong(), byteBuffer.getLong());
}
@@ -1828,7 +1901,7 @@ public UUID toUUID() {
* If you just want to get the first element as {@code byte}, see {@link #byteAt(int)}, using index zero.
*
* @return the byte representation
- * @throws IllegalStateException if byte array has length not equal to 1
+ * @throws IllegalArgumentException if byte array has length not equal to 1
* @see Primitive Types
*/
public byte toByte() {
@@ -1843,7 +1916,7 @@ public byte toByte() {
* If you just want to get the first element as {@code byte}, see {@link #byteAt(int)}, using index zero.
*
* @return the unsigned byte representation wrapped in an int
- * @throws IllegalStateException if byte array has length not equal to 1
+ * @throws IllegalArgumentException if byte array has length not equal to 1
* @see Primitive Types
*/
public int toUnsignedByte() {
@@ -1858,7 +1931,7 @@ public int toUnsignedByte() {
* If you just want to get the first 2 bytes as {@code char}, see {@link #charAt(int)} using index zero.
*
* @return the int representation
- * @throws IllegalStateException if byte array has length not equal to 2
+ * @throws IllegalArgumentException if byte array has length not equal to 2
* @see Primitive Types
*/
public char toChar() {
@@ -1873,7 +1946,7 @@ public char toChar() {
* If you just want to get the first 2 bytes as {@code short}, see {@link #shortAt(int)} using index zero.
*
* @return the int representation
- * @throws IllegalStateException if byte array has length not equal to 2
+ * @throws IllegalArgumentException if byte array has length not equal to 2
* @see Primitive Types
*/
public short toShort() {
@@ -1888,7 +1961,7 @@ public short toShort() {
* If you just want to get the first 4 bytes as {@code int}, see {@link #intAt(int)} using index zero.
*
* @return the int representation
- * @throws IllegalStateException if byte array has length not equal to 4
+ * @throws IllegalArgumentException if byte array has length not equal to 4
* @see Primitive Types
*/
public int toInt() {
@@ -1922,7 +1995,7 @@ public int[] toIntArray() {
* If you just want to get the first 4 bytes as {@code long}, see {@link #longAt(int)} using index zero.
*
* @return the long representation
- * @throws IllegalStateException if byte array has length not equal to 8
+ * @throws IllegalArgumentException if byte array has length not equal to 8
* @see Primitive Types
*/
public long toLong() {
@@ -1931,7 +2004,7 @@ public long toLong() {
}
/**
- * Converts the internal byte array to an long array, that is, every 8 bytes will be packed into a single long.
+ * Converts the internal byte array to a long array, that is, every 8 bytes will be packed into a single long.
*
* E.g. 8 bytes will be packed to a length 1 long array:
*
* E.g. 4 bytes will be packed to a length 1 float array:
*
* E.g. 8 bytes will be packed to a length 1 double array:
*
+ * E.g. 2 bytes will be packed to a length 1 short array:
+ *
+ * This conversion respects the internal byte order. Will only work if all bytes can be directly mapped to short,
+ * which means the byte array length must be dividable by 2 without rest.
+ *
+ * @return new short[] instance representing this byte array
+ * @throws IllegalArgumentException if internal byte length mod 2 != 0
+ */
+ public short[] toShortArray() {
+ Util.Validation.checkModLength(length(), 2, "creating a short array");
+ return Util.Converter.toShortArray(internalArray(), byteOrder);
+ }
+
/**
* Decodes the internal byte array to UTF-8 char array.
* This implementation will not internally create a {@link String}.
@@ -2043,7 +2135,7 @@ public char[] toCharArray(Charset charset) {
* Pairs of {@code byte} elements are compared as if by invoking
* {@link Byte#compare(byte, byte)}.
*
- * Uses {@link ByteBuffer#compareTo(Object)} internally.
+ * Uses {@link ByteBuffer#compareTo(ByteBuffer)} internally.
*
* @return A negative integer, zero, or a positive integer as this buffer
* is less than, equal to, or greater than the given buffer
@@ -2085,7 +2177,7 @@ public boolean equals(byte[] anotherArray) {
* will not break on the first mismatch. This method is useful to prevent some side-channel attacks,
* but is slower on average.
*
- * This implementation uses the algorithm suggested in https://codahale.com/a-lesson-in-timing-attacks/
+ * This implementation uses the algorithm suggested in a-lesson-in-timing-attacks
*
* @param anotherArray to compare with
* @return true if {@link Arrays#equals(byte[], byte[])} returns true on given and internal array
@@ -2128,10 +2220,7 @@ public boolean equalsContent(Bytes other) {
@Override
public int hashCode() {
- if (hashCodeCache == 0) {
- hashCodeCache = Util.Obj.hashCode(internalArray(), byteOrder());
- }
- return hashCodeCache;
+ return Util.Obj.hashCode(internalArray(), byteOrder());
}
/**
diff --git a/src/main/java/at/favre/lib/bytes/BytesTransformer.java b/src/main/java/at/favre/lib/bytes/BytesTransformer.java
index 3612505..efdd12c 100644
--- a/src/main/java/at/favre/lib/bytes/BytesTransformer.java
+++ b/src/main/java/at/favre/lib/bytes/BytesTransformer.java
@@ -21,6 +21,7 @@
package at.favre.lib.bytes;
+import java.nio.ByteOrder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
@@ -131,10 +132,12 @@ public enum Type {
private final int shiftCount;
private final Type type;
+ private final ByteOrder byteOrder;
- ShiftTransformer(int shiftCount, Type type) {
+ ShiftTransformer(int shiftCount, Type type, ByteOrder byteOrder) {
this.shiftCount = shiftCount;
this.type = Objects.requireNonNull(type, "passed shift type must not be null");
+ this.byteOrder = Objects.requireNonNull(byteOrder, "passed byteOrder type must not be null");
}
@Override
@@ -143,10 +146,10 @@ public byte[] transform(byte[] currentArray, boolean inPlace) {
switch (type) {
case RIGHT_SHIFT:
- return Util.Byte.shiftRight(out, shiftCount);
+ return Util.Byte.shiftRight(out, shiftCount, byteOrder);
default:
case LEFT_SHIFT:
- return Util.Byte.shiftLeft(out, shiftCount);
+ return Util.Byte.shiftLeft(out, shiftCount, byteOrder);
}
}
@@ -228,7 +231,7 @@ public boolean supportInPlaceTransformation() {
* contain identical values. For any indices that are valid in the
* copy but not the original, the copy will contain {@code (byte)0}.
*
- * If if the internal array will be grown, zero bytes will be added on the left,
+ * If the internal array will be increased, zero bytes will be added on the left,
* keeping the value the same.
*/
final class ResizeTransformer implements BytesTransformer {
@@ -262,10 +265,12 @@ public byte[] transform(byte[] currentArray, boolean inPlace) {
byte[] resizedArray = new byte[newSize];
if (mode == Mode.RESIZE_KEEP_FROM_MAX_LENGTH) {
+ int max = Math.max(0, Math.abs(newSize - currentArray.length));
+
if (newSize > currentArray.length) {
- System.arraycopy(currentArray, 0, resizedArray, Math.max(0, Math.abs(newSize - currentArray.length)), Math.min(newSize, currentArray.length));
+ System.arraycopy(currentArray, 0, resizedArray, max, currentArray.length);
} else {
- System.arraycopy(currentArray, Math.max(0, Math.abs(newSize - currentArray.length)), resizedArray, Math.min(0, Math.abs(newSize - currentArray.length)), Math.min(newSize, currentArray.length));
+ System.arraycopy(currentArray, max, resizedArray, 0, newSize);
}
} else {
System.arraycopy(currentArray, 0, resizedArray, 0, Math.min(currentArray.length, resizedArray.length));
diff --git a/src/main/java/at/favre/lib/bytes/BytesTransformers.java b/src/main/java/at/favre/lib/bytes/BytesTransformers.java
index f2ae0c7..c1914c0 100644
--- a/src/main/java/at/favre/lib/bytes/BytesTransformers.java
+++ b/src/main/java/at/favre/lib/bytes/BytesTransformers.java
@@ -4,7 +4,6 @@
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.IOException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Comparator;
@@ -45,7 +44,7 @@ public static BytesTransformer shuffle(Random random) {
}
/**
- * Create a {@link BytesTransformer} which sorts the internal byte array with it's natural ordering treating
+ * Create a {@link BytesTransformer} which sorts the internal byte array with its natural ordering treating
* each byte as signed byte (-128...127). Using inplace sorting, this can be reasonable fast.
*
* @return transformer
@@ -55,9 +54,9 @@ public static BytesTransformer sort() {
}
/**
- * Create a {@link BytesTransformer} which sorts the internal byte array with it's natural ordering treating
+ * Create a {@link BytesTransformer} which sorts the internal byte array with its natural ordering treating
* each byte as unsigned byte (0...255). That is, the byte string {@code ff} sorts after {@code 00}.
- *
+ *
* Note: this requires 2 copies of the internal array and a lot of unboxing due to
* the fact that no primitives are not allowed as generic type arguments - so only use on small arrays.
*
@@ -69,7 +68,7 @@ public static BytesTransformer sortUnsigned() {
/**
* Create a {@link BytesTransformer} which sorts the internal byte array according to given comparator.
- *
+ *
* Note: this requires 2 copies of the internal array and a lot of unboxing due to
* the fact that no primitives are not allowed as generic type arguments - so only use on small arrays.
*
@@ -193,7 +192,7 @@ public boolean supportInPlaceTransformation() {
* Sorts the internal byte array with given {@link java.util.Comparator}
*/
public static final class SortTransformer implements BytesTransformer {
- private final Comparator comparator;
+ private final Comparator
* Analysis
@@ -189,7 +189,7 @@ static int countByte(byte[] array, byte target) {
}
/**
- * Counts the times given pattern (ie. an array) can be found in given array
+ * Counts the times given pattern (i.e. an array) can be found in given array
*
*
* Analysis
@@ -226,7 +226,7 @@ static int countByteArray(byte[] array, byte[] pattern) {
* Simple Durstenfeld shuffle.
* This will shuffle given array and will not make a copy, so beware.
*
- * See: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
+ * See: Yates_shuffle
*
*
* Analysis
@@ -291,25 +291,42 @@ static void reverse(byte[] array, int fromIndex, int toIndex) {
*
* @param byteArray to shift
* @param shiftBitCount how many bits to shift
+ * @param byteOrder endianness of given byte array
* @return shifted byte array
*/
- static byte[] shiftLeft(byte[] byteArray, int shiftBitCount) {
+ static byte[] shiftLeft(byte[] byteArray, int shiftBitCount, ByteOrder byteOrder) {
final int shiftMod = shiftBitCount % 8;
final byte carryMask = (byte) ((1 << shiftMod) - 1);
final int offsetBytes = (shiftBitCount / 8);
int sourceIndex;
- for (int i = 0; i < byteArray.length; i++) {
- sourceIndex = i + offsetBytes;
- if (sourceIndex >= byteArray.length) {
- byteArray[i] = 0;
- } else {
- byte src = byteArray[sourceIndex];
- byte dst = (byte) (src << shiftMod);
- if (sourceIndex + 1 < byteArray.length) {
- dst |= byteArray[sourceIndex + 1] >>> (8 - shiftMod) & carryMask;
+ if (byteOrder == ByteOrder.BIG_ENDIAN) {
+ for (int i = 0; i < byteArray.length; i++) {
+ sourceIndex = i + offsetBytes;
+ if (sourceIndex >= byteArray.length) {
+ byteArray[i] = 0;
+ } else {
+ byte src = byteArray[sourceIndex];
+ byte dst = (byte) (src << shiftMod);
+ if (sourceIndex + 1 < byteArray.length) {
+ dst |= byteArray[sourceIndex + 1] >>> (8 - shiftMod) & carryMask & 0xff;
+ }
+ byteArray[i] = dst;
+ }
+ }
+ } else {
+ for (int i = byteArray.length - 1; i >= 0; i--) {
+ sourceIndex = i - offsetBytes;
+ if (sourceIndex < 0) {
+ byteArray[i] = 0;
+ } else {
+ byte src = byteArray[sourceIndex];
+ byte dst = (byte) (src << shiftMod);
+ if (sourceIndex - 1 >= 0) {
+ dst |= byteArray[sourceIndex - 1] >>> (8 - shiftMod) & carryMask & 0xff;
+ }
+ byteArray[i] = dst;
}
- byteArray[i] = dst;
}
}
return byteArray;
@@ -330,25 +347,42 @@ static byte[] shiftLeft(byte[] byteArray, int shiftBitCount) {
*
* @param byteArray to shift
* @param shiftBitCount how many bits to shift
+ * @param byteOrder endianness of given byte array
* @return shifted byte array
*/
- static byte[] shiftRight(byte[] byteArray, int shiftBitCount) {
+ static byte[] shiftRight(byte[] byteArray, int shiftBitCount, ByteOrder byteOrder) {
final int shiftMod = shiftBitCount % 8;
final byte carryMask = (byte) (0xFF << (8 - shiftMod));
final int offsetBytes = (shiftBitCount / 8);
int sourceIndex;
- for (int i = byteArray.length - 1; i >= 0; i--) {
- sourceIndex = i - offsetBytes;
- if (sourceIndex < 0) {
- byteArray[i] = 0;
- } else {
- byte src = byteArray[sourceIndex];
- byte dst = (byte) ((0xff & src) >>> shiftMod);
- if (sourceIndex - 1 >= 0) {
- dst |= byteArray[sourceIndex - 1] << (8 - shiftMod) & carryMask;
+ if (byteOrder == ByteOrder.BIG_ENDIAN) {
+ for (int i = byteArray.length - 1; i >= 0; i--) {
+ sourceIndex = i - offsetBytes;
+ if (sourceIndex < 0) {
+ byteArray[i] = 0;
+ } else {
+ byte src = byteArray[sourceIndex];
+ byte dst = (byte) ((0xff & src) >>> shiftMod);
+ if (sourceIndex - 1 >= 0) {
+ dst |= byteArray[sourceIndex - 1] << (8 - shiftMod) & carryMask & 0xff;
+ }
+ byteArray[i] = dst;
+ }
+ }
+ } else {
+ for (int i = 0; i < byteArray.length; i++) {
+ sourceIndex = i + offsetBytes;
+ if (sourceIndex >= byteArray.length) {
+ byteArray[i] = 0;
+ } else {
+ byte src = byteArray[sourceIndex];
+ byte dst = (byte) ((0xff & src) >>> shiftMod);
+ if (sourceIndex + 1 < byteArray.length) {
+ dst |= byteArray[sourceIndex + 1] << (8 - shiftMod) & carryMask & 0xff;
+ }
+ byteArray[i] = dst;
}
- byteArray[i] = dst;
}
}
return byteArray;
@@ -384,7 +418,7 @@ static boolean constantTimeEquals(byte[] array, byte[] anotherArray) {
* Calculates the entropy factor of a byte array.
*
* This implementation will not create a copy of the internal array and will only internally initialize
- * a int array with 256 elements as temporary buffer.
+ * an int array with 256 elements as temporary buffer.
*
*
* Analysis
@@ -462,7 +496,7 @@ static byte[] toArray(Collection
@@ -510,7 +544,7 @@ static List
@@ -533,6 +567,33 @@ static byte[] toPrimitiveArray(java.lang.Byte[] objectArray) {
return primitivesArray;
}
+ /**
+ * Creates a byte array from given short array.
+ * The resulting byte array will have length shortArray * 2.
+ *
+ *
+ * Analysis
+ *
+ * Analysis
+ *
+ * Analysis
+ *
+ * Analysis
+ *
*
wrap()). It is possible to create a mutable version (see {@link MutableBytes}).
+ * using wrap()). It is possible to create a mutable version (see {@link MutableBytes}).
*
@@ -92,7 +92,7 @@ public static Bytes allocate(int length, byte defaultValue) {
}
/**
- * Creates an Byte instance with an internal empty byte array. Same as calling {@link #allocate(int)} with 0.
+ * Creates a Byte instance with an internal empty byte array. Same as calling {@link #allocate(int)} with 0.
*
* @return the empty instance (always the same reference
*/
@@ -108,7 +108,7 @@ public static Bytes empty() {
* @return new instance
*/
public static Bytes wrap(Bytes bytes) {
- return wrap(bytes.internalArray(), bytes.byteOrder);
+ return wrap(Objects.requireNonNull(bytes, "passed Byte instance must not be null").internalArray(), bytes.byteOrder);
}
/**
@@ -296,6 +296,16 @@ public static Bytes from(short short2Byte) {
return wrap(ByteBuffer.allocate(2).putShort(short2Byte).array());
}
+ /**
+ * Creates a new instance from given 2 byte short array.
+ *
+ * @param shortArray to create from
+ * @return new instance
+ */
+ public static Bytes from(short... shortArray) {
+ return wrap(Util.Converter.toByteArray(Objects.requireNonNull(shortArray, "must provide at least a single short")));
+ }
+
/**
* Creates a new instance from given 4 byte integer.
*
@@ -346,6 +356,16 @@ public static Bytes from(float float4byte) {
return wrap(ByteBuffer.allocate(4).putFloat(float4byte).array());
}
+ /**
+ * Creates a new instance from given float array.
+ *
+ * @param floatArray to create from
+ * @return new instance
+ */
+ public static Bytes from(float... floatArray) {
+ return wrap(Util.Converter.toByteArray(Objects.requireNonNull(floatArray, "must provide at least a single float")));
+ }
+
/**
* Creates a new instance from given 8 byte floating point number (double).
*
@@ -356,6 +376,16 @@ public static Bytes from(double double8Byte) {
return wrap(ByteBuffer.allocate(8).putDouble(double8Byte).array());
}
+ /**
+ * Creates a new instance from given double array.
+ *
+ * @param doubleArray to create from
+ * @return new instance
+ */
+ public static Bytes from(double... doubleArray) {
+ return wrap(Util.Converter.toByteArray(Objects.requireNonNull(doubleArray, "must provide at least a single double")));
+ }
+
/**
* Creates a new instance from given {@link ByteBuffer}.
* Will use the same backing byte array and honour the buffer's byte order.
@@ -421,7 +451,7 @@ public static Bytes from(InputStream stream) {
/**
* Reads given input stream up to maxLength and creates a new instance from read data.
- * Read maxLength is never longer than stream size (ie. maxLength is only limiting, not assuring maxLength)
+ * Read maxLength is never longer than stream size (i.e. maxLength is only limiting, not assuring maxLength)
*
* @param stream to read from
* @param maxLength read to this maxLength or end of stream
@@ -538,7 +568,7 @@ public static Bytes from(char[] charArray, Charset charset, int offset, int leng
/**
* Convert UUID to a newly generated 16 byte long array representation. Puts the 8 byte most significant bits and
- * 8 byte least significant bits into an byte array.
+ * 8 byte the least significant bits into a byte array.
*
* @param uuid to convert to array
* @return new instance
@@ -581,7 +611,7 @@ public static Bytes parseDec(CharSequence decString) {
* Encodes with given radix string representation (e.g. radix 16 would be hex).
* See also {@link BigInteger#toString(int)}.
*
*
*
* @param hexString the encoded string
@@ -624,7 +654,7 @@ public static Bytes parseBase32(CharSequence base32Rfc4648String) {
/**
* Parsing of base36 encoded byte arrays.
* a-f (also mixed case)0x which will be ignoredinternal[i] == subArray[i] for i=0..subArray.length-1
@@ -1313,12 +1383,16 @@ public boolean endsWith(byte[] subArray) {
* 1000 0000 has bitAt(0) == false and bitAt(7) == true.
*
* @param bitIndex the index of the {@code bit} value.
- * @return true if bit at given index is set, false otherwise
+ * @return true if the bit at given index is set, false otherwise
* @throws IndexOutOfBoundsException if the {@code bitIndex} argument is negative or not less than the length of this array in bits.
*/
public boolean bitAt(int bitIndex) {
Util.Validation.checkIndexBounds(lengthBit(), bitIndex, 1, "bit");
- return ((byteAt(length() - 1 - (bitIndex / 8)) >>> bitIndex % 8) & 1) != 0;
+ if (byteOrder == ByteOrder.BIG_ENDIAN) {
+ return ((byteAt(length() - 1 - (bitIndex / 8)) >>> bitIndex % 8) & 1) != 0;
+ } else {
+ return ((byteAt(bitIndex / 8) >>> bitIndex % 8) & 1) != 0;
+ }
}
/**
@@ -1359,7 +1433,7 @@ public int unsignedByteAt(int index) {
*/
public char charAt(int index) {
Util.Validation.checkIndexBounds(length(), index, 2, "char");
- return ((ByteBuffer) internalBuffer().position(index)).getChar();
+ return internalBuffer().position(index).getChar();
}
/**
@@ -1372,7 +1446,7 @@ public char charAt(int index) {
*/
public short shortAt(int index) {
Util.Validation.checkIndexBounds(length(), index, 2, "short");
- return ((ByteBuffer) internalBuffer().position(index)).getShort();
+ return internalBuffer().position(index).getShort();
}
/**
@@ -1385,7 +1459,7 @@ public short shortAt(int index) {
*/
public int intAt(int index) {
Util.Validation.checkIndexBounds(length(), index, 4, "int");
- return ((ByteBuffer) internalBuffer().position(index)).getInt();
+ return internalBuffer().position(index).getInt();
}
/**
@@ -1398,7 +1472,7 @@ public int intAt(int index) {
*/
public long longAt(int index) {
Util.Validation.checkIndexBounds(length(), index, 8, "long");
- return ((ByteBuffer) internalBuffer().position(index)).getLong();
+ return internalBuffer().position(index).getLong();
}
/**
@@ -1460,7 +1534,7 @@ public Bytes duplicate() {
/**
* Set the byte order or endianness of this instance. Default in Java is {@link ByteOrder#BIG_ENDIAN}.
*
@@ -1954,7 +2027,7 @@ public long[] toLongArray() {
* representation for a Java float value. The output is dependent on the set {@link #byteOrder()}.
*
* @return the float representation
- * @throws IllegalStateException if byte array has length not equal to 4
+ * @throws IllegalArgumentException if byte array has length not equal to 4
* @see Primitive Types
*/
public float toFloat() {
@@ -1963,7 +2036,7 @@ public float toFloat() {
}
/**
- * Converts the internal byte array to an float array, that is, every 4 bytes will be packed into a single float.
+ * Converts the internal byte array to a float array, that is, every 4 bytes will be packed into a single float.
*
@@ -1986,7 +2059,7 @@ public float[] toFloatArray() {
* representation for a Java double value. The output is dependent on the set {@link #byteOrder()}.
*
* @return the double representation
- * @throws IllegalStateException if byte array has length not equal to 8
+ * @throws IllegalArgumentException if byte array has length not equal to 8
* @see Primitive Types
*/
public double toDouble() {
@@ -1995,7 +2068,7 @@ public double toDouble() {
}
/**
- * Converts the internal byte array to an double array, that is, every 8 bytes will be packed into a single double.
+ * Converts the internal byte array to a double array, that is, every 8 bytes will be packed into a single double.
*
@@ -2013,6 +2086,25 @@ public double[] toDoubleArray() {
return Util.Converter.toDoubleArray(internalArray(), byteOrder);
}
+ /**
+ * Converts the internal byte array to a short array, that is, every 2 bytes will be packed into a single short.
+ *
+ * [b1, b2] = [short1]
+ *
+ *
+ *
+ * O(n)O(n)false
+ *
+ * O(n)O(n)false
+ *
+ * O(n)O(n)false
* [b1, b2, b3, b4, b5, b6, b7, b8] = [long1]
@@ -719,7 +834,7 @@ static long[] toLongArray(byte[] bytes, ByteOrder byteOrder) {
}
/**
- * Converts the byte array to an float array. This will spread 4 bytes into a single float:
+ * Converts the byte array to a float array. This will spread 4 bytes into a single float:
*
*
* [b1, b2, b3, b4] = [float1]
@@ -746,7 +861,7 @@ static float[] toFloatArray(byte[] bytes, ByteOrder byteOrder) {
}
/**
- * Converts the byte array to an double array. This will spread 8 bytes into a single double:
+ * Converts the byte array to a double array. This will spread 8 bytes into a single double:
*
*
* [b1, b2, b3, b4, b5, b6, b7, b8] = [double1]
@@ -772,9 +887,36 @@ static double[] toDoubleArray(byte[] bytes, ByteOrder byteOrder) {
return array;
}
+ /**
+ * Converts the byte array to a short array. This will spread 2 bytes into a single short:
+ *
+ *
+ * [b1, b2] = [short1]
+ *
+ *
+ *
+ *
+ * O(n)O(n)false
* Analysis @@ -892,13 +1034,13 @@ private Validation() { } /** - * Check if a length of an primitive (e.g. int = 4 byte) fits in given length from given start index. + * Check if a length of a primitive (e.g. int = 4 byte) fits in given length from given start index. * Throws exception with descriptive exception message. * * @param length of the whole array * @param index to start from array length * @param primitiveLength length of the primitive type to check - * @param type for easier debugging the human readable type of the checked primitive + * @param type for easier debugging the human-readable type of the checked primitive * to put in exception message * @throws IndexOutOfBoundsException if index + primitiveLength > length */ @@ -914,7 +1056,7 @@ static void checkIndexBounds(int length, int index, int primitiveLength, String * * @param length of the whole array * @param expectedLength how length is expected - * @param type for easier debugging the human readable type of the checked primitive + * @param type for easier debugging the human-readable type of the checked primitive * to put in exception message * @throws IllegalArgumentException if length != expectedLength */ @@ -931,7 +1073,7 @@ static void checkExactLength(int length, int expectedLength, String type) { * * @param length of the byte array * @param modFactor to divide the length - * @param errorSubject human readable message of the exact error subject + * @param errorSubject human-readable message of the exact error subject * @throws IllegalArgumentException if length % modFactor != 0 */ static void checkModLength(int length, int modFactor, String errorSubject) { @@ -944,7 +1086,7 @@ static void checkModLength(int length, int modFactor, String errorSubject) { * Check if the file exists and is a file. * * @param file to check - * @throws IllegalArgumentException if either file is null, does not exists or is not a file + * @throws IllegalArgumentException if either file is null, does not exist or is not a file */ private static void checkFileExists(java.io.File file) { if (file == null || !file.exists() || !file.isFile()) { @@ -1039,7 +1181,7 @@ static byte[] readFromFile(java.io.File file) { * @param file to read bytes from * @param offset to read * @param length from offset - * @return byte array with length length + * @return byte array with length */ static byte[] readFromFile(java.io.File file, int offset, int length) { Validation.checkFileExists(file); diff --git a/src/test/java/at/favre/lib/bytes/BytesConstructorTests.java b/src/test/java/at/favre/lib/bytes/BytesConstructorTests.java index aa4f8c8..5cf5058 100644 --- a/src/test/java/at/favre/lib/bytes/BytesConstructorTests.java +++ b/src/test/java/at/favre/lib/bytes/BytesConstructorTests.java @@ -67,6 +67,11 @@ public void wrapTest() { assertEquals(0, bNullSafe1.length()); } + @Test(expected = NullPointerException.class) + public void wrapByteNull_shouldThrow() { + Bytes.wrap((Bytes) null); + } + @Test(expected = NullPointerException.class) public void wrapTestNullExpected() { Bytes.wrap((byte[]) null); @@ -74,7 +79,7 @@ public void wrapTestNullExpected() { @Test public void wrapTestNullSafe() { - Bytes.wrapNullSafe(null); + assertSame(Bytes.empty(), Bytes.wrapNullSafe(null)); } @Test @@ -174,6 +179,19 @@ public void fromShort() { assertEquals(test, Bytes.from(test).toShort()); } + @Test(expected = NullPointerException.class) + public void fromShortArray_empty_shouldThrow() { + Bytes.from((short[]) null); + } + + @Test + public void fromShortArray() { + assertArrayEquals(new byte[]{0, 1, 0, 2}, Bytes.from((short) 1, (short) 2).array()); + assertArrayEquals(Bytes.from(Bytes.from((short) 32767), Bytes.from((short) 6761), Bytes.from((short) -8517)).array(), Bytes.from((short) 32767, (short) 6761, (short) -8517).array()); + assertArrayEquals(Bytes.from(Bytes.from((short) 1678), Bytes.from((short) -223), Bytes.from((short) 11114)).array(), Bytes.from((short) 1678, (short) -223, (short) 11114).array()); + assertArrayEquals(new byte[]{114, -123, 35, 53, 0, 0, 56, -70}, Bytes.from((short) 29317, (short) 9013, (short) 0, (short) 14522).array()); + } + @Test public void fromInt() { int test = 722837193; @@ -183,6 +201,11 @@ public void fromInt() { assertEquals(test, Bytes.from(test).toInt()); } + @Test(expected = NullPointerException.class) + public void fromIntArray_empty_shouldThrow() { + Bytes.from((int[]) null); + } + @Test public void fromIntArray() { assertArrayEquals(new byte[]{0, 0, 0, 1, 0, 0, 0, 2}, Bytes.from(1, 2).array()); @@ -207,6 +230,11 @@ public void fromLong() { assertEquals(test, Bytes.from(test).toLong()); } + @Test(expected = NullPointerException.class) + public void fromLongArray_empty_shouldThrow() { + Bytes.from((long[]) null); + } + @Test public void fromLongArray() { assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2}, Bytes.from(new long[]{1, 2}).array()); @@ -224,6 +252,22 @@ public void fromFloat() { assertEquals(test, Bytes.from(test).toFloat(), 0.01); } + @Test(expected = NullPointerException.class) + public void fromFloatArray_empty_shouldThrow() { + Bytes.from((float[]) null); + } + + @Test + public void fromFloatArray() { + assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 0}, Bytes.from(0f, 0f).array()); + assertArrayEquals(new byte[]{0, 0, 0, 0, 63, -128, 0, 0}, Bytes.from(0f, 1f).array()); + assertArrayEquals(new byte[]{0, 0, 0, 0, -65, -128, 0, 0}, Bytes.from(0f, -1f).array()); + assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Bytes.from(0f, 0f, 0f).array()); + assertArrayEquals(new byte[]{66, -105, 0, 0, 71, 119, 46, 31}, Bytes.from(75.5f, 63278.123f).array()); + assertArrayEquals(Bytes.from(Bytes.from(78239.934978f), Bytes.from(-82736.65178f), Bytes.from(0.12879316287461f)).array(), + Bytes.from(78239.934978f, -82736.65178f, 0.12879316287461f).array()); + } + @Test public void fromDouble() { double test = 3423423.8923423974123; @@ -233,6 +277,21 @@ public void fromDouble() { assertEquals(test, Bytes.from(test).toDouble(), 0.01); } + @Test(expected = NullPointerException.class) + public void fromDoubleArray_empty_shouldThrow() { + Bytes.from((double[]) null); + } + + @Test + public void fromDoubleArray() { + assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Bytes.from(0.0, 0.0).array()); + assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 63, -16, 0, 0, 0, 0, 0, 0}, Bytes.from(0.0, 1.0).array()); + assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, -65, -16, 0, 0, 0, 0, 0, 0}, Bytes.from(0.0, -1.0).array()); + assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Bytes.from(0, 0, 0).array()); + assertArrayEquals(Bytes.from(Bytes.from(78239.934978), Bytes.from(-82736.65178), Bytes.from(0.12879316287461)).array(), + Bytes.from(78239.934978, -82736.65178, 0.12879316287461).array()); + } + @Test public void fromByteBuffer() { checkByteBuffer(example_bytes_empty); @@ -325,6 +384,11 @@ public void toCharArrayShouldThroughNullPointer() { Bytes.allocate(4).toCharArray(null); } + @Test(expected = NullPointerException.class) + public void fromMultipleBytes_empty_shouldThrow() { + Bytes.from((Bytes[]) null); + } + @Test public void fromMultipleBytes() { assertArrayEquals(new byte[]{0x01, 0x02, 0x03}, Bytes.from(Bytes.from((byte) 0x01), Bytes.from((byte) 0x02), Bytes.from((byte) 0x03)).array()); @@ -446,6 +510,21 @@ public void fromVariousBytes() { assertArrayEquals(example_bytes_sixteen, Bytes.fromNullSafe(example_bytes_sixteen).array()); } + @Test(expected = NullPointerException.class) + public void fromArray_empty_shouldThrow() { + Bytes.from((byte[]) null); + } + + @Test(expected = NullPointerException.class) + public void wrapArrayByteOrder_empty_shouldThrow() { + Bytes.wrap(null, ByteOrder.BIG_ENDIAN); + } + + @Test(expected = NullPointerException.class) + public void fromPartByte_empty_shouldThrow() { + Bytes.from((byte[]) null, 0, 1); + } + @Test public void fromPartByte() { assertArrayEquals(new byte[]{example_bytes_four[1]}, Bytes.from(example_bytes_four, 1, 1).array()); diff --git a/src/test/java/at/favre/lib/bytes/BytesMiscTest.java b/src/test/java/at/favre/lib/bytes/BytesMiscTest.java index 068a2ec..a57398d 100644 --- a/src/test/java/at/favre/lib/bytes/BytesMiscTest.java +++ b/src/test/java/at/favre/lib/bytes/BytesMiscTest.java @@ -52,14 +52,23 @@ private void testToString(Bytes bytes) { @Test public void testHashcode() { - Bytes instance = Bytes.wrap(example_bytes_seven); + Bytes instance = Bytes.from(example_bytes_seven); assertEquals(instance.hashCode(), instance.hashCode()); assertNotEquals(0, instance.hashCode()); - assertEquals(Bytes.wrap(example_bytes_seven).hashCode(), Bytes.from(example_bytes_seven).hashCode()); - assertEquals(Bytes.wrap(example2_bytes_seven).hashCode(), Bytes.from(example2_bytes_seven).hashCode()); - assertNotEquals(Bytes.wrap(example_bytes_seven).hashCode(), Bytes.wrap(example2_bytes_seven).hashCode()); - assertNotEquals(Bytes.wrap(example_bytes_eight).hashCode(), Bytes.wrap(example2_bytes_seven).hashCode()); - assertNotEquals(0, Bytes.wrap(example2_bytes_seven).hashCode()); + assertEquals(Bytes.from(example_bytes_seven).hashCode(), Bytes.from(example_bytes_seven).hashCode()); + assertEquals(Bytes.from(example2_bytes_seven).hashCode(), Bytes.from(example2_bytes_seven).hashCode()); + assertNotEquals(Bytes.from(example_bytes_seven).hashCode(), Bytes.from(example2_bytes_seven).hashCode()); + assertNotEquals(Bytes.from(example_bytes_eight).hashCode(), Bytes.from(example2_bytes_seven).hashCode()); + assertNotEquals(0, Bytes.from(example2_bytes_seven).hashCode()); + } + + @Test + public void testHashcode_changing() { + MutableBytes instance = Bytes.from(example_bytes_seven).mutable(); + assertEquals(instance.hashCode(), Bytes.from(example_bytes_seven).hashCode()); + + instance.setByteAt(0, (byte) 0x4B); + assertNotEquals(instance.hashCode(), Bytes.from(example_bytes_seven).hashCode()); } @SuppressWarnings("SimplifiableJUnitAssertion") @@ -179,6 +188,15 @@ public void indexOfByteFromIndex() { assertEquals(10, Bytes.from(example_bytes_sixteen).indexOf((byte) 0xFD, 5)); } + @Test + public void indexOfByteFromIndexToIndex() { + assertEquals(4, Bytes.from(example_bytes_seven).indexOf((byte) 0x1E, 0, 7)); + assertEquals(4, Bytes.from(example_bytes_seven).indexOf((byte) 0x1E, 3, 5)); + assertEquals(-1, Bytes.from(example_bytes_seven).indexOf((byte) 0x1E, 0, 3)); + assertEquals(-1, Bytes.from(example_bytes_seven).indexOf((byte) 0x1E, 6, 7)); + assertEquals(-1, Bytes.from(example_bytes_seven).indexOf((byte) 0xCA, 0, 7)); + } + @Test public void indexOfArray() { assertEquals(-1, Bytes.allocate(0).indexOf(new byte[]{(byte) 0xFD})); @@ -195,6 +213,16 @@ public void indexOfArrayFromIndex() { assertEquals(2, Bytes.from(new byte[]{(byte) 0x8E, (byte) 0xD1, (byte) 0x8E, (byte) 0xD1, 0x12, (byte) 0xAF, (byte) 0x78, 0x09, 0x1E, (byte) 0xD1, (byte) 0xFD, (byte) 0xAA, 0x12}).indexOf(new byte[]{(byte) 0x8E, (byte) 0xD1}, 1)); } + @Test + public void indexOfArrayFromIndexToIndex() { + assertEquals(4, Bytes.from(example_bytes_seven).indexOf(new byte[] { (byte) 0x1E, (byte) 0xAF }, 0, 7)); + assertEquals(4, Bytes.from(example_bytes_seven).indexOf(new byte[] { (byte) 0x1E, (byte) 0xAF }, 3, 5)); + assertEquals(4, Bytes.from(example_bytes_seven).indexOf(new byte[] { (byte) 0x1E, (byte) 0xAF, (byte) 0xED }, 4, 5)); + assertEquals(-1, Bytes.from(example_bytes_seven).indexOf(new byte[] { (byte) 0x1E, (byte) 0xAF }, 0, 3)); + assertEquals(-1, Bytes.from(example_bytes_seven).indexOf(new byte[] { (byte) 0x1E, (byte) 0xAF }, 6, 7)); + assertEquals(-1, Bytes.from(example_bytes_seven).indexOf(new byte[] { (byte) 0xCA, (byte) 0xFE }, 0, 7)); + } + @Test public void startsWidth() { assertFalse(Bytes.allocate(0).startsWith(new byte[1])); @@ -263,6 +291,12 @@ public void bitAt() { fail(); } catch (IndexOutOfBoundsException ignored) { } + + Bytes bytes = Bytes.wrap(new byte[]{1, 0, 2, 0}).byteOrder(ByteOrder.LITTLE_ENDIAN); + assertTrue(bytes.bitAt(0)); + assertTrue(bytes.bitAt(17)); + assertFalse(bytes.bitAt(8)); + assertFalse(bytes.bitAt(31)); } @Test diff --git a/src/test/java/at/favre/lib/bytes/BytesToConvertOtherTypesTest.java b/src/test/java/at/favre/lib/bytes/BytesToConvertOtherTypesTest.java index b2f9dd6..efa1559 100644 --- a/src/test/java/at/favre/lib/bytes/BytesToConvertOtherTypesTest.java +++ b/src/test/java/at/favre/lib/bytes/BytesToConvertOtherTypesTest.java @@ -222,17 +222,17 @@ public void toDouble() { } } - @Test(expected = IllegalStateException.class) + @Test(expected = IllegalArgumentException.class) public void testToUUIDToLong() { Bytes.random(17).toUUID(); } - @Test(expected = IllegalStateException.class) + @Test(expected = IllegalArgumentException.class) public void testToUUIDToShort() { Bytes.random(15).toUUID(); } - @Test(expected = IllegalStateException.class) + @Test(expected = IllegalArgumentException.class) public void testToUUIDEmpty() { Bytes.allocate(0).toUUID(); } @@ -406,4 +406,38 @@ public void testToDoubleArrayLittleEndian() { 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0}, ByteOrder.LITTLE_ENDIAN).toDoubleArray(), 0.01); } + + @Test + public void testToShortArrayEmpty() { + assertArrayEquals(new short[0], Bytes.empty().toShortArray()); + } + + + @Test(expected = IllegalArgumentException.class) + public void testToShortArrayNotMod2Was5Byte() { + Bytes.wrap(new byte[]{0, 0, 0, 0, 1}).toShortArray(); + } + + @Test + public void testToShortArray() { + assertArrayEquals(new short[]{1}, Bytes.wrap(new byte[]{0, 1}).toShortArray()); + assertArrayEquals(new short[]{257}, Bytes.wrap(new byte[]{1, 1}).toShortArray()); + assertArrayEquals(new short[]{32_767}, Bytes.wrap(new byte[]{127, -1}).toShortArray()); + + assertArrayEquals(new short[]{1, 1}, Bytes.wrap(new byte[]{0, 1, 0, 1}).toShortArray()); + assertArrayEquals(new short[]{257, 1}, Bytes.wrap(new byte[]{1, 1, 0, 1}).toShortArray()); + assertArrayEquals(new short[]{257, 32_767, 1}, Bytes.wrap(new byte[]{1, 1, 127, -1, 0, 1}).toShortArray()); + } + + @Test + public void testToShortArrayLittleEndian() { + assertArrayEquals(new short[]{1}, Bytes.wrap(new byte[]{1, 0}, ByteOrder.LITTLE_ENDIAN).toShortArray()); + assertArrayEquals(new short[]{257}, Bytes.wrap(new byte[]{1, 1}, ByteOrder.LITTLE_ENDIAN).toShortArray()); + assertArrayEquals(new short[]{32_767}, Bytes.wrap(new byte[]{-1, 127}, ByteOrder.LITTLE_ENDIAN).toShortArray()); + + assertArrayEquals(new short[]{1, 1}, Bytes.wrap(new byte[]{1, 0, 1, 0}, ByteOrder.LITTLE_ENDIAN).toShortArray()); + assertArrayEquals(new short[]{257, 1}, Bytes.wrap(new byte[]{1, 1, 1, 0}, ByteOrder.LITTLE_ENDIAN).toShortArray()); + assertArrayEquals(new short[]{257, 32_767, 1}, Bytes.wrap(new byte[]{1, 1, -1, 127, 1, 0}, ByteOrder.LITTLE_ENDIAN).toShortArray()); + } + } diff --git a/src/test/java/at/favre/lib/bytes/BytesTransformTest.java b/src/test/java/at/favre/lib/bytes/BytesTransformTest.java index dd6feaf..8041380 100644 --- a/src/test/java/at/favre/lib/bytes/BytesTransformTest.java +++ b/src/test/java/at/favre/lib/bytes/BytesTransformTest.java @@ -25,6 +25,7 @@ import java.math.BigInteger; import java.nio.ByteBuffer; +import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.Comparator; @@ -446,7 +447,7 @@ public void transformerInPlaceTest() { assertTrue(new BytesTransformer.BitSwitchTransformer(0, true).supportInPlaceTransformation()); assertTrue(new BytesTransformer.BitWiseOperatorTransformer(new byte[]{}, BytesTransformer.BitWiseOperatorTransformer.Mode.XOR).supportInPlaceTransformation()); assertTrue(new BytesTransformer.NegateTransformer().supportInPlaceTransformation()); - assertTrue(new BytesTransformer.ShiftTransformer(0, BytesTransformer.ShiftTransformer.Type.LEFT_SHIFT).supportInPlaceTransformation()); + assertTrue(new BytesTransformer.ShiftTransformer(0, BytesTransformer.ShiftTransformer.Type.LEFT_SHIFT, ByteOrder.BIG_ENDIAN).supportInPlaceTransformation()); assertTrue(new BytesTransformer.ReverseTransformer().supportInPlaceTransformation()); assertFalse(new BytesTransformer.MessageDigestTransformer("SHA1").supportInPlaceTransformation()); diff --git a/src/test/java/at/favre/lib/bytes/EncodingHexJmhBenchmark.java b/src/test/java/at/favre/lib/bytes/EncodingHexJmhBenchmark.java index e079f2e..80e297b 100644 --- a/src/test/java/at/favre/lib/bytes/EncodingHexJmhBenchmark.java +++ b/src/test/java/at/favre/lib/bytes/EncodingHexJmhBenchmark.java @@ -23,10 +23,13 @@ import org.openjdk.jmh.annotations.*; +import java.io.IOException; import java.math.BigInteger; import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Random; import java.util.concurrent.TimeUnit; @@ -128,6 +131,7 @@ public class EncodingHexJmhBenchmark { private BinaryToTextEncoding.EncoderDecoder option3; private BinaryToTextEncoding.EncoderDecoder option4; private BinaryToTextEncoding.EncoderDecoder option5; + private BinaryToTextEncoding.EncoderDecoder option6; private Random random; @Setup(Level.Trial) @@ -139,6 +143,7 @@ public void setup() { option3 = new BigIntegerHexEncoder(); option4 = new OldBytesImplementation(); option5 = new StackOverflowAnswer2Encoder(); + option6 = new Jdk17HexFormat(); rndMap = new HashMap<>(); int[] lengths = new int[]{4, 8, 16, 32, 128, 512, 1000000}; @@ -176,6 +181,11 @@ public String encodeStackOverflowCode2() { return encodeDecode(option5); } + @Benchmark + public String encodeHexFormatJdk17() { + return encodeDecode(option6); + } + private String encodeDecode(BinaryToTextEncoding.EncoderDecoder encoder) { Bytes[] bytes = rndMap.get(byteLength); int rndNum = random.nextInt(bytes.length); @@ -285,4 +295,140 @@ public byte[] decode(CharSequence encoded) { throw new UnsupportedOperationException(); } } + + /** + * Copy of the JDK 17 implementation of HexFormat, only difference is that we need to create new strings, while + * the JDK can create strings without byte copy, I cant here. + */ + static final class Jdk17HexFormat implements BinaryToTextEncoding.EncoderDecoder { + private static final byte[] LOWERCASE_DIGITS = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', + }; + private final String delimiter = ""; + private final String prefix = ""; + private final String suffix = ""; + private final byte[] digits = LOWERCASE_DIGITS; + + @Override + public String encode(byte[] byteArray, ByteOrder byteOrder) { + return formatHex(byteArray, 0, byteArray.length); + } + + private String formatHex(byte[] bytes, int fromIndex, int toIndex) { + Objects.requireNonNull(bytes, "bytes"); + //Objects.checkFromToIndex(fromIndex, toIndex, bytes.length); + if (toIndex - fromIndex == 0) { + return ""; + } + // Format efficiently if possible + String s = formatOptDelimiter(bytes, fromIndex, toIndex); + if (s == null) { + long stride = prefix.length() + 2L + suffix.length() + delimiter.length(); + int capacity = checkMaxArraySize((toIndex - fromIndex) * stride - delimiter.length()); + StringBuilder sb = new StringBuilder(capacity); + formatHex(sb, bytes, fromIndex, toIndex); + s = sb.toString(); + } + return s; + } + + private A formatHex(A out, byte[] bytes, int fromIndex, int toIndex) { + Objects.requireNonNull(out, "out"); + Objects.requireNonNull(bytes, "bytes"); + //Objects.checkFromToIndex(fromIndex, toIndex, bytes.length); + + int length = toIndex - fromIndex; + if (length > 0) { + try { + String between = suffix + delimiter + prefix; + out.append(prefix); + toHexDigits(out, bytes[fromIndex]); + if (between.isEmpty()) { + for (int i = 1; i < length; i++) { + toHexDigits(out, bytes[fromIndex + i]); + } + } else { + for (int i = 1; i < length; i++) { + out.append(between); + toHexDigits(out, bytes[fromIndex + i]); + } + } + out.append(suffix); + } catch (IOException ioe) { + throw new RuntimeException(ioe.getMessage(), ioe); + } + } + return out; + } + + private A toHexDigits(A out, byte value) { + Objects.requireNonNull(out, "out"); + try { + out.append(toHighHexDigit(value)); + out.append(toLowHexDigit(value)); + return out; + } catch (IOException ioe) { + throw new RuntimeException(ioe.getMessage(), ioe); + } + } + + private String formatOptDelimiter(byte[] bytes, int fromIndex, int toIndex) { + byte[] rep; + if (!prefix.isEmpty() || !suffix.isEmpty()) { + return null; + } + int length = toIndex - fromIndex; + if (delimiter.isEmpty()) { + // Allocate the byte array and fill in the hex pairs for each byte + rep = new byte[checkMaxArraySize(length * 2L)]; + for (int i = 0; i < length; i++) { + rep[i * 2] = (byte) toHighHexDigit(bytes[fromIndex + i]); + rep[i * 2 + 1] = (byte) toLowHexDigit(bytes[fromIndex + i]); + } + } else if (delimiter.length() == 1 && delimiter.charAt(0) < 256) { + // Allocate the byte array and fill in the characters for the first byte + // Then insert the delimiter and hexadecimal characters for each of the remaining bytes + char sep = delimiter.charAt(0); + rep = new byte[checkMaxArraySize(length * 3L - 1L)]; + rep[0] = (byte) toHighHexDigit(bytes[fromIndex]); + rep[1] = (byte) toLowHexDigit(bytes[fromIndex]); + for (int i = 1; i < length; i++) { + rep[i * 3 - 1] = (byte) sep; + rep[i * 3] = (byte) toHighHexDigit(bytes[fromIndex + i]); + rep[i * 3 + 1] = (byte) toLowHexDigit(bytes[fromIndex + i]); + } + } else { + // Delimiter formatting not to a single byte + return null; + } + try { + // Return a new string using the bytes without making a copy -> we cant use this here as we dont have access to JavaLangAccess + //return jla.newStringNoRepl(rep, StandardCharsets.ISO_8859_1); + return new String(rep, StandardCharsets.ISO_8859_1); + } catch (Exception cce) { + throw new AssertionError(cce); + } + } + + private char toHighHexDigit(int value) { + return (char) digits[(value >> 4) & 0xf]; + } + + private char toLowHexDigit(int value) { + return (char) digits[value & 0xf]; + } + + private static int checkMaxArraySize(long length) { + if (length > Integer.MAX_VALUE) + throw new OutOfMemoryError("String size " + length + + " exceeds maximum " + Integer.MAX_VALUE); + return (int) length; + } + + @Override + public byte[] decode(CharSequence encoded) { + throw new UnsupportedOperationException(); + } + } } diff --git a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java index 831cbfe..3ded72c 100644 --- a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java +++ b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java @@ -31,6 +31,20 @@ import static org.junit.Assert.*; public class MutableBytesTest extends ABytesTest { + @Test + public void allocate() { + MutableBytes b = MutableBytes.allocate(8); + assertEquals(8, b.length()); + assertFalse(b.validateNotOnlyZeros()); + } + + @Test + public void allocateFill() { + MutableBytes b = MutableBytes.allocate(1, (byte) 0xFF); + assertEquals(1, b.length()); + assertEquals((byte) 0xFF, b.byteAt(0)); + } + @Test public void overwriteWithEmptyArray() { MutableBytes b = fromAndTest(example_bytes_seven).mutable(); @@ -45,6 +59,13 @@ public void overwriteOtherArray() { assertArrayEquals(example2_bytes_seven, b.array()); } + @Test + public void overwriteOtherBytesInstance() { + MutableBytes b = fromAndTest(example_bytes_seven).mutable(); + assertSame(b, b.overwrite(Bytes.from(example2_bytes_seven))); + assertArrayEquals(example2_bytes_seven, b.array()); + } + @Test public void overwritePartialArray() { MutableBytes b = fromAndTest(example_bytes_seven).mutable(); @@ -66,9 +87,9 @@ public void overwritePartialArray2() { @Test public void overwriteBytes() { MutableBytes a = fromAndTest(example_bytes_seven).mutable(); - MutableBytes b = Bytes.from((byte)0).mutable(); + MutableBytes b = Bytes.from((byte) 0).mutable(); MutableBytes c = a.overwrite(b, 0).mutable(); - MutableBytes d = Bytes.wrap(a).copy(1, a.array().length-1).mutable(); + MutableBytes d = Bytes.wrap(a).copy(1, a.array().length - 1).mutable(); assertArrayEquals(c.array(), Bytes.from(b).append(d).array()); } @@ -79,7 +100,8 @@ public void overwriteTooBigArrayShouldThrowException() { try { b.overwrite(new byte[]{(byte) 0xAA, 0x30}, b.length()); fail(); - } catch(IndexOutOfBoundsException ignored) {} + } catch (IndexOutOfBoundsException ignored) { + } } @@ -89,7 +111,8 @@ public void overwriteTooBigBytesShouldThrowException() { try { b.overwrite(Bytes.from((byte) 0xAA, 0x30), b.length()); fail(); - } catch(IndexOutOfBoundsException ignored) {} + } catch (IndexOutOfBoundsException ignored) { + } } @@ -98,10 +121,11 @@ public void overwriteNullArrayShouldThrowException() { MutableBytes nonsense = null; MutableBytes b = fromAndTest(example_bytes_seven).mutable(); - try{ + try { b.overwrite(nonsense); fail(); - } catch (NullPointerException ignored){} + } catch (NullPointerException ignored) { + } } diff --git a/src/test/java/at/favre/lib/bytes/UtilByteTest.java b/src/test/java/at/favre/lib/bytes/UtilByteTest.java index 26180ea..95b55fb 100644 --- a/src/test/java/at/favre/lib/bytes/UtilByteTest.java +++ b/src/test/java/at/favre/lib/bytes/UtilByteTest.java @@ -25,6 +25,7 @@ import org.junit.Test; import java.math.BigInteger; +import java.nio.ByteOrder; import java.util.Arrays; import java.util.Random; @@ -162,21 +163,34 @@ private static void testReverse(byte[] input, int fromIndex, int toIndex, byte[] @Test public void testLeftShift() { byte[] test = new byte[]{0, 0, 1, 0}; - assertArrayEquals(new byte[]{0, 1, 0, 0}, Util.Byte.shiftLeft(new byte[]{0, 0, -128, 0}, 1)); - assertArrayEquals(new byte[]{0, 1, 0, 0}, Util.Byte.shiftLeft(new byte[]{0, 0, 64, 0}, 2)); - assertArrayEquals(new byte[]{1, 1, 1, 0}, Util.Byte.shiftLeft(new byte[]{-128, -128, -128, -128}, 1)); - assertArrayEquals(new byte[]{0, 0, 2, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 1)); - assertArrayEquals(new byte[]{0, 0, 4, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 2)); - assertArrayEquals(new byte[]{0, 0, 8, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 3)); - assertArrayEquals(new byte[]{0, 1, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 8)); - assertArrayEquals(new byte[]{0, 2, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 9)); - assertArrayEquals(new byte[]{1, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 16)); - assertArrayEquals(new byte[]{2, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 17)); - assertArrayEquals(new byte[]{-128, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 23)); - assertArrayEquals(new byte[]{0, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 24)); - assertArrayEquals(new byte[]{0, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 24)); - - assertSame(test, Util.Byte.shiftLeft(test, 1)); + assertArrayEquals(new byte[]{0, 1, 0, 0}, Util.Byte.shiftLeft(new byte[]{0, 0, -128, 0}, 1, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 1, 0, 0}, Util.Byte.shiftLeft(new byte[]{0, 0, 64, 0}, 2, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{1, 1, 1, 0}, Util.Byte.shiftLeft(new byte[]{-128, -128, -128, -128}, 1, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 0, 2, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 1, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 0, 4, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 2, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 0, 8, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 3, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 1, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 8, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 2, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 9, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{1, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 16, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{2, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 17, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{-128, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 23, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 24, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 24, ByteOrder.BIG_ENDIAN)); + + assertSame(test, Util.Byte.shiftLeft(test, 1, ByteOrder.BIG_ENDIAN)); + + assertArrayEquals(new byte[]{0, 0, 1, 0}, Util.Byte.shiftLeft(new byte[]{0, 1, 0, 0}, 8, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{(byte) 0, 0, 1, 0}, Util.Byte.shiftLeft(new byte[]{(byte) 0, 1, 0, 1}, 8, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{(byte) 0x54, 0x1}, Util.Byte.shiftLeft(new byte[]{(byte) 0xAA, 0}, 1, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{(byte) 0xA8, 0x2}, Util.Byte.shiftLeft(new byte[]{(byte) 0xAA, 0}, 2, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{(byte) 0x50, 0x5}, Util.Byte.shiftLeft(new byte[]{(byte) 0xAA, 0}, 3, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{(byte) 0xA0, 0xA}, Util.Byte.shiftLeft(new byte[]{(byte) 0xAA, 0}, 4, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{(byte) 0x40, 0x15}, Util.Byte.shiftLeft(new byte[]{(byte) 0xAA, 0}, 5, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{(byte) 0x80, 0x2A}, Util.Byte.shiftLeft(new byte[]{(byte) 0xAA, 0}, 6, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{(byte) 0x00, 0x55}, Util.Byte.shiftLeft(new byte[]{(byte) 0xAA, 0}, 7, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{(byte) 0, (byte) 0xAA}, Util.Byte.shiftLeft(new byte[]{(byte) 0xAA, 0}, 8, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{0, 0, 0, 0x40}, Util.Byte.shiftLeft(new byte[]{1, 0, 0, 0}, 30, ByteOrder.LITTLE_ENDIAN)); + } @Test @@ -187,7 +201,7 @@ public void testLeftShiftAgainstRefImpl() { Bytes rnd = Bytes.random(4 + new Random().nextInt(14)); byte[] expected = Bytes.from(new BigInteger(rnd.array()).shiftLeft(shift).toByteArray()).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); - byte[] actual = Bytes.from(Util.Byte.shiftLeft(rnd.copy().array(), shift)).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); + byte[] actual = Bytes.from(Util.Byte.shiftLeft(rnd.copy().array(), shift, ByteOrder.BIG_ENDIAN)).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); System.out.println("Original \t" + rnd.encodeBinary() + " << " + shift); System.out.println("Expected \t" + Bytes.wrap(expected).encodeBinary()); @@ -202,18 +216,23 @@ public void testLeftShiftAgainstRefImpl() { public void testRightShift() { byte[] test = new byte[]{0, 0, 16, 0}; assertEquals(0b01111110, 0b11111101 >>> 1); - assertArrayEquals(new byte[]{0b00101101, (byte) 0b01111110}, Util.Byte.shiftRight(new byte[]{0b01011010, (byte) 0b11111101}, 1)); - assertArrayEquals(new byte[]{0, -128, -128, -128}, Util.Byte.shiftRight(new byte[]{1, 1, 1, 1}, 1)); - assertArrayEquals(new byte[]{0, -128, 66, 0}, Util.Byte.shiftRight(new byte[]{2, 1, 8, 2}, 2)); + assertArrayEquals(new byte[]{0b00101101, (byte) 0b01111110}, Util.Byte.shiftRight(new byte[]{0b01011010, (byte) 0b11111101}, 1, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, -128, -128, -128}, Util.Byte.shiftRight(new byte[]{1, 1, 1, 1}, 1, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, -128, 66, 0}, Util.Byte.shiftRight(new byte[]{2, 1, 8, 2}, 2, ByteOrder.BIG_ENDIAN)); assertArrayEquals(new byte[]{0, -128, 66, 0}, new BigInteger(new byte[]{2, 1, 8, 2}).shiftRight(2).toByteArray()); - assertArrayEquals(new byte[]{0, 0, 0, -128}, Util.Byte.shiftRight(Bytes.from(test).array(), 5)); - assertArrayEquals(new byte[]{0, 0, 0, -128}, Util.Byte.shiftRight(new byte[]{0, 0, 1, 0}, 1)); - assertArrayEquals(new byte[]{0, 0, 8, 0}, Util.Byte.shiftRight(Bytes.from(test).array(), 1)); - assertArrayEquals(new byte[]{0, 0, 4, 0}, Util.Byte.shiftRight(Bytes.from(test).array(), 2)); - assertArrayEquals(new byte[]{0, 0, 2, 0}, Util.Byte.shiftRight(Bytes.from(test).array(), 3)); - assertArrayEquals(new byte[]{0, 0, 1, 0}, Util.Byte.shiftRight(Bytes.from(test).array(), 4)); + assertArrayEquals(new byte[]{0, 0, 0, -128}, Util.Byte.shiftRight(Bytes.from(test).array(), 5, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 0, 0, -128}, Util.Byte.shiftRight(new byte[]{0, 0, 1, 0}, 1, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 0, 8, 0}, Util.Byte.shiftRight(Bytes.from(test).array(), 1, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 0, 4, 0}, Util.Byte.shiftRight(Bytes.from(test).array(), 2, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 0, 2, 0}, Util.Byte.shiftRight(Bytes.from(test).array(), 3, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new byte[]{0, 0, 1, 0}, Util.Byte.shiftRight(Bytes.from(test).array(), 4, ByteOrder.BIG_ENDIAN)); + + assertSame(test, Util.Byte.shiftRight(test, 1, ByteOrder.BIG_ENDIAN)); - assertSame(test, Util.Byte.shiftRight(test, 1)); + assertArrayEquals(new byte[]{0, 0}, Util.Byte.shiftRight(new byte[]{1, 0}, 1, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{(byte) 0x80, 0}, Util.Byte.shiftRight(new byte[]{0, 0x02}, 2, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{(byte) 0x80, 0, 0, 0}, Util.Byte.shiftRight(new byte[]{0, 0, 0, 1}, 17, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new byte[]{(byte) 1, 0, 0, 0}, Util.Byte.shiftRight(new byte[]{0, 0, 0, (byte) 0x80}, 31, ByteOrder.LITTLE_ENDIAN)); } @Test @@ -223,7 +242,7 @@ public void testRightShiftAgainstRefImpl() { Bytes rnd = Bytes.random(4 + new Random().nextInt(12)); if (!rnd.bitAt(rnd.lengthBit() - 1)) { //only unsigned byte[] expected = Bytes.from(new BigInteger(rnd.array()).shiftRight(shift).toByteArray()).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); - byte[] actual = Bytes.from(Util.Byte.shiftRight(rnd.copy().array(), shift)).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); + byte[] actual = Bytes.from(Util.Byte.shiftRight(rnd.copy().array(), shift, ByteOrder.BIG_ENDIAN)).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); // System.out.println("Original \t" + rnd.encodeBinary() + " >> " + shift); // System.out.println("Expected \t" + Bytes.wrap(expected).encodeBinary()); diff --git a/src/test/java/at/favre/lib/bytes/UtilConverterTest.java b/src/test/java/at/favre/lib/bytes/UtilConverterTest.java index 8aa717f..3ac6f7b 100644 --- a/src/test/java/at/favre/lib/bytes/UtilConverterTest.java +++ b/src/test/java/at/favre/lib/bytes/UtilConverterTest.java @@ -193,4 +193,20 @@ public void testToDoubleArray() { assertArrayEquals(new double[0], Util.Converter.toDoubleArray(new byte[0], ByteOrder.LITTLE_ENDIAN), 0.01); assertArrayEquals(new double[0], Util.Converter.toDoubleArray(new byte[0], ByteOrder.BIG_ENDIAN), 0.01); } + + @Test + public void testToShortArray() { + assertArrayEquals(new short[]{1}, Util.Converter.toShortArray(new byte[]{0, 1}, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new short[]{257}, Util.Converter.toShortArray(new byte[]{1, 1}, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new short[]{32_767}, Util.Converter.toShortArray(new byte[]{127, -1}, ByteOrder.BIG_ENDIAN)); + assertArrayEquals(new short[]{257, 32_767, 1}, Util.Converter.toShortArray(new byte[]{1, 1, 127, -1, 0, 1}, ByteOrder.BIG_ENDIAN)); + + assertArrayEquals(new short[]{1}, Util.Converter.toShortArray(new byte[]{1, 0}, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new short[]{257}, Util.Converter.toShortArray(new byte[]{1, 1}, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new short[]{32_767}, Util.Converter.toShortArray(new byte[]{-1, 127}, ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new short[]{257, 32_767, 1}, Util.Converter.toShortArray(new byte[]{1, 1, -1, 127, 1, 0}, ByteOrder.LITTLE_ENDIAN)); + + assertArrayEquals(new short[0], Util.Converter.toShortArray(new byte[0], ByteOrder.LITTLE_ENDIAN)); + assertArrayEquals(new short[0], Util.Converter.toShortArray(new byte[0], ByteOrder.BIG_ENDIAN)); + } }