diff --git a/.gitignore b/.gitignore index 3e49fef..da0faa8 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,11 @@ .idea/**/usage.statistics.xml .idea/**/dictionaries .idea/**/shelf +.idea/AndroidProjectSystem.xml +.idea/discord.xml +.idea/kotlinc.xml +.idea/misc.xml +.idea/vcs.xml # Generated files .idea/**/contentModel.xml @@ -95,7 +100,8 @@ fabric.properties # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* -local.properties # Android +# Android +local.properties # Gradle .gradle diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..30cf57e --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Ignored default folder with query files +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/build.gradle.kts b/build.gradle.kts index 9e29c13..f3c50aa 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,21 +1,10 @@ plugins { - kotlin("multiplatform") version Dependencies.Versions.kotlin apply false - kotlin("plugin.serialization") version Dependencies.Versions.kotlin apply false - id("org.jetbrains.kotlinx.benchmark") version Dependencies.Versions.benchmark apply false -} - -repositories { - mavenCentral() -} - -buildscript { - repositories { - maven("https://plugins.gradle.org/m2/") - } - dependencies { - classpath("org.jlleitschuh.gradle:ktlint-gradle:${Dependencies.Versions.ktlintGradle}") - classpath("org.jetbrains.dokka:dokka-gradle-plugin:${Dependencies.Versions.dokkaGradle}") - } + alias(libs.plugins.kotlin.multiplatform) apply false + alias(libs.plugins.android.library) apply false + alias(libs.plugins.kotlinx.serialization) apply false + alias(libs.plugins.kotlinx.benchmark) apply false + alias(libs.plugins.ktlint) apply false + alias(libs.plugins.dokka) apply false } val snapshot: String? by project @@ -29,19 +18,14 @@ val sonatypePasswordEnv: String? = System.getenv()["SONATYPE_PASSWORD"] val sonatypeUsernameEnv: String? = System.getenv()["SONATYPE_USERNAME"] allprojects { - group = Config.group + group = "com.ensarsarajcic.kotlinx" version = version.toString() + if (snapshot == "true") "-SNAPSHOT" else "" - - apply(plugin = "org.jlleitschuh.gradle.ktlint") - - repositories { - mavenLocal() - mavenCentral() - } } subprojects { afterEvaluate { + if(project.name.endsWith("-benchmarks")) return@afterEvaluate + configure { isRequired = false sign(extensions.getByType().publications) diff --git a/buildSrc/.gitignore b/buildSrc/.gitignore deleted file mode 100644 index 567609b..0000000 --- a/buildSrc/.gitignore +++ /dev/null @@ -1 +0,0 @@ -build/ diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts deleted file mode 100644 index 876c922..0000000 --- a/buildSrc/build.gradle.kts +++ /dev/null @@ -1,7 +0,0 @@ -plugins { - `kotlin-dsl` -} - -repositories { - mavenCentral() -} diff --git a/buildSrc/src/main/kotlin/Config.kt b/buildSrc/src/main/kotlin/Config.kt deleted file mode 100644 index 63b68bb..0000000 --- a/buildSrc/src/main/kotlin/Config.kt +++ /dev/null @@ -1,3 +0,0 @@ -object Config { - const val group = "com.ensarsarajcic.kotlinx" -} \ No newline at end of file diff --git a/buildSrc/src/main/kotlin/Dependencies.kt b/buildSrc/src/main/kotlin/Dependencies.kt deleted file mode 100644 index 822876a..0000000 --- a/buildSrc/src/main/kotlin/Dependencies.kt +++ /dev/null @@ -1,10 +0,0 @@ -object Dependencies { - object Versions { - const val kotlin = "2.1.0" - const val serialization = "1.7.3" - const val datetime = "0.6.1" - const val ktlintGradle = "12.1.2" - const val dokkaGradle = "2.0.0" - const val benchmark = "0.4.13" - } -} diff --git a/gradle.properties b/gradle.properties index b612b30..ce94605 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,13 +1,20 @@ +android.useAndroidX=true +android.injected.build.model.v2=true +android.nonTransitiveRClass=true kotlin.code.style=official -kotlin.incremental.multiplatform=true -kotlin.js.generate.executable.default=false +kotlin.incremental.native=true +kotlin.mpp.androidSourceSetLayoutVersion=2 +kotlin.mpp.enableCInteropCommonization=true kotlin.native.ignoreDisabledTargets=true -org.jetbrains.dokka.experimental.gradle.pluginMode=V2Enabled -org.jetbrains.dokka.experimental.gradle.pluginMode.noWarn=true +kotlin.native.parallelThreads=8 +kotlin.native.enableKlibsCrossCompilation=true org.gradle.vfs.watch=true org.gradle.parallel=true org.gradle.caching=true org.gradle.jvmargs=-XX:MaxMetaspaceSize=1g +org.gradle.configureondemand=false +org.gradle.configuration-cache=true +org.gradle.configuration-cache-problems=warn -version=0.6.1 +version=1.0.0 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..78ce8c1 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,35 @@ +[versions] + +java = "17" + +androidGradle = "9.2.1" +androidMinSdk = "28" +androidTargetSdk = "36" + +kotlin = "2.3.21" +kotlinxSerialization = "1.11.0" +kotlinxBenchmark = "0.4.17" +kotlinBrowser = "2026.4.15" +ktlint = "14.2.0" +dokka = "2.2.0" + +msgpak = "0.9.12" + +[libraries] + +kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" } +kotlinx-benchmark-runtime = { module = "org.jetbrains.kotlinx:kotlinx-benchmark-runtime", version.ref = "kotlinxBenchmark" } +kotlinx-serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core", version.ref = "kotlinxSerialization" } +kotlin-wrappers-browser = { module = "org.jetbrains.kotlin-wrappers:kotlin-browser", version.ref = "kotlinBrowser" } + +msgpak-core = { module = "org.msgpack:msgpack-core", version.ref = "msgpak" } +msgpak-dataformat = { module = "org.msgpack:jackson-dataformat-msgpack", version.ref = "msgpak" } + +[plugins] + +android-library = { id = "com.android.kotlin.multiplatform.library", version.ref = "androidGradle" } +kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } +kotlinx-benchmark = { id = "org.jetbrains.kotlinx.benchmark", version.ref = "kotlinxBenchmark" } +kotlinx-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } +dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } +ktlint = { id = "org.jlleitschuh.gradle.ktlint", version.ref = "ktlint" } \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 490fda8..b1b8ef5 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 81aa1c0..fd771c8 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,10 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip +distributionSha256Sum=a3c4ba4aca8f0075688b9c5b18939fd28e8cb4357c227da5c1d9f38343791439 +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-all.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 2fe81a7..b9bb139 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# 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. @@ -15,80 +15,114 @@ # 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 UN*X -## +# +# 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/3d91ce3b8caaf77ad09f381f43615b715b53f72c/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 -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +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 -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# 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"' +# 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" +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 - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # 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" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -97,87 +131,118 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + 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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +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 -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -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" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + 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 - i=`expr $i + 1` + # 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 - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# 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" \ + -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" "$@" diff --git a/gradlew.bat b/gradlew.bat index 9109989..aa5f10b 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,19 +13,22 @@ @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 +@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 +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,64 +43,40 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +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 +"%COMSPEC%" /c exit 1 :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args +if exist "%JAVA_EXE%" goto execute -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 +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 -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* +"%COMSPEC%" /c exit 1 :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="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! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal +@rem Execute Gradle +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel -:omega +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/local.properties b/local.properties deleted file mode 100644 index e69de29..0000000 diff --git a/serialization-msgpack-benchmarks/build.gradle.kts b/serialization-msgpack-benchmarks/build.gradle.kts new file mode 100644 index 0000000..61ccaa0 --- /dev/null +++ b/serialization-msgpack-benchmarks/build.gradle.kts @@ -0,0 +1,61 @@ +@file:OptIn(ExperimentalWasmDsl::class) + +import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl + +plugins { + alias(libs.plugins.kotlin.multiplatform) + alias(libs.plugins.kotlinx.benchmark) + alias(libs.plugins.kotlinx.serialization) + alias(libs.plugins.ktlint) +} + +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(libs.versions.java.get().toInt())) + } +} + +kotlin { + compilerOptions { + freeCompilerArgs.add("-Xannotation-default-target=param-property") + } + jvmToolchain(libs.versions.java.get().toInt()) + jvm() + js { + browser() + nodejs() + } + wasmJs { + browser() + nodejs() + } + applyDefaultHierarchyTemplate() + sourceSets { + commonMain { + dependencies { + implementation(project(":serialization-msgpack")) + implementation(libs.kotlinx.benchmark.runtime) + } + } + jvmMain { + dependencies { + implementation(libs.msgpak.core) + implementation(libs.msgpak.dataformat) + } + } + webMain { + dependencies { + implementation(npm("@msgpack/msgpack", ">2.0.0 <3.0.0")) + implementation(libs.kotlin.wrappers.browser) + } + } + } +} + +benchmark { + targets { + register("jvm") + register("js") + register("wasmJs") + } +} \ No newline at end of file diff --git a/serialization-msgpack-benchmarks/src/jsMain/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/MsgpackJavascript.kt b/serialization-msgpack-benchmarks/src/jsMain/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/MsgpackJavascript.kt new file mode 100644 index 0000000..b0f0675 --- /dev/null +++ b/serialization-msgpack-benchmarks/src/jsMain/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/MsgpackJavascript.kt @@ -0,0 +1,7 @@ +@file:OptIn(ExperimentalWasmJsInterop::class) + +package com.ensarsarajcic.kotlinx.serialization.msgpack + +actual fun encodeMsgpack(obj: JsAny): ByteArray = encode(obj) + +actual fun decodeMsgpack(bytes: ByteArray): T = decode(bytes) \ No newline at end of file diff --git a/serialization-msgpack-benchmarks/src/jsMain/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/msgpack.kt b/serialization-msgpack-benchmarks/src/jsMain/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/msgpack.kt new file mode 100644 index 0000000..7b884df --- /dev/null +++ b/serialization-msgpack-benchmarks/src/jsMain/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/msgpack.kt @@ -0,0 +1,7 @@ +@file:JsModule("@msgpack/msgpack") @file:JsNonModule + +package com.ensarsarajcic.kotlinx.serialization.msgpack + +internal external fun encode(obj: Any): ByteArray + +internal external fun decode(bytes: ByteArray): T \ No newline at end of file diff --git a/serialization-msgpack/src/jvmBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/DeserializeBenchmarks.kt b/serialization-msgpack-benchmarks/src/jvmMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/DeserializeBenchmarks.kt similarity index 59% rename from serialization-msgpack/src/jvmBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/DeserializeBenchmarks.kt rename to serialization-msgpack-benchmarks/src/jvmMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/DeserializeBenchmarks.kt index be5b2bf..c043e30 100644 --- a/serialization-msgpack/src/jvmBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/DeserializeBenchmarks.kt +++ b/serialization-msgpack-benchmarks/src/jvmMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/DeserializeBenchmarks.kt @@ -18,6 +18,7 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.modules.SerializersModule import org.msgpack.jackson.dataformat.MessagePackFactory +@OptIn(InternalMsgPackApi::class) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(BenchmarkTimeUnit.NANOSECONDS) @Measurement(iterations = 20, time = 1, timeUnit = BenchmarkTimeUnit.SECONDS) @@ -26,24 +27,18 @@ open class DeserializeBenchmarks { @Serializable @JsonIgnoreProperties(ignoreUnknown = true) class SampleClassWithNestedClass( - @JsonProperty("testString") - var testString: String, - @JsonProperty("testInt") - var testInt: Int, - @JsonProperty("testBoolean") - var testBoolean: Boolean, - @JsonProperty("testNested") - var testNested: NestedClass, - @JsonProperty("secondNested") - var secondNested: NestedClass? = null, + @JsonProperty("testString") var testString: String, + @JsonProperty("testInt") var testInt: Int, + @JsonProperty("testBoolean") var testBoolean: Boolean, + @JsonProperty("testNested") var testNested: NestedClass, + @JsonProperty("secondNested") var secondNested: NestedClass? = null, ) { constructor() : this("", 0, false, NestedClass(null), null) @Serializable @JsonIgnoreProperties(ignoreUnknown = true) class NestedClass( - @JsonProperty("testInt") - var testInt: Int? = null, + @JsonProperty("testInt") var testInt: Int? = null, ) { constructor() : this(null) } @@ -52,14 +47,12 @@ open class DeserializeBenchmarks { // The actual benchmark method @Benchmark fun benchmarkKotlinxSerializationMsgpack() { - val decoder = - BasicMsgPackDecoder( - MsgPackConfiguration.default.copy(ignoreUnknownKeys = true), - SerializersModule { - }, - @Suppress("ktlint:standard:max-line-length") - "85aa74657374537472696e67a3646566a774657374496e747bab74657374426f6f6c65616ec3aa746573744e657374656483aa74657374537472696e67a3646566ab74657374426f6f6c65616ec3ae616e6f74686572556e6b6e6f776ea474657374ac7365636f6e644e657374656481ab74657374426f6f6c65616ec2".hexStringToByteArray().toMsgPackBuffer(), - ) + val decoder = BasicMsgPackDecoder( + MsgPackConfiguration.default.copy(ignoreUnknownKeys = true), + SerializersModule {}, + @Suppress("ktlint:standard:max-line-length") "85aa74657374537472696e67a3646566a774657374496e747bab74657374426f6f6c65616ec3aa746573744e657374656483aa74657374537472696e67a3646566ab74657374426f6f6c65616ec3ae616e6f74686572556e6b6e6f776ea474657374ac7365636f6e644e657374656481ab74657374426f6f6c65616ec2".hexStringToByteArray() + .toMsgPackBuffer(), + ) SampleClassWithNestedClass.serializer().deserialize(decoder) } @@ -67,8 +60,7 @@ open class DeserializeBenchmarks { fun benchmarkMsgpackJava() { val objectMapper = ObjectMapper(MessagePackFactory()) objectMapper.readValue( - @Suppress("ktlint:standard:max-line-length") - "85aa74657374537472696e67a3646566a774657374496e747bab74657374426f6f6c65616ec3aa746573744e657374656483aa74657374537472696e67a3646566ab74657374426f6f6c65616ec3ae616e6f74686572556e6b6e6f776ea474657374ac7365636f6e644e657374656481ab74657374426f6f6c65616ec2".hexStringToByteArray(), + @Suppress("ktlint:standard:max-line-length") "85aa74657374537472696e67a3646566a774657374496e747bab74657374426f6f6c65616ec3aa746573744e657374656483aa74657374537472696e67a3646566ab74657374426f6f6c65616ec3ae616e6f74686572556e6b6e6f776ea474657374ac7365636f6e644e657374656481ab74657374426f6f6c65616ec2".hexStringToByteArray(), object : TypeReference() {}, ) } diff --git a/serialization-msgpack-benchmarks/src/jvmMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/SerializeBenchmarks.kt b/serialization-msgpack-benchmarks/src/jvmMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/SerializeBenchmarks.kt new file mode 100644 index 0000000..4cb5a39 --- /dev/null +++ b/serialization-msgpack-benchmarks/src/jvmMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/SerializeBenchmarks.kt @@ -0,0 +1,124 @@ +package com.ensarsarajcic.kotlinx.serialization.msgpack + +import com.fasterxml.jackson.databind.ObjectMapper +import kotlinx.benchmark.Benchmark +import kotlinx.benchmark.BenchmarkMode +import kotlinx.benchmark.BenchmarkTimeUnit +import kotlinx.benchmark.Measurement +import kotlinx.benchmark.Mode +import kotlinx.benchmark.OutputTimeUnit +import kotlinx.benchmark.Scope +import kotlinx.benchmark.State +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.encodeToByteArray +import org.msgpack.jackson.dataformat.MessagePackFactory + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(BenchmarkTimeUnit.NANOSECONDS) +@Measurement(iterations = 20, time = 1, timeUnit = BenchmarkTimeUnit.SECONDS) +@State(Scope.Benchmark) +open class SerializeBenchmarks { + @Serializable + data class SampleClass( + @SerialName("testString") val testString: String, + val testInt: Int, + val testBoolean: Boolean, + ) + + @Serializable + data class SampleClassWithNestedClass( + val testString: String, + val testInt: Int, + val testBoolean: Boolean, + val testNested: NestedClass, + val testSample: SampleClass, + val testSampleList: List, + val testSampleMap: Map, + val extraBytes: ByteArray, + val secondNested: NestedClass? = null, + ) { + @Serializable + data class NestedClass( + val testInt: Int? = null, + ) + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as SampleClassWithNestedClass + + if (testInt != other.testInt) return false + if (testBoolean != other.testBoolean) return false + if (testString != other.testString) return false + if (testNested != other.testNested) return false + if (testSample != other.testSample) return false + if (testSampleList != other.testSampleList) return false + if (testSampleMap != other.testSampleMap) return false + if (!extraBytes.contentEquals(other.extraBytes)) return false + if (secondNested != other.secondNested) return false + + return true + } + + override fun hashCode(): Int { + var result = testInt + result = 31 * result + testBoolean.hashCode() + result = 31 * result + testString.hashCode() + result = 31 * result + testNested.hashCode() + result = 31 * result + testSample.hashCode() + result = 31 * result + testSampleList.hashCode() + result = 31 * result + testSampleMap.hashCode() + result = 31 * result + extraBytes.contentHashCode() + result = 31 * result + (secondNested?.hashCode() ?: 0) + return result + } + } + + // The actual benchmark method + @Benchmark + fun benchmarkKotlinxSerializationMsgpack() { + val instance = SampleClassWithNestedClass( + testString = "testString", + testInt = 10, + testBoolean = true, + testNested = SampleClassWithNestedClass.NestedClass(5), + testSample = SampleClass(testString = "testString2", testInt = 17, testBoolean = false), + testSampleList = listOf( + SampleClass("testString3", testInt = 25, testBoolean = true), + SampleClass("testString4", testInt = 100, testBoolean = false), + ), + testSampleMap = mapOf( + "testString5" to SampleClass("testString5", testInt = 12, testBoolean = false), + "testString6" to SampleClass("testString6", testInt = 15, testBoolean = true), + ), + extraBytes = byteArrayOf(0x12, 0x13, 0x14, 0x15), + secondNested = SampleClassWithNestedClass.NestedClass(null), + ) + MsgPack.encodeToByteArray(instance) + } + + @Benchmark + fun benchmarkMsgpackJava() { + val instance = SampleClassWithNestedClass( + testString = "testString", + testInt = 10, + testBoolean = true, + testNested = SampleClassWithNestedClass.NestedClass(5), + testSample = SampleClass(testString = "testString2", testInt = 17, testBoolean = false), + testSampleList = listOf( + SampleClass("testString3", testInt = 25, testBoolean = true), + SampleClass("testString4", testInt = 100, testBoolean = false), + ), + testSampleMap = mapOf( + "testString5" to SampleClass("testString5", testInt = 12, testBoolean = false), + "testString6" to SampleClass("testString6", testInt = 15, testBoolean = true), + ), + extraBytes = byteArrayOf(0x12, 0x13, 0x14, 0x15), + secondNested = SampleClassWithNestedClass.NestedClass(null), + ) + val objectMapper = ObjectMapper(MessagePackFactory()) + objectMapper.writeValueAsBytes(instance) + } +} diff --git a/serialization-msgpack-benchmarks/src/wasmJsMain/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/MsgpackJavascript.kt b/serialization-msgpack-benchmarks/src/wasmJsMain/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/MsgpackJavascript.kt new file mode 100644 index 0000000..6a1b80e --- /dev/null +++ b/serialization-msgpack-benchmarks/src/wasmJsMain/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/MsgpackJavascript.kt @@ -0,0 +1,10 @@ +@file:OptIn(ExperimentalWasmJsInterop::class) + +package com.ensarsarajcic.kotlinx.serialization.msgpack + +import js.typedarrays.toByteArray +import js.typedarrays.toUint8Array + +actual fun encodeMsgpack(obj: JsAny): ByteArray = encode(obj).toByteArray() + +actual fun decodeMsgpack(bytes: ByteArray): T = decode(bytes.toUint8Array()) \ No newline at end of file diff --git a/serialization-msgpack-benchmarks/src/wasmJsMain/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/msgpack.kt b/serialization-msgpack-benchmarks/src/wasmJsMain/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/msgpack.kt new file mode 100644 index 0000000..bde5b26 --- /dev/null +++ b/serialization-msgpack-benchmarks/src/wasmJsMain/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/msgpack.kt @@ -0,0 +1,13 @@ +@file:OptIn(ExperimentalWasmJsInterop::class) @file:JsModule("@msgpack/msgpack") + +package com.ensarsarajcic.kotlinx.serialization.msgpack + +import js.buffer.ArrayBuffer +import js.typedarrays.Uint8Array + +internal external interface EncoderOptions : JsAny +internal external interface DecoderOptions : JsAny + +internal external fun encode(obj: JsAny, options: EncoderOptions? = definedExternally): Uint8Array + +internal external fun decode(bytes: Uint8Array<*>, options: DecoderOptions? = definedExternally): T \ No newline at end of file diff --git a/serialization-msgpack-benchmarks/src/webMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/DeserializeBenchmarks.kt b/serialization-msgpack-benchmarks/src/webMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/DeserializeBenchmarks.kt new file mode 100644 index 0000000..ed08114 --- /dev/null +++ b/serialization-msgpack-benchmarks/src/webMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/DeserializeBenchmarks.kt @@ -0,0 +1,71 @@ +@file:OptIn(InternalMsgPackApi::class, ExperimentalWasmJsInterop::class) + +package com.ensarsarajcic.kotlinx.serialization.msgpack + +import com.ensarsarajcic.kotlinx.serialization.msgpack.internal.BasicMsgPackDecoder +import com.ensarsarajcic.kotlinx.serialization.msgpack.stream.toMsgPackBuffer +import kotlinx.benchmark.Benchmark +import kotlinx.benchmark.BenchmarkMode +import kotlinx.benchmark.BenchmarkTimeUnit +import kotlinx.benchmark.Measurement +import kotlinx.benchmark.Mode +import kotlinx.benchmark.OutputTimeUnit +import kotlinx.benchmark.Scope +import kotlinx.benchmark.State +import kotlinx.serialization.Serializable +import kotlinx.serialization.modules.SerializersModule +import kotlin.js.ExperimentalWasmJsInterop +import kotlin.js.JsAny + +@Serializable +private class SimpleSampleClassWithNestedClass( + var testString: String, + var testInt: Int, + var testBoolean: Boolean, + var testNested: SimpleNestedClass, + var secondNested: SimpleNestedClass? = null, +) { + @Serializable + class SimpleNestedClass( + var testInt: Int? = null, + ) +} + +private external interface ExtSimpleNestedClass : JsAny { + var testInt: Int? +} + +private external interface ExtSimpleSampleClassWithNestedClass : JsAny { + var testString: String + var testInt: Int + var testBoolean: Boolean + var testNested: ExtSimpleNestedClass + var secondNested: ExtSimpleNestedClass? +} + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(BenchmarkTimeUnit.NANOSECONDS) +@Measurement(iterations = 20, time = 1, timeUnit = BenchmarkTimeUnit.SECONDS) +@State(Scope.Benchmark) +open class DeserializeBenchmarks { + // The actual benchmark method + @Benchmark + fun benchmarkKotlinxSerializationMsgpack() { + val decoder = BasicMsgPackDecoder( + MsgPackConfiguration.default.copy(ignoreUnknownKeys = true), + SerializersModule {}, + @Suppress("ktlint:standard:max-line-length") "85aa74657374537472696e67a3646566a774657374496e747bab74657374426f6f6c65616ec3aa746573744e657374656483aa74657374537472696e67a3646566ab74657374426f6f6c65616ec3ae616e6f74686572556e6b6e6f776ea474657374ac7365636f6e644e657374656481ab74657374426f6f6c65616ec2".hexStringToByteArray() + .toMsgPackBuffer(), + ) + SimpleSampleClassWithNestedClass.serializer().deserialize(decoder) + } + + @Benchmark + fun benchmarkMsgpackJs() { + @Suppress("ktlint:standard:max-line-length") decodeMsgpack( + "85aa74657374537472696e67a3646566a774657374496e747bab74657374426f6f6c65616ec3aa746573744e657374656483aa74657374537472696e67a3646566ab74657374426f6f6c65616ec3ae616e6f74686572556e6b6e6f776ea474657374ac7365636f6e644e657374656481ab74657374426f6f6c65616ec2".hexStringToByteArray(), + ) + } +} + +fun String.hexStringToByteArray() = ByteArray(this.length / 2) { this.substring(it * 2, it * 2 + 2).toInt(16).toByte() } diff --git a/serialization-msgpack-benchmarks/src/webMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgpackJavascript.kt b/serialization-msgpack-benchmarks/src/webMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgpackJavascript.kt new file mode 100644 index 0000000..44d0408 --- /dev/null +++ b/serialization-msgpack-benchmarks/src/webMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgpackJavascript.kt @@ -0,0 +1,10 @@ +@file:OptIn(ExperimentalWasmJsInterop::class) + +package com.ensarsarajcic.kotlinx.serialization.msgpack + +import kotlin.js.ExperimentalWasmJsInterop +import kotlin.js.JsAny + +expect fun encodeMsgpack(obj: JsAny): ByteArray + +expect fun decodeMsgpack(bytes: ByteArray): T diff --git a/serialization-msgpack-benchmarks/src/webMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/SerializeBenchmarks.kt b/serialization-msgpack-benchmarks/src/webMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/SerializeBenchmarks.kt new file mode 100644 index 0000000..ed4b283 --- /dev/null +++ b/serialization-msgpack-benchmarks/src/webMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/SerializeBenchmarks.kt @@ -0,0 +1,178 @@ +@file:OptIn(ExperimentalWasmJsInterop::class) + +package com.ensarsarajcic.kotlinx.serialization.msgpack + +import js.array.jsArrayOf +import js.array.tupleOf +import js.buffer.ArrayBuffer +import js.collections.JsMap +import js.objects.unsafeJso +import js.typedarrays.Int8Array +import js.typedarrays.toInt8Array +import kotlinx.benchmark.Benchmark +import kotlinx.benchmark.BenchmarkMode +import kotlinx.benchmark.BenchmarkTimeUnit +import kotlinx.benchmark.Measurement +import kotlinx.benchmark.Mode +import kotlinx.benchmark.OutputTimeUnit +import kotlinx.benchmark.Scope +import kotlinx.benchmark.State +import kotlinx.serialization.Serializable +import kotlinx.serialization.encodeToByteArray +import kotlin.js.ExperimentalWasmJsInterop +import kotlin.js.JsAny +import kotlin.js.JsArray +import kotlin.js.JsString +import kotlin.js.toJsString + +@Serializable +private data class SampleClass( + val testString: String, + val testInt: Int, + val testBoolean: Boolean, +) + +@Serializable +private data class SampleClassWithNestedClass( + val testString: String, + val testInt: Int, + val testBoolean: Boolean, + val testNested: NestedClass, + val testSample: SampleClass, + val testSampleList: List, + val testSampleMap: Map, + val extraBytes: ByteArray, + val secondNested: NestedClass? = null, +) { + @Serializable + data class NestedClass( + val testInt: Int? = null, + ) + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null || this::class != other::class) return false + + other as SampleClassWithNestedClass + + if (testInt != other.testInt) return false + if (testBoolean != other.testBoolean) return false + if (testString != other.testString) return false + if (testNested != other.testNested) return false + if (testSample != other.testSample) return false + if (testSampleList != other.testSampleList) return false + if (testSampleMap != other.testSampleMap) return false + if (!extraBytes.contentEquals(other.extraBytes)) return false + if (secondNested != other.secondNested) return false + + return true + } + + override fun hashCode(): Int { + var result = testInt + result = 31 * result + testBoolean.hashCode() + result = 31 * result + testString.hashCode() + result = 31 * result + testNested.hashCode() + result = 31 * result + testSample.hashCode() + result = 31 * result + testSampleList.hashCode() + result = 31 * result + testSampleMap.hashCode() + result = 31 * result + extraBytes.contentHashCode() + result = 31 * result + (secondNested?.hashCode() ?: 0) + return result + } +} + +private external interface ExtSampleClass : JsAny { + var testString: String + var testInt: Int + var testBoolean: Boolean +} + +private external interface ExtNestedClass : JsAny { + var testInt: Int? +} + +private external interface ExtSampleClassWithNestedClass : JsAny { + var testString: String + var testInt: Int + var testBoolean: Boolean + var testNested: ExtNestedClass + var testSample: ExtSampleClass + var testSampleList: JsArray + var testSampleMap: JsMap + var extraBytes: Int8Array + var secondNested: ExtNestedClass? +} + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(BenchmarkTimeUnit.NANOSECONDS) +@Measurement(iterations = 20, time = 1, timeUnit = BenchmarkTimeUnit.SECONDS) +@State(Scope.Benchmark) +open class SerializeBenchmarks { + // The actual benchmark method + @Benchmark + fun benchmarkKotlinxSerializationMsgpack() { + val instance = SampleClassWithNestedClass( + testString = "testString", + testInt = 10, + testBoolean = true, + testNested = SampleClassWithNestedClass.NestedClass(5), + testSample = SampleClass(testString = "testString2", testInt = 17, testBoolean = false), + testSampleList = listOf( + SampleClass("testString3", testInt = 25, testBoolean = true), + SampleClass("testString4", testInt = 100, testBoolean = false), + ), + testSampleMap = mapOf( + "testString5" to SampleClass("testString5", testInt = 12, testBoolean = false), + "testString6" to SampleClass("testString6", testInt = 15, testBoolean = true), + ), + extraBytes = byteArrayOf(0x12, 0x13, 0x14, 0x15), + secondNested = SampleClassWithNestedClass.NestedClass(null), + ) + MsgPack.encodeToByteArray(instance) + } + + @Benchmark + fun benchmarkMsgpackJs() { + val instance = unsafeJso { + testString = "testString" + testInt = 10 + testBoolean = true + testNested = unsafeJso { + testInt = 5 + } + testSample = unsafeJso { + testString = "testString2" + testInt = 17 + testBoolean = false + } + testSampleList = jsArrayOf(unsafeJso { + testString = "testString3" + testInt = 25 + testBoolean = true + }, unsafeJso { + testString = "testString4" + testInt = 100 + testBoolean = false + }) + testSampleMap = JsMap( + jsArrayOf( + tupleOf("testString5".toJsString(), unsafeJso { + testString = "testString5" + testInt = 12 + testBoolean = false + }), tupleOf("testString6".toJsString(), unsafeJso { + testString = "testString6" + testInt = 15 + testBoolean = true + }) + ) + ) + extraBytes = byteArrayOf(0x12, 0x13, 0x14, 0x15).toInt8Array() + secondNested = unsafeJso { + testInt = null + } + } + encodeMsgpack(instance) + } +} diff --git a/serialization-msgpack-timestamp-extension/build.gradle.kts b/serialization-msgpack-timestamp-extension/build.gradle.kts index 5f6bb76..1afa1e5 100644 --- a/serialization-msgpack-timestamp-extension/build.gradle.kts +++ b/serialization-msgpack-timestamp-extension/build.gradle.kts @@ -1,19 +1,37 @@ +@file:OptIn(ExperimentalWasmDsl::class) + +import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl + plugins { - kotlin("multiplatform") - kotlin("plugin.serialization") - id("maven-publish") - id("signing") - id("org.jetbrains.dokka") - id("org.jetbrains.kotlinx.benchmark") + alias(libs.plugins.kotlin.multiplatform) + alias(libs.plugins.android.library) + alias(libs.plugins.kotlinx.serialization) + alias(libs.plugins.dokka) + alias(libs.plugins.ktlint) + signing + `maven-publish` +} + +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(libs.versions.java.get().toInt())) + } } kotlin { - applyDefaultHierarchyTemplate() + withSourcesJar() + jvmToolchain(libs.versions.java.get().toInt()) jvm { compilations.create("benchmark") { associateWith(this@jvm.compilations.getByName("main")) } } + android { + namespace = "$group.timestamp" + compileSdk = libs.versions.androidTargetSdk.get().toInt() + minSdk = libs.versions.androidMinSdk.get().toInt() + lint.targetSdk = libs.versions.androidTargetSdk.get().toInt() + } js { browser { testTask { @@ -22,26 +40,33 @@ kotlin { } } } + nodejs() } - iosX64() + wasmJs { + browser { + testTask { + useKarma { + useChromeHeadless() + } + } + } + nodejs() + } + iosArm64() iosX64() iosSimulatorArm64() - tvosX64() tvosArm64() - watchosX64() watchosArm64() - macosX64() macosArm64() mingwX64() linuxX64() + // TODO: remove deprecated targets in next release + macosX64() + tvosX64() + watchosX64() - fun kotlinx( - name: String, - version: String, - ): String = "org.jetbrains.kotlinx:kotlinx-$name:$version" - - fun kotlinxSerialization(name: String) = kotlinx("serialization-$name", Dependencies.Versions.serialization) + applyDefaultHierarchyTemplate() sourceSets { all { @@ -52,35 +77,12 @@ kotlin { commonMain { dependencies { implementation(project(":serialization-msgpack")) - implementation(kotlinx("datetime", Dependencies.Versions.datetime)) } } commonTest { dependencies { - implementation(kotlin("test-common")) - implementation(kotlin("test-annotations-common")) - } - } - jvmTest { - dependencies { - implementation(kotlin("test-junit")) - } - } - val jvmBenchmark by getting { - dependencies { - implementation(kotlinx("benchmark-runtime", Dependencies.Versions.benchmark)) - } - } - jsTest { - dependencies { - implementation(kotlin("test-js")) + implementation(libs.kotlin.test) } } } -} - -benchmark { - targets { - register("jvmBenchmark") - } -} +} \ No newline at end of file diff --git a/serialization-msgpack-timestamp-extension/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/datetime/MsgPackDatetimeSerializer.kt b/serialization-msgpack-timestamp-extension/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/datetime/MsgPackDatetimeSerializer.kt index 695d8ec..6d05128 100644 --- a/serialization-msgpack-timestamp-extension/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/datetime/MsgPackDatetimeSerializer.kt +++ b/serialization-msgpack-timestamp-extension/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/datetime/MsgPackDatetimeSerializer.kt @@ -4,7 +4,7 @@ import com.ensarsarajcic.kotlinx.serialization.msgpack.extensions.BaseMsgPackExt import com.ensarsarajcic.kotlinx.serialization.msgpack.extensions.MsgPackExtension import com.ensarsarajcic.kotlinx.serialization.msgpack.extensions.MsgPackTimestamp import com.ensarsarajcic.kotlinx.serialization.msgpack.extensions.MsgPackTimestampExtensionSerializer -import kotlinx.datetime.Instant +import kotlin.time.Instant sealed class BaseMsgPackDatetimeSerializer(private val outputType: Byte) : BaseMsgPackExtensionSerializer() { init { @@ -22,27 +22,29 @@ sealed class BaseMsgPackDatetimeSerializer(private val outputType: Byte) : BaseM } override fun serialize(extension: Instant): MsgPackExtension { - val timestamp = - when (outputType) { - 0.toByte() -> { - MsgPackTimestamp.T32(extension.epochSeconds) - } - 1.toByte() -> { - MsgPackTimestamp.T64(extension.epochSeconds, extension.nanosecondsOfSecond) - } - 2.toByte() -> { - MsgPackTimestamp.T92(extension.epochSeconds, extension.nanosecondsOfSecond.toLong()) - } - else -> throw AssertionError() + val timestamp = when (outputType) { + 0.toByte() -> { + MsgPackTimestamp.T32(extension.epochSeconds) } + + 1.toByte() -> { + MsgPackTimestamp.T64(extension.epochSeconds, extension.nanosecondsOfSecond) + } + + 2.toByte() -> { + MsgPackTimestamp.T92(extension.epochSeconds, extension.nanosecondsOfSecond.toLong()) + } + + else -> throw AssertionError() + } return timestampSerializer.serialize(timestamp) } override val extTypeId: Byte = -1 } -class MsgPackTimestamp32DatetimeSerializer() : BaseMsgPackDatetimeSerializer(0) +class MsgPackTimestamp32DatetimeSerializer : BaseMsgPackDatetimeSerializer(0) -class MsgPackTimestamp64DatetimeSerializer() : BaseMsgPackDatetimeSerializer(1) +class MsgPackTimestamp64DatetimeSerializer : BaseMsgPackDatetimeSerializer(1) -class MsgPackTimestamp92DatetimeSerializer() : BaseMsgPackDatetimeSerializer(2) +class MsgPackTimestamp92DatetimeSerializer : BaseMsgPackDatetimeSerializer(2) diff --git a/serialization-msgpack-timestamp-extension/src/commonTest/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/datetime/MsgPackDatetimeSerializerTest.kt b/serialization-msgpack-timestamp-extension/src/commonTest/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/datetime/MsgPackDatetimeSerializerTest.kt index f16e32a..81f6341 100644 --- a/serialization-msgpack-timestamp-extension/src/commonTest/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/datetime/MsgPackDatetimeSerializerTest.kt +++ b/serialization-msgpack-timestamp-extension/src/commonTest/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/datetime/MsgPackDatetimeSerializerTest.kt @@ -2,11 +2,11 @@ package com.ensarsarajcic.kotlinx.serialization.msgpack.datetime import com.ensarsarajcic.kotlinx.serialization.msgpack.extensions.MsgPackExtension import com.ensarsarajcic.kotlinx.serialization.msgpack.extensions.MsgPackTimestamp -import kotlinx.datetime.Instant import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.fail +import kotlin.time.Instant class MsgPackDatetimeSerializerTest { private val t32TestPairs = diff --git a/serialization-msgpack-unsigned-support/build.gradle.kts b/serialization-msgpack-unsigned-support/build.gradle.kts index 22aafee..1539903 100644 --- a/serialization-msgpack-unsigned-support/build.gradle.kts +++ b/serialization-msgpack-unsigned-support/build.gradle.kts @@ -1,18 +1,37 @@ +@file:OptIn(ExperimentalWasmDsl::class) + +import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl + plugins { - kotlin("multiplatform") - kotlin("plugin.serialization") - id("maven-publish") - id("signing") - id("org.jetbrains.dokka") - id("org.jetbrains.kotlinx.benchmark") + alias(libs.plugins.kotlin.multiplatform) + alias(libs.plugins.android.library) + alias(libs.plugins.kotlinx.serialization) + alias(libs.plugins.dokka) + alias(libs.plugins.ktlint) + signing + `maven-publish` +} + +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(libs.versions.java.get().toInt())) + } } kotlin { + withSourcesJar() + jvmToolchain(libs.versions.java.get().toInt()) jvm { compilations.create("benchmark") { associateWith(this@jvm.compilations.getByName("main")) } } + android { + namespace = "$group.unsigned" + compileSdk = libs.versions.androidTargetSdk.get().toInt() + minSdk = libs.versions.androidMinSdk.get().toInt() + lint.targetSdk = libs.versions.androidTargetSdk.get().toInt() + } js { browser { testTask { @@ -21,26 +40,33 @@ kotlin { } } } + nodejs() } - applyDefaultHierarchyTemplate() + wasmJs { + browser { + testTask { + useKarma { + useChromeHeadless() + } + } + } + nodejs() + } + iosArm64() iosX64() iosSimulatorArm64() - tvosX64() tvosArm64() - watchosX64() watchosArm64() - macosX64() macosArm64() mingwX64() linuxX64() + // TODO: remove deprecated targets in next release + macosX64() + tvosX64() + watchosX64() - fun kotlinx( - name: String, - version: String, - ): String = "org.jetbrains.kotlinx:kotlinx-$name:$version" - - fun kotlinxSerialization(name: String) = kotlinx("serialization-$name", Dependencies.Versions.serialization) + applyDefaultHierarchyTemplate() sourceSets { all { @@ -55,30 +81,8 @@ kotlin { } commonTest { dependencies { - implementation(kotlin("test-common")) - implementation(kotlin("test-annotations-common")) - } - } - jvmTest { - dependencies { - implementation(kotlin("test-junit")) - } - } - val jvmBenchmark by getting { - dependencies { - implementation(kotlinx("benchmark-runtime", Dependencies.Versions.benchmark)) - } - } - jsTest { - dependencies { - implementation(kotlin("test-js")) + implementation(libs.kotlin.test) } } } -} - -benchmark { - targets { - register("jvmBenchmark") - } -} +} \ No newline at end of file diff --git a/serialization-msgpack/build.gradle.kts b/serialization-msgpack/build.gradle.kts index a6c2d77..3c414f3 100644 --- a/serialization-msgpack/build.gradle.kts +++ b/serialization-msgpack/build.gradle.kts @@ -1,22 +1,44 @@ +@file:OptIn(ExperimentalWasmDsl::class) + +import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl + plugins { - kotlin("multiplatform") - kotlin("plugin.serialization") - id("maven-publish") - id("signing") - id("org.jetbrains.dokka") - id("org.jetbrains.kotlinx.benchmark") + alias(libs.plugins.kotlin.multiplatform) + alias(libs.plugins.android.library) + alias(libs.plugins.kotlinx.serialization) + alias(libs.plugins.dokka) + alias(libs.plugins.ktlint) + signing + `maven-publish` +} + +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(libs.versions.java.get().toInt())) + } } kotlin { - jvm { - compilations.create("benchmark") { - associateWith(this@jvm.compilations.getByName("main")) - } + withSourcesJar() + jvmToolchain(libs.versions.java.get().toInt()) + jvm() + android { + namespace = "$group.core" + compileSdk = libs.versions.androidTargetSdk.get().toInt() + minSdk = libs.versions.androidMinSdk.get().toInt() + lint.targetSdk = libs.versions.androidTargetSdk.get().toInt() } js { - compilations.create("benchmark") { - associateWith(this@js.compilations.getByName("main")) + browser { + testTask { + useKarma { + useChromeHeadless() + } + } } + nodejs() + } + wasmJs { browser { testTask { useKarma { @@ -24,27 +46,23 @@ kotlin { } } } - nodejs {} + nodejs() } - applyDefaultHierarchyTemplate() + iosArm64() iosX64() iosSimulatorArm64() - tvosX64() tvosArm64() - watchosX64() watchosArm64() - macosX64() macosArm64() mingwX64() linuxX64() + // TODO: remove deprecated targets in next release + macosX64() + tvosX64() + watchosX64() - fun kotlinx( - name: String, - version: String, - ): String = "org.jetbrains.kotlinx:kotlinx-$name:$version" - - fun kotlinxSerialization(name: String) = kotlinx("serialization-$name", Dependencies.Versions.serialization) + applyDefaultHierarchyTemplate() sourceSets { all { @@ -54,44 +72,13 @@ kotlin { commonMain { dependencies { - api(kotlinxSerialization("core")) + api(libs.kotlinx.serialization.core) } } commonTest { dependencies { - implementation(kotlin("test-common")) - implementation(kotlin("test-annotations-common")) - } - } - jvmTest { - dependencies { - implementation(kotlin("test-junit")) - } - } - val jvmBenchmark by getting { - dependencies { - implementation(kotlinx("benchmark-runtime", Dependencies.Versions.benchmark)) - implementation("org.msgpack:msgpack-core:0.9.8") - implementation("org.msgpack:jackson-dataformat-msgpack:0.9.8") + implementation(libs.kotlin.test) } } - jsTest { - dependencies { - implementation(kotlin("test-js")) - } - } - val jsBenchmark by getting { - dependencies { - implementation(kotlinx("benchmark-runtime", Dependencies.Versions.benchmark)) - implementation(npm("@msgpack/msgpack", ">2.0.0 <3.0.0")) - } - } - } -} - -benchmark { - targets { - register("jvmBenchmark") - register("jsBenchmark") } } diff --git a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/InternalMsgPackApi.kt b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/InternalMsgPackApi.kt new file mode 100644 index 0000000..0006d7f --- /dev/null +++ b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/InternalMsgPackApi.kt @@ -0,0 +1,5 @@ +package com.ensarsarajcic.kotlinx.serialization.msgpack + +@RequiresOptIn(message = "The API you are trying to use is internal to kotlinx-serialization-msgpack and may change at any time") +@Retention(AnnotationRetention.BINARY) +annotation class InternalMsgPackApi diff --git a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgPack.kt b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgPack.kt index 00941a4..fc3ab0b 100644 --- a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgPack.kt +++ b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgPack.kt @@ -34,7 +34,7 @@ import kotlin.jvm.JvmOverloads * * @see MsgPack.Default The instance using default configurations. */ -@OptIn(ExperimentalSerializationApi::class) +@OptIn(ExperimentalSerializationApi::class, InternalMsgPackApi::class) open class MsgPack @JvmOverloads constructor( diff --git a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgPackDynamicSerializer.kt b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgPackDynamicSerializer.kt index 7647043..da0686b 100644 --- a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgPackDynamicSerializer.kt +++ b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgPackDynamicSerializer.kt @@ -90,6 +90,7 @@ open class MsgPackNullableDynamicSerializer( @OptIn(InternalSerializationApi::class) final override val descriptor: SerialDescriptor = buildSerialDescriptor("MsgPackNullableDynamic", SerialKind.CONTEXTUAL) + @Suppress("UNCHECKED_CAST") @OptIn(InternalSerializationApi::class) final override fun serialize( encoder: Encoder, diff --git a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/extensions/DynamicMsgPackExtensionSerializer.kt b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/extensions/DynamicMsgPackExtensionSerializer.kt index 9eb3226..e25faac 100644 --- a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/extensions/DynamicMsgPackExtensionSerializer.kt +++ b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/extensions/DynamicMsgPackExtensionSerializer.kt @@ -11,6 +11,7 @@ open class DynamicMsgPackExtensionSerializer : BaseMsgPackExtensionSerializer - when { - MsgPackType.Array.FIXARRAY_SIZE_MASK.test(next) -> MsgPackType.Array.FIXARRAY_SIZE_MASK.unMaskValue(next).toInt() - next == MsgPackType.Array.ARRAY16 -> dataBuffer.takeNext(2).joinToNumber() - next == MsgPackType.Array.ARRAY32 -> { - if (configuration.preventOverflows) { - val number = dataBuffer.takeNext(4).joinToNumber() - if (number !in Int.MIN_VALUE..Int.MAX_VALUE) { - throw MsgPackSerializationException.overflowError(dataBuffer) - } else { - number.toInt() - } - } else { - dataBuffer.takeNext(4).joinToNumber() + StructureKind.LIST -> when { + MsgPackType.Array.FIXARRAY_SIZE_MASK.test(next) -> MsgPackType.Array.FIXARRAY_SIZE_MASK.unMaskValue(next) + .toInt() + + next == MsgPackType.Array.ARRAY16 -> dataBuffer.takeNext(2).joinToNumber() + next == MsgPackType.Array.ARRAY32 -> { + if (configuration.preventOverflows) { + val number = dataBuffer.takeNext(4).joinToNumber() + if (number !in Int.MIN_VALUE..Int.MAX_VALUE) { + throw MsgPackSerializationException.overflowError(dataBuffer) + } + else { + number.toInt() } } - else -> { - throw MsgPackSerializationException.deserialization(dataBuffer, "Unknown array type: $next") + else { + dataBuffer.takeNext(4).joinToNumber() } } - StructureKind.CLASS, StructureKind.OBJECT, StructureKind.MAP -> - when { - MsgPackType.Map.FIXMAP_SIZE_MASK.test(next) -> MsgPackType.Map.FIXMAP_SIZE_MASK.unMaskValue(next).toInt() - next == MsgPackType.Map.MAP16 -> dataBuffer.takeNext(2).joinToNumber() - next == MsgPackType.Map.MAP32 -> { - if (configuration.preventOverflows) { - val number = dataBuffer.takeNext(4).joinToNumber() - if (number !in Int.MIN_VALUE..Int.MAX_VALUE) { - throw MsgPackSerializationException.overflowError(dataBuffer) - } else { - number.toInt() - } - } else { - dataBuffer.takeNext(4).joinToNumber() + else -> { + throw MsgPackSerializationException.deserialization(dataBuffer, "Unknown array type: $next") + } + } + + StructureKind.CLASS, StructureKind.OBJECT, StructureKind.MAP -> when { + MsgPackType.Map.FIXMAP_SIZE_MASK.test(next) -> MsgPackType.Map.FIXMAP_SIZE_MASK.unMaskValue(next) + .toInt() + + next == MsgPackType.Map.MAP16 -> dataBuffer.takeNext(2).joinToNumber() + next == MsgPackType.Map.MAP32 -> { + if (configuration.preventOverflows) { + val number = dataBuffer.takeNext(4).joinToNumber() + if (number !in Int.MIN_VALUE..Int.MAX_VALUE) { + throw MsgPackSerializationException.overflowError(dataBuffer) + } + else { + number.toInt() } } - else -> { - throw MsgPackSerializationException.deserialization(dataBuffer, "Unknown map type: $next") + else { + dataBuffer.takeNext(4).joinToNumber() } } + else -> { + throw MsgPackSerializationException.deserialization(dataBuffer, "Unknown map type: $next") + } + } + else -> { - throw MsgPackSerializationException.deserialization(dataBuffer, "Unsupported collection: ${descriptor.kind}") + throw MsgPackSerializationException.deserialization( + dataBuffer, + "Unsupported collection: ${descriptor.kind}" + ) } } } + @Suppress("UNCHECKED_CAST") override fun decodeSerializableValue(deserializer: DeserializationStrategy): T { return if (deserializer == ByteArraySerializer()) { decodeByteArray() as T - } else { + } + else { super.decodeSerializableValue(deserializer) } } @@ -224,7 +241,8 @@ internal class ClassMsgPackDecoder( if (result != CompositeDecoder.DECODE_DONE) decodedElements++ return if (result == CompositeDecoder.UNKNOWN_NAME && configuration.ignoreUnknownKeys) { decodeElementIndex(descriptor) - } else { + } + else { result } } @@ -250,26 +268,32 @@ internal class ExtensionTypeDecoder( val byte = dataBuffer.requireNextByte() bytesRead++ if (!MsgPackType.Ext.isExt(byte)) { - throw MsgPackSerializationException.deserialization(dataBuffer, "Unexpected byte: $byte. Expected extension type byte!") + throw MsgPackSerializationException.deserialization( + dataBuffer, + "Unexpected byte: $byte. Expected extension type byte!" + ) } type = byte if (MsgPackType.Ext.SIZES.containsKey(type)) { size = MsgPackType.Ext.SIZES[type] } type!! - } else if (bytesRead == 1 && size != null) { + } + else if (bytesRead == 1 && size != null) { val byte = dataBuffer.requireNextByte() bytesRead++ typeId = byte typeId!! - } else if (bytesRead == 1 && size == null) { + } + else if (bytesRead == 1 && size == null) { val sizeSize = MsgPackType.Ext.SIZE_SIZE[type] bytesRead += sizeSize!! size = dataBuffer.takeNext(sizeSize).joinToNumber() val byte = dataBuffer.requireNextByte() typeId = byte typeId!! - } else { + } + else { throw AssertionError() } } @@ -282,6 +306,7 @@ internal class ExtensionTypeDecoder( return size ?: 0 } + @Suppress("UNCHECKED_CAST") override fun decodeSerializableValue(deserializer: DeserializationStrategy): T { bytesRead += 1 return dataBuffer.takeNext( diff --git a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/internal/MsgPackEncoder.kt b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/internal/MsgPackEncoder.kt index 09b972c..e733389 100644 --- a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/internal/MsgPackEncoder.kt +++ b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/internal/MsgPackEncoder.kt @@ -78,11 +78,11 @@ internal class BasicMsgPackEncoder( } } - override fun encodeInline(inlineDescriptor: SerialDescriptor): Encoder { - if (inlineEncoders.containsKey(inlineDescriptor)) { - return inlineEncoders[inlineDescriptor]!!(InlineEncoderHelper(serializersModule, result)) + override fun encodeInline(descriptor: SerialDescriptor): Encoder { + if (inlineEncoders.containsKey(descriptor)) { + return inlineEncoders[descriptor]!!(InlineEncoderHelper(serializersModule, result)) } - return super.encodeInline(inlineDescriptor) + return super.encodeInline(descriptor) } override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder { @@ -114,7 +114,7 @@ internal class BasicMsgPackEncoder( } collectionSize <= MsgPackType.Array.MAX_ARRAY32_LENGTH -> { result.add(MsgPackType.Array.ARRAY32) - result.addAll(collectionSize.toInt().splitToByteArray().toList()) + result.addAll(collectionSize.splitToByteArray().toList()) } else -> throw MsgPackSerializationException.serialization( result, @@ -133,7 +133,7 @@ internal class BasicMsgPackEncoder( } collectionSize <= MsgPackType.Map.MAX_MAP32_LENGTH -> { result.add(MsgPackType.Map.MAP32) - result.addAll(collectionSize.toInt().splitToByteArray().toList()) + result.addAll(collectionSize.splitToByteArray().toList()) } else -> throw MsgPackSerializationException.serialization( result, @@ -219,7 +219,7 @@ internal class ExtensionTypeEncoder( when (type) { MsgPackType.Ext.EXT8 -> size!!.toByte().splitToByteArray() MsgPackType.Ext.EXT16 -> size!!.toShort().splitToByteArray() - MsgPackType.Ext.EXT32 -> size!!.toInt().splitToByteArray() + MsgPackType.Ext.EXT32 -> size!!.splitToByteArray() else -> throw MsgPackSerializationException.serialization(result, "Unexpected extension type: $type") }, ) diff --git a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/internal/MsgPacker.kt b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/internal/MsgPacker.kt index dd107d4..03c961c 100644 --- a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/internal/MsgPacker.kt +++ b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/internal/MsgPacker.kt @@ -152,7 +152,7 @@ internal class BasicMsgPacker : MsgPacker { byteArrayOf(MsgPackType.String.STR16) + bytes.size.toShort().splitToByteArray() } bytes.size <= MsgPackType.String.MAX_STR32_LENGTH -> { - byteArrayOf(MsgPackType.String.STR32) + bytes.size.toInt().splitToByteArray() + byteArrayOf(MsgPackType.String.STR32) + bytes.size.splitToByteArray() } else -> throw MsgPackSerializationException.packingError( "String too long. Byte size: ${bytes.size}. Max size: ${MsgPackType.String.MAX_STR32_LENGTH}", @@ -171,7 +171,7 @@ internal class BasicMsgPacker : MsgPacker { byteArrayOf(MsgPackType.Bin.BIN16) + value.size.toShort().splitToByteArray() } value.size <= MsgPackType.Bin.MAX_BIN32_LENGTH -> { - byteArrayOf(MsgPackType.Bin.BIN32) + value.size.toInt().splitToByteArray() + byteArrayOf(MsgPackType.Bin.BIN32) + value.size.splitToByteArray() } else -> throw MsgPackSerializationException.packingError( "Byte array too long. Byte size: ${value.size}. Max size: ${MsgPackType.Bin.MAX_BIN32_LENGTH}", diff --git a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/internal/MsgUnpacker.kt b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/internal/MsgUnpacker.kt index 78ec64b..7e49b16 100644 --- a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/internal/MsgUnpacker.kt +++ b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/internal/MsgUnpacker.kt @@ -1,11 +1,13 @@ package com.ensarsarajcic.kotlinx.serialization.msgpack.internal +import com.ensarsarajcic.kotlinx.serialization.msgpack.InternalMsgPackApi import com.ensarsarajcic.kotlinx.serialization.msgpack.exceptions.MsgPackSerializationException import com.ensarsarajcic.kotlinx.serialization.msgpack.stream.MsgPackDataInputBuffer import com.ensarsarajcic.kotlinx.serialization.msgpack.types.MsgPackType import com.ensarsarajcic.kotlinx.serialization.msgpack.utils.joinToNumber -internal interface MsgUnpacker { +@InternalMsgPackApi +interface MsgUnpacker { fun unpackNull() fun unpackBoolean(): Boolean @@ -39,6 +41,7 @@ internal interface MsgUnpacker { fun unpackByteArray(preventOverflow: Boolean = false): ByteArray } +@OptIn(InternalMsgPackApi::class) internal class BasicMsgUnpacker(private val dataBuffer: MsgPackDataInputBuffer) : MsgUnpacker { override fun unpackNull() { val next = dataBuffer.requireNextByte() @@ -64,28 +67,32 @@ internal class BasicMsgUnpacker(private val dataBuffer: MsgPackDataInputBuffer) dataBuffer.requireNextByte() next } + MsgPackType.Int.isByte(next) -> { dataBuffer.requireNextByte() if (next == MsgPackType.Int.UINT8 && preventOverflow) { val number = (dataBuffer.requireNextByte().toInt() and 0xff).toShort() if (number !in Byte.MIN_VALUE..Byte.MAX_VALUE) { throw MsgPackSerializationException.overflowError(dataBuffer) - } else { + } + else { number.toByte() } - } else { + } + else { dataBuffer.requireNextByte() } } - else -> - if (strict) { - throw MsgPackSerializationException.deserialization( - dataBuffer, - "Expected byte type, but found $next", - ) - } else { - unpackNumber(preventOverflow).toByte() - } + + else -> if (strict) { + throw MsgPackSerializationException.deserialization( + dataBuffer, + "Expected byte type, but found $next", + ) + } + else { + unpackNumber(preventOverflow).toByte() + } } } @@ -101,26 +108,30 @@ internal class BasicMsgUnpacker(private val dataBuffer: MsgPackDataInputBuffer) val number = dataBuffer.takeNext(2).joinToNumber() if (number !in Short.MIN_VALUE..Short.MAX_VALUE) { throw MsgPackSerializationException.overflowError(dataBuffer) - } else { + } + else { number.toShort() } - } else { + } + else { dataBuffer.takeNext(2).joinToNumber() } } + next == MsgPackType.Int.UINT8 -> { dataBuffer.skip(1) (dataBuffer.requireNextByte().toInt() and 0xff).toShort() } - else -> - if (strict) { - throw MsgPackSerializationException.deserialization( - dataBuffer, - "Expected short type, but found $next", - ) - } else { - unpackNumber(preventOverflow).toShort() - } + + else -> if (strict) { + throw MsgPackSerializationException.deserialization( + dataBuffer, + "Expected short type, but found $next", + ) + } + else { + unpackNumber(preventOverflow).toShort() + } } } @@ -136,26 +147,30 @@ internal class BasicMsgUnpacker(private val dataBuffer: MsgPackDataInputBuffer) val number = dataBuffer.takeNext(4).joinToNumber() if (number !in Int.MIN_VALUE..Int.MAX_VALUE) { throw MsgPackSerializationException.overflowError(dataBuffer) - } else { + } + else { number.toInt() } - } else { + } + else { dataBuffer.takeNext(4).joinToNumber() } } + next == MsgPackType.Int.UINT16 -> { dataBuffer.skip(1) dataBuffer.takeNext(2).joinToNumber() } - else -> - if (strict) { - throw MsgPackSerializationException.deserialization( - dataBuffer, - "Expected int type, but found $next", - ) - } else { - unpackNumber(preventOverflow).toInt() - } + + else -> if (strict) { + throw MsgPackSerializationException.deserialization( + dataBuffer, + "Expected int type, but found $next", + ) + } + else { + unpackNumber(preventOverflow).toInt() + } } } @@ -171,26 +186,30 @@ internal class BasicMsgUnpacker(private val dataBuffer: MsgPackDataInputBuffer) val number = dataBuffer.takeNext(8).joinToNumber() if (number < 0) { throw MsgPackSerializationException.overflowError(dataBuffer) - } else { + } + else { number } - } else { + } + else { dataBuffer.takeNext(8).joinToNumber() } } + next == MsgPackType.Int.UINT32 -> { dataBuffer.skip(1) dataBuffer.takeNext(4).joinToNumber() } - else -> - if (strict) { - throw MsgPackSerializationException.deserialization( - dataBuffer, - "Expected long type, but found $next", - ) - } else { - unpackNumber(preventOverflow).toLong() - } + + else -> if (strict) { + throw MsgPackSerializationException.deserialization( + dataBuffer, + "Expected long type, but found $next", + ) + } + else { + unpackNumber(preventOverflow).toLong() + } } } @@ -200,15 +219,16 @@ internal class BasicMsgUnpacker(private val dataBuffer: MsgPackDataInputBuffer) dataBuffer.skip(1) Float.fromBits(dataBuffer.takeNext(4).joinToNumber()) } - else -> - if (strict) { - throw MsgPackSerializationException.deserialization( - dataBuffer, - "Expected float type, but found $type", - ) - } else { - unpackNumber().toFloat() - } + + else -> if (strict) { + throw MsgPackSerializationException.deserialization( + dataBuffer, + "Expected float type, but found $type", + ) + } + else { + unpackNumber().toFloat() + } } } @@ -218,67 +238,74 @@ internal class BasicMsgUnpacker(private val dataBuffer: MsgPackDataInputBuffer) dataBuffer.skip(1) Double.fromBits(dataBuffer.takeNext(8).joinToNumber()) } - else -> - if (strict) { - throw MsgPackSerializationException.deserialization( - dataBuffer, - "Expected double type, but found $type", - ) - } else { - unpackNumber().toDouble() - } + + else -> if (strict) { + throw MsgPackSerializationException.deserialization( + dataBuffer, + "Expected double type, but found $type", + ) + } + else { + unpackNumber().toDouble() + } } } override fun unpackString(preventOverflow: Boolean): String { val next = dataBuffer.requireNextByte() - val length = - when { - MsgPackType.String.FIXSTR_SIZE_MASK.test(next) -> MsgPackType.String.FIXSTR_SIZE_MASK.unMaskValue(next).toInt() - next == MsgPackType.String.STR8 -> dataBuffer.requireNextByte().toInt() and 0xff - next == MsgPackType.String.STR16 -> dataBuffer.takeNext(2).joinToNumber() - next == MsgPackType.String.STR32 -> { - if (preventOverflow) { - val number = dataBuffer.takeNext(4).joinToNumber() - if (number !in Int.MIN_VALUE..Int.MAX_VALUE) { - throw MsgPackSerializationException.overflowError(dataBuffer) - } else { - number.toInt() - } - } else { - dataBuffer.takeNext(4).joinToNumber() + val length = when { + MsgPackType.String.FIXSTR_SIZE_MASK.test(next) -> MsgPackType.String.FIXSTR_SIZE_MASK.unMaskValue(next) + .toInt() + + next == MsgPackType.String.STR8 -> dataBuffer.requireNextByte().toInt() and 0xff + next == MsgPackType.String.STR16 -> dataBuffer.takeNext(2).joinToNumber() + next == MsgPackType.String.STR32 -> { + if (preventOverflow) { + val number = dataBuffer.takeNext(4).joinToNumber() + if (number !in Int.MIN_VALUE..Int.MAX_VALUE) { + throw MsgPackSerializationException.overflowError(dataBuffer) + } + else { + number.toInt() } } - else -> { - throw MsgPackSerializationException.deserialization(dataBuffer, "Expected string type, but found $next") + else { + dataBuffer.takeNext(4).joinToNumber() } } + + else -> { + throw MsgPackSerializationException.deserialization(dataBuffer, "Expected string type, but found $next") + } + } if (length == 0) return "" return dataBuffer.takeNext(length).decodeToString() } override fun unpackByteArray(preventOverflow: Boolean): ByteArray { val next = dataBuffer.requireNextByte() - val length = - when (next) { - MsgPackType.Bin.BIN8 -> dataBuffer.requireNextByte().toInt() and 0xff - MsgPackType.Bin.BIN16 -> dataBuffer.takeNext(2).joinToNumber() - MsgPackType.Bin.BIN32 -> { - if (preventOverflow) { - val number = dataBuffer.takeNext(4).joinToNumber() - if (number !in Int.MIN_VALUE..Int.MAX_VALUE) { - throw MsgPackSerializationException.overflowError(dataBuffer) - } else { - number.toInt() - } - } else { - dataBuffer.takeNext(4).joinToNumber() + val length = when (next) { + MsgPackType.Bin.BIN8 -> dataBuffer.requireNextByte().toInt() and 0xff + MsgPackType.Bin.BIN16 -> dataBuffer.takeNext(2).joinToNumber() + MsgPackType.Bin.BIN32 -> { + if (preventOverflow) { + val number = dataBuffer.takeNext(4).joinToNumber() + if (number !in Int.MIN_VALUE..Int.MAX_VALUE) { + throw MsgPackSerializationException.overflowError(dataBuffer) + } + else { + number.toInt() } } - else -> { - throw MsgPackSerializationException.deserialization(dataBuffer, "Expected binary type, but found $next") + else { + dataBuffer.takeNext(4).joinToNumber() } } + + else -> { + throw MsgPackSerializationException.deserialization(dataBuffer, "Expected binary type, but found $next") + } + } if (length == 0) return byteArrayOf() return dataBuffer.takeNext(length) } @@ -286,15 +313,17 @@ internal class BasicMsgUnpacker(private val dataBuffer: MsgPackDataInputBuffer) private fun unpackNumber(preventOverflow: Boolean = false): Number { val type = dataBuffer.peek() return when { - MsgPackType.Int.POSITIVE_FIXNUM_MASK.test(type) || - MsgPackType.Int.NEGATIVE_FIXNUM_MASK.test(type) || - type == MsgPackType.Int.INT8 -> unpackByte(true, preventOverflow) + MsgPackType.Int.POSITIVE_FIXNUM_MASK.test(type) || MsgPackType.Int.NEGATIVE_FIXNUM_MASK.test(type) || type == MsgPackType.Int.INT8 -> unpackByte( + true, + preventOverflow + ) type == MsgPackType.Int.INT16 || type == MsgPackType.Int.UINT8 -> { val result = unpackShort(true, preventOverflow) if (type == MsgPackType.Int.UINT8 && result <= Byte.MAX_VALUE && result >= Byte.MIN_VALUE) { result.toByte() - } else { + } + else { result } } @@ -303,7 +332,8 @@ internal class BasicMsgUnpacker(private val dataBuffer: MsgPackDataInputBuffer) val result = unpackInt(true, preventOverflow) if (type == MsgPackType.Int.UINT16 && result <= Short.MAX_VALUE && result >= Short.MIN_VALUE) { result.toShort() - } else { + } + else { result } } @@ -312,14 +342,18 @@ internal class BasicMsgUnpacker(private val dataBuffer: MsgPackDataInputBuffer) val result = unpackLong(true, preventOverflow) if (type == MsgPackType.Int.UINT32 && result <= Int.MAX_VALUE && result >= Int.MIN_VALUE) { result.toInt() - } else { + } + else { result } } type == MsgPackType.Float.FLOAT -> unpackFloat(true) type == MsgPackType.Float.DOUBLE -> unpackDouble(true) - else -> throw MsgPackSerializationException.deserialization(dataBuffer, "Expected binary type, but found $type") + else -> throw MsgPackSerializationException.deserialization( + dataBuffer, + "Expected binary type, but found $type" + ) } } } diff --git a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/stream/MsgPackDataBuffer.kt b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/stream/MsgPackDataBuffer.kt index aaf6c7e..87c4974 100644 --- a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/stream/MsgPackDataBuffer.kt +++ b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/stream/MsgPackDataBuffer.kt @@ -1,10 +1,12 @@ package com.ensarsarajcic.kotlinx.serialization.msgpack.stream +import com.ensarsarajcic.kotlinx.serialization.msgpack.InternalMsgPackApi + interface MsgPackDataBuffer { fun toByteArray(): ByteArray } -class MsgPackDataOutputBuffer() : MsgPackDataBuffer { +class MsgPackDataOutputBuffer : MsgPackDataBuffer { private val byteArrays = mutableListOf() fun add(byte: Byte) { @@ -64,4 +66,5 @@ class MsgPackDataInputBuffer(private val byteArray: ByteArray) : MsgPackDataBuff override fun toByteArray() = byteArray } -internal fun ByteArray.toMsgPackBuffer() = MsgPackDataInputBuffer(this) +@InternalMsgPackApi +fun ByteArray.toMsgPackBuffer() = MsgPackDataInputBuffer(this) diff --git a/serialization-msgpack/src/commonTest/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/MsgPackDecoderTest.kt b/serialization-msgpack/src/commonTest/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/MsgPackDecoderTest.kt index f1faceb..ef63b76 100644 --- a/serialization-msgpack/src/commonTest/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/MsgPackDecoderTest.kt +++ b/serialization-msgpack/src/commonTest/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/MsgPackDecoderTest.kt @@ -13,6 +13,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue +@OptIn(InternalMsgPackApi::class) internal class MsgPackDecoderTest { @Test fun testBooleanDecode() { diff --git a/serialization-msgpack/src/commonTest/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/extension/MsgPackExtensionDecoderTest.kt b/serialization-msgpack/src/commonTest/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/extension/MsgPackExtensionDecoderTest.kt index f2df145..9b97d5b 100644 --- a/serialization-msgpack/src/commonTest/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/extension/MsgPackExtensionDecoderTest.kt +++ b/serialization-msgpack/src/commonTest/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/extension/MsgPackExtensionDecoderTest.kt @@ -1,6 +1,7 @@ package com.ensarsarajcic.kotlinx.serialization.msgpack.extension import com.ensarsarajcic.kotlinx.serialization.msgpack.CustomExtensionType +import com.ensarsarajcic.kotlinx.serialization.msgpack.InternalMsgPackApi import com.ensarsarajcic.kotlinx.serialization.msgpack.MsgPackConfiguration import com.ensarsarajcic.kotlinx.serialization.msgpack.extensions.MsgPackExtension import com.ensarsarajcic.kotlinx.serialization.msgpack.hexStringToByteArray @@ -11,6 +12,7 @@ import kotlin.test.Test import kotlin.test.assertEquals // TODO More tests +@OptIn(InternalMsgPackApi::class) internal class MsgPackExtensionDecoderTest { @Test fun testExtensionDecode() { diff --git a/serialization-msgpack/src/jsBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/DeserializeBenchmarks.kt b/serialization-msgpack/src/jsBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/DeserializeBenchmarks.kt deleted file mode 100644 index 3b89518..0000000 --- a/serialization-msgpack/src/jsBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/DeserializeBenchmarks.kt +++ /dev/null @@ -1,58 +0,0 @@ -package com.ensarsarajcic.kotlinx.serialization.msgpack - -import com.ensarsarajcic.kotlinx.serialization.msgpack.internal.BasicMsgPackDecoder -import com.ensarsarajcic.kotlinx.serialization.msgpack.stream.toMsgPackBuffer -import kotlinx.benchmark.Benchmark -import kotlinx.benchmark.BenchmarkMode -import kotlinx.benchmark.BenchmarkTimeUnit -import kotlinx.benchmark.Measurement -import kotlinx.benchmark.Mode -import kotlinx.benchmark.OutputTimeUnit -import kotlinx.benchmark.Scope -import kotlinx.benchmark.State -import kotlinx.serialization.Serializable -import kotlinx.serialization.modules.SerializersModule - -@BenchmarkMode(Mode.AverageTime) -@OutputTimeUnit(BenchmarkTimeUnit.NANOSECONDS) -@Measurement(iterations = 20, time = 1, timeUnit = BenchmarkTimeUnit.SECONDS) -@State(Scope.Benchmark) -open class DeserializeBenchmarks { - @Serializable - class SampleClassWithNestedClass( - var testString: String, - var testInt: Int, - var testBoolean: Boolean, - var testNested: NestedClass, - var secondNested: NestedClass? = null, - ) { - @Serializable - class NestedClass( - var testInt: Int? = null, - ) - } - - // The actual benchmark method - @Benchmark - fun benchmarkKotlinxSerializationMsgpack() { - val decoder = - BasicMsgPackDecoder( - MsgPackConfiguration.default.copy(ignoreUnknownKeys = true), - SerializersModule { - }, - @Suppress("ktlint:standard:max-line-length") - "85aa74657374537472696e67a3646566a774657374496e747bab74657374426f6f6c65616ec3aa746573744e657374656483aa74657374537472696e67a3646566ab74657374426f6f6c65616ec3ae616e6f74686572556e6b6e6f776ea474657374ac7365636f6e644e657374656481ab74657374426f6f6c65616ec2".hexStringToByteArray().toMsgPackBuffer(), - ) - SampleClassWithNestedClass.serializer().deserialize(decoder) - } - - @Benchmark - fun benchmarkMsgpackJs() { - @Suppress("ktlint:standard:max-line-length") - decode( - "85aa74657374537472696e67a3646566a774657374496e747bab74657374426f6f6c65616ec3aa746573744e657374656483aa74657374537472696e67a3646566ab74657374426f6f6c65616ec3ae616e6f74686572556e6b6e6f776ea474657374ac7365636f6e644e657374656481ab74657374426f6f6c65616ec2".hexStringToByteArray(), - ) - } -} - -fun String.hexStringToByteArray() = ByteArray(this.length / 2) { this.substring(it * 2, it * 2 + 2).toInt(16).toByte() } diff --git a/serialization-msgpack/src/jsBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgpackJavascript.kt b/serialization-msgpack/src/jsBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgpackJavascript.kt deleted file mode 100644 index 2ddab37..0000000 --- a/serialization-msgpack/src/jsBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/MsgpackJavascript.kt +++ /dev/null @@ -1,8 +0,0 @@ -@file:JsModule("@msgpack/msgpack") -@file:JsNonModule - -package com.ensarsarajcic.kotlinx.serialization.msgpack - -external fun encode(obj: Any): ByteArray - -external fun decode(bytes: ByteArray): T diff --git a/serialization-msgpack/src/jsBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/SerializeBenchmarks.kt b/serialization-msgpack/src/jsBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/SerializeBenchmarks.kt deleted file mode 100644 index b1b3019..0000000 --- a/serialization-msgpack/src/jsBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/SerializeBenchmarks.kt +++ /dev/null @@ -1,94 +0,0 @@ -package com.ensarsarajcic.kotlinx.serialization.msgpack - -import kotlinx.benchmark.Benchmark -import kotlinx.benchmark.BenchmarkMode -import kotlinx.benchmark.BenchmarkTimeUnit -import kotlinx.benchmark.Measurement -import kotlinx.benchmark.Mode -import kotlinx.benchmark.OutputTimeUnit -import kotlinx.benchmark.Scope -import kotlinx.benchmark.State -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToByteArray - -@BenchmarkMode(Mode.AverageTime) -@OutputTimeUnit(BenchmarkTimeUnit.NANOSECONDS) -@Measurement(iterations = 20, time = 1, timeUnit = BenchmarkTimeUnit.SECONDS) -@State(Scope.Benchmark) -open class SerializeBenchmarks { - @Serializable - data class SampleClass( - val testString: String, - val testInt: Int, - val testBoolean: Boolean, - ) - - @Serializable - data class SampleClassWithNestedClass( - val testString: String, - val testInt: Int, - val testBoolean: Boolean, - val testNested: NestedClass, - val testSample: SampleClass, - val testSampleList: List, - val testSampleMap: Map, - val extraBytes: ByteArray, - val secondNested: NestedClass? = null, - ) { - @Serializable - data class NestedClass( - val testInt: Int? = null, - ) - } - - // The actual benchmark method - @Benchmark - fun benchmarkKotlinxSerializationMsgpack() { - val instance = - SampleClassWithNestedClass( - testString = "testString", - testInt = 10, - testBoolean = true, - testNested = SampleClassWithNestedClass.NestedClass(5), - testSample = SampleClass(testString = "testString2", testInt = 17, testBoolean = false), - testSampleList = - listOf( - SampleClass("testString3", testInt = 25, testBoolean = true), - SampleClass("testString4", testInt = 100, testBoolean = false), - ), - testSampleMap = - mapOf( - "testString5" to SampleClass("testString5", testInt = 12, testBoolean = false), - "testString6" to SampleClass("testString6", testInt = 15, testBoolean = true), - ), - extraBytes = byteArrayOf(0x12, 0x13, 0x14, 0x15), - secondNested = SampleClassWithNestedClass.NestedClass(null), - ) - MsgPack.encodeToByteArray(instance) - } - - @Benchmark - fun benchmarkMsgpackJs() { - val instance = - SampleClassWithNestedClass( - testString = "testString", - testInt = 10, - testBoolean = true, - testNested = SampleClassWithNestedClass.NestedClass(5), - testSample = SampleClass(testString = "testString2", testInt = 17, testBoolean = false), - testSampleList = - listOf( - SampleClass("testString3", testInt = 25, testBoolean = true), - SampleClass("testString4", testInt = 100, testBoolean = false), - ), - testSampleMap = - mapOf( - "testString5" to SampleClass("testString5", testInt = 12, testBoolean = false), - "testString6" to SampleClass("testString6", testInt = 15, testBoolean = true), - ), - extraBytes = byteArrayOf(0x12, 0x13, 0x14, 0x15), - secondNested = SampleClassWithNestedClass.NestedClass(null), - ) - encode(instance) - } -} diff --git a/serialization-msgpack/src/jvmBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/SerializeBenchmarks.kt b/serialization-msgpack/src/jvmBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/SerializeBenchmarks.kt deleted file mode 100644 index 263c3ec..0000000 --- a/serialization-msgpack/src/jvmBenchmark/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/SerializeBenchmarks.kt +++ /dev/null @@ -1,99 +0,0 @@ -package com.ensarsarajcic.kotlinx.serialization.msgpack - -import com.fasterxml.jackson.databind.ObjectMapper -import kotlinx.benchmark.Benchmark -import kotlinx.benchmark.BenchmarkMode -import kotlinx.benchmark.BenchmarkTimeUnit -import kotlinx.benchmark.Measurement -import kotlinx.benchmark.Mode -import kotlinx.benchmark.OutputTimeUnit -import kotlinx.benchmark.Scope -import kotlinx.benchmark.State -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToByteArray -import org.msgpack.jackson.dataformat.MessagePackFactory - -@BenchmarkMode(Mode.AverageTime) -@OutputTimeUnit(BenchmarkTimeUnit.NANOSECONDS) -@Measurement(iterations = 20, time = 1, timeUnit = BenchmarkTimeUnit.SECONDS) -@State(Scope.Benchmark) -open class SerializeBenchmarks { - @Serializable - data class SampleClass( - @SerialName("testString") - val testString: String, - val testInt: Int, - val testBoolean: Boolean, - ) - - @Serializable - data class SampleClassWithNestedClass( - val testString: String, - val testInt: Int, - val testBoolean: Boolean, - val testNested: NestedClass, - val testSample: SampleClass, - val testSampleList: List, - val testSampleMap: Map, - val extraBytes: ByteArray, - val secondNested: NestedClass? = null, - ) { - @Serializable - data class NestedClass( - val testInt: Int? = null, - ) - } - - // The actual benchmark method - @Benchmark - fun benchmarkKotlinxSerializationMsgpack() { - val instance = - SampleClassWithNestedClass( - testString = "testString", - testInt = 10, - testBoolean = true, - testNested = SampleClassWithNestedClass.NestedClass(5), - testSample = SampleClass(testString = "testString2", testInt = 17, testBoolean = false), - testSampleList = - listOf( - SampleClass("testString3", testInt = 25, testBoolean = true), - SampleClass("testString4", testInt = 100, testBoolean = false), - ), - testSampleMap = - mapOf( - "testString5" to SampleClass("testString5", testInt = 12, testBoolean = false), - "testString6" to SampleClass("testString6", testInt = 15, testBoolean = true), - ), - extraBytes = byteArrayOf(0x12, 0x13, 0x14, 0x15), - secondNested = SampleClassWithNestedClass.NestedClass(null), - ) - MsgPack.encodeToByteArray(instance) - } - - @Benchmark - fun benchmarkMsgpackJava() { - val instance = - SampleClassWithNestedClass( - testString = "testString", - testInt = 10, - testBoolean = true, - testNested = SampleClassWithNestedClass.NestedClass(5), - testSample = SampleClass(testString = "testString2", testInt = 17, testBoolean = false), - testSampleList = - listOf( - SampleClass("testString3", testInt = 25, testBoolean = true), - SampleClass("testString4", testInt = 100, testBoolean = false), - ), - testSampleMap = - mapOf( - "testString5" to SampleClass("testString5", testInt = 12, testBoolean = false), - "testString6" to SampleClass("testString6", testInt = 15, testBoolean = true), - ), - extraBytes = byteArrayOf(0x12, 0x13, 0x14, 0x15), - secondNested = SampleClassWithNestedClass.NestedClass(null), - ) - val objectMapper = ObjectMapper(MessagePackFactory()) - objectMapper.writeValueAsBytes(instance) - } -} diff --git a/settings.gradle.kts b/settings.gradle.kts index c438861..f1c16ef 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,6 +1,26 @@ rootProject.name = "kotlinx-serialization-msgpack" -include(":serialization-msgpack") +pluginManagement { + repositories { + google() + mavenCentral() + mavenLocal() + gradlePluginPortal() + maven("https://central.sonatype.com/repository/maven-snapshots") + } +} -include(":serialization-msgpack-timestamp-extension") -include(":serialization-msgpack-unsigned-support") +@Suppress("UnstableApiUsage") +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + mavenLocal() + maven("https://central.sonatype.com/repository/maven-snapshots") + } +} + +include("serialization-msgpack") +include("serialization-msgpack-timestamp-extension") +include("serialization-msgpack-unsigned-support") +include("serialization-msgpack-benchmarks") \ No newline at end of file