de.bixilon.mbf.MBFUtil.kt Maven / Gradle / Ivy
/*
* Minosoft
* Copyright (C) 2021 Moritz Zwerger
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see .
*
* This software is not affiliated with Mojang AB, the original developer of Minecraft.
*/
package de.bixilon.mbf
import java.io.InputStream
import java.io.OutputStream
object MBFUtil {
const val DEFAULT_BUFFER_SIZE = 4096
const val ARRAY_MAX_BYTES = Int.MAX_VALUE
val Any?.generics: List>
get() {
this ?: return listOf()
when (this) {
is Collection<*> -> {
var type: Class<*>? = null
for (entry in this) {
entry ?: continue
val entryClass = entry::class.java
if (type == null) {
type = entryClass
continue
}
if (type != entryClass) {
type = null
break
}
}
return listOf(type ?: Any::class.java)
}
is Map<*, *> -> {
var keyType: Class<*>? = null
var valueType: Class<*>? = null
for ((key, value) in this) {
if (key != null) {
val keyClass = key::class.java
if (keyType == null) {
keyType = keyClass
} else if (keyType != keyClass) {
keyType = Any::class.java
break
}
}
if (value != null) {
val valueClass = value::class.java
if (valueType == null) {
valueType = valueClass
} else if (valueType != valueClass) {
valueType = Any::class.java
break
}
}
}
return listOf(keyType ?: Any::class.java, valueType ?: Any::class.java)
}
}
TODO()
}
/**
* Copies one stream to another
*/
internal fun copyStream(inputStream: InputStream, outputStream: OutputStream, close: Boolean = false) {
var length = 0
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (length >= 0) {
length = inputStream.read(buffer, 0, buffer.size)
if (length > 0) {
outputStream.write(buffer, 0, length)
}
}
if (close) {
inputStream.close()
outputStream.close()
}
}
}