Repository: JakeWharton/byteunits Branch: master Commit: a39d1b03d59e Files: 25 Total size: 69.3 KB Directory structure: gitextract_n29oyt0k/ ├── .editorconfig ├── .gitattributes ├── .github/ │ ├── renovate.json5 │ └── workflows/ │ ├── .java-version │ └── build.yaml ├── .gitignore ├── CHANGELOG.md ├── LICENSE.txt ├── README.md ├── build.gradle ├── gradle/ │ ├── libs.versions.toml │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src/ ├── jvmMain/ │ └── kotlin/ │ └── com/ │ └── jakewharton/ │ └── byteunits/ │ ├── BinaryByteUnit.kt │ ├── BitUnit.kt │ ├── ByteUnit.kt │ ├── DecimalByteUnit.kt │ └── UnitUtil.kt └── jvmTest/ └── kotlin/ └── com/ └── jakewharton/ └── byteunits/ ├── BinaryByteUnitTest.kt ├── BitUnitTest.kt └── DecimalByteUnitTest.kt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] indent_size = 2 charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true max_line_length=100 [*.{kt,kts}] ij_kotlin_imports_layout = * ij_kotlin_allow_trailing_comma = true ij_kotlin_allow_trailing_comma_on_call_site = true ktlint_code_style = intellij_idea ================================================ FILE: .gitattributes ================================================ * text=auto eol=lf *.bat text eol=crlf *.jar binary ================================================ FILE: .github/renovate.json5 ================================================ { $schema: 'https://docs.renovatebot.com/renovate-schema.json', extends: [ 'config:recommended', ], ignorePresets: [ // Ensure we get the latest version and are not pinned to old versions. 'workarounds:javaLTSVersions', ], customManagers: [ // Update .java-version file with the latest JDK version. { customType: 'regex', fileMatch: [ '\\.java-version$', ], matchStrings: [ '(?.*)\\n', ], datasourceTemplate: 'java-version', depNameTemplate: 'java', // Only write the major version. extractVersionTemplate: '^(?\\d+)', }, ], } ================================================ FILE: .github/workflows/.java-version ================================================ 24 ================================================ FILE: .github/workflows/build.yaml ================================================ name: build on: pull_request: push: branches: - '*' tags: - '*' jobs: build: runs-on: macos-latest steps: - uses: actions/checkout@v5 - uses: actions/setup-java@v4 with: distribution: 'zulu' java-version-file: .github/workflows/.java-version - uses: gradle/actions/setup-gradle@v4 - run: ./gradlew build publish: needs: build if: github.repository == 'JakeWharton/byteunits' runs-on: macos-latest steps: - uses: actions/checkout@v5 - uses: actions/setup-java@v4 with: distribution: 'zulu' java-version-file: .github/workflows/.java-version - uses: gradle/actions/setup-gradle@v4 - name: Extract release notes id: release_notes if: startsWith(github.ref, 'refs/tags/') uses: ffurrer2/extract-release-notes@v2 - name: Create Release if: startsWith(github.ref, 'refs/tags/') uses: softprops/action-gh-release@v2 with: body: ${{ steps.release_notes.outputs.release_notes }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Publish Artifacts run: ./gradlew publish if: github.ref == 'refs/heads/trunk' env: ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_NEXUS_USERNAME }} ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_NEXUS_PASSWORD }} ================================================ FILE: .gitignore ================================================ # Eclipse .classpath .project .settings eclipsebin # Ant bin gen build out lib # Gradle .gradle # Maven target pom.xml.* release.properties # IntelliJ .idea *.iml *.iws *.ipr classes .DS_Store ================================================ FILE: CHANGELOG.md ================================================ Change Log ========== Version 0.9.1 *(2015-06-26)* ---------------------------- * New: `format` static methods on `DecimalByteUnit`, `BinaryByteUnit`, and `BitUnit` for creating human-readable strings of the value (e.g., "2 GB"). Version 0.9.0 *(2014-07-20)* ---------------------------- Initial version. ================================================ FILE: LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ================================================ FILE: README.md ================================================ Byte Units ========== Utility classes for converting between granularities of SI and IEC byte units and bit units. **Deprecated!** Prefer https://github.com/saket/byte-size instead. Example Usage ------------- What's the difference in hard drive space between perception and actual? ```java long perception = BinaryByteUnit.TEBIBYTES.toBytes(2); long usable = DecimalByteUnit.TERABYTES.toBytes(2); long lost = BinaryByteUnit.BYTES.toGibibytes(perception - usable); System.out.println(lost + " GiB lost on a 2TB drive."); ``` Method parameter for specifying a resource size. ```java public void installDiskCache(long count, ByteUnit unit) { long size = unit.toBytes(count); // TODO Install disk cache of 'size' bytes. } ``` Print human-readable strings for byte and bit amounts. ```java long bytes = 2 * 1024 * 1024 * 1024; System.out.println(BinaryByteUnit.format(bytes)); ``` Download -------- Grab the [latest .jar][1] or add via Gradle: ```groovy implementation 'com.jakewharton.byteunits:byteunits:0.9.1' ``` or Maven: ```xml com.jakewharton.byteunits byteunits 0.9.1 ``` Snapshots of the development version are available in [Sonatype's `snapshots` repository][snap]. License ------- Copyright 2014 Jake Wharton 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. [1]: https://search.maven.org/remote_content?g=com.jakewharton.byteunits&a=byteunits&v=LATEST [snap]: https://oss.sonatype.org/content/repositories/snapshots/ ================================================ FILE: build.gradle ================================================ import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.tasks.KotlinCompile buildscript { dependencies { classpath libs.kotlin.gradlePlugin classpath libs.mavenPublishPlugin classpath libs.spotlessPlugin classpath libs.animalSnifferPlugin } repositories { mavenCentral() } } apply plugin: 'org.jetbrains.kotlin.multiplatform' apply plugin: 'com.vanniktech.maven.publish' apply plugin: 'com.diffplug.spotless' apply plugin: 'ru.vyarus.animalsniffer' kotlin { jvm() sourceSets { commonTest { dependencies { implementation 'org.jetbrains.kotlin:kotlin-test' } } } } tasks.withType(KotlinCompile).configureEach { compilerOptions { jvmTarget = JvmTarget.JVM_1_8 freeCompilerArgs.addAll([ '-progressive', '-Xjvm-default=all', ]) } } tasks.withType(JavaCompile).configureEach { sourceCompatibility = JavaVersion.VERSION_1_8.toString() targetCompatibility = JavaVersion.VERSION_1_8.toString() } spotless { kotlin { ktlint(libs.ktlint.get().version) .editorConfigOverride([ // Making something an expression body should be a choice around readability. 'ktlint_standard_function-expression-body': 'disabled', ]) target 'src/**/*.kt' } } dependencies { signature 'org.codehaus.mojo.signature:java18:1.0@signature' signature 'net.sf.androidscents.signature:android-api-level-21:5.0.1_r2@signature' } ================================================ FILE: gradle/libs.versions.toml ================================================ [libraries] kotlin-gradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:2.2.10" ktlint = "com.pinterest.ktlint:ktlint-cli:1.7.1" mavenPublishPlugin = "com.vanniktech:gradle-maven-publish-plugin:0.34.0" spotlessPlugin = "com.diffplug.spotless:spotless-plugin-gradle:7.2.1" animalSnifferPlugin = "ru.vyarus:gradle-animalsniffer-plugin:2.0.1" ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-9.0.0-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ GROUP=com.jakewharton.byteunits VERSION_NAME=0.9.2-SNAPSHOT POM_ARTIFACT_ID=byteunits POM_NAME=Byte Units POM_DESCRIPTION=Utility classes for converting between granularities of SI and IEC byte units and bit units. POM_URL=http://github.com/JakeWharton/byteunits POM_SCM_URL=https://github.com/vanniktech/byteunits POM_SCM_CONNECTION=scm:git:git://github.com/JakeWharton/byteunits.git POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/JakeWharton/byteunits.git POM_LICENCE_NAME=The Apache Software License, Version 2.0 POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt POM_LICENCE_DIST=repo POM_DEVELOPER_ID=jakewharton POM_DEVELOPER_NAME=Jake Wharton POM_INCEPTION_YEAR=2014 kotlin.mpp.stability.nowarn=true mavenCentralPublishing=true mavenCentralAutomaticPublishing=true signAllPublications=true ================================================ FILE: gradlew ================================================ #!/bin/sh # # Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # «${var#prefix}», «${var%suffix}», and «$( cmd )»; # * compound commands having a testable exit status, especially «case»; # * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac CLASSPATH="\\\"\\\"" # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD=$JAVA_HOME/jre/sh/java else JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD=java if ! command -v java >/dev/null 2>&1 then die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" # Stop when "xargs" is not available. if ! command -v xargs >/dev/null 2>&1 then die "xargs is not available" fi # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @rem SPDX-License-Identifier: Apache-2.0 @rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute echo. 1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. 1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line set CLASSPATH= @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! set EXIT_CODE=%ERRORLEVEL% if %EXIT_CODE% equ 0 set EXIT_CODE=1 if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: settings.gradle ================================================ pluginManagement { repositories { mavenCentral() google() gradlePluginPortal() } } dependencyResolutionManagement { repositories { mavenCentral() } } ================================================ FILE: src/jvmMain/kotlin/com/jakewharton/byteunits/BinaryByteUnit.kt ================================================ package com.jakewharton.byteunits import java.text.DecimalFormat import java.text.NumberFormat /** * A [BinaryByteUnit] represents power-of-two byte sizes at a given unit of granularity and * provides utility methods to convert across units. A [BinaryByteUnit] does not maintain * byte size information, but only helps organize and use byte size representations that may be * maintained separately across various contexts. */ enum class BinaryByteUnit : ByteUnit { /** Byte unit representing one byte. */ BYTES { override fun convert(sourceCount: Long, sourceUnit: BinaryByteUnit) = sourceUnit.toBytes(sourceCount) override fun toBytes(count: Long) = count override fun toKibibytes(count: Long) = count / (KB / B) override fun toMebibytes(count: Long) = count / (MB / B) override fun toGibibytes(count: Long) = count / (GB / B) override fun toTebibytes(count: Long) = count / (TB / B) override fun toPebibytes(count: Long) = count / (PB / B) }, /** A byte unit representing 1024 bytes. */ KIBIBYTES { override fun convert(sourceCount: Long, sourceUnit: BinaryByteUnit) = sourceUnit.toKibibytes(sourceCount) override fun toBytes(count: Long) = checkedMultiply(count, KB / B, MAX / (KB / B)) override fun toKibibytes(count: Long) = count override fun toMebibytes(count: Long) = count / (MB / KB) override fun toGibibytes(count: Long) = count / (GB / KB) override fun toTebibytes(count: Long) = count / (TB / KB) override fun toPebibytes(count: Long) = count / (PB / KB) }, /** A byte unit representing 1024 kibibytes. */ MEBIBYTES { override fun convert(sourceCount: Long, sourceUnit: BinaryByteUnit) = sourceUnit.toMebibytes(sourceCount) override fun toBytes(count: Long) = checkedMultiply(count, MB / B, MAX / (MB / B)) override fun toKibibytes(count: Long) = checkedMultiply(count, MB / KB, MAX / (MB / KB)) override fun toMebibytes(count: Long) = count override fun toGibibytes(count: Long) = count / (GB / MB) override fun toTebibytes(count: Long) = count / (TB / MB) override fun toPebibytes(count: Long) = count / (PB / MB) }, /** A byte unit representing 1024 mebibytes. */ GIBIBYTES { override fun convert(sourceCount: Long, sourceUnit: BinaryByteUnit) = sourceUnit.toGibibytes(sourceCount) override fun toBytes(count: Long) = checkedMultiply(count, GB / B, MAX / (GB / B)) override fun toKibibytes(count: Long) = checkedMultiply(count, GB / KB, MAX / (GB / KB)) override fun toMebibytes(count: Long) = checkedMultiply(count, GB / MB, MAX / (GB / MB)) override fun toGibibytes(count: Long) = count override fun toTebibytes(count: Long) = count / (TB / GB) override fun toPebibytes(count: Long) = count / (PB / GB) }, /** A byte unit representing 1024 gibibytes. */ TEBIBYTES { override fun convert(sourceCount: Long, sourceUnit: BinaryByteUnit) = sourceUnit.toTebibytes(sourceCount) override fun toBytes(count: Long) = checkedMultiply(count, TB / B, MAX / (TB / B)) override fun toKibibytes(count: Long) = checkedMultiply(count, TB / KB, MAX / (TB / KB)) override fun toMebibytes(count: Long) = checkedMultiply(count, TB / MB, MAX / (TB / MB)) override fun toGibibytes(count: Long) = checkedMultiply(count, TB / GB, MAX / (TB / GB)) override fun toTebibytes(count: Long) = count override fun toPebibytes(count: Long) = count / (PB / TB) }, /** A byte unit representing 1024 tebibytes. */ PEBIBYTES { override fun convert(sourceCount: Long, sourceUnit: BinaryByteUnit) = sourceUnit.toPebibytes(sourceCount) override fun toBytes(count: Long) = checkedMultiply(count, PB / B, MAX / (PB / B)) override fun toKibibytes(count: Long) = checkedMultiply(count, PB / KB, MAX / (PB / KB)) override fun toMebibytes(count: Long) = checkedMultiply(count, PB / MB, MAX / (PB / MB)) override fun toGibibytes(count: Long) = checkedMultiply(count, PB / GB, MAX / (PB / GB)) override fun toTebibytes(count: Long) = checkedMultiply(count, PB / TB, MAX / (PB / TB)) override fun toPebibytes(count: Long) = count }, ; /** * Converts the given size in the given unit to this unit. Conversions from finer to coarser * granularities truncate, so lose precision. For example, converting from `999` bytes to * kibibytes results in `0`. Conversions from coarser to finer granularities with arguments * that would numerically overflow saturate to [Long.MIN_VALUE] if negative or * [Long.MAX_VALUE] if positive. * * * For example, to convert 10 kilobytes to bytes, use: * `ByteUnit.KIBIBYTES.convert(10, ByteUnit.BYTES)` * * [sourceCount] the size in the given [sourceUnit]. * [sourceUnit] the unit of the [sourceCount] argument. * @return the converted size in this unit, or [Long.MIN_VALUE] if conversion would * negatively overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun convert(sourceCount: Long, sourceUnit: BinaryByteUnit): Long /** * Equivalent to [KIBIBYTES.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toKibibytes(count: Long): Long /** * Equivalent to [MEBIBYTES.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toMebibytes(count: Long): Long /** * Equivalent to [GIBIBYTES.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toGibibytes(count: Long): Long /** * Equivalent to [TEBIBYTES.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toTebibytes(count: Long): Long /** * Equivalent to [PEBIBYTES.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toPebibytes(count: Long): Long companion object { private const val B = 1L private const val KB = B * 1024L private const val MB = KB * 1024L private const val GB = MB * 1024L private const val TB = GB * 1024L private const val PB = TB * 1024L private const val MAX = Long.MAX_VALUE private val UNITS = arrayOf("B", "KiB", "MiB", "GiB", "TiB", "PiB") /** * Return `bytes` as human-readable size string (e.g., "1.2 GiB". This will use a * [DecimalFormat] instance with `pattern` for formatting the number. */ fun format(bytes: Long, pattern: String): String { return format(bytes, DecimalFormat(pattern)) } /** * Return `bytes` as human-readable size string (e.g., "1.2 GiB". This will use a default * [DecimalFormat] instance for formatting the number. */ @JvmOverloads fun format( bytes: Long, format: NumberFormat = DecimalFormat( DEFAULT_FORMAT_PATTERN, ), ): String { require(bytes >= 0) { "bytes < 0: $bytes" } var unitIndex = 0 var count = bytes.toDouble() while (count >= 1024.0 && unitIndex < UNITS.size - 1) { count /= 1024.0 unitIndex += 1 } return format.format(count) + ' ' + UNITS[unitIndex] } } } ================================================ FILE: src/jvmMain/kotlin/com/jakewharton/byteunits/BitUnit.kt ================================================ package com.jakewharton.byteunits import java.text.DecimalFormat import java.text.NumberFormat /** * A [BitUnit] represents bit size at a given unit of granularity and provides utility * methods to convert across units. A [BitUnit] does not maintain bit size information, * but only helps organize and use bit size representations that may be maintained separately * across various contexts. */ enum class BitUnit : ByteUnit { /** Bit unit representing one bit. */ BITS { override fun convert(sourceCount: Long, sourceUnit: BitUnit): Long = sourceUnit.toBits(sourceCount) override fun toBytes(count: Long): Long = count / BYTE override fun toBits(count: Long): Long = count override fun toKilobits(count: Long): Long = count / (KB / B) override fun toMegabits(count: Long): Long = count / (MB / B) override fun toGigabits(count: Long): Long = count / (GB / B) override fun toTerabits(count: Long): Long = count / (TB / B) override fun toPetabits(count: Long): Long = count / (PB / B) }, /** A bit unit representing 1000 bits. */ KILOBITS { override fun convert(sourceCount: Long, sourceUnit: BitUnit): Long = sourceUnit.toKilobits(sourceCount) override fun toBytes(count: Long): Long = count * KBYTE override fun toBits(count: Long): Long = checkedMultiply(count, KB / B, MAX / (KB / B)) override fun toKilobits(count: Long): Long = count override fun toMegabits(count: Long): Long = count / (MB / KB) override fun toGigabits(count: Long): Long = count / (GB / KB) override fun toTerabits(count: Long): Long = count / (TB / KB) override fun toPetabits(count: Long): Long = count / (PB / KB) }, /** A bit unit representing 1000 kilobits. */ MEGABITS { override fun convert(sourceCount: Long, sourceUnit: BitUnit): Long = sourceUnit.toMegabits(sourceCount) override fun toBytes(count: Long): Long = count * MBYTE override fun toBits(count: Long): Long = checkedMultiply(count, MB / B, MAX / (MB / B)) override fun toKilobits(count: Long): Long = checkedMultiply(count, MB / KB, MAX / (MB / KB)) override fun toMegabits(count: Long): Long = count override fun toGigabits(count: Long): Long = count / (GB / MB) override fun toTerabits(count: Long): Long = count / (TB / MB) override fun toPetabits(count: Long): Long = count / (PB / MB) }, /** A bit unit representing 1000 megabits. */ GIGABITS { override fun convert(sourceCount: Long, sourceUnit: BitUnit): Long = sourceUnit.toGigabits(sourceCount) override fun toBytes(count: Long): Long = count * GBYTE override fun toBits(count: Long): Long = checkedMultiply(count, GB / B, MAX / (GB / B)) override fun toKilobits(count: Long): Long = checkedMultiply(count, GB / KB, MAX / (GB / KB)) override fun toMegabits(count: Long): Long = checkedMultiply(count, GB / MB, MAX / (GB / MB)) override fun toGigabits(count: Long): Long = count override fun toTerabits(count: Long): Long = count / (TB / GB) override fun toPetabits(count: Long): Long = count / (PB / GB) }, /** A bit unit representing 1000 gigabits. */ TERABITS { override fun convert(sourceCount: Long, sourceUnit: BitUnit): Long = sourceUnit.toTerabits(sourceCount) override fun toBytes(count: Long): Long = count * TBYTE override fun toBits(count: Long): Long = checkedMultiply(count, TB / B, MAX / (TB / B)) override fun toKilobits(count: Long): Long = checkedMultiply(count, TB / KB, MAX / (TB / KB)) override fun toMegabits(count: Long): Long = checkedMultiply(count, TB / MB, MAX / (TB / MB)) override fun toGigabits(count: Long): Long = checkedMultiply(count, TB / GB, MAX / (TB / GB)) override fun toTerabits(count: Long): Long = count override fun toPetabits(count: Long): Long = count / (PB / TB) }, /** A bit unit representing 1000 terabits. */ PETABITS { override fun convert(sourceCount: Long, sourceUnit: BitUnit): Long = sourceUnit.toPetabits(sourceCount) override fun toBytes(count: Long): Long = count * PBYTE override fun toBits(count: Long): Long = checkedMultiply(count, PB / B, MAX / (PB / B)) override fun toKilobits(count: Long): Long = checkedMultiply(count, PB / KB, MAX / (PB / KB)) override fun toMegabits(count: Long): Long = checkedMultiply(count, PB / MB, MAX / (PB / MB)) override fun toGigabits(count: Long): Long = checkedMultiply(count, PB / GB, MAX / (PB / GB)) override fun toTerabits(count: Long): Long = checkedMultiply(count, PB / TB, MAX / (PB / TB)) override fun toPetabits(count: Long): Long = count }, ; /** * Converts the given size in the given unit to this unit. Conversions from finer to coarser * granularities truncate, so lose precision. For example, converting from `999` bit to * kilobits results in `0`. Conversions from coarser to finer granularities with arguments * that would numerically overflow saturate to [Long.MIN_VALUE] if negative or * [Long.MAX_VALUE] if positive. * * * For example, to convert 10 kilobytes to bytes, use: * `ByteUnit.KILOBITS.convert(10, ByteUnit.BITS)` * * [sourceCount] the size in the given [sourceUnit]. * [sourceUnit] the unit of the [sourceCount] argument. * @return the converted size in this unit, or [Long.MIN_VALUE] if conversion would * negatively overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun convert(sourceCount: Long, sourceUnit: BitUnit): Long /** * Equivalent to [BITS.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toBits(count: Long): Long /** * Equivalent to [KILOBITS.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toKilobits(count: Long): Long /** * Equivalent to [MEGABITS.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toMegabits(count: Long): Long /** * Equivalent to [GIGABITS.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toGigabits(count: Long): Long /** * Equivalent to [TERABITS.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toTerabits(count: Long): Long /** * Equivalent to [PETABITS.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toPetabits(count: Long): Long companion object { private const val B = 1L private const val KB = B * 1000L private const val MB = KB * 1000L private const val GB = MB * 1000L private const val TB = GB * 1000L private const val PB = TB * 1000L private const val BYTE = B * 8 private const val KBYTE = 1000L / BYTE private const val MBYTE = KBYTE * 1000L private const val GBYTE = MBYTE * 1000L private const val TBYTE = GBYTE * 1000L private const val PBYTE = TBYTE * 1000L private const val MAX = Long.MAX_VALUE private val UNITS = arrayOf("b", "Kb", "Mb", "Gb", "Tb", "Pb") /** * Return `bits` as human-readable size string (e.g., "1.2 Gb". This will use a * [DecimalFormat] instance with [pattern] for formatting the number. */ fun format(bits: Long, pattern: String): String { return format(bits, DecimalFormat(pattern)) } /** * Return `bits` as human-readable size string (e.g., "1.2 Gb". This will use a default * [DecimalFormat] instance for formatting the number. */ @JvmOverloads fun format( bits: Long, format: NumberFormat = DecimalFormat( DEFAULT_FORMAT_PATTERN, ), ): String { require(bits >= 0) { "bits < 0: $bits" } var unitIndex = 0 var count = bits.toDouble() while (count >= 1000.0 && unitIndex < UNITS.size - 1) { count /= 1000.0 unitIndex += 1 } return format.format(count) + ' ' + UNITS[unitIndex] } } } ================================================ FILE: src/jvmMain/kotlin/com/jakewharton/byteunits/ByteUnit.kt ================================================ package com.jakewharton.byteunits /** * A [ByteUnit] represents a size at a given unit of granularity which can be converted * into bytes. A [ByteUnit] does not maintain byte size information, but only helps use byte * size representations that may be maintained separately across various contexts. * * @see DecimalByteUnit * @see BinaryByteUnit * @see BitUnit */ sealed interface ByteUnit { /** * Converts the given size in the given unit to bytes. Conversions with arguments that would * numerically overflow saturate to [Long.MIN_VALUE] if negative or [Long.MAX_VALUE] * if positive. * * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ fun toBytes(count: Long): Long } ================================================ FILE: src/jvmMain/kotlin/com/jakewharton/byteunits/DecimalByteUnit.kt ================================================ package com.jakewharton.byteunits import java.text.DecimalFormat import java.text.NumberFormat /** * A [DecimalByteUnit] represents power-of-ten byte sizes at a given unit of granularity and * provides utility methods to convert across units. A [DecimalByteUnit] does not maintain * byte size information, but only helps organize and use byte size representations that may be * maintained separately across various contexts. */ enum class DecimalByteUnit : ByteUnit { /** Byte unit representing one byte. */ BYTES { override fun convert(sourceCount: Long, sourceUnit: DecimalByteUnit): Long = sourceUnit.toBytes(sourceCount) override fun toBytes(count: Long): Long = count override fun toKilobytes(count: Long): Long = count / (KB / B) override fun toMegabytes(count: Long): Long = count / (MB / B) override fun toGigabytes(count: Long): Long = count / (GB / B) override fun toTerabytes(count: Long): Long = count / (TB / B) override fun toPetabytes(count: Long): Long = count / (PB / B) }, /** A byte unit representing 1000 bytes. */ KILOBYTES { override fun convert(sourceCount: Long, sourceUnit: DecimalByteUnit): Long = sourceUnit.toKilobytes(sourceCount) override fun toBytes(count: Long): Long = checkedMultiply(count, KB / B, MAX / (KB / B)) override fun toKilobytes(count: Long): Long = count override fun toMegabytes(count: Long): Long = count / (MB / KB) override fun toGigabytes(count: Long): Long = count / (GB / KB) override fun toTerabytes(count: Long): Long = count / (TB / KB) override fun toPetabytes(count: Long): Long = count / (PB / KB) }, /** A byte unit representing 1000 kilobytes. */ MEGABYTES { override fun convert(sourceCount: Long, sourceUnit: DecimalByteUnit): Long = sourceUnit.toMegabytes(sourceCount) override fun toBytes(count: Long): Long = checkedMultiply(count, MB / B, MAX / (MB / B)) override fun toKilobytes(count: Long): Long = checkedMultiply(count, MB / KB, MAX / (MB / KB)) override fun toMegabytes(count: Long): Long = count override fun toGigabytes(count: Long): Long = count / (GB / MB) override fun toTerabytes(count: Long): Long = count / (TB / MB) override fun toPetabytes(count: Long): Long = count / (PB / MB) }, /** A byte unit representing 1000 megabytes. */ GIGABYTES { override fun convert(sourceCount: Long, sourceUnit: DecimalByteUnit): Long = sourceUnit.toGigabytes(sourceCount) override fun toBytes(count: Long): Long = checkedMultiply(count, GB / B, MAX / (GB / B)) override fun toKilobytes(count: Long): Long = checkedMultiply(count, GB / KB, MAX / (GB / KB)) override fun toMegabytes(count: Long): Long = checkedMultiply(count, GB / MB, MAX / (GB / MB)) override fun toGigabytes(count: Long): Long = count override fun toTerabytes(count: Long): Long = count / (TB / GB) override fun toPetabytes(count: Long): Long = count / (PB / GB) }, /** A byte unit representing 1000 gigabytes. */ TERABYTES { override fun convert(sourceCount: Long, sourceUnit: DecimalByteUnit): Long = sourceUnit.toTerabytes(sourceCount) override fun toBytes(count: Long): Long = checkedMultiply(count, TB / B, MAX / (TB / B)) override fun toKilobytes(count: Long): Long = checkedMultiply(count, TB / KB, MAX / (TB / KB)) override fun toMegabytes(count: Long): Long = checkedMultiply(count, TB / MB, MAX / (TB / MB)) override fun toGigabytes(count: Long): Long = checkedMultiply(count, TB / GB, MAX / (TB / GB)) override fun toTerabytes(count: Long): Long = count override fun toPetabytes(count: Long): Long = count / (PB / TB) }, /** A byte unit representing 1000 terabytes. */ PETABYTES { override fun convert(sourceCount: Long, sourceUnit: DecimalByteUnit): Long = sourceUnit.toPetabytes(sourceCount) override fun toBytes(count: Long): Long = checkedMultiply(count, PB / B, MAX / (PB / B)) override fun toKilobytes(count: Long): Long = checkedMultiply(count, PB / KB, MAX / (PB / KB)) override fun toMegabytes(count: Long): Long = checkedMultiply(count, PB / MB, MAX / (PB / MB)) override fun toGigabytes(count: Long): Long = checkedMultiply(count, PB / GB, MAX / (PB / GB)) override fun toTerabytes(count: Long): Long = checkedMultiply(count, PB / TB, MAX / (PB / TB)) override fun toPetabytes(count: Long): Long = count }, ; /** * Converts the given size in the given unit to this unit. Conversions from finer to coarser * granularities truncate, so lose precision. For example, converting from `999` bytes to * kilobytes results in `0`. Conversions from coarser to finer granularities with arguments * that would numerically overflow saturate to [Long.MIN_VALUE] if negative or * [Long.MAX_VALUE] if positive. * * * For example, to convert 10 kilobytes to bytes, use: * `ByteUnit.KILOBYTES.convert(10, ByteUnit.BYTES)` * * [sourceCount] the size in the given [sourceUnit]. * [sourceUnit] the unit of the [sourceCount] argument. * @return the converted size in this unit, or [Long.MIN_VALUE] if conversion would * negatively overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun convert(sourceCount: Long, sourceUnit: DecimalByteUnit): Long /** * Equivalent to [KILOBYTES.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toKilobytes(count: Long): Long /** * Equivalent to [MEGABYTES.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toMegabytes(count: Long): Long /** * Equivalent to [GIGABYTES.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toGigabytes(count: Long): Long /** * Equivalent to [TERABYTES.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toTerabytes(count: Long): Long /** * Equivalent to [PETABYTES.convert(count, this)][convert]. * [count] the bit count * @return the converted count, or [Long.MIN_VALUE] if conversion would negatively * overflow, or [Long.MAX_VALUE] if it would positively overflow. */ abstract fun toPetabytes(count: Long): Long companion object { private const val B = 1L private const val KB = B * 1000L private const val MB = KB * 1000L private const val GB = MB * 1000L private const val TB = GB * 1000L private const val PB = TB * 1000L private const val MAX = Long.MAX_VALUE private val UNITS = arrayOf("B", "KB", "MB", "GB", "TB", "PB") /** * Return `bytes` as human-readable size string (e.g., "1.2 GB". This will use a * [DecimalFormat] instance with `pattern` for formatting the number. */ fun format(bytes: Long, pattern: String): String { return format(bytes, DecimalFormat(pattern)) } /** * Return `bytes` as human-readable size string (e.g., "1.2 GB". This will use a default * [DecimalFormat] instance for formatting the number. */ @JvmOverloads fun format( bytes: Long, format: NumberFormat = DecimalFormat( DEFAULT_FORMAT_PATTERN, ), ): String { require(bytes >= 0) { "bytes < 0: $bytes" } var unitIndex = 0 var count = bytes.toDouble() while (count >= 1000.0 && unitIndex < UNITS.size - 1) { count /= 1000.0 unitIndex += 1 } return format.format(count) + ' ' + UNITS[unitIndex] } } } ================================================ FILE: src/jvmMain/kotlin/com/jakewharton/byteunits/UnitUtil.kt ================================================ package com.jakewharton.byteunits internal const val DEFAULT_FORMAT_PATTERN = "#,##0.#" /** Multiply [size] by [factor] accounting for overflow. */ internal fun checkedMultiply(size: Long, factor: Long, over: Long): Long = when { size > over -> Long.MAX_VALUE size < -over -> Long.MIN_VALUE else -> size * factor } ================================================ FILE: src/jvmTest/kotlin/com/jakewharton/byteunits/BinaryByteUnitTest.kt ================================================ package com.jakewharton.byteunits import com.jakewharton.byteunits.BinaryByteUnit.BYTES import com.jakewharton.byteunits.BinaryByteUnit.GIBIBYTES import com.jakewharton.byteunits.BinaryByteUnit.KIBIBYTES import com.jakewharton.byteunits.BinaryByteUnit.MEBIBYTES import com.jakewharton.byteunits.BinaryByteUnit.PEBIBYTES import com.jakewharton.byteunits.BinaryByteUnit.TEBIBYTES import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.text.NumberFormat import java.util.Locale import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith class BinaryByteUnitTest { @Suppress("KotlinConstantConditions") @Test fun convertInternal() { for (s in 0..998) { assertEquals(s / 1_024L, BYTES.toKibibytes(s.toLong())) assertEquals(s / 1_048_576L, BYTES.toMebibytes(s.toLong())) assertEquals(s / 1_073_741_824L, BYTES.toGibibytes(s.toLong())) assertEquals(s / 1_099_511_627_776L, BYTES.toTebibytes(s.toLong())) assertEquals(s / 1_125_899_906_842_624L, BYTES.toPebibytes(s.toLong())) assertEquals(s * 1_024L, KIBIBYTES.toBytes(s.toLong())) assertEquals(s / 1_024L, KIBIBYTES.toMebibytes(s.toLong())) assertEquals(s / 1_048_576L, KIBIBYTES.toGibibytes(s.toLong())) assertEquals(s / 1_073_741_824L, KIBIBYTES.toTebibytes(s.toLong())) assertEquals(s / 1_099_511_627_776L, KIBIBYTES.toPebibytes(s.toLong())) assertEquals(s * 1_048_576L, MEBIBYTES.toBytes(s.toLong())) assertEquals(s * 1_024L, MEBIBYTES.toKibibytes(s.toLong())) assertEquals(s / 1_024L, MEBIBYTES.toGibibytes(s.toLong())) assertEquals(s / 1_048_576L, MEBIBYTES.toTebibytes(s.toLong())) assertEquals(s / 1_073_741_824L, MEBIBYTES.toPebibytes(s.toLong())) assertEquals(s * 1_073_741_824L, GIBIBYTES.toBytes(s.toLong())) assertEquals(s * 1_048_576L, GIBIBYTES.toKibibytes(s.toLong())) assertEquals(s * 1_024L, GIBIBYTES.toMebibytes(s.toLong())) assertEquals(s / 1_024L, GIBIBYTES.toTebibytes(s.toLong())) assertEquals(s / 1_048_576L, GIBIBYTES.toPebibytes(s.toLong())) assertEquals(s * 1_099_511_627_776L, TEBIBYTES.toBytes(s.toLong())) assertEquals(s * 1_073_741_824L, TEBIBYTES.toKibibytes(s.toLong())) assertEquals(s * 1_048_576L, TEBIBYTES.toMebibytes(s.toLong())) assertEquals(s * 1_024L, TEBIBYTES.toGibibytes(s.toLong())) assertEquals(s / 1_024L, TEBIBYTES.toPebibytes(s.toLong())) assertEquals(s * 1_125_899_906_842_624L, PEBIBYTES.toBytes(s.toLong())) assertEquals(s * 1_099_511_627_776L, PEBIBYTES.toKibibytes(s.toLong())) assertEquals(s * 1_073_741_824L, PEBIBYTES.toMebibytes(s.toLong())) assertEquals(s * 1_048_576L, PEBIBYTES.toGibibytes(s.toLong())) assertEquals(s * 1_024L, PEBIBYTES.toTebibytes(s.toLong())) } } @Test fun format() { assertEquals("0 B", BinaryByteUnit.format(0)) assertEquals("1 B", BinaryByteUnit.format(1)) assertEquals("1 KiB", BinaryByteUnit.format(1024)) assertEquals("1 KiB", BinaryByteUnit.format(1025)) assertEquals("16 KiB", BinaryByteUnit.format(16384)) assertEquals("1.2 MiB", BinaryByteUnit.format(1234567)) assertEquals("1.2 GiB", BinaryByteUnit.format(1288490189)) assertEquals("8,192 PiB", BinaryByteUnit.format(Long.MAX_VALUE)) } @Test fun formatWithPattern() { val pattern = "0.0#" assertEquals("0.0 B", BinaryByteUnit.format(0, pattern)) assertEquals("1.0 B", BinaryByteUnit.format(1, pattern)) assertEquals("1.0 KiB", BinaryByteUnit.format(1024, pattern)) assertEquals("1.0 KiB", BinaryByteUnit.format(1025, pattern)) assertEquals("16.0 KiB", BinaryByteUnit.format(16384, pattern)) assertEquals("1.18 MiB", BinaryByteUnit.format(1234567, pattern)) } @Test fun formatWithDecimalFormat() { val format: NumberFormat = DecimalFormat("#.##", DecimalFormatSymbols(Locale.FRENCH)) assertEquals("16 KiB", BinaryByteUnit.format(16384, format)) assertEquals("1,18 MiB", BinaryByteUnit.format(1234567, format)) } @Test fun formatNegativeValuesThrows() { assertFailsWith { BinaryByteUnit.format(-1) }.also { assertEquals("bytes < 0: -1", it.message) } assertFailsWith { BinaryByteUnit.format(-1, "#.##") }.also { assertEquals("bytes < 0: -1", it.message) } val format: NumberFormat = DecimalFormat("#.##", DecimalFormatSymbols(Locale.FRENCH)) assertFailsWith { BinaryByteUnit.format(-1, format) }.also { assertEquals("bytes < 0: -1", it.message) } } } ================================================ FILE: src/jvmTest/kotlin/com/jakewharton/byteunits/BitUnitTest.kt ================================================ package com.jakewharton.byteunits import com.jakewharton.byteunits.BitUnit.BITS import com.jakewharton.byteunits.BitUnit.GIGABITS import com.jakewharton.byteunits.BitUnit.KILOBITS import com.jakewharton.byteunits.BitUnit.MEGABITS import com.jakewharton.byteunits.BitUnit.PETABITS import com.jakewharton.byteunits.BitUnit.TERABITS import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.text.NumberFormat import java.util.Locale import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith class BitUnitTest { @Suppress("KotlinConstantConditions") @Test fun convertInternal() { for (s in 0..998) { assertEquals(s / 8L, BITS.toBytes(s.toLong())) assertEquals(s / 1000L, BITS.toKilobits(s.toLong())) assertEquals(s / 1000000L, BITS.toMegabits(s.toLong())) assertEquals(s / 1000000000L, BITS.toGigabits(s.toLong())) assertEquals(s / 1000000000000L, BITS.toTerabits(s.toLong())) assertEquals(s / 1000000000000000L, BITS.toPetabits(s.toLong())) assertEquals(s * 125L, KILOBITS.toBytes(s.toLong())) assertEquals(s * 1000L, KILOBITS.toBits(s.toLong())) assertEquals(s / 1000L, KILOBITS.toMegabits(s.toLong())) assertEquals(s / 1000000L, KILOBITS.toGigabits(s.toLong())) assertEquals(s / 1000000000L, KILOBITS.toTerabits(s.toLong())) assertEquals(s / 1000000000000L, KILOBITS.toPetabits(s.toLong())) assertEquals(s * 125000L, MEGABITS.toBytes(s.toLong())) assertEquals(s * 1000000L, MEGABITS.toBits(s.toLong())) assertEquals(s * 1000L, MEGABITS.toKilobits(s.toLong())) assertEquals(s / 1000L, MEGABITS.toGigabits(s.toLong())) assertEquals(s / 1000000L, MEGABITS.toTerabits(s.toLong())) assertEquals(s / 1000000000L, MEGABITS.toPetabits(s.toLong())) assertEquals(s * 125000000L, GIGABITS.toBytes(s.toLong())) assertEquals(s * 1000000000L, GIGABITS.toBits(s.toLong())) assertEquals(s * 1000000L, GIGABITS.toKilobits(s.toLong())) assertEquals(s * 1000L, GIGABITS.toMegabits(s.toLong())) assertEquals(s / 1000L, GIGABITS.toTerabits(s.toLong())) assertEquals(s / 1000000L, GIGABITS.toPetabits(s.toLong())) assertEquals(s * 125000000000L, TERABITS.toBytes(s.toLong())) assertEquals(s * 1000000000000L, TERABITS.toBits(s.toLong())) assertEquals(s * 1000000000L, TERABITS.toKilobits(s.toLong())) assertEquals(s * 1000000L, TERABITS.toMegabits(s.toLong())) assertEquals(s * 1000L, TERABITS.toGigabits(s.toLong())) assertEquals(s / 1000L, TERABITS.toPetabits(s.toLong())) assertEquals(s * 125000000000000L, PETABITS.toBytes(s.toLong())) assertEquals(s * 1000000000000000L, PETABITS.toBits(s.toLong())) assertEquals(s * 1000000000000L, PETABITS.toKilobits(s.toLong())) assertEquals(s * 1000000000L, PETABITS.toMegabits(s.toLong())) assertEquals(s * 1000000L, PETABITS.toGigabits(s.toLong())) assertEquals(s * 1000L, PETABITS.toTerabits(s.toLong())) } } @Test fun format() { assertEquals("0 b", BitUnit.format(0)) assertEquals("1 b", BitUnit.format(1)) assertEquals("1 Kb", BitUnit.format(1000)) assertEquals("1 Kb", BitUnit.format(1001)) assertEquals("16 Kb", BitUnit.format(16000)) assertEquals("1.2 Mb", BitUnit.format(1177171)) assertEquals("1.2 Gb", BitUnit.format(1200000000)) assertEquals("9,223.4 Pb", BitUnit.format(Long.MAX_VALUE)) } @Test fun formatWithPattern() { val pattern = "0.0#" assertEquals("0.0 b", BitUnit.format(0, pattern)) assertEquals("1.0 b", BitUnit.format(1, pattern)) assertEquals("1.0 Kb", BitUnit.format(1000, pattern)) assertEquals("1.0 Kb", BitUnit.format(1001, pattern)) assertEquals("16.0 Kb", BitUnit.format(16000, pattern)) assertEquals("1.18 Mb", BitUnit.format(1177171, pattern)) } @Test fun formatWithDecimalFormat() { val format: NumberFormat = DecimalFormat("#.##", DecimalFormatSymbols(Locale.FRENCH)) assertEquals("16 Kb", BitUnit.format(16000, format)) assertEquals("1,18 Mb", BitUnit.format(1177171, format)) } @Test fun formatNegativeValuesThrows() { assertFailsWith { BitUnit.format(-1) }.also { assertEquals("bits < 0: -1", it.message) } assertFailsWith { BitUnit.format(-1, "#.##") }.also { assertEquals("bits < 0: -1", it.message) } val format: NumberFormat = DecimalFormat("#.##", DecimalFormatSymbols(Locale.FRENCH)) assertFailsWith { BitUnit.format(-1, format) }.also { assertEquals("bits < 0: -1", it.message) } } } ================================================ FILE: src/jvmTest/kotlin/com/jakewharton/byteunits/DecimalByteUnitTest.kt ================================================ package com.jakewharton.byteunits import com.jakewharton.byteunits.DecimalByteUnit.BYTES import com.jakewharton.byteunits.DecimalByteUnit.GIGABYTES import com.jakewharton.byteunits.DecimalByteUnit.KILOBYTES import com.jakewharton.byteunits.DecimalByteUnit.MEGABYTES import com.jakewharton.byteunits.DecimalByteUnit.PETABYTES import com.jakewharton.byteunits.DecimalByteUnit.TERABYTES import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.text.NumberFormat import java.util.Locale import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith class DecimalByteUnitTest { @Suppress("KotlinConstantConditions") @Test fun convertInternal() { for (s in 0..998) { assertEquals(s / 1000L, BYTES.toKilobytes(s.toLong())) assertEquals(s / 1000000L, BYTES.toMegabytes(s.toLong())) assertEquals(s / 1000000000L, BYTES.toGigabytes(s.toLong())) assertEquals(s / 1000000000000L, BYTES.toTerabytes(s.toLong())) assertEquals(s / 1000000000000000L, BYTES.toPetabytes(s.toLong())) assertEquals(s * 1000L, KILOBYTES.toBytes(s.toLong())) assertEquals(s / 1000L, KILOBYTES.toMegabytes(s.toLong())) assertEquals(s / 1000000L, KILOBYTES.toGigabytes(s.toLong())) assertEquals(s / 1000000000L, KILOBYTES.toTerabytes(s.toLong())) assertEquals(s / 1000000000000L, KILOBYTES.toPetabytes(s.toLong())) assertEquals(s * 1000000L, MEGABYTES.toBytes(s.toLong())) assertEquals(s * 1000L, MEGABYTES.toKilobytes(s.toLong())) assertEquals(s / 1000L, MEGABYTES.toGigabytes(s.toLong())) assertEquals(s / 1000000L, MEGABYTES.toTerabytes(s.toLong())) assertEquals(s / 1000000000L, MEGABYTES.toPetabytes(s.toLong())) assertEquals(s * 1000000000L, GIGABYTES.toBytes(s.toLong())) assertEquals(s * 1000000L, GIGABYTES.toKilobytes(s.toLong())) assertEquals(s * 1000L, GIGABYTES.toMegabytes(s.toLong())) assertEquals(s / 1000L, GIGABYTES.toTerabytes(s.toLong())) assertEquals(s / 1000000L, GIGABYTES.toPetabytes(s.toLong())) assertEquals(s * 1000000000000L, TERABYTES.toBytes(s.toLong())) assertEquals(s * 1000000000L, TERABYTES.toKilobytes(s.toLong())) assertEquals(s * 1000000L, TERABYTES.toMegabytes(s.toLong())) assertEquals(s * 1000L, TERABYTES.toGigabytes(s.toLong())) assertEquals(s / 1000L, TERABYTES.toPetabytes(s.toLong())) assertEquals(s * 1000000000000000L, PETABYTES.toBytes(s.toLong())) assertEquals(s * 1000000000000L, PETABYTES.toKilobytes(s.toLong())) assertEquals(s * 1000000000L, PETABYTES.toMegabytes(s.toLong())) assertEquals(s * 1000000L, PETABYTES.toGigabytes(s.toLong())) assertEquals(s * 1000L, PETABYTES.toTerabytes(s.toLong())) } } @Test fun format() { assertEquals("0 B", DecimalByteUnit.format(0)) assertEquals("1 B", DecimalByteUnit.format(1)) assertEquals("1 KB", DecimalByteUnit.format(1000)) assertEquals("1 KB", DecimalByteUnit.format(1001)) assertEquals("16 KB", DecimalByteUnit.format(16000)) assertEquals("1.2 MB", DecimalByteUnit.format(1177171)) assertEquals("1.2 GB", DecimalByteUnit.format(1200000000)) assertEquals("9,223.4 PB", DecimalByteUnit.format(Long.MAX_VALUE)) } @Test fun formatWithPattern() { val pattern = "0.0#" assertEquals("0.0 B", DecimalByteUnit.format(0, pattern)) assertEquals("1.0 B", DecimalByteUnit.format(1, pattern)) assertEquals("1.0 KB", DecimalByteUnit.format(1000, pattern)) assertEquals("1.0 KB", DecimalByteUnit.format(1001, pattern)) assertEquals("16.0 KB", DecimalByteUnit.format(16000, pattern)) assertEquals("1.18 MB", DecimalByteUnit.format(1177171, pattern)) } @Test fun formatWithDecimalFormat() { val format: NumberFormat = DecimalFormat("#.##", DecimalFormatSymbols(Locale.FRENCH)) assertEquals("16 KB", DecimalByteUnit.format(16000, format)) assertEquals("1,18 MB", DecimalByteUnit.format(1177171, format)) } @Test fun formatNegativeValuesThrows() { assertFailsWith { DecimalByteUnit.format(-1) }.also { assertEquals("bytes < 0: -1", it.message) } assertFailsWith { DecimalByteUnit.format(-1, "#.##") }.also { assertEquals("bytes < 0: -1", it.message) } val format: NumberFormat = DecimalFormat("#.##", DecimalFormatSymbols(Locale.FRENCH)) assertFailsWith { DecimalByteUnit.format(-1, format) }.also { assertEquals("bytes < 0: -1", it.message) } } }