path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
library-base/src/main/java/com/example/miaow/base/dialog/StandardDialog.kt
miaowmiaow
364,865,870
false
null
package com.example.fragment.library.common.dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.fragment.library.base.dialog.BaseDialog import com.example.fragment.library.common.databinding.DialogStandardBinding class StandardDialog : BaseDialog() { companion object { @JvmStatic fun newInstance(): StandardDialog { return StandardDialog() } } private lateinit var binding: DialogStandardBinding private var listener: OnDialogClickListener? = null private var title: String? = null private var content: String? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = DialogStandardBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) dialog?.window?.apply { setDimAmount(0.5F) } title?.apply { binding.title.text = this binding.title.visibility = View.VISIBLE } content?.apply { binding.content.text = this binding.content.visibility = View.VISIBLE } binding.confirm.setOnClickListener { dismiss() listener?.apply { onConfirm(this@StandardDialog) } } binding.cancel.setOnClickListener { dismiss() listener?.apply { onCancel(this@StandardDialog) } } } fun setTitle(text: String): StandardDialog { this.title = text return this } fun setContent(text: String): StandardDialog { this.content = text return this } fun setOnDialogClickListener(listener: OnDialogClickListener): StandardDialog { this.listener = listener return this } interface OnDialogClickListener { fun onConfirm(dialog: StandardDialog) fun onCancel(dialog: StandardDialog) } }
1
null
70
991
9007234450343e2c5e2a094a50286cb1d9215ef3
2,214
fragmject
Apache License 2.0
koin-projects/koin-test/src/main/kotlin/org/koin/test/ext/junit/KoinTestExt.kt
JanStoltman
148,633,650
false
null
/* * Copyright 2017-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.test.ext.junit import org.junit.Assert import org.koin.dsl.path.Path import org.koin.standalone.StandAloneContext import org.koin.test.KoinTest import org.koin.test.ext.koin.* import kotlin.reflect.KClass /** * KoinTest extensions for Junit asserts & tools * * @author <NAME> */ private fun context() = StandAloneContext.getKoin().koinContext /** * Assert context beanDefinition definitionCount * @param definitionCount - number of definitions */ fun KoinTest.assertDefinitions(definitionCount: Int) { Assert.assertEquals( "applicationContext must have $definitionCount beanDefinition", definitionCount, context().beanDefinitions().size ) } /** * Assert definitionClazz is defined in given module path * @param definitionClazz - bean beanDefinition class * @param path */ fun KoinTest.assertIsInModulePath(definitionClazz: KClass<*>, path: String) { val definition = context().beanDefinition(definitionClazz) Assert.assertEquals( "$definitionClazz must be in path '$path'", path, definition?.path?.name ?: "" ) } /** * Assert definitionClazz is defined in given module path * @param definitionClazz - bean beanDefinition class * @param path */ fun KoinTest.assertIsInRootPath(definitionClazz: KClass<*>) { val definition = context().beanDefinition(definitionClazz) Assert.assertEquals( "$definitionClazz must be in path " + Path.ROOT, Path.ROOT, definition?.path?.name ?: "" ) } /** * Assert context has beanDefinition instanceCount * @param pathName * @param instanceCount - number of instances */ fun KoinTest.assertContextInstances(pathName: String, instanceCount: Int) { val path = context().getPath(pathName) val definitions = context().beanDefinitions().filter { it.path == path }.toSet() val instances = context().allInstances().map { it.bean }.filter { it in definitions } Assert.assertEquals( "path $pathName must have $instanceCount instances", instanceCount, instances.size ) } /** * Assert path has given parent path * @param path * @param parentPath */ fun KoinTest.assertPath(path: String, parentPath: String) { Assert.assertEquals( "Path '$path' must have parent '$parentPath'", parentPath, context().instanceRegistry.pathRegistry.getPath(path).parent?.name ) } /** * Assert Koin has reminaing instances * @param instanceCount - instances count */ fun KoinTest.assertRemainingInstanceHolders(instanceCount: Int) { Assert.assertEquals( "context must have $instanceCount instances", instanceCount, context().allInstances().size ) } /** * Assert Koin has properties count * @param propertyCount - properties count */ fun KoinTest.assertProperties(propertyCount: Int) { val nonKoinProps = context().allProperties().filterKeys { it != "test.koin" && it != "os.version" } Assert.assertEquals( "context must have $propertyCount properties", propertyCount, nonKoinProps.size ) } /** * Assert Koin has contextCount contexts * @param contextCount - context count */ fun KoinTest.assertContexts(contextCount: Int) { Assert.assertEquals( "context must have $contextCount contexts", contextCount, context().allPaths().size ) }
1
null
1
1
1d95f051d02f62aa7cfb6faed899c4eec146c48e
3,999
koin
Apache License 2.0
koin-projects/koin-test/src/main/kotlin/org/koin/test/ext/junit/KoinTestExt.kt
JanStoltman
148,633,650
false
null
/* * Copyright 2017-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.test.ext.junit import org.junit.Assert import org.koin.dsl.path.Path import org.koin.standalone.StandAloneContext import org.koin.test.KoinTest import org.koin.test.ext.koin.* import kotlin.reflect.KClass /** * KoinTest extensions for Junit asserts & tools * * @author <NAME> */ private fun context() = StandAloneContext.getKoin().koinContext /** * Assert context beanDefinition definitionCount * @param definitionCount - number of definitions */ fun KoinTest.assertDefinitions(definitionCount: Int) { Assert.assertEquals( "applicationContext must have $definitionCount beanDefinition", definitionCount, context().beanDefinitions().size ) } /** * Assert definitionClazz is defined in given module path * @param definitionClazz - bean beanDefinition class * @param path */ fun KoinTest.assertIsInModulePath(definitionClazz: KClass<*>, path: String) { val definition = context().beanDefinition(definitionClazz) Assert.assertEquals( "$definitionClazz must be in path '$path'", path, definition?.path?.name ?: "" ) } /** * Assert definitionClazz is defined in given module path * @param definitionClazz - bean beanDefinition class * @param path */ fun KoinTest.assertIsInRootPath(definitionClazz: KClass<*>) { val definition = context().beanDefinition(definitionClazz) Assert.assertEquals( "$definitionClazz must be in path " + Path.ROOT, Path.ROOT, definition?.path?.name ?: "" ) } /** * Assert context has beanDefinition instanceCount * @param pathName * @param instanceCount - number of instances */ fun KoinTest.assertContextInstances(pathName: String, instanceCount: Int) { val path = context().getPath(pathName) val definitions = context().beanDefinitions().filter { it.path == path }.toSet() val instances = context().allInstances().map { it.bean }.filter { it in definitions } Assert.assertEquals( "path $pathName must have $instanceCount instances", instanceCount, instances.size ) } /** * Assert path has given parent path * @param path * @param parentPath */ fun KoinTest.assertPath(path: String, parentPath: String) { Assert.assertEquals( "Path '$path' must have parent '$parentPath'", parentPath, context().instanceRegistry.pathRegistry.getPath(path).parent?.name ) } /** * Assert Koin has reminaing instances * @param instanceCount - instances count */ fun KoinTest.assertRemainingInstanceHolders(instanceCount: Int) { Assert.assertEquals( "context must have $instanceCount instances", instanceCount, context().allInstances().size ) } /** * Assert Koin has properties count * @param propertyCount - properties count */ fun KoinTest.assertProperties(propertyCount: Int) { val nonKoinProps = context().allProperties().filterKeys { it != "test.koin" && it != "os.version" } Assert.assertEquals( "context must have $propertyCount properties", propertyCount, nonKoinProps.size ) } /** * Assert Koin has contextCount contexts * @param contextCount - context count */ fun KoinTest.assertContexts(contextCount: Int) { Assert.assertEquals( "context must have $contextCount contexts", contextCount, context().allPaths().size ) }
1
null
1
1
1d95f051d02f62aa7cfb6faed899c4eec146c48e
3,999
koin
Apache License 2.0
examples/android-weather-app/src/main/kotlin/fr/ekito/myweatherapp/view/weather/WeatherActivity.kt
InsertKoinIO
176,261,599
false
null
package fr.ekito.myweatherapp.view.weather import android.arch.lifecycle.Observer import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.View import fr.ekito.myweatherapp.R import fr.ekito.myweatherapp.view.Failed import kotlinx.android.synthetic.main.activity_result.* import org.jetbrains.anko.clearTask import org.jetbrains.anko.clearTop import org.jetbrains.anko.intentFor import org.jetbrains.anko.newTask import org.koin.android.viewmodel.ext.android.viewModel /** * Weather Result View */ class WeatherActivity : AppCompatActivity() { private val viewModel: WeatherViewModel by viewModel() private val TAG = this::class.java.simpleName override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_result) val weatherTitleFragment = WeatherHeaderFragment() val resultListFragment = WeatherListFragment() supportFragmentManager .beginTransaction() .replace(R.id.weather_title, weatherTitleFragment) .commit() supportFragmentManager .beginTransaction() .replace(R.id.weather_list, resultListFragment) .commit() viewModel.getWeather() listenToEvents() } private fun listenToEvents() { viewModel.states.observe(this, Observer { when(it){ is Failed -> showError(it.error) } }) } private fun showError(error: Throwable) { Log.e(TAG, "error $error while displaying weather") weather_views.visibility = View.GONE weather_error.visibility = View.VISIBLE Snackbar.make( weather_result, "WeatherActivity got error : $error", Snackbar.LENGTH_INDEFINITE ) .setAction(R.string.retry) { startActivity(intentFor<WeatherActivity>().clearTop().clearTask().newTask()) } .show() } }
5
null
12
26
4d429693bdce0eab4201128cf8bf864de456b7e0
2,100
koin-samples
Apache License 2.0
app/src/main/kotlin/batect/execution/model/rules/cleanup/DeleteTaskNetworkStepRule.kt
batect
102,647,061
false
null
/* Copyright 2017-2021 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.execution.model.rules.cleanup import batect.config.Container import batect.docker.DockerNetwork import batect.execution.model.events.ContainerRemovedEvent import batect.execution.model.events.TaskEvent import batect.execution.model.rules.TaskStepRuleEvaluationResult import batect.execution.model.steps.DeleteTaskNetworkStep import batect.logging.ContainerNameSetSerializer import batect.os.OperatingSystem import batect.primitives.mapToSet import kotlinx.serialization.Serializable import kotlinx.serialization.Transient @Serializable data class DeleteTaskNetworkStepRule( val network: DockerNetwork, @Serializable(with = ContainerNameSetSerializer::class) val containersThatMustBeRemovedFirst: Set<Container> ) : CleanupTaskStepRule() { override fun evaluate(pastEvents: Set<TaskEvent>): TaskStepRuleEvaluationResult { val removedContainers = pastEvents .filterIsInstance<ContainerRemovedEvent>() .mapToSet { it.container } if (removedContainers.containsAll(containersThatMustBeRemovedFirst)) { return TaskStepRuleEvaluationResult.Ready(DeleteTaskNetworkStep(network)) } return TaskStepRuleEvaluationResult.NotReady } override fun getManualCleanupInstructionForOperatingSystem(operatingSystem: OperatingSystem): String? = "docker network rm ${network.id}" @Transient override val manualCleanupSortOrder: ManualCleanupSortOrder = ManualCleanupSortOrder.DeleteTaskNetwork }
13
Kotlin
47
620
1b6cb1d79d91a70a0cb038cc29b2db1c025fea9e
2,081
batect
Apache License 2.0
app/src/main/java/org/p2p/wallet/sell/interactor/HistoryItemMapper.kt
p2p-org
306,035,988
false
null
package org.p2p.wallet.sell.interactor import android.content.res.Resources import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.withContext import org.p2p.core.utils.Constants import org.p2p.core.utils.formatFiat import org.p2p.core.utils.formatToken import org.p2p.ethereumkit.external.model.ERC20Tokens import org.p2p.wallet.R import org.p2p.wallet.common.date.isSameDayAs import org.p2p.wallet.common.date.toZonedDateTime import org.p2p.wallet.history.model.HistoryTransaction import org.p2p.wallet.history.model.bridge.BridgeHistoryTransaction import org.p2p.wallet.history.model.rpc.RpcHistoryTransaction import org.p2p.wallet.history.ui.model.HistoryItem import org.p2p.core.dispatchers.CoroutineDispatchers import org.p2p.wallet.moonpay.model.SellTransaction import org.p2p.wallet.moonpay.serversideapi.response.SellTransactionStatus import org.p2p.wallet.sell.ui.lock.SellTransactionViewDetails import org.p2p.wallet.user.repository.UserLocalRepository import org.p2p.core.crypto.Base58String import org.p2p.wallet.utils.cutStart import org.p2p.wallet.utils.getStatusIcon private const val USDT_ETH_TOKEN_SYMBOL = "USDTet" private const val USDC_ETH_TOKEN_SYMBOL = "USDCet" class HistoryItemMapper( private val resources: Resources, private val dispatchers: CoroutineDispatchers, private val userLocalRepository: UserLocalRepository ) { private val historyItemFlow = MutableStateFlow<List<HistoryItem>?>(null) fun getHistoryAdapterItemFlow(): MutableStateFlow<List<HistoryItem>?> { return historyItemFlow } suspend fun toAdapterItem( tokenMintAddress: Base58String?, transactions: List<HistoryTransaction>, userSendLinksCount: Int ) { val rpcHistoryItems = mutableListOf<HistoryItem>() val sellHistoryItems = mutableListOf<HistoryItem>() val bridgeHistoryItems = mutableListOf<HistoryItem>() val filterBundleIds = transactions.filterIsInstance<BridgeHistoryTransaction>() .filter { it.isProcessing() } .map { it.getHistoryTransactionId() } withContext(dispatchers.io) { transactions.forEachIndexed { _, item -> when (item) { is RpcHistoryTransaction -> { if (item.isNotProcessing(filterBundleIds)) { parse(item, rpcHistoryItems) } } is SellTransaction -> { // Sell transactions with cancel reason, should not appear in history if (!item.isCancelled()) { parse(item, sellHistoryItems) } } is BridgeHistoryTransaction -> { parse(item, bridgeHistoryItems) } } } val swapBannerItem: HistoryItem.SwapBannerItem? = tokenMintAddress?.let(::createSwapBanner) val userSendLinksItem: HistoryItem.UserSendLinksItem? = createUserSendLinksItem(userSendLinksCount) val historyItems = listOfNotNull(swapBannerItem, userSendLinksItem) .plus(sellHistoryItems) .plus(bridgeHistoryItems) .plus(rpcHistoryItems) historyItemFlow.emit(historyItems) } } private fun RpcHistoryTransaction.isNotProcessing(filterBundleIds: List<String>): Boolean { return when (this) { is RpcHistoryTransaction.WormholeReceive -> claimKey !in filterBundleIds is RpcHistoryTransaction.WormholeSend -> message !in filterBundleIds else -> true } } private fun createSwapBanner(tokenMintAddress: Base58String): HistoryItem.SwapBannerItem? { return when (tokenMintAddress.base58Value) { Constants.USDC_MINT -> { HistoryItem.SwapBannerItem( sourceTokenMintAddress = Constants.USDC_MINT, sourceTokenSymbol = Constants.USDC_SYMBOL, destinationTokenMintAddress = ERC20Tokens.USDC.mintAddress, destinationTokenSymbol = USDC_ETH_TOKEN_SYMBOL ) } Constants.USDT_MINT -> { HistoryItem.SwapBannerItem( sourceTokenMintAddress = Constants.USDT_MINT, sourceTokenSymbol = Constants.USDT_SYMBOL, destinationTokenMintAddress = ERC20Tokens.USDT.mintAddress, destinationTokenSymbol = USDT_ETH_TOKEN_SYMBOL ) } else -> { null } } } private fun createUserSendLinksItem(userSendLinksCount: Int): HistoryItem.UserSendLinksItem? { return HistoryItem.UserSendLinksItem(userSendLinksCount) .takeIf { userSendLinksCount > 0 } } fun parse(transaction: RpcHistoryTransaction, cache: MutableList<HistoryItem>) { val isCurrentAndPreviousTransactionOnSameDay = cache.isNotEmpty() && cache.last().date.isSameDayAs(transaction.date) var tokenIconUrl: String? = null var sourceTokenIconUrl: String? = null var destinationTokenIconUrl: String? = null val startTitle: String? val startSubtitle: String? var endTopValue: String? = null var endTopValueTextColor: Int? = null var endBottomValue: String? = null val iconRes: Int when (transaction) { is RpcHistoryTransaction.Swap -> with(transaction) { sourceTokenIconUrl = sourceIconUrl destinationTokenIconUrl = destinationIconUrl iconRes = R.drawable.ic_swap_arrows startTitle = "$sourceSymbol to $destinationSymbol" startSubtitle = resources.getString(getTypeName()) endTopValue = "+${getDestinationTotal()}" endTopValueTextColor = getTextColor() endBottomValue = getSourceTotal() } is RpcHistoryTransaction.Transfer -> with(transaction) { tokenIconUrl = getTokenIconUrl() iconRes = getIcon() startTitle = getFormattedUsernameOrAddress() startSubtitle = resources.getString(getTypeName()) endTopValue = getFormattedFiatValue() endTopValueTextColor = getTextColor() endBottomValue = getTotalWithSymbol() } is RpcHistoryTransaction.StakeUnstake -> with(transaction) { tokenIconUrl = getTokenIconUrl() iconRes = getIcon() startTitle = resources.getString(getTypeName()) startSubtitle = resources.getString(R.string.transaction_history_vote_format, getAddress()) endTopValue = getValue() endTopValueTextColor = getTextColor() endBottomValue = getTotal() } is RpcHistoryTransaction.BurnOrMint -> with(transaction) { tokenIconUrl = iconUrl iconRes = R.drawable.ic_placeholder_image startTitle = resources.getString(getTitle()) startSubtitle = resources.getString(R.string.transaction_history_signature_format, signature.cutStart()) endTopValue = getUsdAmount() endTopValueTextColor = getTextColor() endBottomValue = getTotal() } is RpcHistoryTransaction.CreateAccount -> with(transaction) { tokenIconUrl = iconUrl iconRes = R.drawable.ic_transaction_create startTitle = resources.getString(R.string.transaction_history_create) startSubtitle = resources.getString(R.string.transaction_history_signature_format, signature.cutStart()) } is RpcHistoryTransaction.CloseAccount -> with(transaction) { tokenIconUrl = iconUrl iconRes = R.drawable.ic_transaction_closed startTitle = resources.getString(R.string.transaction_history_closed) startSubtitle = resources.getString(R.string.transaction_history_signature_format, signature.cutStart()) } is RpcHistoryTransaction.WormholeSend -> with(transaction) { tokenIconUrl = iconUrl iconRes = R.drawable.ic_transaction_send startTitle = resources.getString(getTitle()) startSubtitle = resources.getString(getSubtitle()) endTopValue = getUsdAmount() endTopValueTextColor = getTextColor() endBottomValue = getTotal() } is RpcHistoryTransaction.WormholeReceive -> with(transaction) { tokenIconUrl = iconUrl iconRes = R.drawable.ic_transaction_send startTitle = resources.getString(getTitle()) startSubtitle = resources.getString(getSubtitle()) endTopValue = getUsdAmount() endTopValueTextColor = getTextColor() endBottomValue = getTotal() } is RpcHistoryTransaction.Unknown -> { iconRes = R.drawable.ic_transaction_unknown startTitle = resources.getString(R.string.transaction_history_unknown) startSubtitle = resources.getString( R.string.transaction_history_signature_format, transaction.signature.cutStart() ) } } val historyItem = HistoryItem.TransactionItem( transactionId = transaction.getHistoryTransactionId(), sourceIconUrl = sourceTokenIconUrl, destinationIconUrl = destinationTokenIconUrl, tokenIconUrl = tokenIconUrl, iconRes = iconRes, startTitle = startTitle, startSubtitle = startSubtitle, endTopValue = endTopValue, endTopValueTextColor = endTopValueTextColor, endBottomValue = endBottomValue, statusIcon = transaction.status.getStatusIcon(), date = transaction.date ) if (isCurrentAndPreviousTransactionOnSameDay) { cache.add(historyItem) } else { cache.addAll( listOf( HistoryItem.DateItem(transaction.date), historyItem ) ) } } fun parse( transaction: SellTransaction, cache: MutableList<HistoryItem> ) { val receiverAddress = if (transaction is SellTransaction.WaitingForDepositTransaction) { transaction.moonpayDepositWalletAddress.base58Value } else { resources.getString(R.string.sell_details_receiver_moonpay_bank) } val formattedSolAmount = transaction.amounts.tokenAmount.formatToken() val formattedFiatAmount = transaction.amounts.amountInFiat.formatFiat() val fiatUiName = transaction.selectedFiat.uiSymbol val iconRes: Int val backgroundRes: Int val iconColor: Int val titleStatus: String val subtitleReceiver: String var endTopValue: String = resources.getString( R.string.transaction_history_moonpay_amount_sol, formattedSolAmount, ) when (transaction.status) { SellTransactionStatus.WAITING_FOR_DEPOSIT -> { titleStatus = resources.getString(R.string.transaction_history_moonpay_waiting_for_deposit_title) subtitleReceiver = resources.getString( R.string.transaction_history_moonpay_waiting_for_deposit_subtitle, receiverAddress.cutStart() ) iconRes = R.drawable.ic_alert_rounded backgroundRes = R.drawable.bg_rounded_solid_rain_24 iconColor = R.color.icons_night } SellTransactionStatus.FAILED -> { titleStatus = resources.getString(R.string.transaction_history_moonpay_failed_title) subtitleReceiver = resources.getString(R.string.transaction_history_moonpay_failed_subtitle) iconRes = R.drawable.ic_alert_rounded backgroundRes = R.drawable.bg_rounded_solid_rose20_24 iconColor = R.color.icons_rose } SellTransactionStatus.PENDING -> { titleStatus = resources.getString(R.string.transaction_history_moonpay_pending_title) subtitleReceiver = resources.getString(R.string.transaction_history_moonpay_completed_subtitle) iconRes = R.drawable.ic_action_schedule_filled backgroundRes = R.drawable.bg_rounded_solid_rain_24 iconColor = R.color.icons_night } SellTransactionStatus.COMPLETED -> { titleStatus = resources.getString(R.string.transaction_history_moonpay_completed_title) subtitleReceiver = resources.getString(R.string.transaction_history_moonpay_completed_subtitle) iconRes = R.drawable.ic_action_schedule_filled backgroundRes = R.drawable.bg_rounded_solid_rain_24 iconColor = R.color.icons_night endTopValue = resources.getString( R.string.transaction_history_moonpay_amount_fiat, formattedFiatAmount, fiatUiName.uppercase() ) } } cache.add( HistoryItem.MoonpayTransactionItem( transactionId = transaction.transactionId, statusIconRes = iconRes, statusBackgroundRes = backgroundRes, statusIconColor = iconColor, titleStatus = titleStatus, subtitleReceiver = subtitleReceiver, endTopValue = endTopValue, date = transaction.updatedAt.toZonedDateTime() ) ) } fun parse(item: BridgeHistoryTransaction, cache: MutableList<HistoryItem>) { if (item is BridgeHistoryTransaction.Send) { val sendTokenSymbol = item.sendDetails.amount.symbol val tokenIconUrl = userLocalRepository.getTokensData() .firstOrNull { it.symbol == sendTokenSymbol } ?.iconUrl val item = HistoryItem.BridgeSendItem( id = item.id, sendDetails = item.sendDetails, tokenIconUrl = tokenIconUrl ) cache.add(item) } else if (item is BridgeHistoryTransaction.Claim) { val claimTokenSymbol = item.bundle.resultAmount.symbol val tokenIconUrl = userLocalRepository.getTokensData() .firstOrNull { it.symbol == claimTokenSymbol } ?.iconUrl val item = HistoryItem.BridgeClaimItem( bundleId = item.bundleId, bundle = item.bundle, tokenIconUrl = tokenIconUrl ) cache.add(item) } } fun toSellDetailsModel(sellTransaction: SellTransaction): SellTransactionViewDetails { val receiverAddress = if (sellTransaction is SellTransaction.WaitingForDepositTransaction) { sellTransaction.moonpayDepositWalletAddress.base58Value } else { resources.getString(R.string.sell_details_receiver_moonpay_bank) } val formattedSolAmount = sellTransaction.amounts.tokenAmount.formatToken() val formattedFiatAmount = sellTransaction.amounts.amountInFiat.formatFiat() val fiatUiName = sellTransaction.selectedFiat.uiSymbol return SellTransactionViewDetails( transactionId = sellTransaction.transactionId, status = sellTransaction.status, formattedSolAmount = formattedSolAmount, formattedFiatAmount = formattedFiatAmount, fiatUiName = fiatUiName, receiverAddress = receiverAddress, updatedAt = sellTransaction.updatedAt, ) } }
8
null
18
34
d091e18b7d88c936b7c6c627f4fec96bcf4a0356
16,315
key-app-android
MIT License
plugins/kotlin/maven/tests/test/org/jetbrains/kotlin/idea/maven/importer/KotlinMavenImporterTest06.kt
zhoumin03
128,005,393
false
{"Text": 6391, "XML": 6476, "YAML": 417, "Ant Build System": 12, "Shell": 563, "Markdown": 577, "Ignore List": 97, "Git Attributes": 10, "EditorConfig": 233, "Batchfile": 27, "SVG": 2415, "Java": 76791, "Kotlin": 42750, "Java Properties": 199, "HTML": 2907, "INI": 428, "JFlex": 31, "CSS": 59, "Groovy": 3467, "XSLT": 112, "JavaScript": 211, "JSON": 1033, "desktop": 1, "Python": 13170, "Maven POM": 76, "JAR Manifest": 16, "PHP": 47, "Gradle Kotlin DSL": 273, "Protocol Buffer": 3, "Microsoft Visual Studio Solution": 5, "C#": 37, "Smalltalk": 17, "Diff": 131, "Erlang": 1, "Rich Text Format": 2, "AspectJ": 2, "Perl": 6, "HLSL": 2, "Objective-C": 21, "CoffeeScript": 3, "HTTP": 2, "JSON with Comments": 59, "GraphQL": 49, "OpenStep Property List": 46, "Tcl": 1, "fish": 1, "Gradle": 433, "Dockerfile": 3, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 4, "XML Property List": 86, "Vim Script": 7, "Vim Snippet": 3, "Vim Help File": 2, "Starlark": 2, "E-mail": 18, "Roff": 249, "Roff Manpage": 39, "Swift": 3, "C": 47, "TOML": 103, "Proguard": 2, "Checksums": 58, "Java Server Pages": 8, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 2, "CMake": 15, "C++": 32, "VBScript": 1, "NSIS": 5, "PlantUML": 5, "Thrift": 3, "Cython": 14, "reStructuredText": 56, "Regular Expression": 3, "JSON5": 4}
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.maven.importer import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.impl.libraries.LibraryEx import org.jetbrains.idea.maven.MavenImportingTestCase import org.jetbrains.kotlin.idea.framework.CommonLibraryKind import org.jetbrains.kotlin.idea.framework.KotlinSdkType import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.junit.Assert import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class KotlinMavenImporterTest06 : AbstractKotlinMavenImporterTest() { fun testCommonDetectionByGoalWithCommonStdlib() { createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm") importProject( """ <groupId>test</groupId>0 <artifactId>project</artifactId> <version>1.0.0</version> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib-common</artifactId> <version>$kotlinVersion</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/kotlin</sourceDirectory> <plugins> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <executions> <execution> <id>compile</id> <goals> <goal>metadata</goal> </goals> </execution> </executions> </plugin> </plugins> </build> """ ) assertModules("project") assertImporterStatePresent() Assert.assertTrue(facetSettings.targetPlatform.isCommon()) val rootManager = ModuleRootManager.getInstance(getModule("project")) val stdlib = rootManager.orderEntries.filterIsInstance<LibraryOrderEntry>().single().library MavenImportingTestCase.assertEquals(CommonLibraryKind, (stdlib as LibraryEx).kind) Assert.assertTrue(ModuleRootManager.getInstance(getModule("project")).sdk!!.sdkType is KotlinSdkType) assertKotlinSources("project", "src/main/kotlin") assertKotlinTestSources("project", "src/test/java") assertKotlinResources("project", "src/main/resources") assertKotlinTestResources("project", "src/test/resources") } fun testJvmDetectionByConflictingGoalsAndJvmStdlib() { createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm") importProject( """ <groupId>test</groupId> <artifactId>project</artifactId> <version>1.0.0</version> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <version>$kotlinVersion</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/kotlin</sourceDirectory> <plugins> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <executions> <execution> <id>compile</id> <goals> <goal>js</goal> </goals> </execution> <execution> <id>test-compile</id> <goals> <goal>test-compile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> """ ) assertModules("project") assertImporterStatePresent() Assert.assertEquals(JvmPlatforms.jvm16, facetSettings.targetPlatform) assertKotlinSources("project", "src/main/kotlin") assertKotlinTestSources("project", "src/test/java") assertKotlinResources("project", "src/main/resources") assertKotlinTestResources("project", "src/test/resources") } fun testJsDetectionByConflictingGoalsAndJsStdlib() { createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm") importProject( """ <groupId>test</groupId> <artifactId>project</artifactId> <version>1.0.0</version> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib-js</artifactId> <version>$kotlinVersion</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/kotlin</sourceDirectory> <plugins> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <executions> <execution> <id>compile</id> <goals> <goal>js</goal> </goals> </execution> <execution> <id>test-compile</id> <goals> <goal>test-compile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> """ ) assertModules("project") assertImporterStatePresent() Assert.assertTrue(facetSettings.targetPlatform.isJs()) assertKotlinSources("project", "src/main/kotlin") assertKotlinTestSources("project", "src/test/java") assertKotlinResources("project", "src/main/resources") assertKotlinTestResources("project", "src/test/resources") } fun testCommonDetectionByConflictingGoalsAndCommonStdlib() { createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm") importProject( """ <groupId>test</groupId> <artifactId>project</artifactId> <version>1.0.0</version> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib-common</artifactId> <version>$kotlinVersion</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/kotlin</sourceDirectory> <plugins> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <executions> <execution> <id>compile</id> <goals> <goal>js</goal> </goals> </execution> <execution> <id>test-compile</id> <goals> <goal>test-compile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> """ ) assertModules("project") assertImporterStatePresent() Assert.assertTrue(facetSettings.targetPlatform.isCommon()) assertKotlinSources("project", "src/main/kotlin") assertKotlinTestSources("project", "src/test/java") assertKotlinResources("project", "src/main/resources") assertKotlinTestResources("project", "src/test/resources") } }
1
null
1
1
85e5e3f22943744eaf80e844fdf195ca1130b14b
9,080
intellij-community
Apache License 2.0
app/src/main/java/com/viniciusjanner/desafio/sicredi/util/validation/ValidaEmail.kt
viniciusjanner
693,962,041
false
{"Kotlin": 93899, "Java": 115}
package com.viniciusjanner.desafio.sicredi.util.validation import android.widget.EditText import com.google.android.material.textfield.TextInputLayout class ValidaEmail(private val textInputEmail: TextInputLayout) : Validator { private val fieldEmail: EditText = this.textInputEmail.editText!! private val patternValidation: PatternValidation = PatternValidation(this.textInputEmail) private fun valida(email: String): Boolean { if (isEmailValid(email)) { return true } textInputEmail.error = "E-mail inválido" return false } override fun isValid(): Boolean { if (!patternValidation.isValid) return false val email: String = fieldEmail.text.toString() return valida(email) } private fun isEmailValid(email: String): Boolean { return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() } }
0
Kotlin
0
0
6a66a9a4d5a125b9212dfc62bf0325698f4fc502
914
android_desafio_tecnico_empresa_sicredi
Apache License 2.0
app/src/main/java/com/pr0gramm/app/io/Cache.kt
mopsalarm
30,804,448
false
{"Kotlin": 1414351, "Shell": 6752, "Python": 1124}
package com.pr0gramm.app.io import android.app.Application import android.net.Uri import androidx.core.net.toFile import com.pr0gramm.app.Duration.Companion.seconds import com.pr0gramm.app.Logger import com.pr0gramm.app.Stats import com.pr0gramm.app.util.doInBackground import com.pr0gramm.app.util.isLocalFile import com.pr0gramm.app.util.runEvery import okhttp3.* import okio.Okio import java.io.Closeable import java.io.File import java.io.InputStream import java.util.* /** * A cache we can use for linear caching of http requests. */ class Cache(private val context: Application, private val httpClient: OkHttpClient) { private val MEGA = (1024 * 1024).toLong() private val logger = Logger("Cache") private val root: File = File(context.cacheDir, "mediacache") private val lock = Any() private val cache = HashMap<String, Entry>() init { doInBackground { runEvery(seconds(60), initial = seconds(10)) { cleanupCache() } } } /** * Returns a cached or caching entry. You need to close your reference * once you are finish with it. */ fun get(uri: Uri): Cache.Entry { val key = cacheKeyOf(uri) synchronized(lock) { logger.debug { "Looking up cache entry for $key" } var entry: Entry? = cache[key] if (entry?.valid != true) { entry = createEntry(uri) cache[key] = entry } return refCountIfNeeded(entry) } } private fun refCountIfNeeded(entry: Entry): Entry { if (entry is CacheEntry) { entry.incrementRefCount() } return entry } private fun createEntry(uri: Uri): Entry { logger.debug { "Creating a new cache entry for uri $uri" } // just open the file directly if it is already local. if (uri.isLocalFile) { logger.debug { "Uri is local, returning FileEntry(${uri.toFile()})" } return FileEntry(uri.toFile()) } // derive the files basename from the url val basename = uri.toString() .replaceFirst("https?://".toRegex(), "") .replace("[^a-zA-Z0-9.]+".toRegex(), "_") // check if we have a fully cached file val fullyCached = File(root, "$basename.ok") if (fullyCached.exists() && fullyCached.length() > 0) { logger.debug { "Fully cached file exists, returning FileEntry(${fullyCached}" } return FileEntry(fullyCached) } logger.debug { "No cached file found for $uri, creating new CacheEntry." } // resume a previously cached file val partialCached = File(root, "$basename.part") return CacheEntry(httpClient, partialCached, fullyCached, uri) } /** * Checks for old files in the cache directory and removes the oldest files * if they exceed the maximum cache size. */ private fun cleanupCache() { if (!root.exists()) { return } // cache times to sort without someone modifying timestamps during sorting between val modificationTimes = root.listFiles().associate { Pair(it, it.lastModified()) } val files = modificationTimes.keys.sortedByDescending { modificationTimes[it] } // The space already in use by the cache val usedCacheSpace = files.fold(0L) { acc, file -> acc + file.length() } // The amount that can be used by apps val usableSpace = root.usableSpace - 1024 * MEGA // Ignoring what the cache already uses, this is the amount of space that // is available to us. val availableSpace = usedCacheSpace + usableSpace // Now put it in sane limits. val maxCacheSize = availableSpace.coerceIn(256 * MEGA, 1024 * MEGA) logger.debug { "Doing cache cleanup, maxCacheSize=${formatSpace(maxCacheSize)}, found ${files.size} files using ${formatSpace(usedCacheSpace)}" } var usedSpace: Long = 0 for (file in files) { usedSpace += file.length() if (usedSpace > maxCacheSize) { forgetEntryForFile(file) } } // do some tracking of cache sizes Stats().histogram("cache.maxSize", maxCacheSize) Stats().histogram("cache.usedSize", usedSpace) Stats().histogram("cache.usage", usedSpace.toDouble() / maxCacheSize) } /** * Removes the cached entry with the given filename. */ private fun forgetEntryForFile(file: File) { logger.debug { "Remove old cache file $file" } if (!file.delete()) { logger.warn { "Could not delete cached file $file" } } } private fun formatSpace(space: Long): String { return "%1.2fmb".format(space.toFloat() / (1024f * 1024f)) } private fun cacheKeyOf(uri: Uri): String { return uri.toString().replaceFirst("http://", "https://") } interface Entry : Closeable { /** * Total size of this cache entry. */ val totalSize: Int /** * Returns a value between 0 and 1 that specifies how much of this * entry is actually cached. Returns -1 if no estimate is currently available. */ val fractionCached: Float /** * Not null if this cache entry is backed by a file. */ val file: File? /** * Check if the entry is still valid */ val valid: Boolean get() = file?.exists() == true /** * An input stream that starts at the given place in the file. */ fun inputStreamAt(offset: Int): InputStream /** * Closes the reference to the entry. Must be called after getting * a Entry instance using Cache#get. */ override fun close() fun toResponse(request: Request, mediaType: MediaType? = null): Response { val body = ResponseBody.create( mediaType, totalSize.toLong(), Okio.buffer(Okio.source(inputStreamAt(0)))) return Response.Builder() .request(request) .protocol(Protocol.HTTP_1_0) .code(200) .message("OK") .body(body) .build() } } }
39
Kotlin
41
284
d6917f3ec16b6664a90a4519843f3d3d4ccae2cf
6,429
Pr0
MIT License
rhine/src/main/java/com/qingmei2/rhine/base/view/BaseInjectFragment.kt
hnxyy
159,758,594
true
{"Kotlin": 119214}
package com.qingmei2.rhine.base.view import android.support.v4.app.Fragment import org.kodein.di.KodeinAware import org.kodein.di.android.support.closestKodein import org.kodein.di.generic.kcontext abstract class BaseInjectFragment : Fragment(), KodeinAware, IView { protected val parentKodein by closestKodein() override val kodeinContext = kcontext<Fragment>(this) }
0
Kotlin
0
0
12de83a94657d1ce85e3d59c079d07c3c855787c
388
MVVM-Rhine
Apache License 2.0
app/src/main/java/com/katana/mvvm/data/local/StudentDao.kt
bmskyline
165,634,913
true
{"Kotlin": 76282, "Java": 1545}
package com.katana.mvvm.data.local import android.arch.lifecycle.LiveData import android.arch.persistence.room.* import com.katana.mvvm.model.Student /** * Created by Kaz on 11:37 2018-12-18 */ @Dao interface StudentDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertStudent(student: Student): Long @Query("select * from student") fun getAllStudent(): LiveData<List<Student>> @Delete fun deleteStudent(vararg student: Student) }
0
Kotlin
0
0
1386fda0a9a16498a908aed3d2cc6328f94500f5
473
mvvm-kotlin
Apache License 2.0
app/src/main/kotlin/com/alexrdclement/uiplayground/demo/experiments/demo/textfield/CurrencyAmountField.kt
alexrdclement
661,077,963
false
{"Kotlin": 204619}
package com.alexrdclement.uiplayground.demo.experiments.demo.textfield import androidx.annotation.CheckResult import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.input.InputTransformation import androidx.compose.foundation.text.input.OutputTransformation import androidx.compose.foundation.text.input.TextFieldBuffer import androidx.compose.foundation.text.input.TextFieldLineLimits import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.foundation.text.input.delete import androidx.compose.foundation.text.input.insert import androidx.compose.foundation.text.input.rememberTextFieldState import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import com.alexrdclement.uiplayground.components.Text import com.alexrdclement.uiplayground.components.TextField import com.alexrdclement.uiplayground.theme.PlaygroundTheme import com.alexrdclement.uiplayground.ui.preview.UiPlaygroundPreview import java.text.DecimalFormatSymbols import kotlin.math.min private val decimalFormatSymbols = DecimalFormatSymbols.getInstance() private val currencySymbol = decimalFormatSymbols.currencySymbol private val decimalSeparator = decimalFormatSymbols.decimalSeparator private val decimalSeparatorStr = decimalSeparator.toString() private val groupingSeparator = decimalFormatSymbols.groupingSeparator.toString() @Composable fun CurrencyAmountField( textFieldState: TextFieldState = rememberTextFieldState(), placeholder: String = "0", includeCurrencyPrefix: Boolean = true, maxNumDecimalValues: Int = 2 ) { TextField( state = textFieldState, textStyle = PlaygroundTheme.typography.headline, modifier = Modifier .width(IntrinsicSize.Min) .padding(PlaygroundTheme.spacing.medium), inputTransformation = CurrencyAmountFieldInputTransformation(maxNumDecimalValues), outputTransformation = CurrencyAmountFieldOutputTransformation, lineLimits = TextFieldLineLimits.SingleLine, decorator = { textField -> Row( horizontalArrangement = Arrangement.spacedBy(PlaygroundTheme.spacing.small), ) { if (includeCurrencyPrefix) { Text( text = currencySymbol, style = PlaygroundTheme.typography.headline ) } Box { if (textFieldState.text.isEmpty()) { Text( text = placeholder, style = PlaygroundTheme.typography.headline.copy( color = PlaygroundTheme.colorScheme.primary.copy( alpha = 0.5f, ), ) ) } // Min width to ensure cursor still appears Box(modifier = Modifier.widthIn(min = PlaygroundTheme.spacing.small)) { textField() } } } } ) } private class CurrencyAmountFieldInputTransformation( private val maxNumDecimalValues: Int, ) : InputTransformation { override val keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Decimal, ) override fun TextFieldBuffer.transformInput() { filterChars() filterConsecutiveDecimals() val parts = asCharSequence().split(decimalSeparatorStr) val intPart = parts.firstOrNull()?.filter { it.isDigit() } ?: "" val decimalPart = parts.getOrNull(1)?.filter { it.isDigit() } if (parts.size > 2) { // Instead of rejecting changes with multiple decimals, recalculate according to the // first one. replace(intPart.length + 1, length, decimalPart ?: "") } val filteredIntPart = filterIntPart(intPart, hasDecimalPart = decimalPart != null) filterDecimalPart(decimalPart, startIndex = filteredIntPart.length + 1) } private fun TextFieldBuffer.filterChars() { val proposed = asCharSequence() if (proposed.any { !it.isDigit() && it != decimalSeparator }) { // Reject changes for any non-digit, non-decimal characters revertAllChanges() } } private fun TextFieldBuffer.filterConsecutiveDecimals() { val proposed = asCharSequence() var prevChar = proposed.firstOrNull() for (char in proposed.drop(1)) { if (prevChar == decimalSeparator && char == decimalSeparator) { // Reject changes for consecutive decimals revertAllChanges() return } prevChar = char } } @CheckResult private fun TextFieldBuffer.filterIntPart( intPart: String, hasDecimalPart: Boolean, ): String { var mutableIntPart = intPart if (mutableIntPart.startsWith('0')) { // Allow single leading zero. Replace leading zero if followed by another digit. val indexOfFirstNonZero = mutableIntPart.indexOfFirst { it != '0' } val newIntPart = if (indexOfFirstNonZero > 0) { mutableIntPart.substring(indexOfFirstNonZero) } else { "0" } replace(0, mutableIntPart.length, newIntPart) mutableIntPart = newIntPart } if (mutableIntPart.isEmpty() && hasDecimalPart) { // Prefill 0 when only decimal part is entered val newIntPart = "0" replace(0, mutableIntPart.length, newIntPart) mutableIntPart = newIntPart } return mutableIntPart } private fun TextFieldBuffer.filterDecimalPart( decimalPart: String?, startIndex: Int, ) { if (decimalPart != null && decimalPart.length > maxNumDecimalValues) { // Replace chars one-by-one so the cursor advances as expected for (index in startIndex until min(maxNumDecimalValues, decimalPart.length)) { replace(index, index + 1, decimalPart[index].toString()) } delete(startIndex + maxNumDecimalValues, length) } } } private object CurrencyAmountFieldOutputTransformation: OutputTransformation { override fun TextFieldBuffer.transformOutput() { // Insert grouping separators every 3 digits val intPart = originalText.split(decimalSeparatorStr, limit = 2).firstOrNull() ?: "" for (index in 1 until intPart.length) { if (index % 3 == 0) { insert(intPart.length - index, groupingSeparator) } } } } @Preview @Composable private fun Preview() { UiPlaygroundPreview { val textFieldState = rememberTextFieldState(initialText = "") CurrencyAmountField(textFieldState = textFieldState) } }
0
Kotlin
0
0
c04ec33a87a39b40551cc87a5dbf874483d77518
7,482
UiPlayground
Apache License 2.0
docs-deployer/src/main/kotlin/com/avito/android/plugin/DocsPlugin.kt
mduisenov
237,274,875
true
{"Kotlin": 2360982, "Python": 14063, "Shell": 13206, "Dockerfile": 7097, "Makefile": 35}
package com.avito.android.plugin import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.JavaBasePlugin import org.gradle.kotlin.dsl.create import org.gradle.kotlin.dsl.register import java.io.File @Suppress("UnstableApiUsage") class DocsPlugin : Plugin<Project> { override fun apply(target: Project) { val docs = File(target.rootDir, "docs") val extension = target.extensions.create<DocsExtension>("docsDeploy") target.tasks.register<DocsCheckTask>(docsCheckTaskName) { group = JavaBasePlugin.DOCUMENTATION_GROUP docsDirectory.set(docs) } target.tasks.register<DeployDocsTask>(docsDeployTaskName) { group = JavaBasePlugin.DOCUMENTATION_GROUP docsDirectory.set(docs) registry.set(extension.registry) targetHost.set(extension.targetHost) } } }
0
Kotlin
0
0
b0513404cc36196fb87ddadd1894b9015beac952
911
avito-android
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/audio/OfflineAudioContext.events.kt
karakum-team
393,199,102
false
{"Kotlin": 6214094}
// Automatically generated - do not modify! package web.audio import web.events.EventInstance inline val <C : OfflineAudioContext> C.completeEvent: EventInstance<OfflineAudioCompletionEvent, C, C> get() = EventInstance(this, OfflineAudioCompletionEvent.complete())
0
Kotlin
7
35
ac6d96e24eb8d07539990dc2d88cbe85aa811312
272
types-kotlin
Apache License 2.0
app/src/main/java/com/musical/instrument/simulator/app/screens/piano/MyDialog.kt
daovu97
813,488,266
false
{"Kotlin": 224082, "Java": 149657}
package com.musical.instrument.simulator.app.screens.piano import android.app.Dialog import android.content.Context import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.view.Window import android.widget.AbsListView object MyDialog { fun getDialogRecord(context: Context, layout: Int): Dialog { val dialog = Dialog(context) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.setContentView(layout) val window = dialog.window window!!.setLayout( AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT ) dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) dialog.setCancelable(false) return dialog } }
0
Kotlin
0
0
714fbd3f48c359e4dfa16a6455a44d6617028d93
794
MusicInstrument
MIT License
library/src/nativeMain/kotlin/us/q3q/fidok/NativeDeviceInterface.kt
BryanJacobs
684,573,020
false
{"Kotlin": 780971}
@file:Suppress("unused") @file:OptIn(ExperimentalNativeApi::class) package us.q3q.fidok import co.touchlab.kermit.Logger import kotlinx.cinterop.ByteVar import kotlinx.cinterop.COpaquePointer import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.cinterop.StableRef import kotlinx.cinterop.asStableRef import kotlinx.cinterop.reinterpret import kotlinx.cinterop.set import kotlinx.coroutines.runBlocking import us.q3q.fidok.ctap.AuthenticatorDevice import us.q3q.fidok.ctap.AuthenticatorListing import us.q3q.fidok.ctap.FIDOkLibrary import kotlin.experimental.ExperimentalNativeApi expect fun platformDeviceProviders(): List<AuthenticatorListing> data class DeviceListingResult( val devices: List<AuthenticatorDevice>?, ) @OptIn(ExperimentalForeignApi::class) @CName("fidok_device_list") fun listDevices(library: COpaquePointer): COpaquePointer { val fidok = library.asStableRef<FIDOkLibrary>().get() val providers = platformDeviceProviders() val foundDevices = arrayListOf<AuthenticatorDevice>() for (provider in providers) { runBlocking { foundDevices.addAll(provider.listDevices(fidok)) } } val ret = DeviceListingResult(foundDevices) return StableRef.create(ret).asCPointer() } @OptIn(ExperimentalForeignApi::class) @CName("fidok_device_count") fun countDevicesInList(listing: COpaquePointer): Int { return listing.asStableRef<DeviceListingResult>().get().devices?.size ?: 0 } @OptIn(ExperimentalForeignApi::class) @CName("fidok_free_device_list") fun freeDeviceList(listing: COpaquePointer) { return listing.asStableRef<DeviceListingResult>().dispose() } @Suppress("LocalVariableName") @OptIn(ExperimentalForeignApi::class) @CName("fidok_send_bytes") fun sendToDevice( listing: COpaquePointer, device_number: Int, input: COpaquePointer, input_len: Int, output: COpaquePointer, output_len: COpaquePointer, ): Int { val validDevices = listing.asStableRef<DeviceListingResult>().get().devices if (validDevices == null) { Logger.e { "Attempted to use native device $device_number when devices not listed" } return -1 } val device = validDevices[device_number] val inB = inAsByteArray(input, input_len) val outputLenB = inAsByteArray(output_len, 4) var outputLen = 0 for (i in 0..3) { outputLen += (outputLenB[i].toUByte().toUInt() shl (8 * (3 - i))).toInt() } val ret = device.sendBytes(inB) if (ret.size > outputLen) { Logger.e { "Response was ${ret.size} bytes long, but maximum buffer size is $outputLen" } return -1 } val outLenB = output_len.reinterpret<ByteVar>() for (i in 0..3) { outLenB[i] = ((ret.size and (0xFF shl (8 * (3 - i)))) shr (8 * (3 - i))).toByte() } outFill(ret, output) return 0 }
0
Kotlin
1
9
459274c1808bd5d733757c371e927f6d806ab7bb
2,834
FIDOk
MIT License
frontend/src/main/kotlin/components/App.kt
NikkyAI
182,227,647
false
null
package components import com.ccfraser.muirwik.components.HRefOptions import com.ccfraser.muirwik.components.MGridSize import com.ccfraser.muirwik.components.MGridSpacing import com.ccfraser.muirwik.components.MGridWrap import com.ccfraser.muirwik.components.MTabIndicatorColor import com.ccfraser.muirwik.components.MTabOrientation import com.ccfraser.muirwik.components.MTabTextColor import com.ccfraser.muirwik.components.MTabVariant import com.ccfraser.muirwik.components.MTypographyVariant import com.ccfraser.muirwik.components.mGridContainer import com.ccfraser.muirwik.components.mGridItem import com.ccfraser.muirwik.components.mIcon import com.ccfraser.muirwik.components.mLink import com.ccfraser.muirwik.components.mTab import com.ccfraser.muirwik.components.mTabs import com.ccfraser.muirwik.components.mTypography import com.ccfraser.muirwik.components.spacingUnits import com.ccfraser.muirwik.components.variant import containers.pentaSvgInteractive import kotlinx.css.flexGrow import kotlinx.css.marginTop import react.RBuilder import react.RComponent import react.RProps import react.RState import react.setState import styled.css enum class Tabs { help, multiplayer, about, debug_game } class App : RComponent<RProps, RState>() { var tabValue: Any = Tabs.help override fun RBuilder.render() { mGridContainer(spacing = MGridSpacing.spacing2) { css { flexGrow = 1.0 } mGridItem(xs = MGridSize.cells6) { pentaSvgInteractive {} } mGridItem(xs = MGridSize.cells6) { mTypography("Pentagame", variant = MTypographyVariant.h2) gameSetupControls {} // mTypography("Kotlin React + React-Dom + Redux + React-Redux", variant = MTypographyVariant.h2) mGridContainer(wrap = MGridWrap.noWrap) { css { marginTop = 3.spacingUnits flexGrow = 1.0 /*backgroundColor = Color(theme.palette.background.paper)*/ } mGridItem(xs = MGridSize.cellsTrue) { when (tabValue as Tabs) { Tabs.help -> { mTypography("Rules", paragraph = true) mTypography(text = null, paragraph = true) { mLink( text = "Illustated Rules (English)", hRefOptions = HRefOptions( href = "http://pentagame.org/pdf/Illustrated_Rules.pdf", targetBlank = true ) ) { attrs.variant = MTypographyVariant.button } } mTypography(text = null, paragraph = true) { mLink( text = "Illustated Rules (German)", hRefOptions = HRefOptions( href = "http://pentagame.org/pdf/Illustrated_Rules__German_.pdf", targetBlank = true ) ) { attrs.variant = MTypographyVariant.button } } } Tabs.multiplayer -> { textConnection {} } Tabs.about -> { mTypography("About") mLink( text = "About Pentagame", hRefOptions = HRefOptions( href = "http://pentagame.org/", targetBlank = true ) ) { attrs.variant = MTypographyVariant.button } } Tabs.debug_game -> { textBoardState {} } } } mGridItem(xs = MGridSize.cellsAuto) { mTabs( tabValue, variant = MTabVariant.scrollable, textColor = MTabTextColor.primary, indicatorColor = MTabIndicatorColor.primary, orientation = MTabOrientation.vertical, onChange = { _, value -> setState { tabValue = value } } ) { // TODO: add conditional tabs (game list) mTab("Rules", Tabs.help, icon = mIcon("help", addAsChild = false)) mTab("Multiplayer", Tabs.multiplayer, icon = mIcon("people", addAsChild = false)) mTab("About", Tabs.about, icon = mIcon("info", addAsChild = false)) // mTab("Item Five", 4, icon = mIcon("shopping_basket", addAsChild = false)) // mTab("Item Six", 5, icon = mIcon("thumb_down", addAsChild = false)) // mTab("Item Seven", 6, icon = mIcon("thumb_up", addAsChild = false)) mTab("Debug Game", Tabs.debug_game, icon = mIcon("developer_mode", addAsChild = false)) } } } } } } } fun RBuilder.app() = child(App::class) {}
1
Kotlin
3
10
2c26c2ea122525ba2825f32cbf24bde3c78afa6a
6,165
pentagame
MIT License
src/api/kotlin/net/ndrei/bushmaster/api/IHarvestable.kt
MinecraftModDevelopmentMods
104,491,477
false
null
package net.ndrei.bushmaster.api import net.minecraft.block.state.IBlockState import net.minecraft.item.ItemStack import net.minecraft.util.math.BlockPos import net.minecraft.world.World /** * Interface for easier handling of bushes and other plant like things that can be harvested without being destroyed. */ interface IHarvestable { /** * Specifies if the target block is a harvestable block. */ fun canBeHarvested(worldIn: World, pos: BlockPos, state: IBlockState): Boolean /** * Specifies if the target block can provide the list of dropped items without actually dropping them. * This will usually be 'true' if implemented in a mod, and 'false' if it comes from a wrapper. */ fun canSimulateHarvest(worldIn: World, pos: BlockPos, state: IBlockState) = false /** * Harvests the block into [loot]. If [canSimulateHarvest] is 'false' then it should do nothing if [simulate] is true. */ fun harvest(loot: MutableList<ItemStack>, worldIn: World, pos: BlockPos, state: IBlockState, simulate: Boolean) /** * Harvests the block. If [canSimulateHarvest] is 'false' then it should do nothing if [simulate] is true. */ fun harvest(worldIn: World, pos: BlockPos, state: IBlockState, simulate: Boolean) = mutableListOf<ItemStack>().also { this.harvest(it, worldIn, pos, state, simulate) }.toList() }
1
Kotlin
1
1
f3de934b381e53212344604c003c2a8f567da7d5
1,385
Bush-Master-Core
MIT License
app/src/main/java/com/lettytrain/notesapp/entities/Notes.kt
Changliting-letty
413,246,732
false
null
package com.lettytrain.notesapp.entities import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.io.Serializable @Entity(tableName = "notes") class Notes : Serializable { @PrimaryKey(autoGenerate = true) var id: Int? = null @ColumnInfo(name = "userId") var userId: Int? = null @ColumnInfo(name = "title") var title: String? = null @ColumnInfo(name = "sub_title") var subTitle: String? = null @ColumnInfo(name = "create_time") var createTime: String? = null @ColumnInfo(name = "update_time") var updateTime: String? = null @ColumnInfo(name = "note_text") var noteText: String? = null @ColumnInfo(name = "img_path") var imgPath: String? = null @ColumnInfo(name = "web_link") var webLink: String? = null @ColumnInfo(name = "color") var color: String? = null }
1
Kotlin
0
0
82a0e0cac43e251dee0533652d7b0792409321d3
897
NotesApp
Apache License 2.0
android/src/main/kotlin/dev/msfjarvis/claw/android/viewmodel/SavedPostsRepository.kt
msfjarvis
289,347,156
false
null
package dev.msfjarvis.claw.android.viewmodel import com.squareup.sqldelight.runtime.coroutines.asFlow import com.squareup.sqldelight.runtime.coroutines.mapToList import dev.msfjarvis.claw.database.LobstersDatabase import dev.msfjarvis.claw.database.local.SavedPost import javax.inject.Inject import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class SavedPostsRepository @Inject constructor( database: LobstersDatabase, ) { private val savedPostQueries = database.savedPostQueries val savedPosts = savedPostQueries.selectAllPosts().asFlow().mapToList() suspend fun savePost(post: SavedPost) { println("Saving post: ${post.shortId}") withContext(Dispatchers.IO) { savedPostQueries.insertOrReplacePost(post) } } suspend fun removePost(post: SavedPost) { println("Removing post: ${post.shortId}") withContext(Dispatchers.IO) { savedPostQueries.deletePost(post.shortId) } } }
6
Kotlin
4
20
2f60aa0ae008b0a5ad3c2c623e9d38560870052c
930
compose-lobsters
The Unlicense
bound/kt/src/main/kotlin/web5/sdk/rust/UniFFI.kt
TBD54566975
716,632,191
false
null
// This file was autogenerated by some hot garbage in the `uniffi` crate. // Trust me, you don't want to mess with it! @file:Suppress("NAME_SHADOWING") package web5.sdk.rust; // Common helper code. // // Ideally this would live in a separate .kt file where it can be unittested etc // in isolation, and perhaps even published as a re-useable package. // // However, it's important that the details of how this helper code works (e.g. the // way that different builtin types are passed across the FFI) exactly match what's // expected by the Rust code on the other side of the interface. In practice right // now that means coming from the exact some version of `uniffi` that was used to // compile the Rust component. The easiest way to ensure this is to bundle the Kotlin // helpers directly inline like we're doing here. import com.sun.jna.Library import com.sun.jna.IntegerType import com.sun.jna.Native import com.sun.jna.Pointer import com.sun.jna.Structure import com.sun.jna.Callback import com.sun.jna.ptr.* import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.CharBuffer import java.nio.charset.CodingErrorAction import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean // This is a helper for safely working with byte buffers returned from the Rust code. // A rust-owned buffer is represented by its capacity, its current length, and a // pointer to the underlying data. @Structure.FieldOrder("capacity", "len", "data") open class RustBuffer : Structure() { // Note: `capacity` and `len` are actually `ULong` values, but JVM only supports signed values. // When dealing with these fields, make sure to call `toULong()`. @JvmField var capacity: Long = 0 @JvmField var len: Long = 0 @JvmField var data: Pointer? = null class ByValue: RustBuffer(), Structure.ByValue class ByReference: RustBuffer(), Structure.ByReference internal fun setValue(other: RustBuffer) { capacity = other.capacity len = other.len data = other.data } companion object { internal fun alloc(size: ULong = 0UL) = uniffiRustCall() { status -> // Note: need to convert the size to a `Long` value to make this work with JVM. UniffiLib.INSTANCE.ffi_web5_uniffi_rustbuffer_alloc(size.toLong(), status) }.also { if(it.data == null) { throw RuntimeException("RustBuffer.alloc() returned null data pointer (size=${size})") } } internal fun create(capacity: ULong, len: ULong, data: Pointer?): RustBuffer.ByValue { var buf = RustBuffer.ByValue() buf.capacity = capacity.toLong() buf.len = len.toLong() buf.data = data return buf } internal fun free(buf: RustBuffer.ByValue) = uniffiRustCall() { status -> UniffiLib.INSTANCE.ffi_web5_uniffi_rustbuffer_free(buf, status) } } @Suppress("TooGenericExceptionThrown") fun asByteBuffer() = this.data?.getByteBuffer(0, this.len.toLong())?.also { it.order(ByteOrder.BIG_ENDIAN) } } /** * The equivalent of the `*mut RustBuffer` type. * Required for callbacks taking in an out pointer. * * Size is the sum of all values in the struct. */ class RustBufferByReference : ByReference(16) { /** * Set the pointed-to `RustBuffer` to the given value. */ fun setValue(value: RustBuffer.ByValue) { // NOTE: The offsets are as they are in the C-like struct. val pointer = getPointer() pointer.setLong(0, value.capacity) pointer.setLong(8, value.len) pointer.setPointer(16, value.data) } /** * Get a `RustBuffer.ByValue` from this reference. */ fun getValue(): RustBuffer.ByValue { val pointer = getPointer() val value = RustBuffer.ByValue() value.writeField("capacity", pointer.getLong(0)) value.writeField("len", pointer.getLong(8)) value.writeField("data", pointer.getLong(16)) return value } } // This is a helper for safely passing byte references into the rust code. // It's not actually used at the moment, because there aren't many things that you // can take a direct pointer to in the JVM, and if we're going to copy something // then we might as well copy it into a `RustBuffer`. But it's here for API // completeness. @Structure.FieldOrder("len", "data") open class ForeignBytes : Structure() { @JvmField var len: Int = 0 @JvmField var data: Pointer? = null class ByValue : ForeignBytes(), Structure.ByValue } // The FfiConverter interface handles converter types to and from the FFI // // All implementing objects should be public to support external types. When a // type is external we need to import it's FfiConverter. public interface FfiConverter<KotlinType, FfiType> { // Convert an FFI type to a Kotlin type fun lift(value: FfiType): KotlinType // Convert an Kotlin type to an FFI type fun lower(value: KotlinType): FfiType // Read a Kotlin type from a `ByteBuffer` fun read(buf: ByteBuffer): KotlinType // Calculate bytes to allocate when creating a `RustBuffer` // // This must return at least as many bytes as the write() function will // write. It can return more bytes than needed, for example when writing // Strings we can't know the exact bytes needed until we the UTF-8 // encoding, so we pessimistically allocate the largest size possible (3 // bytes per codepoint). Allocating extra bytes is not really a big deal // because the `RustBuffer` is short-lived. fun allocationSize(value: KotlinType): ULong // Write a Kotlin type to a `ByteBuffer` fun write(value: KotlinType, buf: ByteBuffer) // Lower a value into a `RustBuffer` // // This method lowers a value into a `RustBuffer` rather than the normal // FfiType. It's used by the callback interface code. Callback interface // returns are always serialized into a `RustBuffer` regardless of their // normal FFI type. fun lowerIntoRustBuffer(value: KotlinType): RustBuffer.ByValue { val rbuf = RustBuffer.alloc(allocationSize(value)) try { val bbuf = rbuf.data!!.getByteBuffer(0, rbuf.capacity).also { it.order(ByteOrder.BIG_ENDIAN) } write(value, bbuf) rbuf.writeField("len", bbuf.position().toLong()) return rbuf } catch (e: Throwable) { RustBuffer.free(rbuf) throw e } } // Lift a value from a `RustBuffer`. // // This here mostly because of the symmetry with `lowerIntoRustBuffer()`. // It's currently only used by the `FfiConverterRustBuffer` class below. fun liftFromRustBuffer(rbuf: RustBuffer.ByValue): KotlinType { val byteBuf = rbuf.asByteBuffer()!! try { val item = read(byteBuf) if (byteBuf.hasRemaining()) { throw RuntimeException("junk remaining in buffer after lifting, something is very wrong!!") } return item } finally { RustBuffer.free(rbuf) } } } // FfiConverter that uses `RustBuffer` as the FfiType public interface FfiConverterRustBuffer<KotlinType>: FfiConverter<KotlinType, RustBuffer.ByValue> { override fun lift(value: RustBuffer.ByValue) = liftFromRustBuffer(value) override fun lower(value: KotlinType) = lowerIntoRustBuffer(value) } // A handful of classes and functions to support the generated data structures. // This would be a good candidate for isolating in its own ffi-support lib. internal const val UNIFFI_CALL_SUCCESS = 0.toByte() internal const val UNIFFI_CALL_ERROR = 1.toByte() internal const val UNIFFI_CALL_UNEXPECTED_ERROR = 2.toByte() @Structure.FieldOrder("code", "error_buf") internal open class UniffiRustCallStatus : Structure() { @JvmField var code: Byte = 0 @JvmField var error_buf: RustBuffer.ByValue = RustBuffer.ByValue() class ByValue: UniffiRustCallStatus(), Structure.ByValue fun isSuccess(): Boolean { return code == UNIFFI_CALL_SUCCESS } fun isError(): Boolean { return code == UNIFFI_CALL_ERROR } fun isPanic(): Boolean { return code == UNIFFI_CALL_UNEXPECTED_ERROR } companion object { fun create(code: Byte, errorBuf: RustBuffer.ByValue): UniffiRustCallStatus.ByValue { val callStatus = UniffiRustCallStatus.ByValue() callStatus.code = code callStatus.error_buf = errorBuf return callStatus } } } class InternalException(message: String) : Exception(message) // Each top-level error class has a companion object that can lift the error from the call status's rust buffer interface UniffiRustCallStatusErrorHandler<E> { fun lift(error_buf: RustBuffer.ByValue): E; } // Helpers for calling Rust // In practice we usually need to be synchronized to call this safely, so it doesn't // synchronize itself // Call a rust function that returns a Result<>. Pass in the Error class companion that corresponds to the Err private inline fun <U, E: Exception> uniffiRustCallWithError(errorHandler: UniffiRustCallStatusErrorHandler<E>, callback: (UniffiRustCallStatus) -> U): U { var status = UniffiRustCallStatus(); val return_value = callback(status) uniffiCheckCallStatus(errorHandler, status) return return_value } // Check UniffiRustCallStatus and throw an error if the call wasn't successful private fun<E: Exception> uniffiCheckCallStatus(errorHandler: UniffiRustCallStatusErrorHandler<E>, status: UniffiRustCallStatus) { if (status.isSuccess()) { return } else if (status.isError()) { throw errorHandler.lift(status.error_buf) } else if (status.isPanic()) { // when the rust code sees a panic, it tries to construct a rustbuffer // with the message. but if that code panics, then it just sends back // an empty buffer. if (status.error_buf.len > 0) { throw InternalException(FfiConverterString.lift(status.error_buf)) } else { throw InternalException("Rust panic") } } else { throw InternalException("Unknown rust call status: $status.code") } } // UniffiRustCallStatusErrorHandler implementation for times when we don't expect a CALL_ERROR object UniffiNullRustCallStatusErrorHandler: UniffiRustCallStatusErrorHandler<InternalException> { override fun lift(error_buf: RustBuffer.ByValue): InternalException { RustBuffer.free(error_buf) return InternalException("Unexpected CALL_ERROR") } } // Call a rust function that returns a plain value private inline fun <U> uniffiRustCall(callback: (UniffiRustCallStatus) -> U): U { return uniffiRustCallWithError(UniffiNullRustCallStatusErrorHandler, callback); } internal inline fun<T> uniffiTraitInterfaceCall( callStatus: UniffiRustCallStatus, makeCall: () -> T, writeReturn: (T) -> Unit, ) { try { writeReturn(makeCall()) } catch(e: Exception) { callStatus.code = UNIFFI_CALL_UNEXPECTED_ERROR callStatus.error_buf = FfiConverterString.lower(e.toString()) } } internal inline fun<T, reified E: Throwable> uniffiTraitInterfaceCallWithError( callStatus: UniffiRustCallStatus, makeCall: () -> T, writeReturn: (T) -> Unit, lowerError: (E) -> RustBuffer.ByValue ) { try { writeReturn(makeCall()) } catch(e: Exception) { if (e is E) { callStatus.code = UNIFFI_CALL_ERROR callStatus.error_buf = lowerError(e) } else { callStatus.code = UNIFFI_CALL_UNEXPECTED_ERROR callStatus.error_buf = FfiConverterString.lower(e.toString()) } } } // Map handles to objects // // This is used pass an opaque 64-bit handle representing a foreign object to the Rust code. internal class UniffiHandleMap<T: Any> { private val map = ConcurrentHashMap<Long, T>() private val counter = java.util.concurrent.atomic.AtomicLong(0) val size: Int get() = map.size // Insert a new object into the handle map and get a handle for it fun insert(obj: T): Long { val handle = counter.getAndAdd(1) map.put(handle, obj) return handle } // Get an object from the handle map fun get(handle: Long): T { return map.get(handle) ?: throw InternalException("UniffiHandleMap.get: Invalid handle") } // Remove an entry from the handlemap and get the Kotlin object back fun remove(handle: Long): T { return map.remove(handle) ?: throw InternalException("UniffiHandleMap: Invalid handle") } } // Contains loading, initialization code, // and the FFI Function declarations in a com.sun.jna.Library. @Synchronized private fun findLibraryName(componentName: String): String { val libOverride = System.getProperty("uniffi.component.$componentName.libraryOverride") if (libOverride != null) { return libOverride } return "web5_uniffi_aarch64_apple_darwin" } private inline fun <reified Lib : Library> loadIndirect( componentName: String ): Lib { return Native.load<Lib>(detectSystemTarget(), Lib::class.java) } // Define FFI callback types internal interface UniffiRustFutureContinuationCallback : com.sun.jna.Callback { fun callback(`data`: Long,`pollResult`: Byte,) } internal interface UniffiForeignFutureFree : com.sun.jna.Callback { fun callback(`handle`: Long,) } internal interface UniffiCallbackInterfaceFree : com.sun.jna.Callback { fun callback(`handle`: Long,) } @Structure.FieldOrder("handle", "free") internal open class UniffiForeignFuture( @JvmField internal var `handle`: Long = 0.toLong(), @JvmField internal var `free`: UniffiForeignFutureFree? = null, ) : Structure() { class UniffiByValue( `handle`: Long = 0.toLong(), `free`: UniffiForeignFutureFree? = null, ): UniffiForeignFuture(`handle`,`free`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFuture) { `handle` = other.`handle` `free` = other.`free` } } @Structure.FieldOrder("returnValue", "callStatus") internal open class UniffiForeignFutureStructU8( @JvmField internal var `returnValue`: Byte = 0.toByte(), @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `returnValue`: Byte = 0.toByte(), `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructU8(`returnValue`,`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructU8) { `returnValue` = other.`returnValue` `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompleteU8 : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructU8.UniffiByValue,) } @Structure.FieldOrder("returnValue", "callStatus") internal open class UniffiForeignFutureStructI8( @JvmField internal var `returnValue`: Byte = 0.toByte(), @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `returnValue`: Byte = 0.toByte(), `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructI8(`returnValue`,`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructI8) { `returnValue` = other.`returnValue` `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompleteI8 : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructI8.UniffiByValue,) } @Structure.FieldOrder("returnValue", "callStatus") internal open class UniffiForeignFutureStructU16( @JvmField internal var `returnValue`: Short = 0.toShort(), @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `returnValue`: Short = 0.toShort(), `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructU16(`returnValue`,`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructU16) { `returnValue` = other.`returnValue` `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompleteU16 : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructU16.UniffiByValue,) } @Structure.FieldOrder("returnValue", "callStatus") internal open class UniffiForeignFutureStructI16( @JvmField internal var `returnValue`: Short = 0.toShort(), @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `returnValue`: Short = 0.toShort(), `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructI16(`returnValue`,`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructI16) { `returnValue` = other.`returnValue` `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompleteI16 : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructI16.UniffiByValue,) } @Structure.FieldOrder("returnValue", "callStatus") internal open class UniffiForeignFutureStructU32( @JvmField internal var `returnValue`: Int = 0, @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `returnValue`: Int = 0, `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructU32(`returnValue`,`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructU32) { `returnValue` = other.`returnValue` `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompleteU32 : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructU32.UniffiByValue,) } @Structure.FieldOrder("returnValue", "callStatus") internal open class UniffiForeignFutureStructI32( @JvmField internal var `returnValue`: Int = 0, @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `returnValue`: Int = 0, `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructI32(`returnValue`,`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructI32) { `returnValue` = other.`returnValue` `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompleteI32 : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructI32.UniffiByValue,) } @Structure.FieldOrder("returnValue", "callStatus") internal open class UniffiForeignFutureStructU64( @JvmField internal var `returnValue`: Long = 0.toLong(), @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `returnValue`: Long = 0.toLong(), `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructU64(`returnValue`,`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructU64) { `returnValue` = other.`returnValue` `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompleteU64 : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructU64.UniffiByValue,) } @Structure.FieldOrder("returnValue", "callStatus") internal open class UniffiForeignFutureStructI64( @JvmField internal var `returnValue`: Long = 0.toLong(), @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `returnValue`: Long = 0.toLong(), `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructI64(`returnValue`,`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructI64) { `returnValue` = other.`returnValue` `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompleteI64 : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructI64.UniffiByValue,) } @Structure.FieldOrder("returnValue", "callStatus") internal open class UniffiForeignFutureStructF32( @JvmField internal var `returnValue`: Float = 0.0f, @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `returnValue`: Float = 0.0f, `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructF32(`returnValue`,`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructF32) { `returnValue` = other.`returnValue` `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompleteF32 : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructF32.UniffiByValue,) } @Structure.FieldOrder("returnValue", "callStatus") internal open class UniffiForeignFutureStructF64( @JvmField internal var `returnValue`: Double = 0.0, @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `returnValue`: Double = 0.0, `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructF64(`returnValue`,`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructF64) { `returnValue` = other.`returnValue` `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompleteF64 : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructF64.UniffiByValue,) } @Structure.FieldOrder("returnValue", "callStatus") internal open class UniffiForeignFutureStructPointer( @JvmField internal var `returnValue`: Pointer = Pointer.NULL, @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `returnValue`: Pointer = Pointer.NULL, `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructPointer(`returnValue`,`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructPointer) { `returnValue` = other.`returnValue` `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompletePointer : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructPointer.UniffiByValue,) } @Structure.FieldOrder("returnValue", "callStatus") internal open class UniffiForeignFutureStructRustBuffer( @JvmField internal var `returnValue`: RustBuffer.ByValue = RustBuffer.ByValue(), @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `returnValue`: RustBuffer.ByValue = RustBuffer.ByValue(), `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructRustBuffer(`returnValue`,`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructRustBuffer) { `returnValue` = other.`returnValue` `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompleteRustBuffer : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructRustBuffer.UniffiByValue,) } @Structure.FieldOrder("callStatus") internal open class UniffiForeignFutureStructVoid( @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ) : Structure() { class UniffiByValue( `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), ): UniffiForeignFutureStructVoid(`callStatus`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiForeignFutureStructVoid) { `callStatus` = other.`callStatus` } } internal interface UniffiForeignFutureCompleteVoid : com.sun.jna.Callback { fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructVoid.UniffiByValue,) } internal interface UniffiCallbackInterfaceKeyManagerMethod0 : com.sun.jna.Callback { fun callback(`uniffiHandle`: Long,`publicJwk`: RustBuffer.ByValue,`uniffiOutReturn`: PointerByReference,uniffiCallStatus: UniffiRustCallStatus,) } internal interface UniffiCallbackInterfaceKeyManagerMethod1 : com.sun.jna.Callback { fun callback(`uniffiHandle`: Long,`privateJwk`: RustBuffer.ByValue,`uniffiOutReturn`: RustBuffer,uniffiCallStatus: UniffiRustCallStatus,) } internal interface UniffiCallbackInterfaceSignerMethod0 : com.sun.jna.Callback { fun callback(`uniffiHandle`: Long,`payload`: RustBuffer.ByValue,`uniffiOutReturn`: RustBuffer,uniffiCallStatus: UniffiRustCallStatus,) } internal interface UniffiCallbackInterfaceVerifierMethod0 : com.sun.jna.Callback { fun callback(`uniffiHandle`: Long,`message`: RustBuffer.ByValue,`signature`: RustBuffer.ByValue,`uniffiOutReturn`: Pointer,uniffiCallStatus: UniffiRustCallStatus,) } @Structure.FieldOrder("getSigner", "importPrivateJwk", "uniffiFree") internal open class UniffiVTableCallbackInterfaceKeyManager( @JvmField internal var `getSigner`: UniffiCallbackInterfaceKeyManagerMethod0? = null, @JvmField internal var `importPrivateJwk`: UniffiCallbackInterfaceKeyManagerMethod1? = null, @JvmField internal var `uniffiFree`: UniffiCallbackInterfaceFree? = null, ) : Structure() { class UniffiByValue( `getSigner`: UniffiCallbackInterfaceKeyManagerMethod0? = null, `importPrivateJwk`: UniffiCallbackInterfaceKeyManagerMethod1? = null, `uniffiFree`: UniffiCallbackInterfaceFree? = null, ): UniffiVTableCallbackInterfaceKeyManager(`getSigner`,`importPrivateJwk`,`uniffiFree`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiVTableCallbackInterfaceKeyManager) { `getSigner` = other.`getSigner` `importPrivateJwk` = other.`importPrivateJwk` `uniffiFree` = other.`uniffiFree` } } @Structure.FieldOrder("sign", "uniffiFree") internal open class UniffiVTableCallbackInterfaceSigner( @JvmField internal var `sign`: UniffiCallbackInterfaceSignerMethod0? = null, @JvmField internal var `uniffiFree`: UniffiCallbackInterfaceFree? = null, ) : Structure() { class UniffiByValue( `sign`: UniffiCallbackInterfaceSignerMethod0? = null, `uniffiFree`: UniffiCallbackInterfaceFree? = null, ): UniffiVTableCallbackInterfaceSigner(`sign`,`uniffiFree`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiVTableCallbackInterfaceSigner) { `sign` = other.`sign` `uniffiFree` = other.`uniffiFree` } } @Structure.FieldOrder("verify", "uniffiFree") internal open class UniffiVTableCallbackInterfaceVerifier( @JvmField internal var `verify`: UniffiCallbackInterfaceVerifierMethod0? = null, @JvmField internal var `uniffiFree`: UniffiCallbackInterfaceFree? = null, ) : Structure() { class UniffiByValue( `verify`: UniffiCallbackInterfaceVerifierMethod0? = null, `uniffiFree`: UniffiCallbackInterfaceFree? = null, ): UniffiVTableCallbackInterfaceVerifier(`verify`,`uniffiFree`,), Structure.ByValue internal fun uniffiSetValue(other: UniffiVTableCallbackInterfaceVerifier) { `verify` = other.`verify` `uniffiFree` = other.`uniffiFree` } } // A JNA Library to expose the extern-C FFI definitions. // This is an implementation detail which will be called internally by the public API. internal interface UniffiLib : Library { companion object { internal val INSTANCE: UniffiLib by lazy { loadIndirect<UniffiLib>(componentName = "web5") .also { lib: UniffiLib -> uniffiCheckContractApiVersion(lib) uniffiCheckApiChecksums(lib) uniffiCallbackInterfaceKeyManager.register(lib) uniffiCallbackInterfaceSigner.register(lib) uniffiCallbackInterfaceVerifier.register(lib) } } // The Cleaner for the whole library internal val CLEANER: UniffiCleaner by lazy { UniffiCleaner.create() } } fun uniffi_web5_uniffi_fn_clone_bearerdid(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_bearerdid(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_constructor_bearerdid_from_portable_did(`portableDid`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_constructor_bearerdid_new(`uri`: RustBuffer.ByValue,`keyManager`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_bearerdid_get_data(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_method_bearerdid_get_signer(`ptr`: Pointer,`keyId`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_clone_did(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_did(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_constructor_did_new(`uri`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_did_get_data(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_clone_document(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_document(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_constructor_document_new(`data`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_document_get_data(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_clone_ed25519signer(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_ed25519signer(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_constructor_ed25519signer_new(`privateKey`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_ed25519signer_sign(`ptr`: Pointer,`payload`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_clone_ed25519verifier(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_ed25519verifier(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_constructor_ed25519verifier_new(`publicJwk`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_ed25519verifier_verify(`ptr`: Pointer,`message`: RustBuffer.ByValue,`signature`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_clone_inmemorykeymanager(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_inmemorykeymanager(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_constructor_inmemorykeymanager_new(uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_inmemorykeymanager_get_as_key_manager(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_inmemorykeymanager_get_signer(`ptr`: Pointer,`publicJwk`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_inmemorykeymanager_import_private_jwk(`ptr`: Pointer,`privateJwk`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_clone_jwk(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_jwk(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_constructor_jwk_new(`data`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_jwk_compute_thumbprint(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_method_jwk_get_data(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_clone_keymanager(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_keymanager(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_init_callback_vtable_keymanager(`vtable`: UniffiVTableCallbackInterfaceKeyManager, ): Unit fun uniffi_web5_uniffi_fn_method_keymanager_get_signer(`ptr`: Pointer,`publicJwk`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_keymanager_import_private_jwk(`ptr`: Pointer,`privateJwk`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_clone_portabledid(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_portabledid(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_constructor_portabledid_from_json_string(`json`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_portabledid_get_data(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_method_portabledid_to_json_string(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_clone_presentationdefinition(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_presentationdefinition(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_constructor_presentationdefinition_new(`jsonSerializedPresentationDefinition`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_presentationdefinition_get_json_serialized_presentation_definition(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_method_presentationdefinition_select_credentials(`ptr`: Pointer,`vcJwts`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_clone_resolutionresult(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_resolutionresult(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_constructor_resolutionresult_new(`uri`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_resolutionresult_get_data(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_clone_signer(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_signer(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_init_callback_vtable_signer(`vtable`: UniffiVTableCallbackInterfaceSigner, ): Unit fun uniffi_web5_uniffi_fn_method_signer_sign(`ptr`: Pointer,`payload`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_clone_verifiablecredential(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_verifiablecredential(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_constructor_verifiablecredential_create(`jsonSerializedIssuer`: RustBuffer.ByValue,`jsonSerializedCredentialSubject`: RustBuffer.ByValue,`options`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_method_verifiablecredential_get_data(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun uniffi_web5_uniffi_fn_clone_verifier(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_free_verifier(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_init_callback_vtable_verifier(`vtable`: UniffiVTableCallbackInterfaceVerifier, ): Unit fun uniffi_web5_uniffi_fn_method_verifier_verify(`ptr`: Pointer,`message`: RustBuffer.ByValue,`signature`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_func_did_dht_create(`options`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_func_did_dht_publish(`bearerDid`: Pointer,`options`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_fn_func_did_dht_resolve(`uri`: RustBuffer.ByValue,`options`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_func_did_jwk_create(`options`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_func_did_jwk_resolve(`uri`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_func_did_web_create(`domain`: RustBuffer.ByValue,`options`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_func_did_web_resolve(`uri`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun uniffi_web5_uniffi_fn_func_ed25519_generator_generate(uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun ffi_web5_uniffi_rustbuffer_alloc(`size`: Long,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun ffi_web5_uniffi_rustbuffer_from_bytes(`bytes`: ForeignBytes.ByValue,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun ffi_web5_uniffi_rustbuffer_free(`buf`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Unit fun ffi_web5_uniffi_rustbuffer_reserve(`buf`: RustBuffer.ByValue,`additional`: Long,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun ffi_web5_uniffi_rust_future_poll_u8(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_u8(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_u8(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_u8(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): Byte fun ffi_web5_uniffi_rust_future_poll_i8(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_i8(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_i8(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_i8(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): Byte fun ffi_web5_uniffi_rust_future_poll_u16(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_u16(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_u16(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_u16(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): Short fun ffi_web5_uniffi_rust_future_poll_i16(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_i16(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_i16(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_i16(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): Short fun ffi_web5_uniffi_rust_future_poll_u32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_u32(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_u32(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_u32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): Int fun ffi_web5_uniffi_rust_future_poll_i32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_i32(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_i32(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_i32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): Int fun ffi_web5_uniffi_rust_future_poll_u64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_u64(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_u64(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_u64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): Long fun ffi_web5_uniffi_rust_future_poll_i64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_i64(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_i64(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_i64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): Long fun ffi_web5_uniffi_rust_future_poll_f32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_f32(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_f32(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_f32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): Float fun ffi_web5_uniffi_rust_future_poll_f64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_f64(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_f64(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_f64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): Double fun ffi_web5_uniffi_rust_future_poll_pointer(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_pointer(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_pointer(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_pointer(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): Pointer fun ffi_web5_uniffi_rust_future_poll_rust_buffer(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_rust_buffer(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_rust_buffer(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_rust_buffer(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue fun ffi_web5_uniffi_rust_future_poll_void(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, ): Unit fun ffi_web5_uniffi_rust_future_cancel_void(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_free_void(`handle`: Long, ): Unit fun ffi_web5_uniffi_rust_future_complete_void(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, ): Unit fun uniffi_web5_uniffi_checksum_func_did_dht_create( ): Short fun uniffi_web5_uniffi_checksum_func_did_dht_publish( ): Short fun uniffi_web5_uniffi_checksum_func_did_dht_resolve( ): Short fun uniffi_web5_uniffi_checksum_func_did_jwk_create( ): Short fun uniffi_web5_uniffi_checksum_func_did_jwk_resolve( ): Short fun uniffi_web5_uniffi_checksum_func_did_web_create( ): Short fun uniffi_web5_uniffi_checksum_func_did_web_resolve( ): Short fun uniffi_web5_uniffi_checksum_func_ed25519_generator_generate( ): Short fun uniffi_web5_uniffi_checksum_method_bearerdid_get_data( ): Short fun uniffi_web5_uniffi_checksum_method_bearerdid_get_signer( ): Short fun uniffi_web5_uniffi_checksum_method_did_get_data( ): Short fun uniffi_web5_uniffi_checksum_method_document_get_data( ): Short fun uniffi_web5_uniffi_checksum_method_ed25519signer_sign( ): Short fun uniffi_web5_uniffi_checksum_method_ed25519verifier_verify( ): Short fun uniffi_web5_uniffi_checksum_method_inmemorykeymanager_get_as_key_manager( ): Short fun uniffi_web5_uniffi_checksum_method_inmemorykeymanager_get_signer( ): Short fun uniffi_web5_uniffi_checksum_method_inmemorykeymanager_import_private_jwk( ): Short fun uniffi_web5_uniffi_checksum_method_jwk_compute_thumbprint( ): Short fun uniffi_web5_uniffi_checksum_method_jwk_get_data( ): Short fun uniffi_web5_uniffi_checksum_method_keymanager_get_signer( ): Short fun uniffi_web5_uniffi_checksum_method_keymanager_import_private_jwk( ): Short fun uniffi_web5_uniffi_checksum_method_portabledid_get_data( ): Short fun uniffi_web5_uniffi_checksum_method_portabledid_to_json_string( ): Short fun uniffi_web5_uniffi_checksum_method_presentationdefinition_get_json_serialized_presentation_definition( ): Short fun uniffi_web5_uniffi_checksum_method_presentationdefinition_select_credentials( ): Short fun uniffi_web5_uniffi_checksum_method_resolutionresult_get_data( ): Short fun uniffi_web5_uniffi_checksum_method_signer_sign( ): Short fun uniffi_web5_uniffi_checksum_method_verifiablecredential_get_data( ): Short fun uniffi_web5_uniffi_checksum_method_verifier_verify( ): Short fun uniffi_web5_uniffi_checksum_constructor_bearerdid_from_portable_did( ): Short fun uniffi_web5_uniffi_checksum_constructor_bearerdid_new( ): Short fun uniffi_web5_uniffi_checksum_constructor_did_new( ): Short fun uniffi_web5_uniffi_checksum_constructor_document_new( ): Short fun uniffi_web5_uniffi_checksum_constructor_ed25519signer_new( ): Short fun uniffi_web5_uniffi_checksum_constructor_ed25519verifier_new( ): Short fun uniffi_web5_uniffi_checksum_constructor_inmemorykeymanager_new( ): Short fun uniffi_web5_uniffi_checksum_constructor_jwk_new( ): Short fun uniffi_web5_uniffi_checksum_constructor_portabledid_from_json_string( ): Short fun uniffi_web5_uniffi_checksum_constructor_presentationdefinition_new( ): Short fun uniffi_web5_uniffi_checksum_constructor_resolutionresult_new( ): Short fun uniffi_web5_uniffi_checksum_constructor_verifiablecredential_create( ): Short fun ffi_web5_uniffi_uniffi_contract_version( ): Int } private fun uniffiCheckContractApiVersion(lib: UniffiLib) { // Get the bindings contract version from our ComponentInterface val bindings_contract_version = 26 // Get the scaffolding contract version by calling the into the dylib val scaffolding_contract_version = lib.ffi_web5_uniffi_uniffi_contract_version() if (bindings_contract_version != scaffolding_contract_version) { throw RuntimeException("UniFFI contract version mismatch: try cleaning and rebuilding your project") } } @Suppress("UNUSED_PARAMETER") private fun uniffiCheckApiChecksums(lib: UniffiLib) { if (lib.uniffi_web5_uniffi_checksum_func_did_dht_create() != 3925.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_func_did_dht_publish() != 33632.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_func_did_dht_resolve() != 43251.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_func_did_jwk_create() != 64914.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_func_did_jwk_resolve() != 47278.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_func_did_web_create() != 8722.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_func_did_web_resolve() != 15538.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_func_ed25519_generator_generate() != 57849.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_bearerdid_get_data() != 23985.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_bearerdid_get_signer() != 49175.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_did_get_data() != 55630.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_document_get_data() != 16490.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_ed25519signer_sign() != 7079.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_ed25519verifier_verify() != 54498.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_inmemorykeymanager_get_as_key_manager() != 57819.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_inmemorykeymanager_get_signer() != 64632.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_inmemorykeymanager_import_private_jwk() != 1224.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_jwk_compute_thumbprint() != 15254.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_jwk_get_data() != 12450.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_keymanager_get_signer() != 27148.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_keymanager_import_private_jwk() != 6800.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_portabledid_get_data() != 27045.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_portabledid_to_json_string() != 53673.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_presentationdefinition_get_json_serialized_presentation_definition() != 52261.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_presentationdefinition_select_credentials() != 27039.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_resolutionresult_get_data() != 57220.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_signer_sign() != 5738.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_verifiablecredential_get_data() != 34047.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_method_verifier_verify() != 51688.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_constructor_bearerdid_from_portable_did() != 49122.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_constructor_bearerdid_new() != 7404.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_constructor_did_new() != 60730.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_constructor_document_new() != 10173.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_constructor_ed25519signer_new() != 48464.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_constructor_ed25519verifier_new() != 21891.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_constructor_inmemorykeymanager_new() != 16598.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_constructor_jwk_new() != 59888.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_constructor_portabledid_from_json_string() != 64165.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_constructor_presentationdefinition_new() != 13282.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_constructor_resolutionresult_new() != 23836.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if (lib.uniffi_web5_uniffi_checksum_constructor_verifiablecredential_create() != 31236.toShort()) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } } // Async support // Public interface members begin here. // Interface implemented by anything that can contain an object reference. // // Such types expose a `destroy()` method that must be called to cleanly // dispose of the contained objects. Failure to call this method may result // in memory leaks. // // The easiest way to ensure this method is called is to use the `.use` // helper method to execute a block and destroy the object at the end. interface Disposable { fun destroy() companion object { fun destroy(vararg args: Any?) { args.filterIsInstance<Disposable>() .forEach(Disposable::destroy) } } } inline fun <T : Disposable?, R> T.use(block: (T) -> R) = try { block(this) } finally { try { // N.B. our implementation is on the nullable type `Disposable?`. this?.destroy() } catch (e: Throwable) { // swallow } } /** Used to instantiate an interface without an actual pointer, for fakes in tests, mostly. */ object NoPointer public object FfiConverterBoolean: FfiConverter<Boolean, Byte> { override fun lift(value: Byte): Boolean { return value.toInt() != 0 } override fun read(buf: ByteBuffer): Boolean { return lift(buf.get()) } override fun lower(value: Boolean): Byte { return if (value) 1.toByte() else 0.toByte() } override fun allocationSize(value: Boolean) = 1UL override fun write(value: Boolean, buf: ByteBuffer) { buf.put(lower(value)) } } public object FfiConverterString: FfiConverter<String, RustBuffer.ByValue> { // Note: we don't inherit from FfiConverterRustBuffer, because we use a // special encoding when lowering/lifting. We can use `RustBuffer.len` to // store our length and avoid writing it out to the buffer. override fun lift(value: RustBuffer.ByValue): String { try { val byteArr = ByteArray(value.len.toInt()) value.asByteBuffer()!!.get(byteArr) return byteArr.toString(Charsets.UTF_8) } finally { RustBuffer.free(value) } } override fun read(buf: ByteBuffer): String { val len = buf.getInt() val byteArr = ByteArray(len) buf.get(byteArr) return byteArr.toString(Charsets.UTF_8) } fun toUtf8(value: String): ByteBuffer { // Make sure we don't have invalid UTF-16, check for lone surrogates. return Charsets.UTF_8.newEncoder().run { onMalformedInput(CodingErrorAction.REPORT) encode(CharBuffer.wrap(value)) } } override fun lower(value: String): RustBuffer.ByValue { val byteBuf = toUtf8(value) // Ideally we'd pass these bytes to `ffi_bytebuffer_from_bytes`, but doing so would require us // to copy them into a JNA `Memory`. So we might as well directly copy them into a `RustBuffer`. val rbuf = RustBuffer.alloc(byteBuf.limit().toULong()) rbuf.asByteBuffer()!!.put(byteBuf) return rbuf } // We aren't sure exactly how many bytes our string will be once it's UTF-8 // encoded. Allocate 3 bytes per UTF-16 code unit which will always be // enough. override fun allocationSize(value: String): ULong { val sizeForLength = 4UL val sizeForString = value.length.toULong() * 3UL return sizeForLength + sizeForString } override fun write(value: String, buf: ByteBuffer) { val byteBuf = toUtf8(value) buf.putInt(byteBuf.limit()) buf.put(byteBuf) } } public object FfiConverterByteArray: FfiConverterRustBuffer<ByteArray> { override fun read(buf: ByteBuffer): ByteArray { val len = buf.getInt() val byteArr = ByteArray(len) buf.get(byteArr) return byteArr } override fun allocationSize(value: ByteArray): ULong { return 4UL + value.size.toULong() } override fun write(value: ByteArray, buf: ByteBuffer) { buf.putInt(value.size) buf.put(value) } } public object FfiConverterTimestamp: FfiConverterRustBuffer<java.time.Instant> { override fun read(buf: ByteBuffer): java.time.Instant { val seconds = buf.getLong() // Type mismatch (should be u32) but we check for overflow/underflow below val nanoseconds = buf.getInt().toLong() if (nanoseconds < 0) { throw java.time.DateTimeException("Instant nanoseconds exceed minimum or maximum supported by uniffi") } if (seconds >= 0) { return java.time.Instant.EPOCH.plus(java.time.Duration.ofSeconds(seconds, nanoseconds)) } else { return java.time.Instant.EPOCH.minus(java.time.Duration.ofSeconds(-seconds, nanoseconds)) } } // 8 bytes for seconds, 4 bytes for nanoseconds override fun allocationSize(value: java.time.Instant) = 12UL override fun write(value: java.time.Instant, buf: ByteBuffer) { var epochOffset = java.time.Duration.between(java.time.Instant.EPOCH, value) var sign = 1 if (epochOffset.isNegative()) { sign = -1 epochOffset = epochOffset.negated() } if (epochOffset.nano < 0) { // Java docs provide guarantee that nano will always be positive, so this should be impossible // See: https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html throw IllegalArgumentException("Invalid timestamp, nano value must be non-negative") } buf.putLong(sign * epochOffset.seconds) // Type mismatch (should be u32) but since values will always be between 0 and 999,999,999 it should be OK buf.putInt(epochOffset.nano) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // // The cleaner interface for Object finalization code to run. // This is the entry point to any implementation that we're using. // // The cleaner registers objects and returns cleanables, so now we are // defining a `UniffiCleaner` with a `UniffiClenaer.Cleanable` to abstract the // different implmentations available at compile time. interface UniffiCleaner { interface Cleanable { fun clean() } fun register(value: Any, cleanUpTask: Runnable): UniffiCleaner.Cleanable companion object } // The fallback Jna cleaner, which is available for both Android, and the JVM. private class UniffiJnaCleaner : UniffiCleaner { private val cleaner = com.sun.jna.internal.Cleaner.getCleaner() override fun register(value: Any, cleanUpTask: Runnable): UniffiCleaner.Cleanable = UniffiJnaCleanable(cleaner.register(value, cleanUpTask)) } private class UniffiJnaCleanable( private val cleanable: com.sun.jna.internal.Cleaner.Cleanable, ) : UniffiCleaner.Cleanable { override fun clean() = cleanable.clean() } // We decide at uniffi binding generation time whether we were // using Android or not. // There are further runtime checks to chose the correct implementation // of the cleaner. private fun UniffiCleaner.Companion.create(): UniffiCleaner = try { // For safety's sake: if the library hasn't been run in android_cleaner = true // mode, but is being run on Android, then we still need to think about // Android API versions. // So we check if java.lang.ref.Cleaner is there, and use that… java.lang.Class.forName("java.lang.ref.Cleaner") JavaLangRefCleaner() } catch (e: ClassNotFoundException) { // … otherwise, fallback to the JNA cleaner. UniffiJnaCleaner() } private class JavaLangRefCleaner : UniffiCleaner { val cleaner = java.lang.ref.Cleaner.create() override fun register(value: Any, cleanUpTask: Runnable): UniffiCleaner.Cleanable = JavaLangRefCleanable(cleaner.register(value, cleanUpTask)) } private class JavaLangRefCleanable( val cleanable: java.lang.ref.Cleaner.Cleanable ) : UniffiCleaner.Cleanable { override fun clean() = cleanable.clean() } public interface BearerDidInterface { fun `getData`(): BearerDidData fun `getSigner`(`keyId`: kotlin.String): Signer companion object } open class BearerDid: Disposable, AutoCloseable, BearerDidInterface { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } constructor(`uri`: kotlin.String, `keyManager`: KeyManager) : this( uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_constructor_bearerdid_new( FfiConverterString.lower(`uri`),FfiConverterTypeKeyManager.lower(`keyManager`),_status) } ) protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_bearerdid(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_bearerdid(pointer!!, status) } } override fun `getData`(): BearerDidData { return FfiConverterTypeBearerDidData.lift( callWithPointer { uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_bearerdid_get_data( it, _status) } } ) } @Throws(Web5Exception::class)override fun `getSigner`(`keyId`: kotlin.String): Signer { return FfiConverterTypeSigner.lift( callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_bearerdid_get_signer( it, FfiConverterString.lower(`keyId`),_status) } } ) } companion object { @Throws(Web5Exception::class) fun `fromPortableDid`(`portableDid`: PortableDid): BearerDid { return FfiConverterTypeBearerDid.lift( uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_constructor_bearerdid_from_portable_did( FfiConverterTypePortableDid.lower(`portableDid`),_status) } ) } } } public object FfiConverterTypeBearerDid: FfiConverter<BearerDid, Pointer> { override fun lower(value: BearerDid): Pointer { return value.uniffiClonePointer() } override fun lift(value: Pointer): BearerDid { return BearerDid(value) } override fun read(buf: ByteBuffer): BearerDid { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: BearerDid) = 8UL override fun write(value: BearerDid, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface DidInterface { fun `getData`(): DidData companion object } open class Did: Disposable, AutoCloseable, DidInterface { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } constructor(`uri`: kotlin.String) : this( uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_constructor_did_new( FfiConverterString.lower(`uri`),_status) } ) protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_did(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_did(pointer!!, status) } } override fun `getData`(): DidData { return FfiConverterTypeDidData.lift( callWithPointer { uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_did_get_data( it, _status) } } ) } companion object } public object FfiConverterTypeDid: FfiConverter<Did, Pointer> { override fun lower(value: Did): Pointer { return value.uniffiClonePointer() } override fun lift(value: Pointer): Did { return Did(value) } override fun read(buf: ByteBuffer): Did { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: Did) = 8UL override fun write(value: Did, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface DocumentInterface { fun `getData`(): DocumentData companion object } open class Document: Disposable, AutoCloseable, DocumentInterface { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } constructor(`data`: DocumentData) : this( uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_constructor_document_new( FfiConverterTypeDocumentData.lower(`data`),_status) } ) protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_document(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_document(pointer!!, status) } } override fun `getData`(): DocumentData { return FfiConverterTypeDocumentData.lift( callWithPointer { uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_document_get_data( it, _status) } } ) } companion object } public object FfiConverterTypeDocument: FfiConverter<Document, Pointer> { override fun lower(value: Document): Pointer { return value.uniffiClonePointer() } override fun lift(value: Pointer): Document { return Document(value) } override fun read(buf: ByteBuffer): Document { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: Document) = 8UL override fun write(value: Document, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface Ed25519SignerInterface { fun `sign`(`payload`: kotlin.ByteArray): kotlin.ByteArray companion object } open class Ed25519Signer: Disposable, AutoCloseable, Ed25519SignerInterface { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } constructor(`privateKey`: JwkData) : this( uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_constructor_ed25519signer_new( FfiConverterTypeJwkData.lower(`privateKey`),_status) } ) protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_ed25519signer(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_ed25519signer(pointer!!, status) } } @Throws(Web5Exception::class)override fun `sign`(`payload`: kotlin.ByteArray): kotlin.ByteArray { return FfiConverterByteArray.lift( callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_ed25519signer_sign( it, FfiConverterByteArray.lower(`payload`),_status) } } ) } companion object } public object FfiConverterTypeEd25519Signer: FfiConverter<Ed25519Signer, Pointer> { override fun lower(value: Ed25519Signer): Pointer { return value.uniffiClonePointer() } override fun lift(value: Pointer): Ed25519Signer { return Ed25519Signer(value) } override fun read(buf: ByteBuffer): Ed25519Signer { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: Ed25519Signer) = 8UL override fun write(value: Ed25519Signer, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface Ed25519VerifierInterface { fun `verify`(`message`: kotlin.ByteArray, `signature`: kotlin.ByteArray) companion object } open class Ed25519Verifier: Disposable, AutoCloseable, Ed25519VerifierInterface { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } constructor(`publicJwk`: JwkData) : this( uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_constructor_ed25519verifier_new( FfiConverterTypeJwkData.lower(`publicJwk`),_status) } ) protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_ed25519verifier(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_ed25519verifier(pointer!!, status) } } @Throws(Web5Exception::class)override fun `verify`(`message`: kotlin.ByteArray, `signature`: kotlin.ByteArray) = callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_ed25519verifier_verify( it, FfiConverterByteArray.lower(`message`),FfiConverterByteArray.lower(`signature`),_status) } } companion object } public object FfiConverterTypeEd25519Verifier: FfiConverter<Ed25519Verifier, Pointer> { override fun lower(value: Ed25519Verifier): Pointer { return value.uniffiClonePointer() } override fun lift(value: Pointer): Ed25519Verifier { return Ed25519Verifier(value) } override fun read(buf: ByteBuffer): Ed25519Verifier { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: Ed25519Verifier) = 8UL override fun write(value: Ed25519Verifier, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface InMemoryKeyManagerInterface { fun `getAsKeyManager`(): KeyManager fun `getSigner`(`publicJwk`: JwkData): Signer fun `importPrivateJwk`(`privateJwk`: JwkData): JwkData companion object } open class InMemoryKeyManager: Disposable, AutoCloseable, InMemoryKeyManagerInterface { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } constructor() : this( uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_constructor_inmemorykeymanager_new( _status) } ) protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_inmemorykeymanager(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_inmemorykeymanager(pointer!!, status) } } override fun `getAsKeyManager`(): KeyManager { return FfiConverterTypeKeyManager.lift( callWithPointer { uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_inmemorykeymanager_get_as_key_manager( it, _status) } } ) } @Throws(Web5Exception::class)override fun `getSigner`(`publicJwk`: JwkData): Signer { return FfiConverterTypeSigner.lift( callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_inmemorykeymanager_get_signer( it, FfiConverterTypeJwkData.lower(`publicJwk`),_status) } } ) } @Throws(Web5Exception::class)override fun `importPrivateJwk`(`privateJwk`: JwkData): JwkData { return FfiConverterTypeJwkData.lift( callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_inmemorykeymanager_import_private_jwk( it, FfiConverterTypeJwkData.lower(`privateJwk`),_status) } } ) } companion object } public object FfiConverterTypeInMemoryKeyManager: FfiConverter<InMemoryKeyManager, Pointer> { override fun lower(value: InMemoryKeyManager): Pointer { return value.uniffiClonePointer() } override fun lift(value: Pointer): InMemoryKeyManager { return InMemoryKeyManager(value) } override fun read(buf: ByteBuffer): InMemoryKeyManager { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: InMemoryKeyManager) = 8UL override fun write(value: InMemoryKeyManager, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface JwkInterface { fun `computeThumbprint`(): kotlin.String fun `getData`(): JwkData companion object } open class Jwk: Disposable, AutoCloseable, JwkInterface { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } constructor(`data`: JwkData) : this( uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_constructor_jwk_new( FfiConverterTypeJwkData.lower(`data`),_status) } ) protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_jwk(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_jwk(pointer!!, status) } } @Throws(Web5Exception::class)override fun `computeThumbprint`(): kotlin.String { return FfiConverterString.lift( callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_jwk_compute_thumbprint( it, _status) } } ) } override fun `getData`(): JwkData { return FfiConverterTypeJwkData.lift( callWithPointer { uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_jwk_get_data( it, _status) } } ) } companion object } public object FfiConverterTypeJwk: FfiConverter<Jwk, Pointer> { override fun lower(value: Jwk): Pointer { return value.uniffiClonePointer() } override fun lift(value: Pointer): Jwk { return Jwk(value) } override fun read(buf: ByteBuffer): Jwk { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: Jwk) = 8UL override fun write(value: Jwk, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface KeyManager { fun `getSigner`(`publicJwk`: JwkData): Signer fun `importPrivateJwk`(`privateJwk`: JwkData): JwkData companion object } open class KeyManagerImpl: Disposable, AutoCloseable, KeyManager { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_keymanager(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_keymanager(pointer!!, status) } } @Throws(Web5Exception::class)override fun `getSigner`(`publicJwk`: JwkData): Signer { return FfiConverterTypeSigner.lift( callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_keymanager_get_signer( it, FfiConverterTypeJwkData.lower(`publicJwk`),_status) } } ) } @Throws(Web5Exception::class)override fun `importPrivateJwk`(`privateJwk`: JwkData): JwkData { return FfiConverterTypeJwkData.lift( callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_keymanager_import_private_jwk( it, FfiConverterTypeJwkData.lower(`privateJwk`),_status) } } ) } companion object } // Magic number for the Rust proxy to call using the same mechanism as every other method, // to free the callback once it's dropped by Rust. internal const val IDX_CALLBACK_FREE = 0 // Callback return codes internal const val UNIFFI_CALLBACK_SUCCESS = 0 internal const val UNIFFI_CALLBACK_ERROR = 1 internal const val UNIFFI_CALLBACK_UNEXPECTED_ERROR = 2 public abstract class FfiConverterCallbackInterface<CallbackInterface: Any>: FfiConverter<CallbackInterface, Long> { internal val handleMap = UniffiHandleMap<CallbackInterface>() internal fun drop(handle: Long) { handleMap.remove(handle) } override fun lift(value: Long): CallbackInterface { return handleMap.get(value) } override fun read(buf: ByteBuffer) = lift(buf.getLong()) override fun lower(value: CallbackInterface) = handleMap.insert(value) override fun allocationSize(value: CallbackInterface) = 8UL override fun write(value: CallbackInterface, buf: ByteBuffer) { buf.putLong(lower(value)) } } // Put the implementation in an object so we don't pollute the top-level namespace internal object uniffiCallbackInterfaceKeyManager { internal object `getSigner`: UniffiCallbackInterfaceKeyManagerMethod0 { override fun callback(`uniffiHandle`: Long,`publicJwk`: RustBuffer.ByValue,`uniffiOutReturn`: PointerByReference,uniffiCallStatus: UniffiRustCallStatus,) { val uniffiObj = FfiConverterTypeKeyManager.handleMap.get(uniffiHandle) val makeCall = { -> uniffiObj.`getSigner`( FfiConverterTypeJwkData.lift(`publicJwk`), ) } val writeReturn = { value: Signer -> uniffiOutReturn.setValue(FfiConverterTypeSigner.lower(value)) } uniffiTraitInterfaceCallWithError( uniffiCallStatus, makeCall, writeReturn, { e: Web5Exception -> FfiConverterTypeWeb5Error.lower(e) } ) } } internal object `importPrivateJwk`: UniffiCallbackInterfaceKeyManagerMethod1 { override fun callback(`uniffiHandle`: Long,`privateJwk`: RustBuffer.ByValue,`uniffiOutReturn`: RustBuffer,uniffiCallStatus: UniffiRustCallStatus,) { val uniffiObj = FfiConverterTypeKeyManager.handleMap.get(uniffiHandle) val makeCall = { -> uniffiObj.`importPrivateJwk`( FfiConverterTypeJwkData.lift(`privateJwk`), ) } val writeReturn = { value: JwkData -> uniffiOutReturn.setValue(FfiConverterTypeJwkData.lower(value)) } uniffiTraitInterfaceCallWithError( uniffiCallStatus, makeCall, writeReturn, { e: Web5Exception -> FfiConverterTypeWeb5Error.lower(e) } ) } } internal object uniffiFree: UniffiCallbackInterfaceFree { override fun callback(handle: Long) { FfiConverterTypeKeyManager.handleMap.remove(handle) } } internal var vtable = UniffiVTableCallbackInterfaceKeyManager.UniffiByValue( `getSigner`, `importPrivateJwk`, uniffiFree, ) // Registers the foreign callback with the Rust side. // This method is generated for each callback interface. internal fun register(lib: UniffiLib) { lib.uniffi_web5_uniffi_fn_init_callback_vtable_keymanager(vtable) } } public object FfiConverterTypeKeyManager: FfiConverter<KeyManager, Pointer> { internal val handleMap = UniffiHandleMap<KeyManager>() override fun lower(value: KeyManager): Pointer { return Pointer(handleMap.insert(value)) } override fun lift(value: Pointer): KeyManager { return KeyManagerImpl(value) } override fun read(buf: ByteBuffer): KeyManager { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: KeyManager) = 8UL override fun write(value: KeyManager, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface PortableDidInterface { fun `getData`(): PortableDidData fun `toJsonString`(): kotlin.String companion object } open class PortableDid: Disposable, AutoCloseable, PortableDidInterface { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_portabledid(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_portabledid(pointer!!, status) } } override fun `getData`(): PortableDidData { return FfiConverterTypePortableDidData.lift( callWithPointer { uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_portabledid_get_data( it, _status) } } ) } @Throws(Web5Exception::class)override fun `toJsonString`(): kotlin.String { return FfiConverterString.lift( callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_portabledid_to_json_string( it, _status) } } ) } companion object { @Throws(Web5Exception::class) fun `fromJsonString`(`json`: kotlin.String): PortableDid { return FfiConverterTypePortableDid.lift( uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_constructor_portabledid_from_json_string( FfiConverterString.lower(`json`),_status) } ) } } } public object FfiConverterTypePortableDid: FfiConverter<PortableDid, Pointer> { override fun lower(value: PortableDid): Pointer { return value.uniffiClonePointer() } override fun lift(value: Pointer): PortableDid { return PortableDid(value) } override fun read(buf: ByteBuffer): PortableDid { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: PortableDid) = 8UL override fun write(value: PortableDid, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface PresentationDefinitionInterface { fun `getJsonSerializedPresentationDefinition`(): kotlin.String fun `selectCredentials`(`vcJwts`: List<kotlin.String>): List<kotlin.String> companion object } open class PresentationDefinition: Disposable, AutoCloseable, PresentationDefinitionInterface { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } constructor(`jsonSerializedPresentationDefinition`: kotlin.String) : this( uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_constructor_presentationdefinition_new( FfiConverterString.lower(`jsonSerializedPresentationDefinition`),_status) } ) protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_presentationdefinition(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_presentationdefinition(pointer!!, status) } } @Throws(Web5Exception::class)override fun `getJsonSerializedPresentationDefinition`(): kotlin.String { return FfiConverterString.lift( callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_presentationdefinition_get_json_serialized_presentation_definition( it, _status) } } ) } @Throws(Web5Exception::class)override fun `selectCredentials`(`vcJwts`: List<kotlin.String>): List<kotlin.String> { return FfiConverterSequenceString.lift( callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_presentationdefinition_select_credentials( it, FfiConverterSequenceString.lower(`vcJwts`),_status) } } ) } companion object } public object FfiConverterTypePresentationDefinition: FfiConverter<PresentationDefinition, Pointer> { override fun lower(value: PresentationDefinition): Pointer { return value.uniffiClonePointer() } override fun lift(value: Pointer): PresentationDefinition { return PresentationDefinition(value) } override fun read(buf: ByteBuffer): PresentationDefinition { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: PresentationDefinition) = 8UL override fun write(value: PresentationDefinition, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface ResolutionResultInterface { fun `getData`(): ResolutionResultData companion object } open class ResolutionResult: Disposable, AutoCloseable, ResolutionResultInterface { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } constructor(`uri`: kotlin.String) : this( uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_constructor_resolutionresult_new( FfiConverterString.lower(`uri`),_status) } ) protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_resolutionresult(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_resolutionresult(pointer!!, status) } } override fun `getData`(): ResolutionResultData { return FfiConverterTypeResolutionResultData.lift( callWithPointer { uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_resolutionresult_get_data( it, _status) } } ) } companion object } public object FfiConverterTypeResolutionResult: FfiConverter<ResolutionResult, Pointer> { override fun lower(value: ResolutionResult): Pointer { return value.uniffiClonePointer() } override fun lift(value: Pointer): ResolutionResult { return ResolutionResult(value) } override fun read(buf: ByteBuffer): ResolutionResult { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: ResolutionResult) = 8UL override fun write(value: ResolutionResult, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface Signer { fun `sign`(`payload`: kotlin.ByteArray): kotlin.ByteArray companion object } open class SignerImpl: Disposable, AutoCloseable, Signer { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_signer(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_signer(pointer!!, status) } } @Throws(Web5Exception::class)override fun `sign`(`payload`: kotlin.ByteArray): kotlin.ByteArray { return FfiConverterByteArray.lift( callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_signer_sign( it, FfiConverterByteArray.lower(`payload`),_status) } } ) } companion object } // Put the implementation in an object so we don't pollute the top-level namespace internal object uniffiCallbackInterfaceSigner { internal object `sign`: UniffiCallbackInterfaceSignerMethod0 { override fun callback(`uniffiHandle`: Long,`payload`: RustBuffer.ByValue,`uniffiOutReturn`: RustBuffer,uniffiCallStatus: UniffiRustCallStatus,) { val uniffiObj = FfiConverterTypeSigner.handleMap.get(uniffiHandle) val makeCall = { -> uniffiObj.`sign`( FfiConverterByteArray.lift(`payload`), ) } val writeReturn = { value: kotlin.ByteArray -> uniffiOutReturn.setValue(FfiConverterByteArray.lower(value)) } uniffiTraitInterfaceCallWithError( uniffiCallStatus, makeCall, writeReturn, { e: Web5Exception -> FfiConverterTypeWeb5Error.lower(e) } ) } } internal object uniffiFree: UniffiCallbackInterfaceFree { override fun callback(handle: Long) { FfiConverterTypeSigner.handleMap.remove(handle) } } internal var vtable = UniffiVTableCallbackInterfaceSigner.UniffiByValue( `sign`, uniffiFree, ) // Registers the foreign callback with the Rust side. // This method is generated for each callback interface. internal fun register(lib: UniffiLib) { lib.uniffi_web5_uniffi_fn_init_callback_vtable_signer(vtable) } } public object FfiConverterTypeSigner: FfiConverter<Signer, Pointer> { internal val handleMap = UniffiHandleMap<Signer>() override fun lower(value: Signer): Pointer { return Pointer(handleMap.insert(value)) } override fun lift(value: Pointer): Signer { return SignerImpl(value) } override fun read(buf: ByteBuffer): Signer { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: Signer) = 8UL override fun write(value: Signer, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface VerifiableCredentialInterface { fun `getData`(): VerifiableCredentialData companion object } open class VerifiableCredential: Disposable, AutoCloseable, VerifiableCredentialInterface { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_verifiablecredential(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_verifiablecredential(pointer!!, status) } } override fun `getData`(): VerifiableCredentialData { return FfiConverterTypeVerifiableCredentialData.lift( callWithPointer { uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_verifiablecredential_get_data( it, _status) } } ) } companion object { @Throws(Web5Exception::class) fun `create`(`jsonSerializedIssuer`: kotlin.String, `jsonSerializedCredentialSubject`: kotlin.String, `options`: VerifiableCredentialCreateOptionsData?): VerifiableCredential { return FfiConverterTypeVerifiableCredential.lift( uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_constructor_verifiablecredential_create( FfiConverterString.lower(`jsonSerializedIssuer`),FfiConverterString.lower(`jsonSerializedCredentialSubject`),FfiConverterOptionalTypeVerifiableCredentialCreateOptionsData.lower(`options`),_status) } ) } } } public object FfiConverterTypeVerifiableCredential: FfiConverter<VerifiableCredential, Pointer> { override fun lower(value: VerifiableCredential): Pointer { return value.uniffiClonePointer() } override fun lift(value: Pointer): VerifiableCredential { return VerifiableCredential(value) } override fun read(buf: ByteBuffer): VerifiableCredential { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: VerifiableCredential) = 8UL override fun write(value: VerifiableCredential, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } // This template implements a class for working with a Rust struct via a Pointer/Arc<T> // to the live Rust struct on the other side of the FFI. // // Each instance implements core operations for working with the Rust `Arc<T>` and the // Kotlin Pointer to work with the live Rust struct on the other side of the FFI. // // There's some subtlety here, because we have to be careful not to operate on a Rust // struct after it has been dropped, and because we must expose a public API for freeing // theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: // // * Each instance holds an opaque pointer to the underlying Rust struct. // Method calls need to read this pointer from the object's state and pass it in to // the Rust FFI. // // * When an instance is no longer needed, its pointer should be passed to a // special destructor function provided by the Rust FFI, which will drop the // underlying Rust struct. // // * Given an instance, calling code is expected to call the special // `destroy` method in order to free it after use, either by calling it explicitly // or by using a higher-level helper like the `use` method. Failing to do so risks // leaking the underlying Rust struct. // // * We can't assume that calling code will do the right thing, and must be prepared // to handle Kotlin method calls executing concurrently with or even after a call to // `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. // // * We must never allow Rust code to operate on the underlying Rust struct after // the destructor has been called, and must never call the destructor more than once. // Doing so may trigger memory unsafety. // // * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` // is implemented to call the destructor when the Kotlin object becomes unreachable. // This is done in a background thread. This is not a panacea, and client code should be aware that // 1. the thread may starve if some there are objects that have poorly performing // `drop` methods or do significant work in their `drop` methods. // 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, // or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). // // If we try to implement this with mutual exclusion on access to the pointer, there is the // possibility of a race between a method call and a concurrent call to `destroy`: // // * Thread A starts a method call, reads the value of the pointer, but is interrupted // before it can pass the pointer over the FFI to Rust. // * Thread B calls `destroy` and frees the underlying Rust struct. // * Thread A resumes, passing the already-read pointer value to Rust and triggering // a use-after-free. // // One possible solution would be to use a `ReadWriteLock`, with each method call taking // a read lock (and thus allowed to run concurrently) and the special `destroy` method // taking a write lock (and thus blocking on live method calls). However, we aim not to // generate methods with any hidden blocking semantics, and a `destroy` method that might // block if called incorrectly seems to meet that bar. // // So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track // the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` // has been called. These are updated according to the following rules: // // * The initial value of the counter is 1, indicating a live object with no in-flight calls. // The initial value for the flag is false. // // * At the start of each method call, we atomically check the counter. // If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. // If it is nonzero them we atomically increment it by 1 and proceed with the method call. // // * At the end of each method call, we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // * When `destroy` is called, we atomically flip the flag from false to true. // If the flag was already true we silently fail. // Otherwise we atomically decrement and check the counter. // If it has reached zero then we destroy the underlying Rust struct. // // Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, // and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. // // The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been // called *and* all in-flight method calls have completed, avoiding violating any of the expectations // of the underlying Rust code. // // This makes a cleaner a better alternative to _not_ calling `destroy()` as // and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` // method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner // thread may be starved, and the app will leak memory. // // In this case, `destroy`ing manually may be a better solution. // // The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects // with Rust peers are reclaimed: // // 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: // 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: // 3. The memory is reclaimed when the process terminates. // // [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 // public interface Verifier { fun `verify`(`message`: kotlin.ByteArray, `signature`: kotlin.ByteArray) companion object } open class VerifierImpl: Disposable, AutoCloseable, Verifier { constructor(pointer: Pointer) { this.pointer = pointer this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } /** * This constructor can be used to instantiate a fake object. Only used for tests. Any * attempt to actually use an object constructed this way will fail as there is no * connected Rust object. */ @Suppress("UNUSED_PARAMETER") constructor(noPointer: NoPointer) { this.pointer = null this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) } protected val pointer: Pointer? protected val cleanable: UniffiCleaner.Cleanable private val wasDestroyed = AtomicBoolean(false) private val callCounter = AtomicLong(1) override fun destroy() { // Only allow a single call to this method. // TODO: maybe we should log a warning if called more than once? if (this.wasDestroyed.compareAndSet(false, true)) { // This decrement always matches the initial count of 1 given at creation time. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } @Synchronized override fun close() { this.destroy() } internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { // Check and increment the call counter, to keep the object alive. // This needs a compare-and-set retry loop in case of concurrent updates. do { val c = this.callCounter.get() if (c == 0L) { throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") } if (c == Long.MAX_VALUE) { throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") } } while (! this.callCounter.compareAndSet(c, c + 1L)) // Now we can safely do the method call without the pointer being freed concurrently. try { return block(this.uniffiClonePointer()) } finally { // This decrement always matches the increment we performed above. if (this.callCounter.decrementAndGet() == 0L) { cleanable.clean() } } } // Use a static inner class instead of a closure so as not to accidentally // capture `this` as part of the cleanable's action. private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { override fun run() { pointer?.let { ptr -> uniffiRustCall { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_free_verifier(ptr, status) } } } } fun uniffiClonePointer(): Pointer { return uniffiRustCall() { status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_clone_verifier(pointer!!, status) } } @Throws(Web5Exception::class)override fun `verify`(`message`: kotlin.ByteArray, `signature`: kotlin.ByteArray) = callWithPointer { uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_method_verifier_verify( it, FfiConverterByteArray.lower(`message`),FfiConverterByteArray.lower(`signature`),_status) } } companion object } // Put the implementation in an object so we don't pollute the top-level namespace internal object uniffiCallbackInterfaceVerifier { internal object `verify`: UniffiCallbackInterfaceVerifierMethod0 { override fun callback(`uniffiHandle`: Long,`message`: RustBuffer.ByValue,`signature`: RustBuffer.ByValue,`uniffiOutReturn`: Pointer,uniffiCallStatus: UniffiRustCallStatus,) { val uniffiObj = FfiConverterTypeVerifier.handleMap.get(uniffiHandle) val makeCall = { -> uniffiObj.`verify`( FfiConverterByteArray.lift(`message`), FfiConverterByteArray.lift(`signature`), ) } val writeReturn = { _: Unit -> Unit } uniffiTraitInterfaceCallWithError( uniffiCallStatus, makeCall, writeReturn, { e: Web5Exception -> FfiConverterTypeWeb5Error.lower(e) } ) } } internal object uniffiFree: UniffiCallbackInterfaceFree { override fun callback(handle: Long) { FfiConverterTypeVerifier.handleMap.remove(handle) } } internal var vtable = UniffiVTableCallbackInterfaceVerifier.UniffiByValue( `verify`, uniffiFree, ) // Registers the foreign callback with the Rust side. // This method is generated for each callback interface. internal fun register(lib: UniffiLib) { lib.uniffi_web5_uniffi_fn_init_callback_vtable_verifier(vtable) } } public object FfiConverterTypeVerifier: FfiConverter<Verifier, Pointer> { internal val handleMap = UniffiHandleMap<Verifier>() override fun lower(value: Verifier): Pointer { return Pointer(handleMap.insert(value)) } override fun lift(value: Pointer): Verifier { return VerifierImpl(value) } override fun read(buf: ByteBuffer): Verifier { // The Rust code always writes pointers as 8 bytes, and will // fail to compile if they don't fit. return lift(Pointer(buf.getLong())) } override fun allocationSize(value: Verifier) = 8UL override fun write(value: Verifier, buf: ByteBuffer) { // The Rust code always expects pointers written as 8 bytes, // and will fail to compile if they don't fit. buf.putLong(Pointer.nativeValue(lower(value))) } } data class BearerDidData ( var `did`: DidData, var `document`: DocumentData, var `keyManager`: KeyManager ) : Disposable { @Suppress("UNNECESSARY_SAFE_CALL") // codegen is much simpler if we unconditionally emit safe calls here override fun destroy() { Disposable.destroy( this.`did`, this.`document`, this.`keyManager`) } companion object } public object FfiConverterTypeBearerDidData: FfiConverterRustBuffer<BearerDidData> { override fun read(buf: ByteBuffer): BearerDidData { return BearerDidData( FfiConverterTypeDidData.read(buf), FfiConverterTypeDocumentData.read(buf), FfiConverterTypeKeyManager.read(buf), ) } override fun allocationSize(value: BearerDidData) = ( FfiConverterTypeDidData.allocationSize(value.`did`) + FfiConverterTypeDocumentData.allocationSize(value.`document`) + FfiConverterTypeKeyManager.allocationSize(value.`keyManager`) ) override fun write(value: BearerDidData, buf: ByteBuffer) { FfiConverterTypeDidData.write(value.`did`, buf) FfiConverterTypeDocumentData.write(value.`document`, buf) FfiConverterTypeKeyManager.write(value.`keyManager`, buf) } } data class DidData ( var `uri`: kotlin.String, var `url`: kotlin.String, var `method`: kotlin.String, var `id`: kotlin.String, var `params`: Map<kotlin.String, kotlin.String>?, var `path`: kotlin.String?, var `query`: kotlin.String?, var `fragment`: kotlin.String? ) { companion object } public object FfiConverterTypeDidData: FfiConverterRustBuffer<DidData> { override fun read(buf: ByteBuffer): DidData { return DidData( FfiConverterString.read(buf), FfiConverterString.read(buf), FfiConverterString.read(buf), FfiConverterString.read(buf), FfiConverterOptionalMapStringString.read(buf), FfiConverterOptionalString.read(buf), FfiConverterOptionalString.read(buf), FfiConverterOptionalString.read(buf), ) } override fun allocationSize(value: DidData) = ( FfiConverterString.allocationSize(value.`uri`) + FfiConverterString.allocationSize(value.`url`) + FfiConverterString.allocationSize(value.`method`) + FfiConverterString.allocationSize(value.`id`) + FfiConverterOptionalMapStringString.allocationSize(value.`params`) + FfiConverterOptionalString.allocationSize(value.`path`) + FfiConverterOptionalString.allocationSize(value.`query`) + FfiConverterOptionalString.allocationSize(value.`fragment`) ) override fun write(value: DidData, buf: ByteBuffer) { FfiConverterString.write(value.`uri`, buf) FfiConverterString.write(value.`url`, buf) FfiConverterString.write(value.`method`, buf) FfiConverterString.write(value.`id`, buf) FfiConverterOptionalMapStringString.write(value.`params`, buf) FfiConverterOptionalString.write(value.`path`, buf) FfiConverterOptionalString.write(value.`query`, buf) FfiConverterOptionalString.write(value.`fragment`, buf) } } data class DidDhtCreateOptions ( var `publish`: kotlin.Boolean?, var `gatewayUrl`: kotlin.String?, var `keyManager`: KeyManager?, var `service`: List<ServiceData>?, var `controller`: List<kotlin.String>?, var `alsoKnownAs`: List<kotlin.String>?, var `verificationMethod`: List<VerificationMethodData>? ) : Disposable { @Suppress("UNNECESSARY_SAFE_CALL") // codegen is much simpler if we unconditionally emit safe calls here override fun destroy() { Disposable.destroy( this.`publish`, this.`gatewayUrl`, this.`keyManager`, this.`service`, this.`controller`, this.`alsoKnownAs`, this.`verificationMethod`) } companion object } public object FfiConverterTypeDidDhtCreateOptions: FfiConverterRustBuffer<DidDhtCreateOptions> { override fun read(buf: ByteBuffer): DidDhtCreateOptions { return DidDhtCreateOptions( FfiConverterOptionalBoolean.read(buf), FfiConverterOptionalString.read(buf), FfiConverterOptionalTypeKeyManager.read(buf), FfiConverterOptionalSequenceTypeServiceData.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalSequenceTypeVerificationMethodData.read(buf), ) } override fun allocationSize(value: DidDhtCreateOptions) = ( FfiConverterOptionalBoolean.allocationSize(value.`publish`) + FfiConverterOptionalString.allocationSize(value.`gatewayUrl`) + FfiConverterOptionalTypeKeyManager.allocationSize(value.`keyManager`) + FfiConverterOptionalSequenceTypeServiceData.allocationSize(value.`service`) + FfiConverterOptionalSequenceString.allocationSize(value.`controller`) + FfiConverterOptionalSequenceString.allocationSize(value.`alsoKnownAs`) + FfiConverterOptionalSequenceTypeVerificationMethodData.allocationSize(value.`verificationMethod`) ) override fun write(value: DidDhtCreateOptions, buf: ByteBuffer) { FfiConverterOptionalBoolean.write(value.`publish`, buf) FfiConverterOptionalString.write(value.`gatewayUrl`, buf) FfiConverterOptionalTypeKeyManager.write(value.`keyManager`, buf) FfiConverterOptionalSequenceTypeServiceData.write(value.`service`, buf) FfiConverterOptionalSequenceString.write(value.`controller`, buf) FfiConverterOptionalSequenceString.write(value.`alsoKnownAs`, buf) FfiConverterOptionalSequenceTypeVerificationMethodData.write(value.`verificationMethod`, buf) } } data class DidDhtPublishOptions ( var `gatewayUrl`: kotlin.String? ) { companion object } public object FfiConverterTypeDidDhtPublishOptions: FfiConverterRustBuffer<DidDhtPublishOptions> { override fun read(buf: ByteBuffer): DidDhtPublishOptions { return DidDhtPublishOptions( FfiConverterOptionalString.read(buf), ) } override fun allocationSize(value: DidDhtPublishOptions) = ( FfiConverterOptionalString.allocationSize(value.`gatewayUrl`) ) override fun write(value: DidDhtPublishOptions, buf: ByteBuffer) { FfiConverterOptionalString.write(value.`gatewayUrl`, buf) } } data class DidDhtResolveOptions ( var `gatewayUrl`: kotlin.String? ) { companion object } public object FfiConverterTypeDidDhtResolveOptions: FfiConverterRustBuffer<DidDhtResolveOptions> { override fun read(buf: ByteBuffer): DidDhtResolveOptions { return DidDhtResolveOptions( FfiConverterOptionalString.read(buf), ) } override fun allocationSize(value: DidDhtResolveOptions) = ( FfiConverterOptionalString.allocationSize(value.`gatewayUrl`) ) override fun write(value: DidDhtResolveOptions, buf: ByteBuffer) { FfiConverterOptionalString.write(value.`gatewayUrl`, buf) } } data class DidJwkCreateOptions ( var `keyManager`: KeyManager?, var `dsa`: Dsa? ) : Disposable { @Suppress("UNNECESSARY_SAFE_CALL") // codegen is much simpler if we unconditionally emit safe calls here override fun destroy() { Disposable.destroy( this.`keyManager`, this.`dsa`) } companion object } public object FfiConverterTypeDidJwkCreateOptions: FfiConverterRustBuffer<DidJwkCreateOptions> { override fun read(buf: ByteBuffer): DidJwkCreateOptions { return DidJwkCreateOptions( FfiConverterOptionalTypeKeyManager.read(buf), FfiConverterOptionalTypeDsa.read(buf), ) } override fun allocationSize(value: DidJwkCreateOptions) = ( FfiConverterOptionalTypeKeyManager.allocationSize(value.`keyManager`) + FfiConverterOptionalTypeDsa.allocationSize(value.`dsa`) ) override fun write(value: DidJwkCreateOptions, buf: ByteBuffer) { FfiConverterOptionalTypeKeyManager.write(value.`keyManager`, buf) FfiConverterOptionalTypeDsa.write(value.`dsa`, buf) } } data class DidWebCreateOptions ( var `keyManager`: KeyManager?, var `dsa`: Dsa?, var `service`: List<ServiceData>?, var `controller`: List<kotlin.String>?, var `alsoKnownAs`: List<kotlin.String>?, var `verificationMethod`: List<VerificationMethodData>? ) : Disposable { @Suppress("UNNECESSARY_SAFE_CALL") // codegen is much simpler if we unconditionally emit safe calls here override fun destroy() { Disposable.destroy( this.`keyManager`, this.`dsa`, this.`service`, this.`controller`, this.`alsoKnownAs`, this.`verificationMethod`) } companion object } public object FfiConverterTypeDidWebCreateOptions: FfiConverterRustBuffer<DidWebCreateOptions> { override fun read(buf: ByteBuffer): DidWebCreateOptions { return DidWebCreateOptions( FfiConverterOptionalTypeKeyManager.read(buf), FfiConverterOptionalTypeDsa.read(buf), FfiConverterOptionalSequenceTypeServiceData.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalSequenceTypeVerificationMethodData.read(buf), ) } override fun allocationSize(value: DidWebCreateOptions) = ( FfiConverterOptionalTypeKeyManager.allocationSize(value.`keyManager`) + FfiConverterOptionalTypeDsa.allocationSize(value.`dsa`) + FfiConverterOptionalSequenceTypeServiceData.allocationSize(value.`service`) + FfiConverterOptionalSequenceString.allocationSize(value.`controller`) + FfiConverterOptionalSequenceString.allocationSize(value.`alsoKnownAs`) + FfiConverterOptionalSequenceTypeVerificationMethodData.allocationSize(value.`verificationMethod`) ) override fun write(value: DidWebCreateOptions, buf: ByteBuffer) { FfiConverterOptionalTypeKeyManager.write(value.`keyManager`, buf) FfiConverterOptionalTypeDsa.write(value.`dsa`, buf) FfiConverterOptionalSequenceTypeServiceData.write(value.`service`, buf) FfiConverterOptionalSequenceString.write(value.`controller`, buf) FfiConverterOptionalSequenceString.write(value.`alsoKnownAs`, buf) FfiConverterOptionalSequenceTypeVerificationMethodData.write(value.`verificationMethod`, buf) } } data class DocumentData ( var `id`: kotlin.String, var `context`: List<kotlin.String>?, var `controller`: List<kotlin.String>?, var `alsoKnownAs`: List<kotlin.String>?, var `verificationMethod`: List<VerificationMethodData>, var `authentication`: List<kotlin.String>?, var `assertionMethod`: List<kotlin.String>?, var `keyAgreement`: List<kotlin.String>?, var `capabilityInvocation`: List<kotlin.String>?, var `capabilityDelegation`: List<kotlin.String>?, var `service`: List<ServiceData>? ) { companion object } public object FfiConverterTypeDocumentData: FfiConverterRustBuffer<DocumentData> { override fun read(buf: ByteBuffer): DocumentData { return DocumentData( FfiConverterString.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterSequenceTypeVerificationMethodData.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalSequenceTypeServiceData.read(buf), ) } override fun allocationSize(value: DocumentData) = ( FfiConverterString.allocationSize(value.`id`) + FfiConverterOptionalSequenceString.allocationSize(value.`context`) + FfiConverterOptionalSequenceString.allocationSize(value.`controller`) + FfiConverterOptionalSequenceString.allocationSize(value.`alsoKnownAs`) + FfiConverterSequenceTypeVerificationMethodData.allocationSize(value.`verificationMethod`) + FfiConverterOptionalSequenceString.allocationSize(value.`authentication`) + FfiConverterOptionalSequenceString.allocationSize(value.`assertionMethod`) + FfiConverterOptionalSequenceString.allocationSize(value.`keyAgreement`) + FfiConverterOptionalSequenceString.allocationSize(value.`capabilityInvocation`) + FfiConverterOptionalSequenceString.allocationSize(value.`capabilityDelegation`) + FfiConverterOptionalSequenceTypeServiceData.allocationSize(value.`service`) ) override fun write(value: DocumentData, buf: ByteBuffer) { FfiConverterString.write(value.`id`, buf) FfiConverterOptionalSequenceString.write(value.`context`, buf) FfiConverterOptionalSequenceString.write(value.`controller`, buf) FfiConverterOptionalSequenceString.write(value.`alsoKnownAs`, buf) FfiConverterSequenceTypeVerificationMethodData.write(value.`verificationMethod`, buf) FfiConverterOptionalSequenceString.write(value.`authentication`, buf) FfiConverterOptionalSequenceString.write(value.`assertionMethod`, buf) FfiConverterOptionalSequenceString.write(value.`keyAgreement`, buf) FfiConverterOptionalSequenceString.write(value.`capabilityInvocation`, buf) FfiConverterOptionalSequenceString.write(value.`capabilityDelegation`, buf) FfiConverterOptionalSequenceTypeServiceData.write(value.`service`, buf) } } data class DocumentMetadataData ( var `created`: kotlin.String?, var `updated`: kotlin.String?, var `deactivated`: kotlin.Boolean?, var `nextUpdate`: kotlin.String?, var `versionId`: kotlin.String?, var `nextVersionId`: kotlin.String?, var `equivalentId`: List<kotlin.String>?, var `canonicalId`: kotlin.String? ) { companion object } public object FfiConverterTypeDocumentMetadataData: FfiConverterRustBuffer<DocumentMetadataData> { override fun read(buf: ByteBuffer): DocumentMetadataData { return DocumentMetadataData( FfiConverterOptionalString.read(buf), FfiConverterOptionalString.read(buf), FfiConverterOptionalBoolean.read(buf), FfiConverterOptionalString.read(buf), FfiConverterOptionalString.read(buf), FfiConverterOptionalString.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalString.read(buf), ) } override fun allocationSize(value: DocumentMetadataData) = ( FfiConverterOptionalString.allocationSize(value.`created`) + FfiConverterOptionalString.allocationSize(value.`updated`) + FfiConverterOptionalBoolean.allocationSize(value.`deactivated`) + FfiConverterOptionalString.allocationSize(value.`nextUpdate`) + FfiConverterOptionalString.allocationSize(value.`versionId`) + FfiConverterOptionalString.allocationSize(value.`nextVersionId`) + FfiConverterOptionalSequenceString.allocationSize(value.`equivalentId`) + FfiConverterOptionalString.allocationSize(value.`canonicalId`) ) override fun write(value: DocumentMetadataData, buf: ByteBuffer) { FfiConverterOptionalString.write(value.`created`, buf) FfiConverterOptionalString.write(value.`updated`, buf) FfiConverterOptionalBoolean.write(value.`deactivated`, buf) FfiConverterOptionalString.write(value.`nextUpdate`, buf) FfiConverterOptionalString.write(value.`versionId`, buf) FfiConverterOptionalString.write(value.`nextVersionId`, buf) FfiConverterOptionalSequenceString.write(value.`equivalentId`, buf) FfiConverterOptionalString.write(value.`canonicalId`, buf) } } data class JwkData ( var `alg`: kotlin.String?, var `kty`: kotlin.String, var `crv`: kotlin.String, var `d`: kotlin.String?, var `x`: kotlin.String, var `y`: kotlin.String? ) { companion object } public object FfiConverterTypeJwkData: FfiConverterRustBuffer<JwkData> { override fun read(buf: ByteBuffer): JwkData { return JwkData( FfiConverterOptionalString.read(buf), FfiConverterString.read(buf), FfiConverterString.read(buf), FfiConverterOptionalString.read(buf), FfiConverterString.read(buf), FfiConverterOptionalString.read(buf), ) } override fun allocationSize(value: JwkData) = ( FfiConverterOptionalString.allocationSize(value.`alg`) + FfiConverterString.allocationSize(value.`kty`) + FfiConverterString.allocationSize(value.`crv`) + FfiConverterOptionalString.allocationSize(value.`d`) + FfiConverterString.allocationSize(value.`x`) + FfiConverterOptionalString.allocationSize(value.`y`) ) override fun write(value: JwkData, buf: ByteBuffer) { FfiConverterOptionalString.write(value.`alg`, buf) FfiConverterString.write(value.`kty`, buf) FfiConverterString.write(value.`crv`, buf) FfiConverterOptionalString.write(value.`d`, buf) FfiConverterString.write(value.`x`, buf) FfiConverterOptionalString.write(value.`y`, buf) } } data class PortableDidData ( var `didUri`: kotlin.String, var `document`: DocumentData, var `privateJwks`: List<JwkData> ) { companion object } public object FfiConverterTypePortableDidData: FfiConverterRustBuffer<PortableDidData> { override fun read(buf: ByteBuffer): PortableDidData { return PortableDidData( FfiConverterString.read(buf), FfiConverterTypeDocumentData.read(buf), FfiConverterSequenceTypeJwkData.read(buf), ) } override fun allocationSize(value: PortableDidData) = ( FfiConverterString.allocationSize(value.`didUri`) + FfiConverterTypeDocumentData.allocationSize(value.`document`) + FfiConverterSequenceTypeJwkData.allocationSize(value.`privateJwks`) ) override fun write(value: PortableDidData, buf: ByteBuffer) { FfiConverterString.write(value.`didUri`, buf) FfiConverterTypeDocumentData.write(value.`document`, buf) FfiConverterSequenceTypeJwkData.write(value.`privateJwks`, buf) } } data class ResolutionMetadataData ( var `error`: ResolutionMetadataError? ) { companion object } public object FfiConverterTypeResolutionMetadataData: FfiConverterRustBuffer<ResolutionMetadataData> { override fun read(buf: ByteBuffer): ResolutionMetadataData { return ResolutionMetadataData( FfiConverterOptionalTypeResolutionMetadataError.read(buf), ) } override fun allocationSize(value: ResolutionMetadataData) = ( FfiConverterOptionalTypeResolutionMetadataError.allocationSize(value.`error`) ) override fun write(value: ResolutionMetadataData, buf: ByteBuffer) { FfiConverterOptionalTypeResolutionMetadataError.write(value.`error`, buf) } } data class ResolutionResultData ( var `document`: DocumentData?, var `documentMetadata`: DocumentMetadataData?, var `resolutionMetadata`: ResolutionMetadataData ) { companion object } public object FfiConverterTypeResolutionResultData: FfiConverterRustBuffer<ResolutionResultData> { override fun read(buf: ByteBuffer): ResolutionResultData { return ResolutionResultData( FfiConverterOptionalTypeDocumentData.read(buf), FfiConverterOptionalTypeDocumentMetadataData.read(buf), FfiConverterTypeResolutionMetadataData.read(buf), ) } override fun allocationSize(value: ResolutionResultData) = ( FfiConverterOptionalTypeDocumentData.allocationSize(value.`document`) + FfiConverterOptionalTypeDocumentMetadataData.allocationSize(value.`documentMetadata`) + FfiConverterTypeResolutionMetadataData.allocationSize(value.`resolutionMetadata`) ) override fun write(value: ResolutionResultData, buf: ByteBuffer) { FfiConverterOptionalTypeDocumentData.write(value.`document`, buf) FfiConverterOptionalTypeDocumentMetadataData.write(value.`documentMetadata`, buf) FfiConverterTypeResolutionMetadataData.write(value.`resolutionMetadata`, buf) } } data class ServiceData ( var `id`: kotlin.String, var `type`: kotlin.String, var `serviceEndpoint`: List<kotlin.String> ) { companion object } public object FfiConverterTypeServiceData: FfiConverterRustBuffer<ServiceData> { override fun read(buf: ByteBuffer): ServiceData { return ServiceData( FfiConverterString.read(buf), FfiConverterString.read(buf), FfiConverterSequenceString.read(buf), ) } override fun allocationSize(value: ServiceData) = ( FfiConverterString.allocationSize(value.`id`) + FfiConverterString.allocationSize(value.`type`) + FfiConverterSequenceString.allocationSize(value.`serviceEndpoint`) ) override fun write(value: ServiceData, buf: ByteBuffer) { FfiConverterString.write(value.`id`, buf) FfiConverterString.write(value.`type`, buf) FfiConverterSequenceString.write(value.`serviceEndpoint`, buf) } } data class VerifiableCredentialCreateOptionsData ( var `id`: kotlin.String?, var `context`: List<kotlin.String>?, var `type`: List<kotlin.String>?, var `issuanceDate`: java.time.Instant?, var `expirationDate`: java.time.Instant? ) { companion object } public object FfiConverterTypeVerifiableCredentialCreateOptionsData: FfiConverterRustBuffer<VerifiableCredentialCreateOptionsData> { override fun read(buf: ByteBuffer): VerifiableCredentialCreateOptionsData { return VerifiableCredentialCreateOptionsData( FfiConverterOptionalString.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalSequenceString.read(buf), FfiConverterOptionalTimestamp.read(buf), FfiConverterOptionalTimestamp.read(buf), ) } override fun allocationSize(value: VerifiableCredentialCreateOptionsData) = ( FfiConverterOptionalString.allocationSize(value.`id`) + FfiConverterOptionalSequenceString.allocationSize(value.`context`) + FfiConverterOptionalSequenceString.allocationSize(value.`type`) + FfiConverterOptionalTimestamp.allocationSize(value.`issuanceDate`) + FfiConverterOptionalTimestamp.allocationSize(value.`expirationDate`) ) override fun write(value: VerifiableCredentialCreateOptionsData, buf: ByteBuffer) { FfiConverterOptionalString.write(value.`id`, buf) FfiConverterOptionalSequenceString.write(value.`context`, buf) FfiConverterOptionalSequenceString.write(value.`type`, buf) FfiConverterOptionalTimestamp.write(value.`issuanceDate`, buf) FfiConverterOptionalTimestamp.write(value.`expirationDate`, buf) } } data class VerifiableCredentialData ( var `context`: List<kotlin.String>, var `type`: List<kotlin.String>, var `id`: kotlin.String, var `jsonSerializedIssuer`: kotlin.String, var `jsonSerializedCredentialSubject`: kotlin.String, var `issuanceDate`: java.time.Instant, var `expirationDate`: java.time.Instant? ) { companion object } public object FfiConverterTypeVerifiableCredentialData: FfiConverterRustBuffer<VerifiableCredentialData> { override fun read(buf: ByteBuffer): VerifiableCredentialData { return VerifiableCredentialData( FfiConverterSequenceString.read(buf), FfiConverterSequenceString.read(buf), FfiConverterString.read(buf), FfiConverterString.read(buf), FfiConverterString.read(buf), FfiConverterTimestamp.read(buf), FfiConverterOptionalTimestamp.read(buf), ) } override fun allocationSize(value: VerifiableCredentialData) = ( FfiConverterSequenceString.allocationSize(value.`context`) + FfiConverterSequenceString.allocationSize(value.`type`) + FfiConverterString.allocationSize(value.`id`) + FfiConverterString.allocationSize(value.`jsonSerializedIssuer`) + FfiConverterString.allocationSize(value.`jsonSerializedCredentialSubject`) + FfiConverterTimestamp.allocationSize(value.`issuanceDate`) + FfiConverterOptionalTimestamp.allocationSize(value.`expirationDate`) ) override fun write(value: VerifiableCredentialData, buf: ByteBuffer) { FfiConverterSequenceString.write(value.`context`, buf) FfiConverterSequenceString.write(value.`type`, buf) FfiConverterString.write(value.`id`, buf) FfiConverterString.write(value.`jsonSerializedIssuer`, buf) FfiConverterString.write(value.`jsonSerializedCredentialSubject`, buf) FfiConverterTimestamp.write(value.`issuanceDate`, buf) FfiConverterOptionalTimestamp.write(value.`expirationDate`, buf) } } data class VerificationMethodData ( var `id`: kotlin.String, var `type`: kotlin.String, var `controller`: kotlin.String, var `publicKeyJwk`: JwkData ) { companion object } public object FfiConverterTypeVerificationMethodData: FfiConverterRustBuffer<VerificationMethodData> { override fun read(buf: ByteBuffer): VerificationMethodData { return VerificationMethodData( FfiConverterString.read(buf), FfiConverterString.read(buf), FfiConverterString.read(buf), FfiConverterTypeJwkData.read(buf), ) } override fun allocationSize(value: VerificationMethodData) = ( FfiConverterString.allocationSize(value.`id`) + FfiConverterString.allocationSize(value.`type`) + FfiConverterString.allocationSize(value.`controller`) + FfiConverterTypeJwkData.allocationSize(value.`publicKeyJwk`) ) override fun write(value: VerificationMethodData, buf: ByteBuffer) { FfiConverterString.write(value.`id`, buf) FfiConverterString.write(value.`type`, buf) FfiConverterString.write(value.`controller`, buf) FfiConverterTypeJwkData.write(value.`publicKeyJwk`, buf) } } enum class Dsa { ED25519, SECP256K1; companion object } public object FfiConverterTypeDsa: FfiConverterRustBuffer<Dsa> { override fun read(buf: ByteBuffer) = try { Dsa.values()[buf.getInt() - 1] } catch (e: IndexOutOfBoundsException) { throw RuntimeException("invalid enum value, something is very wrong!!", e) } override fun allocationSize(value: Dsa) = 4UL override fun write(value: Dsa, buf: ByteBuffer) { buf.putInt(value.ordinal + 1) } } enum class ResolutionMetadataError { INVALID_DID, NOT_FOUND, REPRESENTATION_NOT_SUPPORTED, METHOD_NOT_SUPPORTED, INVALID_DID_DOCUMENT, INVALID_PUBLIC_KEY, INVALID_DID_DOCUMENT_LENGTH, INTERNAL_ERROR; companion object } public object FfiConverterTypeResolutionMetadataError: FfiConverterRustBuffer<ResolutionMetadataError> { override fun read(buf: ByteBuffer) = try { ResolutionMetadataError.values()[buf.getInt() - 1] } catch (e: IndexOutOfBoundsException) { throw RuntimeException("invalid enum value, something is very wrong!!", e) } override fun allocationSize(value: ResolutionMetadataError) = 4UL override fun write(value: ResolutionMetadataError, buf: ByteBuffer) { buf.putInt(value.ordinal + 1) } } sealed class Web5Exception: Exception() { class Exception( val `type`: kotlin.String, val `variant`: kotlin.String, val `msg`: kotlin.String ) : Web5Exception() { override val message get() = "type=${ `type` }, variant=${ `variant` }, msg=${ `msg` }" } companion object ErrorHandler : UniffiRustCallStatusErrorHandler<Web5Exception> { override fun lift(error_buf: RustBuffer.ByValue): Web5Exception = FfiConverterTypeWeb5Error.lift(error_buf) } } public object FfiConverterTypeWeb5Error : FfiConverterRustBuffer<Web5Exception> { override fun read(buf: ByteBuffer): Web5Exception { return when(buf.getInt()) { 1 -> Web5Exception.Exception( FfiConverterString.read(buf), FfiConverterString.read(buf), FfiConverterString.read(buf), ) else -> throw RuntimeException("invalid error enum value, something is very wrong!!") } } override fun allocationSize(value: Web5Exception): ULong { return when(value) { is Web5Exception.Exception -> ( // Add the size for the Int that specifies the variant plus the size needed for all fields 4UL + FfiConverterString.allocationSize(value.`type`) + FfiConverterString.allocationSize(value.`variant`) + FfiConverterString.allocationSize(value.`msg`) ) } } override fun write(value: Web5Exception, buf: ByteBuffer) { when(value) { is Web5Exception.Exception -> { buf.putInt(1) FfiConverterString.write(value.`type`, buf) FfiConverterString.write(value.`variant`, buf) FfiConverterString.write(value.`msg`, buf) Unit } }.let { /* this makes the `when` an expression, which ensures it is exhaustive */ } } } public object FfiConverterOptionalBoolean: FfiConverterRustBuffer<kotlin.Boolean?> { override fun read(buf: ByteBuffer): kotlin.Boolean? { if (buf.get().toInt() == 0) { return null } return FfiConverterBoolean.read(buf) } override fun allocationSize(value: kotlin.Boolean?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterBoolean.allocationSize(value) } } override fun write(value: kotlin.Boolean?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterBoolean.write(value, buf) } } } public object FfiConverterOptionalString: FfiConverterRustBuffer<kotlin.String?> { override fun read(buf: ByteBuffer): kotlin.String? { if (buf.get().toInt() == 0) { return null } return FfiConverterString.read(buf) } override fun allocationSize(value: kotlin.String?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterString.allocationSize(value) } } override fun write(value: kotlin.String?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterString.write(value, buf) } } } public object FfiConverterOptionalTimestamp: FfiConverterRustBuffer<java.time.Instant?> { override fun read(buf: ByteBuffer): java.time.Instant? { if (buf.get().toInt() == 0) { return null } return FfiConverterTimestamp.read(buf) } override fun allocationSize(value: java.time.Instant?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterTimestamp.allocationSize(value) } } override fun write(value: java.time.Instant?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterTimestamp.write(value, buf) } } } public object FfiConverterOptionalTypeKeyManager: FfiConverterRustBuffer<KeyManager?> { override fun read(buf: ByteBuffer): KeyManager? { if (buf.get().toInt() == 0) { return null } return FfiConverterTypeKeyManager.read(buf) } override fun allocationSize(value: KeyManager?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterTypeKeyManager.allocationSize(value) } } override fun write(value: KeyManager?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterTypeKeyManager.write(value, buf) } } } public object FfiConverterOptionalTypeDidDhtCreateOptions: FfiConverterRustBuffer<DidDhtCreateOptions?> { override fun read(buf: ByteBuffer): DidDhtCreateOptions? { if (buf.get().toInt() == 0) { return null } return FfiConverterTypeDidDhtCreateOptions.read(buf) } override fun allocationSize(value: DidDhtCreateOptions?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterTypeDidDhtCreateOptions.allocationSize(value) } } override fun write(value: DidDhtCreateOptions?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterTypeDidDhtCreateOptions.write(value, buf) } } } public object FfiConverterOptionalTypeDidDhtPublishOptions: FfiConverterRustBuffer<DidDhtPublishOptions?> { override fun read(buf: ByteBuffer): DidDhtPublishOptions? { if (buf.get().toInt() == 0) { return null } return FfiConverterTypeDidDhtPublishOptions.read(buf) } override fun allocationSize(value: DidDhtPublishOptions?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterTypeDidDhtPublishOptions.allocationSize(value) } } override fun write(value: DidDhtPublishOptions?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterTypeDidDhtPublishOptions.write(value, buf) } } } public object FfiConverterOptionalTypeDidDhtResolveOptions: FfiConverterRustBuffer<DidDhtResolveOptions?> { override fun read(buf: ByteBuffer): DidDhtResolveOptions? { if (buf.get().toInt() == 0) { return null } return FfiConverterTypeDidDhtResolveOptions.read(buf) } override fun allocationSize(value: DidDhtResolveOptions?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterTypeDidDhtResolveOptions.allocationSize(value) } } override fun write(value: DidDhtResolveOptions?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterTypeDidDhtResolveOptions.write(value, buf) } } } public object FfiConverterOptionalTypeDidJwkCreateOptions: FfiConverterRustBuffer<DidJwkCreateOptions?> { override fun read(buf: ByteBuffer): DidJwkCreateOptions? { if (buf.get().toInt() == 0) { return null } return FfiConverterTypeDidJwkCreateOptions.read(buf) } override fun allocationSize(value: DidJwkCreateOptions?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterTypeDidJwkCreateOptions.allocationSize(value) } } override fun write(value: DidJwkCreateOptions?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterTypeDidJwkCreateOptions.write(value, buf) } } } public object FfiConverterOptionalTypeDidWebCreateOptions: FfiConverterRustBuffer<DidWebCreateOptions?> { override fun read(buf: ByteBuffer): DidWebCreateOptions? { if (buf.get().toInt() == 0) { return null } return FfiConverterTypeDidWebCreateOptions.read(buf) } override fun allocationSize(value: DidWebCreateOptions?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterTypeDidWebCreateOptions.allocationSize(value) } } override fun write(value: DidWebCreateOptions?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterTypeDidWebCreateOptions.write(value, buf) } } } public object FfiConverterOptionalTypeDocumentData: FfiConverterRustBuffer<DocumentData?> { override fun read(buf: ByteBuffer): DocumentData? { if (buf.get().toInt() == 0) { return null } return FfiConverterTypeDocumentData.read(buf) } override fun allocationSize(value: DocumentData?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterTypeDocumentData.allocationSize(value) } } override fun write(value: DocumentData?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterTypeDocumentData.write(value, buf) } } } public object FfiConverterOptionalTypeDocumentMetadataData: FfiConverterRustBuffer<DocumentMetadataData?> { override fun read(buf: ByteBuffer): DocumentMetadataData? { if (buf.get().toInt() == 0) { return null } return FfiConverterTypeDocumentMetadataData.read(buf) } override fun allocationSize(value: DocumentMetadataData?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterTypeDocumentMetadataData.allocationSize(value) } } override fun write(value: DocumentMetadataData?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterTypeDocumentMetadataData.write(value, buf) } } } public object FfiConverterOptionalTypeVerifiableCredentialCreateOptionsData: FfiConverterRustBuffer<VerifiableCredentialCreateOptionsData?> { override fun read(buf: ByteBuffer): VerifiableCredentialCreateOptionsData? { if (buf.get().toInt() == 0) { return null } return FfiConverterTypeVerifiableCredentialCreateOptionsData.read(buf) } override fun allocationSize(value: VerifiableCredentialCreateOptionsData?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterTypeVerifiableCredentialCreateOptionsData.allocationSize(value) } } override fun write(value: VerifiableCredentialCreateOptionsData?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterTypeVerifiableCredentialCreateOptionsData.write(value, buf) } } } public object FfiConverterOptionalTypeDsa: FfiConverterRustBuffer<Dsa?> { override fun read(buf: ByteBuffer): Dsa? { if (buf.get().toInt() == 0) { return null } return FfiConverterTypeDsa.read(buf) } override fun allocationSize(value: Dsa?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterTypeDsa.allocationSize(value) } } override fun write(value: Dsa?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterTypeDsa.write(value, buf) } } } public object FfiConverterOptionalTypeResolutionMetadataError: FfiConverterRustBuffer<ResolutionMetadataError?> { override fun read(buf: ByteBuffer): ResolutionMetadataError? { if (buf.get().toInt() == 0) { return null } return FfiConverterTypeResolutionMetadataError.read(buf) } override fun allocationSize(value: ResolutionMetadataError?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterTypeResolutionMetadataError.allocationSize(value) } } override fun write(value: ResolutionMetadataError?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterTypeResolutionMetadataError.write(value, buf) } } } public object FfiConverterOptionalSequenceString: FfiConverterRustBuffer<List<kotlin.String>?> { override fun read(buf: ByteBuffer): List<kotlin.String>? { if (buf.get().toInt() == 0) { return null } return FfiConverterSequenceString.read(buf) } override fun allocationSize(value: List<kotlin.String>?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterSequenceString.allocationSize(value) } } override fun write(value: List<kotlin.String>?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterSequenceString.write(value, buf) } } } public object FfiConverterOptionalSequenceTypeServiceData: FfiConverterRustBuffer<List<ServiceData>?> { override fun read(buf: ByteBuffer): List<ServiceData>? { if (buf.get().toInt() == 0) { return null } return FfiConverterSequenceTypeServiceData.read(buf) } override fun allocationSize(value: List<ServiceData>?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterSequenceTypeServiceData.allocationSize(value) } } override fun write(value: List<ServiceData>?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterSequenceTypeServiceData.write(value, buf) } } } public object FfiConverterOptionalSequenceTypeVerificationMethodData: FfiConverterRustBuffer<List<VerificationMethodData>?> { override fun read(buf: ByteBuffer): List<VerificationMethodData>? { if (buf.get().toInt() == 0) { return null } return FfiConverterSequenceTypeVerificationMethodData.read(buf) } override fun allocationSize(value: List<VerificationMethodData>?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterSequenceTypeVerificationMethodData.allocationSize(value) } } override fun write(value: List<VerificationMethodData>?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterSequenceTypeVerificationMethodData.write(value, buf) } } } public object FfiConverterOptionalMapStringString: FfiConverterRustBuffer<Map<kotlin.String, kotlin.String>?> { override fun read(buf: ByteBuffer): Map<kotlin.String, kotlin.String>? { if (buf.get().toInt() == 0) { return null } return FfiConverterMapStringString.read(buf) } override fun allocationSize(value: Map<kotlin.String, kotlin.String>?): ULong { if (value == null) { return 1UL } else { return 1UL + FfiConverterMapStringString.allocationSize(value) } } override fun write(value: Map<kotlin.String, kotlin.String>?, buf: ByteBuffer) { if (value == null) { buf.put(0) } else { buf.put(1) FfiConverterMapStringString.write(value, buf) } } } public object FfiConverterSequenceString: FfiConverterRustBuffer<List<kotlin.String>> { override fun read(buf: ByteBuffer): List<kotlin.String> { val len = buf.getInt() return List<kotlin.String>(len) { FfiConverterString.read(buf) } } override fun allocationSize(value: List<kotlin.String>): ULong { val sizeForLength = 4UL val sizeForItems = value.map { FfiConverterString.allocationSize(it) }.sum() return sizeForLength + sizeForItems } override fun write(value: List<kotlin.String>, buf: ByteBuffer) { buf.putInt(value.size) value.iterator().forEach { FfiConverterString.write(it, buf) } } } public object FfiConverterSequenceTypeJwkData: FfiConverterRustBuffer<List<JwkData>> { override fun read(buf: ByteBuffer): List<JwkData> { val len = buf.getInt() return List<JwkData>(len) { FfiConverterTypeJwkData.read(buf) } } override fun allocationSize(value: List<JwkData>): ULong { val sizeForLength = 4UL val sizeForItems = value.map { FfiConverterTypeJwkData.allocationSize(it) }.sum() return sizeForLength + sizeForItems } override fun write(value: List<JwkData>, buf: ByteBuffer) { buf.putInt(value.size) value.iterator().forEach { FfiConverterTypeJwkData.write(it, buf) } } } public object FfiConverterSequenceTypeServiceData: FfiConverterRustBuffer<List<ServiceData>> { override fun read(buf: ByteBuffer): List<ServiceData> { val len = buf.getInt() return List<ServiceData>(len) { FfiConverterTypeServiceData.read(buf) } } override fun allocationSize(value: List<ServiceData>): ULong { val sizeForLength = 4UL val sizeForItems = value.map { FfiConverterTypeServiceData.allocationSize(it) }.sum() return sizeForLength + sizeForItems } override fun write(value: List<ServiceData>, buf: ByteBuffer) { buf.putInt(value.size) value.iterator().forEach { FfiConverterTypeServiceData.write(it, buf) } } } public object FfiConverterSequenceTypeVerificationMethodData: FfiConverterRustBuffer<List<VerificationMethodData>> { override fun read(buf: ByteBuffer): List<VerificationMethodData> { val len = buf.getInt() return List<VerificationMethodData>(len) { FfiConverterTypeVerificationMethodData.read(buf) } } override fun allocationSize(value: List<VerificationMethodData>): ULong { val sizeForLength = 4UL val sizeForItems = value.map { FfiConverterTypeVerificationMethodData.allocationSize(it) }.sum() return sizeForLength + sizeForItems } override fun write(value: List<VerificationMethodData>, buf: ByteBuffer) { buf.putInt(value.size) value.iterator().forEach { FfiConverterTypeVerificationMethodData.write(it, buf) } } } public object FfiConverterMapStringString: FfiConverterRustBuffer<Map<kotlin.String, kotlin.String>> { override fun read(buf: ByteBuffer): Map<kotlin.String, kotlin.String> { val len = buf.getInt() return buildMap<kotlin.String, kotlin.String>(len) { repeat(len) { val k = FfiConverterString.read(buf) val v = FfiConverterString.read(buf) this[k] = v } } } override fun allocationSize(value: Map<kotlin.String, kotlin.String>): ULong { val spaceForMapSize = 4UL val spaceForChildren = value.map { (k, v) -> FfiConverterString.allocationSize(k) + FfiConverterString.allocationSize(v) }.sum() return spaceForMapSize + spaceForChildren } override fun write(value: Map<kotlin.String, kotlin.String>, buf: ByteBuffer) { buf.putInt(value.size) // The parens on `(k, v)` here ensure we're calling the right method, // which is important for compatibility with older android devices. // Ref https://blog.danlew.net/2017/03/16/kotlin-puzzler-whose-line-is-it-anyways/ value.forEach { (k, v) -> FfiConverterString.write(k, buf) FfiConverterString.write(v, buf) } } } @Throws(Web5Exception::class) fun `didDhtCreate`(`options`: DidDhtCreateOptions?): BearerDid { return FfiConverterTypeBearerDid.lift( uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_func_did_dht_create( FfiConverterOptionalTypeDidDhtCreateOptions.lower(`options`),_status) } ) } @Throws(Web5Exception::class) fun `didDhtPublish`(`bearerDid`: BearerDid, `options`: DidDhtPublishOptions?) = uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_func_did_dht_publish( FfiConverterTypeBearerDid.lower(`bearerDid`),FfiConverterOptionalTypeDidDhtPublishOptions.lower(`options`),_status) } fun `didDhtResolve`(`uri`: kotlin.String, `options`: DidDhtResolveOptions?): ResolutionResult { return FfiConverterTypeResolutionResult.lift( uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_func_did_dht_resolve( FfiConverterString.lower(`uri`),FfiConverterOptionalTypeDidDhtResolveOptions.lower(`options`),_status) } ) } @Throws(Web5Exception::class) fun `didJwkCreate`(`options`: DidJwkCreateOptions?): BearerDid { return FfiConverterTypeBearerDid.lift( uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_func_did_jwk_create( FfiConverterOptionalTypeDidJwkCreateOptions.lower(`options`),_status) } ) } fun `didJwkResolve`(`uri`: kotlin.String): ResolutionResult { return FfiConverterTypeResolutionResult.lift( uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_func_did_jwk_resolve( FfiConverterString.lower(`uri`),_status) } ) } @Throws(Web5Exception::class) fun `didWebCreate`(`domain`: kotlin.String, `options`: DidWebCreateOptions?): BearerDid { return FfiConverterTypeBearerDid.lift( uniffiRustCallWithError(Web5Exception) { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_func_did_web_create( FfiConverterString.lower(`domain`),FfiConverterOptionalTypeDidWebCreateOptions.lower(`options`),_status) } ) } fun `didWebResolve`(`uri`: kotlin.String): ResolutionResult { return FfiConverterTypeResolutionResult.lift( uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_func_did_web_resolve( FfiConverterString.lower(`uri`),_status) } ) } fun `ed25519GeneratorGenerate`(): JwkData { return FfiConverterTypeJwkData.lift( uniffiRustCall() { _status -> UniffiLib.INSTANCE.uniffi_web5_uniffi_fn_func_ed25519_generator_generate( _status) } ) }
96
null
7
9
caacb9a38db2548e14f79165ca8c303c064ee616
275,731
web5-rs
Apache License 2.0
src/main/kotlin/com/projectcitybuild/features/bans/usecases/UnbanUUID.kt
projectcitybuild
42,997,941
false
null
package com.projectcitybuild.features.bans.usecases import com.projectcitybuild.core.utilities.Failure import com.projectcitybuild.core.utilities.Result import com.projectcitybuild.core.utilities.Success import com.projectcitybuild.repositories.PlayerBanRepository import com.projectcitybuild.repositories.PlayerUUIDRepository import net.md_5.bungee.api.ChatColor import net.md_5.bungee.api.chat.TextComponent import org.bukkit.Server import java.util.UUID class UnbanUUID( private val playerBanRepository: PlayerBanRepository, private val playerUUIDRepository: PlayerUUIDRepository, private val server: Server, ) { enum class FailureReason { PlayerDoesNotExist, PlayerNotBanned, } suspend fun unban( targetPlayerName: String, bannerUUID: UUID?, ): Result<Unit, FailureReason> { try { val targetPlayerUUID = playerUUIDRepository.get(targetPlayerName) ?: return Failure(FailureReason.PlayerDoesNotExist) playerBanRepository.unban( targetPlayerUUID = targetPlayerUUID, staffId = bannerUUID, ) server.broadcastMessage( TextComponent("$targetPlayerName has been unbanned").apply { color = ChatColor.GRAY isItalic = true }.toLegacyText() ) return Success(Unit) } catch (e: PlayerBanRepository.PlayerNotBannedException) { return Failure(FailureReason.PlayerNotBanned) } } }
9
Kotlin
0
3
36a7197d870aa24a9b9ea65567a35fa38f86a31d
1,566
PCBridge
MIT License
moneyGiftAssistant/src/main/java/com/alphago/moneypacket/utils/UpdateTask.kt
songlea
126,107,355
false
null
package com.songlea.hongbao.util import android.content.Context import android.content.Intent import android.net.Uri import android.os.AsyncTask import android.widget.Toast import com.songlea.hongbao.R import org.apache.http.HttpResponse import org.apache.http.client.methods.HttpGet import org.apache.http.impl.client.DefaultHttpClient import org.json.JSONObject import java.io.ByteArrayOutputStream import java.io.IOException /** * Created by Zhongyi on 1/20/16. * Util for app update task. */ class UpdateTask(private val context: Context, private val isUpdateOnRelease: Boolean) : AsyncTask<String, String, String>() { init { if (this.isUpdateOnRelease) Toast.makeText(context, context.getString(R.string.checking_new_version), Toast.LENGTH_SHORT).show() } override fun doInBackground(vararg uri: String): String? { val httpclient = DefaultHttpClient() val response: HttpResponse var responseString: String? = null try { response = httpclient.execute(HttpGet(uri[0])) val statusLine = response.statusLine if (statusLine.statusCode == 200) { val out = ByteArrayOutputStream() response.entity.writeTo(out) responseString = out.toString() out.close() } else { // Close the connection. response.entity.content.close() throw IOException(statusLine.reasonPhrase) } } catch (e: Exception) { return null } return responseString } override fun onPostExecute(result: String) { super.onPostExecute(result) try { count += 1 val release = JSONObject(result) // Get current version val pInfo = context.packageManager.getPackageInfo(context.packageName, 0) val version = pInfo.versionName val latestVersion = release.getString("tag_name") val isPreRelease = release.getBoolean("prerelease") if (!isPreRelease && version.compareTo(latestVersion, ignoreCase = true) >= 0) { // Your version is ahead of or same as the latest. if (this.isUpdateOnRelease) Toast.makeText(context, R.string.update_already_latest, Toast.LENGTH_SHORT).show() } else { if (!isUpdateOnRelease) { Toast.makeText(context, context.getString(R.string.update_new_seg1) + latestVersion + context.getString(R.string.update_new_seg3), Toast.LENGTH_LONG).show() return } // Need update. val downloadUrl = release.getJSONArray("assets").getJSONObject(0).getString("browser_download_url") // Give up on the fucking DownloadManager. The downloaded apk got renamed and unable to install. Fuck. val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(downloadUrl)) browserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK context.startActivity(browserIntent) Toast.makeText(context, context.getString(R.string.update_new_seg1) + latestVersion + context.getString(R.string.update_new_seg2), Toast.LENGTH_LONG).show() } } catch (e: Exception) { e.printStackTrace() if (this.isUpdateOnRelease) Toast.makeText(context, R.string.update_error, Toast.LENGTH_LONG).show() } } fun update() { super.execute(updateUrl) } companion object { var count = 0 val updateUrl = "https://api.github.com/repos/geeeeeeeeek/WeChatLuckyMoney/releases/latest" } }
0
Kotlin
0
0
d8ec617c8e9cb078fb9e81d9e27fa70a657e5fe2
3,722
WeChatLuckyMoney
MIT License
app/src/main/java/com/pr0gramm/app/util/ExceptionHandler.kt
VladimirObama
158,547,370
true
{"Kotlin": 1141144, "Shell": 6640, "IDL": 3434, "Python": 1124}
package com.pr0gramm.app.util import kotlinx.coroutines.CancellationException import java.io.IOException class ExceptionHandler private constructor(private val delegate: Thread.UncaughtExceptionHandler) : Thread.UncaughtExceptionHandler { override fun uncaughtException(thread: Thread, err: Throwable) { if (err.causalChain.containsType<CancellationException>()) { return } if (err is IllegalStateException) { // this is an exception happening in gms ads. we'll ignore it. if (err.message == "Results have already been set") { if (err.stackTrace.any { it.methodName == "setResult" }) { return } } } if (err is IOException) { logger.warn(err) { "Uncaught IOException" } return } delegate.uncaughtException(thread, err) } companion object { private val logger = logger("ExceptionHandler") fun install() { logger.info { "Install uncaught exception handler" } val previous = Thread.getDefaultUncaughtExceptionHandler() val handler = ExceptionHandler(previous) Thread.setDefaultUncaughtExceptionHandler(handler) } } }
0
Kotlin
0
0
676e078f0cd93205db18f5f26f3143667441fc9b
1,287
Pr0
MIT License
mvvm-dagger/src/main/java/com/nphau/android/shared/screens/dialogs/VBBottomSheetDialogFragment.kt
ThanhHuong98
432,947,065
false
{"Kotlin": 165721, "Java": 1330, "Shell": 87}
package com.imstudio.android.shared.screens.dialogs import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.viewbinding.ViewBinding import com.imstudio.android.shared.screens.BindingDSL abstract class VBBottomSheetDialogFragment<VB : ViewBinding> : IBindingFragment<VB>, RoundedBottomSheetDialogFragment() { private var _binding: VB? = null /** * Binding variable to be used for accessing views. * @return ViewBinding * */ @BindingDSL protected val binding: VB get() = requireNotNull(_binding) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = inflate(context) return requireNotNull(_binding).root } final override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) onSyncViews(savedInstanceState) onSyncEvents() onSyncData() } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
null
0
1
ac0402ae4734285ef5e647d1f53a1f9f4a8d98cd
1,175
android.clean-architecture.mvvm
Apache License 2.0
serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/TermDeserializer.kt
tuProlog
230,784,338
false
null
package it.unibo.tuprolog.serialize import it.unibo.tuprolog.core.Term import kotlin.js.JsName import kotlin.jvm.JvmStatic interface TermDeserializer : Deserializer<Term> { companion object { @JvmStatic @JsName("of") fun of(mimeType: MimeType): TermDeserializer { return termDeserializer(mimeType) } } }
92
null
14
93
3223ffc302e5da0efe2b254045fa1b6a1a122519
358
2p-kt
Apache License 2.0
src/main/kotlin/no/nav/tiltaksarrangor/config/HttpClientConfig.kt
navikt
616,496,742
false
{"Kotlin": 441381, "PLpgSQL": 635, "Dockerfile": 96}
package no.nav.tiltaksarrangor.config import no.nav.security.token.support.client.core.ClientProperties import no.nav.security.token.support.client.core.oauth2.OAuth2AccessTokenService import no.nav.security.token.support.client.spring.ClientConfigurationProperties import no.nav.security.token.support.client.spring.oauth2.EnableOAuth2Client import okhttp3.Interceptor import okhttp3.OkHttpClient import org.springframework.boot.web.client.RestTemplateBuilder import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import java.util.concurrent.TimeUnit @EnableOAuth2Client(cacheEnabled = true) @Configuration class HttpClientConfig { @Bean fun amtTiltakHttpClient( clientConfigurationProperties: ClientConfigurationProperties, oAuth2AccessTokenService: OAuth2AccessTokenService, ): OkHttpClient { val registrationName = "amt-tiltak-tokenx" val clientProperties = clientConfigurationProperties.registration[registrationName] ?: throw RuntimeException("Fant ikke config for $registrationName") return OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .followRedirects(false) .addInterceptor(bearerTokenInterceptor(clientProperties, oAuth2AccessTokenService)) .build() } @Bean fun amtArrangorHttpClient( clientConfigurationProperties: ClientConfigurationProperties, oAuth2AccessTokenService: OAuth2AccessTokenService, ): OkHttpClient { val registrationName = "amt-arrangor-tokenx" val clientProperties = clientConfigurationProperties.registration[registrationName] ?: throw RuntimeException("Fant ikke config for $registrationName") return OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .followRedirects(false) .addInterceptor(bearerTokenInterceptor(clientProperties, oAuth2AccessTokenService)) .build() } @Bean fun amtArrangorAADHttpClient( restTemplateBuilder: RestTemplateBuilder, clientConfigurationProperties: ClientConfigurationProperties, oAuth2AccessTokenService: OAuth2AccessTokenService, ): OkHttpClient { val registrationName = "amt-arrangor-aad" val clientProperties = clientConfigurationProperties.registration[registrationName] ?: throw RuntimeException("Fant ikke config for $registrationName") return OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .followRedirects(false) .addInterceptor(bearerTokenInterceptor(clientProperties, oAuth2AccessTokenService)) .build() } @Bean fun simpleHttpClient(): OkHttpClient { return OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .followRedirects(false) .build() } private fun bearerTokenInterceptor( clientProperties: ClientProperties, oAuth2AccessTokenService: OAuth2AccessTokenService, ): Interceptor { return Interceptor { chain: Interceptor.Chain -> val accessTokenResponse = oAuth2AccessTokenService.getAccessToken(clientProperties) val request = chain.request() val requestWithToken = request.newBuilder() .addHeader("Authorization", "Bearer ${accessTokenResponse.accessToken}") .build() chain.proceed(requestWithToken) } } }
2
Kotlin
0
2
fa85a7a425ef5c5ca8d11be169744f26270b4f12
3,293
amt-tiltaksarrangor-bff
MIT License
composeApp/src/commonMain/kotlin/com/borealnetwork/allen/modules/test/ui/TestViewCompose.kt
baudelioandalon
742,906,893
false
{"Kotlin": 534389, "Swift": 654}
package com.borealnetwork.allen.modules.test.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import com.borealnetwork.allen.modules.test.domain.view_models.TestViewModel import com.borealnetwork.allensharedui.components.BlueButton import com.borealnetwork.allensharedui.components.ToolbarTitle import com.borealnetwork.allensharedui.components.loading.Loading import com.borealnetwork.shared.domain.models.StateApi import moe.tlaster.precompose.flow.collectAsStateWithLifecycle import moe.tlaster.precompose.navigation.Navigator import org.jetbrains.compose.ui.tooling.preview.Preview import org.koin.compose.koinInject @Preview @Composable fun TestViewCompose( navigator: Navigator, testViewModel: TestViewModel? = koinInject() ) { val setProductsResult = testViewModel?.setProductsResult?.collectAsStateWithLifecycle()?.value val setSellerResult = testViewModel?.setSellerResult?.collectAsStateWithLifecycle()?.value Scaffold(topBar = { ToolbarTitle( titleText = "Test", showStartImage = false, startClicked = { navigator.goBack() }, showEndImage = false, ) }) { Column( modifier = Modifier.padding(it).fillMaxSize(), verticalArrangement = Arrangement.Center ) { BlueButton( text = "Nuevo Producto" ) { testViewModel?.pushNewProduct() } BlueButton( text = "Nuevo vendedor" ) { testViewModel?.pushNewSeller() } } Loading(showOrHide = setProductsResult?.status == StateApi.Loading || setSellerResult?.status == StateApi.Loading) } }
0
Kotlin
0
0
ad163dde7d0c7a9e2d66eb79f66417bd40d24d92
2,036
AllenMultiplatform
Apache License 2.0
cuber-location/src/main/kotlin/cuber/post/app/location/Servlet.kt
hchery
840,416,011
false
{"Kotlin": 39508, "Java": 6927}
package cuber.post.app.location import cuber.post.app.sdk.Auto import cuber.post.app.sdk.service.CurrentClientIP import jakarta.servlet.http.HttpServletRequest import org.springframework.stereotype.Component /** * DATE: 2024/8/21 * AUTHOR: hchery * URL: https://github.com/hchery * EMAIL: <EMAIL> */ private val IpHeaders = arrayOf( "X-Real-IP", "x-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP" ) @Component class ServletCurrentClientIP @Auto constructor( private val request: HttpServletRequest, ): CurrentClientIP { override fun invoke(): String { return servletRemoteIp(request) } } private fun servletRemoteIp(request: HttpServletRequest): String { val ip = fetchHeaderIp(request) ?: return request.remoteAddr val idx = ip.indexOf(',') return if (idx >= 0) ip.substring(0, idx) else ip } private fun fetchHeaderIp(request: HttpServletRequest): String? { return IpHeaders.map { request.getHeader(it) } .firstOrNull(::isValidIp) } private fun isValidIp(ip: String?): Boolean { return !ip.isNullOrBlank() && !"unknown".equals(ip, ignoreCase = true) }
0
Kotlin
0
0
3cc72a40523a97c80a58ce08089cfb6e9e0b8522
1,147
PostCuber
MIT License
android/src/com/android/tools/idea/editors/literals/actions/ToggleLiveLiteralsStatusAction.kt
phpc0de
470,555,455
false
{"Java": 39631279, "Kotlin": 28526369, "HTML": 1206758, "Starlark": 482060, "C": 66005, "Python": 59985, "NSIS": 58515, "Lex": 46798, "CMake": 24483, "JavaScript": 18437, "C++": 11882, "Shell": 7470, "RenderScript": 4411, "AIDL": 3251, "Makefile": 2298, "IDL": 269, "QMake": 18}
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.editors.literals.actions import com.android.tools.idea.editors.literals.LiveLiteralsApplicationConfiguration import com.android.tools.idea.editors.literals.ui.LiveLiteralsConfigurable import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.options.ShowSettingsUtil import org.jetbrains.android.util.AndroidBundle.message /** * Action that opens the Live Literals settings page for the user to enable/disable live literals. */ internal class ToggleLiveLiteralsStatusAction: AnAction() { override fun update(e: AnActionEvent) { e.presentation.text = if (LiveLiteralsApplicationConfiguration.getInstance().isEnabled) message("live.literals.action.disable.title") else message("live.literals.action.enable.title") } override fun actionPerformed(e: AnActionEvent) { ShowSettingsUtil.getInstance().showSettingsDialog(e.project, LiveLiteralsConfigurable::class.java) } }
0
Java
1
1
79e20f027ca1d047b91aa7acd92fb71fa2968a09
1,628
idea-android
Apache License 2.0
app/src/main/java/com/odogwudev/example/cinephilescompanion/MainApplication.kt
odogwudev
592,877,753
false
null
package com.odogwudev.example.cinephilescompanion import android.app.Application import com.odogwudev.example.cinephilescompanion.di.createAppModule import com.odogwudev.example.cinephilescompanion.tooling.setupBeagle import com.odogwudev.example.firebase_api.AuthenticationService import org.koin.android.ext.android.inject import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin import org.koin.core.logger.Level class MainApplication : Application() { private val authService: AuthenticationService by inject() override fun onCreate() { super.onCreate() setupKoin() setupBeagle(application = this) } private fun setupKoin() { startKoin { androidLogger(level = Level.DEBUG) androidContext(androidContext = this@MainApplication) modules(modules = createAppModule()) authService.initialize(context = this@MainApplication) } } }
0
Kotlin
0
4
82791abdcf1554d2a2cd498a19cd93952f90e53e
1,018
CinephilesCompanion
MIT License
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/exceptions/AccessDeniedDataFetcherExceptionResolver.kt
nemerosa
19,351,480
false
{"Kotlin": 9640276, "JavaScript": 3232252, "Java": 1029918, "HTML": 507415, "Groovy": 372843, "CSS": 137546, "Less": 35335, "Dockerfile": 6298, "Shell": 5086}
package net.nemerosa.ontrack.graphql.exceptions import graphql.GraphQLError import graphql.GraphqlErrorBuilder import graphql.schema.DataFetchingEnvironment import org.springframework.graphql.execution.DataFetcherExceptionResolverAdapter import org.springframework.graphql.execution.ErrorType import org.springframework.security.access.AccessDeniedException import org.springframework.stereotype.Component @Component class AccessDeniedDataFetcherExceptionResolver : DataFetcherExceptionResolverAdapter() { override fun resolveToSingleError(ex: Throwable, env: DataFetchingEnvironment): GraphQLError? = if (ex is AccessDeniedException) { GraphqlErrorBuilder.newError() .errorType(ErrorType.FORBIDDEN) .message(ex.message) .build() } else { null } }
49
Kotlin
25
96
759f17484c9b507204e5a89524e07df871697e74
895
ontrack
MIT License
collector-media3-exoplayer/src/main/java/com/bitmovin/analytics/media3/exoplayer/Media3ExoPlayerUtil.kt
bitmovin
120,633,749
false
{"Kotlin": 1468376, "Java": 25098, "Shell": 13133}
package com.bitmovin.analytics.media3.exoplayer import android.os.Handler import android.os.Looper import androidx.media3.common.C import androidx.media3.common.Format import androidx.media3.common.MediaLibraryInfo import androidx.media3.common.Player import androidx.media3.common.util.UnstableApi import com.bitmovin.analytics.utils.Util internal object Media3ExoPlayerUtil { private const val DASH_MANIFEST_CLASSNAME = "androidx.media3.exoplayer.dash.manifest.DashManifest" private const val HLS_MANIFEST_CLASSNAME = "androidx.media3.exoplayer.hls.HlsManifest" // used to make sure that class is loaded before we try accessing it // since otherwise we might get a ClassNotFoundException especially since media3 // support for dash and hls is optional and a separate dependency val isDashManifestClassLoaded by lazy { Util.isClassLoaded(DASH_MANIFEST_CLASSNAME, this.javaClass.classLoader) } val isHlsManifestClassLoaded by lazy { Util.isClassLoaded(HLS_MANIFEST_CLASSNAME, this.javaClass.classLoader) } fun exoStateToString(state: Int): String { return when (state) { Player.STATE_IDLE -> "Idle" Player.STATE_BUFFERING -> "Buffering" Player.STATE_READY -> "Ready" Player.STATE_ENDED -> "Ended" else -> "Unknown PlayerState" } } val playerVersion: String @androidx.annotation.OptIn(UnstableApi::class) get() { try { // we use reflective access here since otherwise the static version field // is compiled into the class and not evaluated during runtime // thus if customer is using a different version of media3 it will not be // taken into account! val versionField = MediaLibraryInfo::class.java.getField("VERSION") return versionField[null] as String } catch (ignored: NoSuchFieldException) { } catch (ignored: IllegalAccessException) { } catch (ignored: Exception) { } return "unknown" } // Method that can be used to make sure a certain code block is executed // on same thread as provided looper // Be careful, given code is either executed synchronously when calling // thread is same thread as applicationLooper, or asynchronously if not // This means code calling this cannot rely on order of execution fun executeSyncOrAsyncOnLooperThread(applicationLooper: Looper, function: () -> Unit) { if (Thread.currentThread() != applicationLooper.thread) { val handler = Handler(applicationLooper) handler.post { function.invoke() } } else { function.invoke() } } /** * Exoplayer organizes audio, video, subtitles, etc.. in track groups. * reference: https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/source/TrackGroup.html * * This method shouldn't be used to determine the currently played audio and video formats since * it will return the first selected one in a trackgroup. * * Each track group has a field that determines if the group is selected, and an array which specifies * which tracks in the group are selected specifically. Selected doesn't mean that there can only be * one in a track group, for example if all video bitrates are of a track group can be played with the * underlying hardware, then all of them will be selected. * * Example * TrackGroup1 -> video with tracks for bitrate 1kb, 2kb, 3kb, etc.. * TrackGroup2 -> audio english with tracks for stereo, surround, etc.. * TrackGroup3 -> audio german with tracks for stereo, surround, etc.. * TrackGroup4 -> subtitles english with 1 track for english * TrackGroup5 -> subtitles german with 1 track for german */ fun getActiveSubtitles(player: Player): Format? { try { if (!player.isCommandAvailable(Player.COMMAND_GET_TRACKS)) { return null } val trackGroups = player.currentTracks.groups // subtitles are using C.TRACK_TYPE_TEXT val trackGroupsWithTrackType = trackGroups.filter { track -> track.type == C.TRACK_TYPE_TEXT } val selectedTrackGroup = trackGroupsWithTrackType.firstOrNull { it.isSelected } ?: return null // bit cumbersome to find the actual track in the track group that is selected // but I couldn't find a better way for (index in 0 until selectedTrackGroup.length) { if (selectedTrackGroup.isTrackSelected(index)) { return selectedTrackGroup.getTrackFormat(index) } } } catch (_: Exception) { } return null } }
1
Kotlin
6
9
563f8c3ea8542d1dd6cf0ed664786c514a3df4e8
4,921
bitmovin-analytics-collector-android
Amazon Digital Services License
app/src/main/java/com/sjn/stamp/controller/SongHistoryController.kt
sjnyag
81,733,859
false
null
package com.sjn.stamp.controller import android.content.Context import android.os.AsyncTask import android.support.v4.media.MediaMetadataCompat import com.sjn.stamp.model.* import com.sjn.stamp.model.constant.RecordType import com.sjn.stamp.model.dao.SongDao import com.sjn.stamp.model.dao.SongHistoryDao import com.sjn.stamp.model.dao.TotalSongHistoryDao import com.sjn.stamp.ui.custom.PeriodSelectLayout import com.sjn.stamp.utils.LogHelper import com.sjn.stamp.utils.MediaIDHelper.resolveMusicId import com.sjn.stamp.utils.MediaItemHelper import com.sjn.stamp.utils.NotificationHelper import com.sjn.stamp.utils.RealmHelper import io.realm.Realm import java.lang.ref.WeakReference import java.util.* class SongHistoryController(private val context: Context) { val topSongList: List<MediaMetadataCompat> get() = RealmHelper.realmInstance.use { realm -> val songList = ArrayList<MediaMetadataCompat>() TotalSongHistoryDao.findPlayed(realm).forEach loop@{ songHistory -> if (songHistory.playCount == 0 || songList.size >= UserSettingController().mostPlayedSongSize) { return@loop } songHistory.song?.let { if (it.isNotEmpty() && it.first().mediaId.isNotEmpty()) { songList.add(MediaItemHelper.convertToMetadata(songHistory.song.first())) } } } songList } val hasHistory: Boolean get() = RealmHelper.realmInstance.use { realm -> TotalSongHistoryDao.isPlayedExists(realm) } fun onPlay(mediaId: String, date: Date) { LogHelper.d(TAG, "insertPLAY ", mediaId) register(mediaId, RecordType.PLAY, date) } fun onSkip(mediaId: String, date: Date) { LogHelper.d(TAG, "insertSKIP ", mediaId) register(mediaId, RecordType.SKIP, date) } fun onStart(mediaId: String, date: Date) { LogHelper.d(TAG, "insertSTART ", mediaId) register(mediaId, RecordType.START, date) } fun onComplete(mediaId: String, date: Date) { LogHelper.d(TAG, "insertComplete ", mediaId) register(mediaId, RecordType.COMPLETE, date) } fun delete(songHistoryId: Long) { RealmHelper.realmInstance.use { realm -> SongHistoryDao.delete(realm, songHistoryId) } } fun getManagedTimeline(realm: Realm): List<SongHistory> = SongHistoryDao.timeline(realm, RecordType.PLAY.databaseValue) fun getRankedSongList(realm: Realm, period: PeriodSelectLayout.Period): List<RankedSong> = getRankedSongList(realm, period.from(), period.to(), 30) fun getRankedArtistList(realm: Realm, period: PeriodSelectLayout.Period): List<RankedArtist> = getRankedArtistList(realm, period.from(), period.to(), 30) private fun register(mediaId: String, recordType: RecordType, date: Date) { val musicId = resolveMusicId(mediaId) ?: return RealmHelper.realmInstance.use { realm -> val song = SongDao.findOrCreateByMusicId(realm, musicId, context) song ?: return val playCount = TotalSongHistoryDao.increment(realm, song.id, recordType) SongHistoryDao.create(realm, song, recordType, date, playCount) if (recordType === RecordType.PLAY) { sendNotificationBySongCount(realm, song, playCount) sendNotificationByArtistCount(song) } SongController(context).calculateSmartStamp(song.id, playCount, recordType) } } private fun sendNotificationBySongCount(realm: Realm, song: Song, playCount: Int) { if (NotificationHelper.isSendPlayedNotification(playCount)) { NotificationHelper.sendPlayedNotification(context, song, song.albumArtUri, playCount, SongHistoryDao.findOldest(realm, song.id)!!.recordedAt) } } private fun sendNotificationByArtistCount(song: Song) { ArtistCountAsyncTask(context, song.artist.name).execute() } private fun getRankedSongList(realm: Realm, from: Date?, to: Date?, count: Int?): List<RankedSong> { LogHelper.d(TAG, "getRankedSongList start") LogHelper.d(TAG, "calc historyList") val songCountMap = HashMap<Song, Int>() LogHelper.d(TAG, "put songCountMap") for (songHistory in SongHistoryDao.where(realm, from, to, RecordType.PLAY.databaseValue)) { if (songCountMap.containsKey(songHistory.song)) { songCountMap[songHistory.song] = songCountMap[songHistory.song]!! + 1 } else { songCountMap[songHistory.song] = 1 } } LogHelper.d(TAG, "create rankedSongList") var rankedSongList: MutableList<RankedSong> = ArrayList() for ((key, value) in songCountMap) { rankedSongList.add(RankedSong(value, key)) } LogHelper.d(TAG, "sort rankedSongList") rankedSongList.sortWith(Comparator { t1, t2 -> t2.playCount - t1.playCount }) count?.let { if (rankedSongList.size > count) { rankedSongList = rankedSongList.subList(0, count) } } LogHelper.d(TAG, "getRankedSongList end") return rankedSongList } fun getRankedArtistList(realm: Realm, from: Date?, to: Date?, count: Int?): List<RankedArtist> { LogHelper.d(TAG, "getRankedArtistList start") val historyList = SongHistoryDao.where(realm, from, to, RecordType.PLAY.databaseValue) val artistMap = HashMap<Artist, ArtistCounter>() for (songHistory in historyList) { ArtistCounter.count(artistMap, songHistory.song.artist, songHistory.song) } var rankedArtistList: MutableList<RankedArtist> = ArrayList() for ((key, value) in artistMap) { rankedArtistList.add(RankedArtist(value.count, key, value.songCountMap)) } rankedArtistList.sortWith(Comparator { t1, t2 -> t2.playCount - t1.playCount }) count?.let { if (rankedArtistList.size > count) { rankedArtistList = rankedArtistList.subList(0, count) } } LogHelper.d(TAG, "getRankedArtistList end") return rankedArtistList } private class ArtistCounter { internal var count = 0 internal var songCountMap: MutableMap<Song, Int> = HashMap() internal fun increment(song: Song) { count++ if (songCountMap.containsKey(song)) { songCountMap[song] = songCountMap[song]!! + 1 } else { songCountMap[song] = 1 } } companion object { fun count(artistMap: MutableMap<Artist, ArtistCounter>, artist: Artist, song: Song) { val counter = if (artistMap.containsKey(artist)) artistMap[artist] else ArtistCounter() counter?.let { artistCounter -> artistCounter.increment(song) artistMap.put(artist, artistCounter) } } } } companion object { private val TAG = LogHelper.makeLogTag(SongHistoryController::class.java) private class ArtistCountAsyncTask constructor(context: Context, internal var artistName: String) : AsyncTask<Void, Void, Void>() { val context = WeakReference(context) override fun doInBackground(vararg params: Void): Void? { RealmHelper.realmInstance.use { realm -> val historyList = SongHistoryDao.findPlayRecordByArtist(realm, artistName) if (!NotificationHelper.isSendPlayedNotification(historyList.size)) { return null } val oldestSongHistory = SongHistoryDao.findOldestByArtist(realm, artistName) context.get()?.let { NotificationHelper.sendPlayedNotification(it, artistName, oldestSongHistory!!.song.albumArtUri, historyList.size, oldestSongHistory.recordedAt) } } return null } } } }
59
null
3
9
cb145824f9e06cd17266502a5e85d8a9fa276bb0
8,274
stamp
Apache License 2.0
chanho/practice-apps/example_ui_compose/app/src/main/java/com/example/example_ui_compose/TwoViewModel.kt
inu-appcenter
778,262,806
false
{"Kotlin": 61740}
package com.example.example_ui_compose import androidx.lifecycle.ViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update class TwoViewModel : ViewModel() { private val _counter: MutableStateFlow<Int> = MutableStateFlow(0) val counter = _counter.asStateFlow() fun plusCounter(){ _counter.update { counter.value.plus(1) } } fun minusCounter(){ _counter.update { counter.value.minus(1) } } }
1
Kotlin
0
0
537bfaefb189946c8bbeeccb21b1c43b88898b52
516
android-study-16th
MIT License
tenkey/src/main/java/com/kazumaproject/tenkey/image_effect/ImageEffects.kt
KazumaProject
696,033,236
false
{"Kotlin": 409131, "Java": 366556}
package com.kazumaproject.tenkey.image_effect import android.graphics.RenderEffect import android.graphics.Shader import android.view.View object ImageEffects { fun applyBlurEffect(view: View, blurRadius: Float) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { val blurEffect = RenderEffect.createBlurEffect( blurRadius, blurRadius, Shader.TileMode.CLAMP ) view.setRenderEffect(blurEffect) } else { // Handle older versions gracefully or provide an alternative // For example, show a message or apply a different effect } } fun removeBlurEffect(view: View) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { view.setRenderEffect(null) } else { // Handle older versions gracefully or provide an alternative // For example, show a message or apply a different effect } } }
0
Kotlin
0
9
7e9fe6c92475b9384ccf1f96be4c41b181e26d17
1,037
JapaneseKeyboard
MIT License
core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt
evisoft
75,185,334
false
null
package net.corda.core.serialization import net.corda.core.contracts.* import net.corda.core.crypto.CompositeKey import net.corda.core.crypto.SecureHash import net.corda.core.crypto.composite import net.corda.core.seconds import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.* import net.corda.testing.MINI_CORP import net.corda.testing.generateStateRef import org.junit.Before import org.junit.Test import java.security.SignatureException import java.util.* import kotlin.test.assertEquals import kotlin.test.assertFailsWith val TEST_PROGRAM_ID = TransactionSerializationTests.TestCash() class TransactionSerializationTests { class TestCash : Contract { override val legalContractReference = SecureHash.sha256("TestCash") override fun verify(tx: TransactionForContract) { } data class State( val deposit: PartyAndReference, val amount: Amount<Currency>, override val owner: CompositeKey) : OwnableState { override val contract: Contract = TEST_PROGRAM_ID override val participants: List<CompositeKey> get() = listOf(owner) override fun withNewOwner(newOwner: CompositeKey) = Pair(Commands.Move(), copy(owner = newOwner)) } interface Commands : CommandData { class Move() : TypeOnlyCommandData(), Commands } } // Simple TX that takes 1000 pounds from me and sends 600 to someone else (with 400 change). // It refers to a fake TX/state that we don't bother creating here. val depositRef = MINI_CORP.ref(1) val fakeStateRef = generateStateRef() val inputState = StateAndRef(TransactionState(TestCash.State(depositRef, 100.POUNDS, DUMMY_PUBKEY_1), DUMMY_NOTARY), fakeStateRef) val outputState = TransactionState(TestCash.State(depositRef, 600.POUNDS, DUMMY_PUBKEY_1), DUMMY_NOTARY) val changeState = TransactionState(TestCash.State(depositRef, 400.POUNDS, DUMMY_KEY_1.public.composite), DUMMY_NOTARY) lateinit var tx: TransactionBuilder @Before fun setup() { tx = TransactionType.General.Builder(DUMMY_NOTARY).withItems( inputState, outputState, changeState, Command(TestCash.Commands.Move(), arrayListOf(DUMMY_KEY_1.public.composite)) ) } @Test fun signWireTX() { tx.signWith(DUMMY_NOTARY_KEY) tx.signWith(DUMMY_KEY_1) val signedTX = tx.toSignedTransaction() // Now check that the signature we just made verifies. signedTX.verifySignatures() // Corrupt the data and ensure the signature catches the problem. signedTX.id.bytes[5] = signedTX.id.bytes[5].inc() assertFailsWith(SignatureException::class) { signedTX.verifySignatures() } } @Test fun wrongKeys() { // Can't convert if we don't have signatures for all commands assertFailsWith(IllegalStateException::class) { tx.toSignedTransaction() } tx.signWith(DUMMY_KEY_1) tx.signWith(DUMMY_NOTARY_KEY) val signedTX = tx.toSignedTransaction() // Cannot construct with an empty sigs list. assertFailsWith(IllegalArgumentException::class) { signedTX.copy(sigs = emptyList()) } // If the signature was replaced in transit, we don't like it. assertFailsWith(SignatureException::class) { val tx2 = TransactionType.General.Builder(DUMMY_NOTARY).withItems(inputState, outputState, changeState, Command(TestCash.Commands.Move(), DUMMY_KEY_2.public.composite)) tx2.signWith(DUMMY_NOTARY_KEY) tx2.signWith(DUMMY_KEY_2) signedTX.copy(sigs = tx2.toSignedTransaction().sigs).verifySignatures() } } @Test fun timestamp() { tx.setTime(TEST_TX_TIME, 30.seconds) tx.signWith(DUMMY_KEY_1) tx.signWith(DUMMY_NOTARY_KEY) val stx = tx.toSignedTransaction() assertEquals(TEST_TX_TIME, stx.tx.timestamp?.midpoint) } }
4
null
1
1
4a9f5cafc1f2f09e8f612a09f30f9dfffd985a6c
4,094
corda
Apache License 2.0
marketkit/src/main/java/com/bolotoken/marketkit/managers/GlobalMarketInfoManager.kt
BoloToken
857,880,569
false
{"Kotlin": 190260}
package com.bolotoken.marketkit.managers import com.bolotoken.marketkit.models.GlobalMarketInfo import com.bolotoken.marketkit.models.GlobalMarketPoint import com.bolotoken.marketkit.models.HsTimePeriod import com.bolotoken.marketkit.providers.HsProvider import com.bolotoken.marketkit.storage.GlobalMarketInfoStorage import io.reactivex.Single class GlobalMarketInfoManager( private val provider: HsProvider, private val storage: GlobalMarketInfoStorage ) { private val expirationInterval = 600 // 10 minutes fun globalMarketInfoSingle(currencyCode: String, timePeriod: HsTimePeriod): Single<List<GlobalMarketPoint>> { val currentTimestamp = System.currentTimeMillis() / 1000 storage.globalMarketInfo(currencyCode, timePeriod)?.let { data -> if (currentTimestamp - data.timestamp <= expirationInterval) return Single.just(data.points) } return provider.getGlobalMarketPointsSingle(currencyCode, timePeriod) .map { globalMarketPoints -> storage.save(GlobalMarketInfo(currencyCode, timePeriod, globalMarketPoints, currentTimestamp)) globalMarketPoints } } }
0
Kotlin
0
0
3b92e7ed7e1f6e19bfe1305c2662dad2c16c26eb
1,199
market-kit-android
MIT License
lib/src/main/kotlin/com/bloidonia/advent/day19/Day19.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day19 import java.lang.StrictMath.pow import kotlin.math.sqrt data class Vector(val x: Int, val y: Int, val z: Int) { operator fun plus(other: Vector) = Vector(x + other.x, y + other.y, z + other.z) operator fun times(other: Vector) = Vector(x * other.x, y * other.y, z * other.y) fun distance(other: Vector) = sqrt( pow(other.x - x.toDouble(), 2.0) + pow(other.y - y.toDouble(), 2.0) + pow(other.z - z.toDouble(), 2.0) ) } fun <T, S> Collection<T>.cartesianProduct(other: Iterable<S>): List<Pair<T, S>> { return cartesianProduct(other) { first, second -> first to second } } fun <T, S, V> Collection<T>.cartesianProduct(other: Iterable<S>, transformer: (first: T, second: S) -> V): List<V> { return this.flatMap { first -> other.map { second -> transformer.invoke(first, second) } } } class Scanner(val readings: List<Vector>) { fun distance(index: Int) = readings.map { readings[index].distance(it) } } fun String.toScanners() = this.split("\n\n").map { Scanner(readings = it.split("\n") .drop(1) .map { line -> line.split(",").let { (x, y, z) -> Vector(x.toInt(), y.toInt(), z.toInt()) } } ) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
1,252
advent-of-kotlin-2021
MIT License
android-uitests/testData/DatabindingBasicExample/app/src/main/java/com/example/android/databinding/basicsample/ui/ObservableFieldActivity.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.databinding.basicsample.ui import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.databinding.ObservableInt import com.example.android.databinding.basicsample.R import com.example.android.databinding.basicsample.data.ObservableFieldProfile import com.example.android.databinding.basicsample.databinding.MahdiLayoutBinding import com.example.android.databinding.basicsample.databinding.ObservableFieldProfileBinding /** * This activity shows shows static data and lets the user increment the * number of likes by clicking a button. See [ViewModelActivity] for a better implementation. */ class ObservableFieldActivity : AppCompatActivity() { private val observableFieldProfile = ObservableFieldProfile("Mahdi", "Tajik", ObservableInt(0)) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // val binding: ObservableFieldProfileBinding = // DataBindingUtil.setContentView(this, R.layout.observable_field_profile) val binding2: MahdiLayoutBinding = DataBindingUtil.setContentView(this, R.layout.mahdi_layout) // binding.user = observableFieldProfile binding2.user = observableFieldProfile } /** * This method is triggered by the `android:onclick` attribute in the layout. It puts business * logic in the activity, which is not ideal. See {@link ViewModelActivity} for a better * solution. */ fun onLike(view: View) { observableFieldProfile.likes.set(observableFieldProfile.likes.get() + 1) } }
5
null
473
948
10110983c7e784122d94c7467e9d243aba943bf4
2,295
android
Apache License 2.0
reactiveandroid/src/main/kotlin/com/github/kittinunf/reactiveandroid/CreateMutableProperty.kt
kittinunf
50,813,818
false
null
package com.github.kittinunf.reactiveandroid import rx.Scheduler inline fun <T> createMutableProperty(getter: () -> T, crossinline setter: (T) -> Unit, observeScheduler: Scheduler): MutableProperty<T> { return MutableProperty(getter()).apply { observable.observeOn(observeScheduler).subscribe { setter(it) } } } inline fun <reified T : Any> createMutableProperty(crossinline setter: (T) -> Unit, observeScheduler: Scheduler): MutableProperty<T> { val t = T::class.java.newInstance() return MutableProperty(t).apply { observable.observeOn(observeScheduler).subscribe { setter(it) } } }
5
Kotlin
12
79
117cb3e9738df17bb4c8b9f73d2a21bc5b97f6f5
664
ReactiveAndroid
MIT License
src/main/kotlin/venus/assembler/AssemblerError.kt
ics-jku
470,084,492
false
null
package venus.assembler /** * Thrown when errors occur during assembly. * * @todo split this into AssemblerUserError and AssemblerError */ class AssemblerError : Throwable { var line: Int? = null /** * @param msg the message to error with */ constructor(msg: String? = null) : super(msg) /** * @param errorLine the line the error occurred on * @param e the original error to pass along */ constructor(errorLine: Int, e: Throwable) : this(e.message) { line = errorLine } override fun toString(): String { if (line == null) return super.toString() else return "${super.toString()} on line $line" } }
1
null
1
4
429d323b98a33db67074e44f164c8d1044f406de
687
venus
MIT License
presentation/src/main/java/appus/software/githubusers/presentation/common/recycler/ListDelegateAdapter.kt
appus-studio
180,989,176
false
null
package appus.software.githubusers.presentation.common.recycler import android.util.SparseArray import android.view.ViewGroup import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.RecyclerView import java.util.* /** * Created by bogdan.martynov on 2019-04-25 12:14. top-github-contributors-android */ class ListDelegateAdapter<T> : RecyclerView.Adapter<BindingHolder<ViewDataBinding>> { private var mListener: OnRecyclerItemClick<T>? = null private var delegatesManager: AdapterDelegatesManager<T>? = null private var items: MutableList<T>? = null var data: MutableList<T>? get() = items set(data) { items = data } private constructor() constructor(builder: Builder<T>) { mListener = builder.getListener() delegatesManager = builder.getDelegatesManager() items = builder.getItems() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingHolder<ViewDataBinding> { return delegatesManager!!.onCreateViewHolder(parent, viewType, mListener) } override fun onBindViewHolder(holder: BindingHolder<ViewDataBinding>, position: Int) { delegatesManager!!.onBindViewHolder(items!![position], position, holder) } override fun getItemViewType(position: Int): Int { return delegatesManager!!.getItemViewType(items!![position], position) } override fun onViewRecycled(holder: BindingHolder<ViewDataBinding>) { delegatesManager!!.onViewRecycled(holder) } override fun onFailedToRecycleView(holder: BindingHolder<ViewDataBinding>): Boolean { return delegatesManager!!.onFailedToRecycleView(holder) } override fun onViewAttachedToWindow(holder: BindingHolder<ViewDataBinding>) { delegatesManager!!.onViewAttachedToWindow(holder) } override fun onViewDetachedFromWindow(holder: BindingHolder<ViewDataBinding>) { delegatesManager!!.onViewDetachedFromWindow(holder) } /** * Get the items / data source of this adapter * * @return The items / data source */ fun getItems(): List<T>? { return items } override fun getItemCount(): Int { return if (items == null) 0 else items!!.size } fun updateItems(models: List<T>?) { items = models?.let { ArrayList(it) } ?: ArrayList() notifyDataSetChanged() } @JvmOverloads fun updateItemByPosition(model: T?, position: Int, notifyChanged: Boolean = true) { if (getItems()!!.size >= position && position >= 0 && model != null) { items!![position] = model if (notifyChanged) { notifyItemChanged(position) } } } fun updateItemsByPosition(array: SparseArray<T>) { for (i in 0 until array.size()) { val position = array.keyAt(i) updateItemByPosition(array.get(position), position) } } fun removeItem(position: Int) { if (position >= 0 && position < items!!.size) { items!!.removeAt(position) notifyItemRemoved(position) } } fun removeItem(from: Int, count: Int) { if (from >= 0 && from + count <= items!!.size) { for (i in 0 until count) items!!.removeAt(from) notifyItemRangeRemoved(from, count) } } fun clear() { items!!.clear() notifyDataSetChanged() } fun addItem(item: T) { items!!.add(item) notifyItemRangeChanged(items!!.size - 1, 1) } fun addItem(position: Int, item: T) { if (position >= 0 && position < items!!.size) { items!!.add(position, item) notifyItemInserted(position) } } fun setItem(position: Int, item: T) { if (position >= 0 && position < items!!.size) { items!![position] = item notifyItemChanged(position) } } fun addItem(from: Int, models: List<T>?) { if (from >= 0 && from <= items!!.size && models != null) { // for (int i = from; i <= models.size(); i++) items!!.addAll(from, models) notifyItemRangeInserted(from, models.size) } } fun getItem(position: Int): T? { return if (position >= 0 && position < itemCount) items!![position] else null } fun insertItems(data: List<T>, position: Int) { if (position >= 0 && items!!.size >= position && !data.isEmpty()) { items!!.addAll(position, data) notifyItemRangeInserted(position, data.size) } } fun deleteItems(position: Int, count: Int) { var lCount = count if (position >= 0 && position < items!!.size && position + lCount <= items!!.size) { while (lCount > 0) { items!!.removeAt(position) lCount-- } notifyItemRangeRemoved(position, count) } } class Builder<T> { private var mListener: OnRecyclerItemClick<T>? = null private var delegatesManager: AdapterDelegatesManager<T>? = null private var items: MutableList<T>? = null init { delegatesManager = AdapterDelegatesManager() items = ArrayList() } fun getListener(): OnRecyclerItemClick<T>? { return mListener } fun setListener(listener: OnRecyclerItemClick<T>): Builder<T> { this.mListener = listener return this } fun getDelegatesManager(): AdapterDelegatesManager<T>? { return delegatesManager } fun setDelegatesManager(delegatesManager: AdapterDelegatesManager<T>): Builder<T> { this.delegatesManager = delegatesManager return this } fun getItems(): MutableList<T>? { return items } fun setItems(items: MutableList<T>): Builder<T> { this.items = items return this } fun addDelegate(item: AdapterDelegate<T>): Builder<T> { if (delegatesManager == null) { throw IllegalArgumentException("provide DelegateManager") } if (items == null) { throw IllegalArgumentException("provide AdapterDelegate<T> item") } delegatesManager!!.addDelegate(item) return this } fun build(): ListDelegateAdapter<T> { return ListDelegateAdapter(this) } } }
0
Kotlin
0
1
72b630dbaffe7e2d6c08a81ac48d551f8578b627
6,573
top-github-contributors-android
Apache License 2.0
app/src/main/java/com/example/lively/repository/MatchesRepository.kt
utkarshgupta2009
848,772,461
false
{"Kotlin": 34410}
package com.example.lively.repository import com.example.lively.data.remote.RapidApiServices import com.example.lively.data.remote.models.FixtureResponse import javax.inject.Inject class MatchesRepository @Inject constructor(private val rapidApiServices: RapidApiServices){ suspend fun getLiveMatches(leagueId: Int): List<FixtureResponse> = rapidApiServices.getLiveMatches(leagueId).response suspend fun getUpcomingMatches(date: String, leagueId:Int, season:Int): List<FixtureResponse> = rapidApiServices.getUpcomingMatches(date,leagueId,season).response }
0
Kotlin
0
0
a3d148b30a8864ffee12c78a1c7c0c7f74e909c0
587
Lively
MIT License
panel-androidx/src/main/java/com/effective/android/panel/utils/DisplayUtil.kt
DSAppTeam
140,263,533
false
{"Java": 258589, "Kotlin": 236332}
package com.effective.android.panel.utils import android.annotation.TargetApi import android.app.Activity import android.content.Context import android.content.res.Configuration import android.content.res.Resources import android.graphics.Point import android.graphics.Rect import android.os.Build import android.provider.Settings import android.util.DisplayMetrics import android.util.Log import android.view.* import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.effective.android.panel.Constants import com.effective.android.panel.R import java.util.* object DisplayUtil { /** * 获取toolar的高度,但是这个方法仅仅在非沉浸下才有用。 * * @param window * @return */ @JvmStatic fun getToolbarHeight(window: Window): Int { return window.decorView.findViewById<View>(Window.ID_ANDROID_CONTENT).top } @JvmStatic fun getLocationOnScreen(view: View): IntArray { val contentViewLocationInScreen = IntArray(2) view.getLocationOnScreen(contentViewLocationInScreen) return contentViewLocationInScreen } @JvmStatic fun getLocationOnWindow(view: View): IntArray { val location = IntArray(2) view.getLocationInWindow(location) return location } @JvmStatic fun contentViewCanDrawStatusBarArea(window: Window): Boolean { return getLocationOnScreen(window.decorView.findViewById(Window.ID_ANDROID_CONTENT))[1] == 0 } /** * 对应 id 为 @Android:id/content 的 FrameLayout 所加载的布局。 * 也就是我们 setContentView 的布局高度 * * @param window * @return */ @JvmStatic fun getContentViewHeight(window: Window): Int { return window.decorView.findViewById<View>(Window.ID_ANDROID_CONTENT).height } /** * 获取设备真实高度,包含可能存在的虚拟导航栏,未显示的刘海区域,状态栏等 */ fun getScreenRealHeight(window: Window): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { val wm = window.context .getSystemService(Context.WINDOW_SERVICE) as WindowManager val outMetrics = DisplayMetrics() wm.defaultDisplay.getRealMetrics(outMetrics) return outMetrics.heightPixels } else { getScreenHeightWithSystemUI(window) } } /** * 实际上获取的是DecorView的布局高度,是一个 FrameLayout,其内置布局 id 为 com.android.internal.R.layout.screen_simple 的 LinearLayout * 包含 id为 @+id/action_mode_bar_stub_ViewStub 的 ViewStub 还有 id 为 @Android:id/content 的 FrameLayout。 * 如果系统设置刘海留空,则 该高度不包含刘海高度 * * @param window * @return */ @JvmStatic fun getScreenHeightWithSystemUI(window: Window): Int { return window.decorView.height } @JvmStatic fun getScreenHeightWithoutNavigationBar(context: Context): Int { return context.resources.displayMetrics.heightPixels } @JvmStatic fun getScreenHeightWithoutSystemUI(window: Window): Int { val r = Rect() window.decorView.getWindowVisibleDisplayFrame(r) return r.bottom - r.top } @JvmStatic fun isFullScreen(activity: Activity): Boolean { return (activity.window.attributes.flags and WindowManager.LayoutParams.FLAG_FULLSCREEN == WindowManager.LayoutParams.FLAG_FULLSCREEN) } @JvmStatic fun isFullScreen(window: Window): Boolean { return (window.attributes.flags and WindowManager.LayoutParams.FLAG_FULLSCREEN == WindowManager.LayoutParams.FLAG_FULLSCREEN) } @JvmStatic fun getStatusBarHeight(window: Window): Int { val frame = Rect() window.decorView.getWindowVisibleDisplayFrame(frame) return frame.top } @JvmStatic fun getNavigationBarHeight(context: Context, window: Window): Int { val deviceNavigationHeight = getInternalDimensionSize(context.resources, Constants.NAVIGATION_BAR_HEIGHT_RES_NAME) val manufacturer = if (Build.MANUFACTURER == null) "" else Build.MANUFACTURER.trim { it <= ' ' } if (manufacturer.toLowerCase(Locale.ROOT).contains("samsung")) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { //三星android9 OneUI2.0一下打开全面屏手势,导航栏实际高度比 deviceHeight 小,需要做兼容 window.decorView.rootWindowInsets?.let { val stableBottom = it.stableInsetBottom if (stableBottom < deviceNavigationHeight) { return stableBottom } } } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) { //三星android 11 显示可隐藏键盘的按钮,导致导航栏高度会变化 val navigationBarHeight = ViewCompat.getRootWindowInsets(window.decorView)?.getInsets(WindowInsetsCompat.Type.navigationBars())?.bottom ?: 0 if (navigationBarHeight > deviceNavigationHeight) { return navigationBarHeight } } } return deviceNavigationHeight } private fun getInternalDimensionSize(res: Resources, key: String): Int { var result = 0 val resourceId = res.getIdentifier(key, Constants.DIMEN, Constants.ANDROID) if (resourceId > 0) { result = res.getDimensionPixelSize(resourceId) } return result } @JvmStatic fun isPortrait(context: Context): Boolean { return when (context.resources.configuration.orientation) { Configuration.ORIENTATION_PORTRAIT -> { true } Configuration.ORIENTATION_LANDSCAPE -> { false } else -> { val display = (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay val point = Point() display.getSize(point) point.x <= point.y } } } /** * */ @JvmStatic @TargetApi(14) fun isNavigationBarShow(context: Context, window: Window): Boolean { return isNavBarVisible(context, window) } /** * Decorview 源码 * public static final ColorViewAttributes NAVIGATION_BAR_COLOR_VIEW_ATTRIBUTES = * new ColorViewAttributes( * SYSTEM_UI_FLAG_HIDE_NAVIGATION, FLAG_TRANSLUCENT_NAVIGATION, * Gravity.BOTTOM, Gravity.RIGHT, Gravity.LEFT, * Window.NAVIGATION_BAR_BACKGROUND_TRANSITION_NAME, * com.android.internal.R.id.navigationBarBackground, * * @param context * @param window * @return */ fun isNavBarVisible(context: Context, window: Window): Boolean { var isVisible = false val viewGroup: ViewGroup? = window.decorView as ViewGroup? viewGroup?.let { for (i in 0 until it.childCount) { val id: Int = it.getChildAt(i).id if (id != android.view.View.NO_ID) { try { val resourceEntryName: String? = context.resources.getResourceEntryName(id) if ((("navigationBarBackground" == resourceEntryName) && it.getChildAt(i).visibility == android.view.View.VISIBLE)) { isVisible = true } } catch (e: Exception) { Log.d("isNavBarVisible", "error msg : ${e.message}") } } } if (!isVisible) { val navigationBarView: View? = it.findViewById(R.id.immersion_navigation_bar_view) navigationBarView?.let { navigationBar -> if (navigationBar.visibility == View.VISIBLE) { isVisible = true } } } } val manufacturer = if (Build.MANUFACTURER == null) "" else Build.MANUFACTURER.trim { it <= ' ' } val isSamsung = manufacturer.toLowerCase().contains("samsung") if((viewGroup == null || !isVisible) && isSamsung){ isVisible = hasNavBar(context) } if (isVisible) { // 对于三星手机,android10以下非OneUI2的版本,比如 s8,note8 等设备上,导航栏显示存在bug:"当用户隐藏导航栏时显示输入法的时候导航栏会跟随显示",会导致隐藏输入之后判断错误 // 这个问题在 OneUI 2 & android 10 版本已修复, if (isSamsung && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { try { isVisible = Settings.Global.getInt( context.contentResolver, "navigationbar_hide_bar_enabled" ) == 0 if (isVisible) return true } catch (e: Exception) { e.printStackTrace() } } isVisible = !hasSystemUIFlag(window, View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) } return isVisible } private fun hasNavBar(context: Context): Boolean { val res = context.resources val resourceId = res.getIdentifier( Constants.SHOW_NAV_BAR_RES_NAME, "bool", "android" ) return if (resourceId != 0) { var hasNav = res.getBoolean(resourceId) // check override flag (see static block) // Android allows a system property to override the presence of the navigation bar. // Used by the emulator. // See https://github.com/android/platform_frameworks_base/blob/master/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java#L1076 var sNavBarOverride:String? = null if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { try { val c = Class.forName("android.os.SystemProperties") val m = c.getDeclaredMethod("get", String::class.java) m.isAccessible = true sNavBarOverride = m.invoke(null, "qemu.hw.mainkeys") as? String } catch (e: Throwable) { sNavBarOverride = null } } if ("1" == sNavBarOverride) { hasNav = false } else if ("0" == sNavBarOverride) { hasNav = true } hasNav } else { // fallback !ViewConfiguration.get(context).hasPermanentMenuKey() } } @JvmStatic fun dip2px(context: Context, dipValue: Float): Int { compatSizeProxy?.let { return it.dip2px(context, dipValue) } val scale: Float = context.resources.displayMetrics.density return (dipValue * scale + 0.5f).toInt() } fun hasSystemUIFlag(window: Window, flag: Int): Boolean = window.decorView.systemUiVisibility and flag == flag interface CompatSizeProxy { fun dip2px(context: Context, dipValue: Float): Int } private var compatSizeProxy: CompatSizeProxy? = null /** * 兼容autoSize */ @JvmStatic fun setCompatSizeProxy(proxy: CompatSizeProxy) { this.compatSizeProxy = compatSizeProxy } }
9
Java
283
2,376
bcd0083297eee6e2f3e8f35241218a8c59c29598
11,086
PanelSwitchHelper
Apache License 2.0
Data/azure.android.data/src/main/java/com/microsoft/azureandroid/data/model/Document.kt
NateRickard
108,568,001
false
{"Text": 1, "Ignore List": 4, "Markdown": 4, "Gradle": 4, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 2, "XML": 36, "Kotlin": 95, "Java": 3}
package com.azure.data.model import com.azure.data.model.partition.PartitionKeyResource import com.google.gson.annotations.SerializedName /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ abstract class Document(id: String? = null) : Resource(id), PartitionKeyResource { // Gets the self-link corresponding to attachments of the document from the Azure Cosmos DB service. @SerializedName(Keys.attachmentsLinkKey) var attachmentsLink: String? = null // Gets or sets the time to live in seconds of the document in the Azure Cosmos DB service. var timeToLive: Int? = null companion object { const val resourceName = "Document" const val listName = "Documents" object Keys { const val attachmentsLinkKey = "_attachments" val list = mutableListOf(attachmentsLinkKey) init { list.addAll(Resource.Companion.Keys.list) } } } }
1
null
1
1
4eab6b9b30698081e7f7092e3b5d7e5645fd33f9
1,008
Azure.Android
MIT License
src/en/animekhor/src/eu/kanade/tachiyomi/animeextension/en/animekhor/extractors/AnimeABCExtractor.kt
almightyhak
817,607,446
false
{"Kotlin": 4066862}
package eu.kanade.tachiyomi.animeextension.en.animekhor.extractors import eu.kanade.tachiyomi.animesource.model.Video import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.util.asJsoup import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import okhttp3.Headers import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.OkHttpClient import uy.kohesive.injekt.injectLazy class AnimeABCExtractor(private val client: OkHttpClient, private val headers: Headers) { private val json: Json by injectLazy() fun videosFromUrl(url: String, prefix: String = ""): List<Video> { val videoList = mutableListOf<Video>() val document = client.newCall(GET(url, headers = headers)).execute().asJsoup() val data = document.selectFirst("script:containsData(m3u8)")?.data() ?: return emptyList() val sources = json.decodeFromString<List<Source>>( "[${data.substringAfter("sources:") .substringAfter("[") .substringBefore("]")}]", ) sources.forEach { src -> val masterplHeaders = headers.newBuilder() .add("Accept", "*/*") .add("Connection", "keep-alive") .add("Host", url.toHttpUrl().host) .add("Referer", url) .build() val masterPlaylist = client.newCall( GET(src.file.replace("^//".toRegex(), "https://"), headers = masterplHeaders), ).execute().body.string() masterPlaylist.substringAfter("#EXT-X-STREAM-INF:").split("#EXT-X-STREAM-INF:").forEach { val quality = prefix + it.substringAfter("RESOLUTION=").substringAfter("x").substringBefore("\n") + "p ${src.label ?: ""}" val videoUrl = it.substringAfter("\n").substringBefore("\n") videoList.add(Video(videoUrl, quality, videoUrl, headers = masterplHeaders)) } } return videoList } @Serializable data class Source( val file: String, val label: String? = null, ) }
55
Kotlin
28
93
507dddff536702999357b17577edc48353eab5ad
2,095
aniyomi-extensions
Apache License 2.0
app/src/test/java/io/github/vishalecho/android/cnews/data/remote/NewsServicesTest.kt
vishalecho
278,807,537
false
null
package io.github.vishalecho.android.cnews.data.remote import android.os.Build import com.vishalecho.android.core.test.DependencyProvider import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.junit.After import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import java.io.IOException /** * Test for [NewsServices] class */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [Build.VERSION_CODES.P]) class NewsServicesTest { private lateinit var newsServices: NewsServices private lateinit var mockWebServer: MockWebServer @Before fun init() { mockWebServer = MockWebServer() newsServices = DependencyProvider.getRetrofit(mockWebServer.url("/")).create(NewsServices::class.java) } @After @Throws(IOException::class) fun tearDown() { mockWebServer.shutdown() } @Test fun getNews() { queueResponse { setResponseCode(200) setBody(DependencyProvider.getResponseFromJson("carousell_news")) } newsServices.getNews() .test() .run { assertNoErrors() assertValueCount(1) Assert.assertEquals(valueCount(), 1) Assert.assertEquals(values()[0][0].id, "121") Assert.assertEquals(values()[0][0].rank, 2) Assert.assertEquals(values()[0][0].time_created, 1532853058) } } private fun queueResponse(block: MockResponse.() -> Unit) { mockWebServer.enqueue(MockResponse().apply(block)) } }
0
Kotlin
0
0
43bfb84254c1200b99893f6d864c95f4b914c24b
1,736
CNews
Apache License 2.0
app/src/main/java/com/ctrlaccess/moviebuff/ui/MovieFragmentFactory.kt
galemu2
415,395,349
false
{"Kotlin": 67065}
package com.ctrlaccess.moviebuff.ui import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentFactory import com.bumptech.glide.RequestManager import com.ctrlaccess.moviebuff.adapters.MoviesCurrentAdapter import com.ctrlaccess.moviebuff.adapters.MoviesPopularAdaptor import com.ctrlaccess.moviebuff.ui.fragments.FragmentDetails import com.ctrlaccess.moviebuff.ui.fragments.FragmentMain import javax.inject.Inject class MovieFragmentFactory @Inject constructor( private val moviesCurrentAdapter: MoviesCurrentAdapter, private val moviesPopularAdaptor: MoviesPopularAdaptor, private val glide: RequestManager, ) : FragmentFactory() { override fun instantiate(classLoader: ClassLoader, className: String): Fragment { return when (className) { FragmentMain::class.java.name -> FragmentMain( moviesCurrentAdapter, moviesPopularAdaptor ) FragmentDetails::class.java.name -> FragmentDetails(glide) else -> super.instantiate(classLoader, className) } } }
0
Kotlin
0
0
287fa00f50eb97c7da2ef43231fbc59e4ccc6156
1,082
Movie-Buff
MIT License
runtime/common/src/testWithNative/kotlinx/serialization/json/JsonModesTest.kt
physphil
192,001,800
true
{"Kotlin": 612251}
/* * Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.json import kotlinx.serialization.Serializable import kotlinx.serialization.SerializationException import kotlinx.serialization.test.assertStringFormAndRestored import kotlin.test.* class JsonModesTest : JsonTestBase() { @Test fun testNan() = parametrizedTest(nonStrict) { assertStringFormAndRestored("{\"double\":NaN,\"float\":NaN}", Box(Double.NaN, Float.NaN), Box.serializer()) } @Test fun testInfinity() = parametrizedTest(nonStrict) { assertStringFormAndRestored( "{\"double\":Infinity,\"float\":-Infinity}", Box(Double.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY), Box.serializer() ) } @Test fun nonStrictJsonCanSkipValues() = parametrizedTest { useStreaming -> val data = JsonOptionalTests.Data() assertEquals( nonStrict.parse(JsonOptionalTests.Data.serializer(), "{strangeField: 100500, a:0}", useStreaming), data ) assertEquals( nonStrict.parse(JsonOptionalTests.Data.serializer(), "{a:0, strangeField: 100500}", useStreaming), data ) } @Test fun nonStrictJsonCanSkipComplexValues() = parametrizedTest { useStreaming -> val data = JsonOptionalTests.Data() assertEquals( nonStrict.parse( JsonOptionalTests.Data.serializer(), "{a: 0, strangeField: {a: b, c: {d: e}, f: [g,h,j] }}", useStreaming ), data) assertEquals( nonStrict.parse( JsonOptionalTests.Data.serializer(), "{strangeField: {a: b, c: {d: e}, f: [g,h,j] }, a: 0}", useStreaming ), data) } @Test fun testSerializeQuotedJson() = parametrizedTest { useStreaming -> assertEquals( """{"a":10,"e":false,"c":"Hello"}""", strict.stringify( JsonTransientTest.Data.serializer(), JsonTransientTest.Data(10, 100), useStreaming)) } @Test fun testParseEscapedSymbols() = parametrizedTest { useStreaming -> assertEquals( Url("https://t.co/M1uhwigsMT"), strict.parse(Url.serializer(), """{"url":"https:\/\/t.co\/M1uhwigsMT"}""", useStreaming) ) assertEquals(Url("\"test\""), strict.parse(Url.serializer(), """{"url": "\"test\""}""", useStreaming)) assertEquals(Url("\u00c9"), strict.parse(Url.serializer(), """{"url": "\u00c9"}""", useStreaming)) assertEquals(Url("""\\"""), strict.parse(Url.serializer(), """{"url": "\\\\"}""", useStreaming)) } @Test fun testStrictJsonCanNotSkipValues() = parametrizedTest { useStreaming -> assertFailsWith(SerializationException::class) { strict.parse(JsonOptionalTests.Data.serializer(), "{strangeField: 100500, a:0}", useStreaming) } } @Serializable data class Box(val double: Double, val float: Float) @Serializable data class Url(val url: String) }
0
Kotlin
0
0
fe1fe4b5c46c7bc49de74a2b97502256af972dc3
3,179
kotlinx.serialization
Apache License 2.0
build-setup/src/main/kotlin/co/touchlab/skie/buildsetup/plugins/SkieRuntimeSwift.kt
touchlab
685,579,240
false
{"Kotlin": 1644009, "Swift": 6029, "Shell": 1040}
package co.touchlab.skie.buildsetup.plugins import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.apply import org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper abstract class SkieRuntimeSwift : Plugin<Project> { override fun apply(target: Project): Unit = with(target) { apply<SkieBase>() apply<KotlinPluginWrapper>() } }
9
Kotlin
8
735
b96044d4dec91e4b85c5b310226c6f56e3bfa2b5
389
SKIE
Apache License 2.0
presentation/src/main/java/com/alorma/presentation/detail/DetailMapper.kt
Alhima
160,325,370
false
null
package com.alorma.presentation.detail import com.alorma.domain.common.ResourceProvider import com.alorma.domain.model.Configuration import com.alorma.domain.model.Movie import com.alorma.presentation.R import com.alorma.presentation.common.DateFormatter import com.alorma.presentation.movies.MovieItemVM import java.util.* class DetailMapper(private val resources: ResourceProvider, private val dateFormatter: DateFormatter) { fun success(movie: Movie, conf: Configuration): MovieDetailVM = MovieDetailVM(movie.id, movie.title, movie.overview, getHeroImage(conf, movie), mapDate(movie.date), mapVotes(movie.vote), addGenres(movie.genres, conf.genres)) private fun getHeroImage(conf: Configuration, movie: Movie) = if (movie.images.backdrop.isNullOrBlank() && movie.images.poster.isNullOrBlank()) { null } else { "${conf.imagesUrl}${conf.imageSize}${movie.images.backdrop ?: movie.images.poster}" } fun mapSimilar(movies: List<Movie>, conf: Configuration): List<MovieItemVM> = movies.map { mapSimilar(it, conf) } fun mapSimilar(movie: Movie, conf: Configuration): MovieItemVM = MovieItemVM(movie.id, movie.title, "${conf.imagesUrl}${conf.imageSize}${movie.images.poster}", mapVotes(movie.vote)) private fun mapVotes(vote: Float): String = String.format("%.1f", vote) private fun addGenres(ids: List<Int>, config: List<Pair<Int, String>>): List<String> = config.toMap().filterKeys { ids.contains(it) }.values.toList() private fun mapDate(date: Date?): String = date?.let { dateFormatter format it } ?: resources.getString(R.string.no_release_date) infix fun mapError(it: Throwable): String = resources.getString(R.string.generic_error) }
0
Kotlin
0
0
aad70ea89f3ba47402538c1ee3d8c4cbb90f019e
1,921
TrendingMovies
Apache License 2.0
app/src/main/java/org/stepic/droid/persistence/di/DownloadInteractorsModule.kt
abhirocks1211
205,717,847
false
{"Gradle": 12, "Java Properties": 2, "Text": 19, "Shell": 2, "Ignore List": 5, "Batchfile": 1, "Git Attributes": 1, "Markdown": 2, "XML": 519, "YAML": 1, "Kotlin": 1311, "Proguard": 3, "Prolog": 1, "Java": 190, "CSS": 2, "SVG": 65, "JSON": 4, "JavaScript": 3}
package org.stepic.droid.persistence.di import dagger.Module import dagger.Provides import org.stepic.droid.persistence.downloads.helpers.AddDownloadTaskHelper import org.stepic.droid.persistence.downloads.helpers.RemoveDownloadTaskHelper import org.stepic.droid.persistence.downloads.interactor.* import org.stepic.droid.persistence.downloads.resolvers.structure.StructureResolver import org.stepik.android.domain.network.repository.NetworkTypeRepository import org.stepik.android.model.Section import org.stepik.android.model.Unit @Module abstract class DownloadInteractorsModule { @Module companion object { @JvmStatic @Provides @PersistenceScope fun provideSectionDownloadInteractor( structureResolver: StructureResolver<Section>, addDownloadTasksHelper: AddDownloadTaskHelper, removeDownloadTaskHelper: RemoveDownloadTaskHelper, networkTypeRepository: NetworkTypeRepository ): DownloadInteractor<Section> = DownloadInteractorBase(structureResolver, addDownloadTasksHelper, removeDownloadTaskHelper, networkTypeRepository) @JvmStatic @Provides @PersistenceScope fun provideUnitDownloadInteractor( structureResolver: StructureResolver<Unit>, addDownloadTasksHelper: AddDownloadTaskHelper, removeDownloadTaskHelper: RemoveDownloadTaskHelper, networkTypeRepository: NetworkTypeRepository ): DownloadInteractor<Unit> = DownloadInteractorBase(structureResolver, addDownloadTasksHelper, removeDownloadTaskHelper, networkTypeRepository) } }
1
null
1
1
8a2ead7334b6b26a281b3a7842e6502fd96b2cc5
1,698
stepik
Apache License 2.0
framework-docs/src/main/kotlin/org/springframework/docs/integration/jmx/jmxexporting/JmxConfiguration.kt
spring-projects
1,148,753
false
null
/* * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.docs.integration.jmx.jmxexporting import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.jmx.export.MBeanExporter // tag::snippet[] @Configuration class JmxConfiguration { @Bean fun exporter(testBean: JmxTestBean) = MBeanExporter().apply { setBeans(mapOf("bean:name=testBean1" to testBean)) } @Bean fun testBean() = JmxTestBean().apply { name = "TEST" age = 100 } } // end::snippet[]
4
null
4
56,506
52e813d0ad2a5d3439c1880b481b6942a138a8dc
1,133
spring-framework
Apache License 2.0
core/src/main/java/com/kiptechie/core/domain/use_cases/FilterOutDigits.kt
kiptechie
456,271,423
false
{"Kotlin": 484123}
package com.omaroid.core.domain.use_cases class FilterOutDigits { operator fun invoke(text: String): String { return text.filter { it.isDigit() } } }
1
Kotlin
3
5
1bee22359b263c90d1dbb03bf96f7d64e1fcc458
166
ComposeCalorieTracker
MIT License
core/generated-sources/src/main/kotlin/org/jetbrains/kotlinx/dataframe/api/colsOfKind.kt
Kotlin
259,256,617
false
null
package org.jetbrains.kotlinx.dataframe.api import org.jetbrains.kotlinx.dataframe.ColumnFilter import org.jetbrains.kotlinx.dataframe.DataFrame import org.jetbrains.kotlinx.dataframe.DataRow import org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.Grammar.ColumnGroupName import org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.Grammar.ColumnSetName import org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.Grammar.PlainDslName import org.jetbrains.kotlinx.dataframe.columns.ColumnKind import org.jetbrains.kotlinx.dataframe.columns.ColumnPath import org.jetbrains.kotlinx.dataframe.columns.ColumnReference import org.jetbrains.kotlinx.dataframe.columns.ColumnSet import org.jetbrains.kotlinx.dataframe.columns.ColumnsResolver import org.jetbrains.kotlinx.dataframe.columns.SingleColumn import org.jetbrains.kotlinx.dataframe.documentation.AccessApi import org.jetbrains.kotlinx.dataframe.documentation.DslGrammarTemplateColumnsSelectionDsl.DslGrammarTemplate import org.jetbrains.kotlinx.dataframe.documentation.Indent import org.jetbrains.kotlinx.dataframe.documentation.LineBreak import org.jetbrains.kotlinx.dataframe.impl.columns.TransformableColumnSet import org.jetbrains.kotlinx.dataframe.impl.headPlusArray import kotlin.reflect.KProperty // region ColumnsSelectionDsl /** * ## Cols Of Kind [Columns Selection DSL][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl] * * See [Grammar] for all functions in this interface. */ public interface ColsOfKindColumnsSelectionDsl { /** * ## Cols Of Kind Grammar * * * &nbsp;&nbsp;&nbsp;&nbsp; * * [(What is this notation?)][org.jetbrains.kotlinx.dataframe.documentation.DslGrammar] * &nbsp;&nbsp;&nbsp;&nbsp; * * ### Definitions: * `columnSet: `[`ColumnSet`][org.jetbrains.kotlinx.dataframe.columns.ColumnSet]`<*>` * * &nbsp;&nbsp;&nbsp;&nbsp; * * `columnGroup: `[`SingleColumn`][org.jetbrains.kotlinx.dataframe.columns.SingleColumn]`<`[`DataRow`][org.jetbrains.kotlinx.dataframe.DataRow]`<*>> | `[`String`][String]` | `[`KProperty`][kotlin.reflect.KProperty]`<* | `[`DataRow`][org.jetbrains.kotlinx.dataframe.DataRow]`<*>> | `[`ColumnPath`][org.jetbrains.kotlinx.dataframe.columns.ColumnPath] * * &nbsp;&nbsp;&nbsp;&nbsp; * * `condition: `[`ColumnFilter`][org.jetbrains.kotlinx.dataframe.ColumnFilter] * * &nbsp;&nbsp;&nbsp;&nbsp; * * `kind: `[`ColumnKind`][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] * * &nbsp;&nbsp;&nbsp;&nbsp; * * ### What can be called directly in the [Columns Selection DSL][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl]: * * * &nbsp;&nbsp;&nbsp;&nbsp; * * [**`colsOfKind`**][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colGroups]**`(`**[`kind`][org.jetbrains.kotlinx.dataframe.documentation.DslGrammarTemplateColumnsSelectionDsl.DslGrammarTemplate.ColumnKindDef]**`,`**` ..`**`)`**` [ `**`{ `**[`condition`][org.jetbrains.kotlinx.dataframe.documentation.DslGrammarTemplateColumnsSelectionDsl.DslGrammarTemplate.ConditionDef]**` }`**` ]` * * &nbsp;&nbsp;&nbsp;&nbsp; * * ### What can be called on a [ColumnSet][org.jetbrains.kotlinx.dataframe.columns.ColumnSet]: * * * &nbsp;&nbsp;&nbsp;&nbsp; * * [`columnSet`][org.jetbrains.kotlinx.dataframe.documentation.DslGrammarTemplateColumnsSelectionDsl.DslGrammarTemplate.ColumnSetDef] * * &nbsp;&nbsp;&nbsp;&nbsp;__`.`__[**`colsOfKind`**][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colGroups]**`(`**[`kind`][org.jetbrains.kotlinx.dataframe.documentation.DslGrammarTemplateColumnsSelectionDsl.DslGrammarTemplate.ColumnKindDef]**`,`**` ..`**`)`**` [ `**`{ `**[`condition`][org.jetbrains.kotlinx.dataframe.documentation.DslGrammarTemplateColumnsSelectionDsl.DslGrammarTemplate.ConditionDef]**` }`**` ]` * * &nbsp;&nbsp;&nbsp;&nbsp; * * ### What can be called on a [Column Group (reference)][org.jetbrains.kotlinx.dataframe.documentation.DslGrammarTemplateColumnsSelectionDsl.DslGrammarTemplate.ColumnGroupDef]: * * * &nbsp;&nbsp;&nbsp;&nbsp; * * [`columnGroup`][org.jetbrains.kotlinx.dataframe.documentation.DslGrammarTemplateColumnsSelectionDsl.DslGrammarTemplate.ColumnGroupDef] * * &nbsp;&nbsp;&nbsp;&nbsp;__`.`__[**`colsOfKind`**][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colGroups]**`(`**[`kind`][org.jetbrains.kotlinx.dataframe.documentation.DslGrammarTemplateColumnsSelectionDsl.DslGrammarTemplate.ColumnKindDef]**`,`**` ..`**`)`**` [ `**`{ `**[`condition`][org.jetbrains.kotlinx.dataframe.documentation.DslGrammarTemplateColumnsSelectionDsl.DslGrammarTemplate.ConditionDef]**` }`**` ]` * * * * * * * * * * * * * */ public interface Grammar { /** [**`colsOfKind`**][ColumnsSelectionDsl.colGroups] */ public interface PlainDslName /** __`.`__[**`colsOfKind`**][ColumnsSelectionDsl.colGroups] */ public interface ColumnSetName /** __`.`__[**`colsOfKind`**][ColumnsSelectionDsl.colGroups] */ public interface ColumnGroupName } /** * ## Cols Of Kind * Creates a subset of columns from [this] that are of the given kind(s). * * You can optionally use a [filter] to only include certain columns. * [colsOfKind] can be called using any of the supported [APIs][AccessApi] (+ [ColumnPath]). * * This function operates solely on columns at the top-level. * * ### Check out: [Grammar] * * #### For example: * * `df.`[select][DataFrame.select]` { `[colsOfKind][ColumnsSelectionDsl.colsOfKind]`(`[Value][ColumnKind.Value]`, `[Frame][ColumnKind.Frame]`) { it.`[name][ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }` * * `df.`[select][DataFrame.select]` { `[colsOfKind][ColumnsSelectionDsl.colsOfKind]`(`[Group][ColumnKind.Group]`) }` * * `df.`[select][DataFrame.select]` { "myColGroup".`[colsOfKind][String.colsOfKind]`(`[Frame][ColumnKind.Frame]`) }` * * #### Examples for this overload: * * * * @param [filter] An optional [predicate][ColumnFilter] to filter the columns of given kind(s) by. * @param [kind] The [kind][ColumnKind] of columns to include. * @param [others] Other optional [kinds][ColumnKind] of columns to include. * @return A [ColumnSet] of columns of the given kind(s). * @see [ColumnsSelectionDsl.valueCols] * @see [ColumnsSelectionDsl.frameCols] * @see [ColumnsSelectionDsl.colGroups] * @see [ColumnsSelectionDsl.cols] */ private interface CommonColsOfKindDocs { /** Example argument */ interface ExampleArg } /** * ## Cols Of Kind * Creates a subset of columns from [this] that are of the given kind(s). * * You can optionally use a [filter] to only include certain columns. * [colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.colsOfKind] can be called using any of the supported [APIs][org.jetbrains.kotlinx.dataframe.documentation.AccessApi] (+ [ColumnPath][org.jetbrains.kotlinx.dataframe.columns.ColumnPath]). * * This function operates solely on columns at the top-level. * * ### Check out: [Grammar][org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.Grammar] * * #### For example: * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { `[colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colsOfKind]`(`[Value][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Value]`, `[Frame][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Frame]`) { it.`[name][org.jetbrains.kotlinx.dataframe.columns.ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }` * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { `[colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colsOfKind]`(`[Group][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Group]`) }` * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { "myColGroup".`[colsOfKind][kotlin.String.colsOfKind]`(`[Frame][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Frame]`) }` * * #### Examples for this overload: * * `df.`[select][DataFrame.select]` { `[cols][ColumnsSelectionDsl.cols]` { it.`[name][ColumnReference.name]`.`[startsWith][String.startsWith]`("my") }.`[colsOfKind][ColumnSet.colsOfKind]`(`[Value][ColumnKind.Value]`, `[Frame][ColumnKind.Frame]`) }` * * `// NOTE: This can be shortened to just:` * * `df.`[select][DataFrame.select]` { `[colsOfKind][ColumnsSelectionDsl.colsOfKind]`(`[Value][ColumnKind.Value]`, `[Frame][ColumnKind.Frame]`) { it.`[name][ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }` * * @param [filter] An optional [predicate][org.jetbrains.kotlinx.dataframe.ColumnFilter] to filter the columns of given kind(s) by. * @param [kind] The [kind][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] of columns to include. * @param [others] Other optional [kinds][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] of columns to include. * @return A [ColumnSet][org.jetbrains.kotlinx.dataframe.columns.ColumnSet] of columns of the given kind(s). * @see [ColumnsSelectionDsl.valueCols] * @see [ColumnsSelectionDsl.frameCols] * @see [ColumnsSelectionDsl.colGroups] * @see [ColumnsSelectionDsl.cols] */ public fun ColumnSet<*>.colsOfKind( kind: ColumnKind, vararg others: ColumnKind, filter: ColumnFilter<*> = { true }, ): TransformableColumnSet<*> = columnsOfKindInternal( kinds = headPlusArray(kind, others).toSet(), filter = filter ) /** * ## Cols Of Kind * Creates a subset of columns from [this] that are of the given kind(s). * * You can optionally use a [filter] to only include certain columns. * [colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.colsOfKind] can be called using any of the supported [APIs][org.jetbrains.kotlinx.dataframe.documentation.AccessApi] (+ [ColumnPath][org.jetbrains.kotlinx.dataframe.columns.ColumnPath]). * * This function operates solely on columns at the top-level. * * ### Check out: [Grammar][org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.Grammar] * * #### For example: * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { `[colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colsOfKind]`(`[Value][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Value]`, `[Frame][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Frame]`) { it.`[name][org.jetbrains.kotlinx.dataframe.columns.ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }` * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { `[colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colsOfKind]`(`[Group][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Group]`) }` * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { "myColGroup".`[colsOfKind][kotlin.String.colsOfKind]`(`[Frame][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Frame]`) }` * * #### Examples for this overload: * * `df.`[select][DataFrame.select]` { `[colsOfKind][ColumnsSelectionDsl.colsOfKind]`(`[Value][ColumnKind.Value]`, `[Frame][ColumnKind.Frame]`) { it.`[name][ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }` * * @param [filter] An optional [predicate][org.jetbrains.kotlinx.dataframe.ColumnFilter] to filter the columns of given kind(s) by. * @param [kind] The [kind][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] of columns to include. * @param [others] Other optional [kinds][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] of columns to include. * @return A [ColumnSet][org.jetbrains.kotlinx.dataframe.columns.ColumnSet] of columns of the given kind(s). * @see [ColumnsSelectionDsl.valueCols] * @see [ColumnsSelectionDsl.frameCols] * @see [ColumnsSelectionDsl.colGroups] * @see [ColumnsSelectionDsl.cols] */ public fun ColumnsSelectionDsl<*>.colsOfKind( kind: ColumnKind, vararg others: ColumnKind, filter: ColumnFilter<*> = { true }, ): TransformableColumnSet<*> = asSingleColumn().columnsOfKindInternal( kinds = headPlusArray(kind, others).toSet(), filter = filter ) /** * ## Cols Of Kind * Creates a subset of columns from [this] that are of the given kind(s). * * You can optionally use a [filter] to only include certain columns. * [colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.colsOfKind] can be called using any of the supported [APIs][org.jetbrains.kotlinx.dataframe.documentation.AccessApi] (+ [ColumnPath][org.jetbrains.kotlinx.dataframe.columns.ColumnPath]). * * This function operates solely on columns at the top-level. * * ### Check out: [Grammar][org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.Grammar] * * #### For example: * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { `[colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colsOfKind]`(`[Value][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Value]`, `[Frame][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Frame]`) { it.`[name][org.jetbrains.kotlinx.dataframe.columns.ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }` * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { `[colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colsOfKind]`(`[Group][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Group]`) }` * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { "myColGroup".`[colsOfKind][kotlin.String.colsOfKind]`(`[Frame][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Frame]`) }` * * #### Examples for this overload: * * `df.`[select][DataFrame.select]` { myColumnGroup.`[colsOfKind][SingleColumn.colsOfKind]`(`[Value][ColumnKind.Value]`, `[Frame][ColumnKind.Frame]`) }` * * @param [filter] An optional [predicate][org.jetbrains.kotlinx.dataframe.ColumnFilter] to filter the columns of given kind(s) by. * @param [kind] The [kind][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] of columns to include. * @param [others] Other optional [kinds][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] of columns to include. * @return A [ColumnSet][org.jetbrains.kotlinx.dataframe.columns.ColumnSet] of columns of the given kind(s). * @see [ColumnsSelectionDsl.valueCols] * @see [ColumnsSelectionDsl.frameCols] * @see [ColumnsSelectionDsl.colGroups] * @see [ColumnsSelectionDsl.cols] */ public fun SingleColumn<DataRow<*>>.colsOfKind( kind: ColumnKind, vararg others: ColumnKind, filter: ColumnFilter<*> = { true }, ): TransformableColumnSet<*> = this.ensureIsColumnGroup().columnsOfKindInternal( kinds = headPlusArray(kind, others).toSet(), filter = filter ) /** * ## Cols Of Kind * Creates a subset of columns from [this] that are of the given kind(s). * * You can optionally use a [filter] to only include certain columns. * [colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.colsOfKind] can be called using any of the supported [APIs][org.jetbrains.kotlinx.dataframe.documentation.AccessApi] (+ [ColumnPath][org.jetbrains.kotlinx.dataframe.columns.ColumnPath]). * * This function operates solely on columns at the top-level. * * ### Check out: [Grammar][org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.Grammar] * * #### For example: * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { `[colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colsOfKind]`(`[Value][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Value]`, `[Frame][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Frame]`) { it.`[name][org.jetbrains.kotlinx.dataframe.columns.ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }` * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { `[colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colsOfKind]`(`[Group][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Group]`) }` * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { "myColGroup".`[colsOfKind][kotlin.String.colsOfKind]`(`[Frame][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Frame]`) }` * * #### Examples for this overload: * * `df.`[select][DataFrame.select]` { "myColumnGroup".`[colsOfKind][SingleColumn.colsOfKind]`(`[Value][ColumnKind.Value]`, `[Frame][ColumnKind.Frame]`) }` * * @param [filter] An optional [predicate][org.jetbrains.kotlinx.dataframe.ColumnFilter] to filter the columns of given kind(s) by. * @param [kind] The [kind][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] of columns to include. * @param [others] Other optional [kinds][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] of columns to include. * @return A [ColumnSet][org.jetbrains.kotlinx.dataframe.columns.ColumnSet] of columns of the given kind(s). * @see [ColumnsSelectionDsl.valueCols] * @see [ColumnsSelectionDsl.frameCols] * @see [ColumnsSelectionDsl.colGroups] * @see [ColumnsSelectionDsl.cols] */ public fun String.colsOfKind( kind: ColumnKind, vararg others: ColumnKind, filter: ColumnFilter<*> = { true }, ): TransformableColumnSet<*> = columnGroup(this).colsOfKind(kind, *others, filter = filter) /** * ## Cols Of Kind * Creates a subset of columns from [this] that are of the given kind(s). * * You can optionally use a [filter] to only include certain columns. * [colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.colsOfKind] can be called using any of the supported [APIs][org.jetbrains.kotlinx.dataframe.documentation.AccessApi] (+ [ColumnPath][org.jetbrains.kotlinx.dataframe.columns.ColumnPath]). * * This function operates solely on columns at the top-level. * * ### Check out: [Grammar][org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.Grammar] * * #### For example: * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { `[colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colsOfKind]`(`[Value][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Value]`, `[Frame][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Frame]`) { it.`[name][org.jetbrains.kotlinx.dataframe.columns.ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }` * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { `[colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colsOfKind]`(`[Group][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Group]`) }` * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { "myColGroup".`[colsOfKind][kotlin.String.colsOfKind]`(`[Frame][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Frame]`) }` * * #### Examples for this overload: * * `df.`[select][DataFrame.select]` { Type::myColumnGroup.`[colsOfKind][KProperty.colsOfKind]`(`[Value][ColumnKind.Value]`, `[Frame][ColumnKind.Frame]`) }` * * @param [filter] An optional [predicate][org.jetbrains.kotlinx.dataframe.ColumnFilter] to filter the columns of given kind(s) by. * @param [kind] The [kind][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] of columns to include. * @param [others] Other optional [kinds][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] of columns to include. * @return A [ColumnSet][org.jetbrains.kotlinx.dataframe.columns.ColumnSet] of columns of the given kind(s). * @see [ColumnsSelectionDsl.valueCols] * @see [ColumnsSelectionDsl.frameCols] * @see [ColumnsSelectionDsl.colGroups] * @see [ColumnsSelectionDsl.cols] */ public fun KProperty<*>.colsOfKind( kind: ColumnKind, vararg others: ColumnKind, filter: ColumnFilter<*> = { true }, ): TransformableColumnSet<*> = columnGroup(this).colsOfKind(kind, *others, filter = filter) /** * ## Cols Of Kind * Creates a subset of columns from [this] that are of the given kind(s). * * You can optionally use a [filter] to only include certain columns. * [colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.colsOfKind] can be called using any of the supported [APIs][org.jetbrains.kotlinx.dataframe.documentation.AccessApi] (+ [ColumnPath][org.jetbrains.kotlinx.dataframe.columns.ColumnPath]). * * This function operates solely on columns at the top-level. * * ### Check out: [Grammar][org.jetbrains.kotlinx.dataframe.api.ColsOfKindColumnsSelectionDsl.Grammar] * * #### For example: * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { `[colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colsOfKind]`(`[Value][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Value]`, `[Frame][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Frame]`) { it.`[name][org.jetbrains.kotlinx.dataframe.columns.ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }` * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { `[colsOfKind][org.jetbrains.kotlinx.dataframe.api.ColumnsSelectionDsl.colsOfKind]`(`[Group][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Group]`) }` * * `df.`[select][org.jetbrains.kotlinx.dataframe.DataFrame.select]` { "myColGroup".`[colsOfKind][kotlin.String.colsOfKind]`(`[Frame][org.jetbrains.kotlinx.dataframe.columns.ColumnKind.Frame]`) }` * * #### Examples for this overload: * * `df.`[select][DataFrame.select]` { "pathTo"["myColumnGroup"].`[colsOfKind][ColumnPath.colsOfKind]`(`[Value][ColumnKind.Value]`, `[Frame][ColumnKind.Frame]`) }` * * @param [filter] An optional [predicate][org.jetbrains.kotlinx.dataframe.ColumnFilter] to filter the columns of given kind(s) by. * @param [kind] The [kind][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] of columns to include. * @param [others] Other optional [kinds][org.jetbrains.kotlinx.dataframe.columns.ColumnKind] of columns to include. * @return A [ColumnSet][org.jetbrains.kotlinx.dataframe.columns.ColumnSet] of columns of the given kind(s). * @see [ColumnsSelectionDsl.valueCols] * @see [ColumnsSelectionDsl.frameCols] * @see [ColumnsSelectionDsl.colGroups] * @see [ColumnsSelectionDsl.cols] */ public fun ColumnPath.colsOfKind( kind: ColumnKind, vararg others: ColumnKind, filter: ColumnFilter<*> = { true }, ): TransformableColumnSet<*> = columnGroup(this).colsOfKind(kind, *others, filter = filter) // endregion } /** * Returns a TransformableColumnSet containing the columns of given kind(s) that satisfy the given filter. * * @param filter The filter function to apply on each column. Must accept a ColumnWithPath object and return a Boolean. * @return A [TransformableColumnSet] containing the columns of given kinds that satisfy the filter. */ internal fun ColumnsResolver<*>.columnsOfKindInternal( kinds: Set<ColumnKind>, filter: ColumnFilter<*>, ): TransformableColumnSet<*> = colsInternal { it.kind() in kinds && filter(it) } // endregion
235
null
60
833
54d00e69ae7c06ff254c6591242413eaf7894f01
24,250
dataframe
Apache License 2.0
app/src/main/java/com/xpense/MainActivity.kt
kelvinkioko
592,435,039
false
null
package com.xpense import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import com.xpense.presentation.home.HomeScreen import com.xpense.ui.theme.XpenseTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { XpenseTheme { HomeScreen() } } } }
0
Kotlin
0
0
68a79225719a1c793fccc888a305819c018ff5fc
534
xpense
Apache License 2.0
app/src/main/java/com/tommasoberlose/anotherwidget/ui/fragments/tabs/LayoutFragment.kt
cccClyde
353,914,989
true
{"Kotlin": 505727}
package com.tommasoberlose.anotherwidget.ui.fragments.tabs import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import com.chibatching.kotpref.blockingBulk import com.google.android.material.transition.MaterialSharedAxis import com.tommasoberlose.anotherwidget.R import com.tommasoberlose.anotherwidget.components.BottomSheetColorPicker import com.tommasoberlose.anotherwidget.components.BottomSheetMenu import com.tommasoberlose.anotherwidget.databinding.FragmentTabLayoutBinding import com.tommasoberlose.anotherwidget.global.Constants import com.tommasoberlose.anotherwidget.global.Preferences import com.tommasoberlose.anotherwidget.helpers.ColorHelper import com.tommasoberlose.anotherwidget.helpers.ColorHelper.toHexValue import com.tommasoberlose.anotherwidget.helpers.ColorHelper.toIntValue import com.tommasoberlose.anotherwidget.helpers.DateHelper import com.tommasoberlose.anotherwidget.ui.activities.tabs.CustomDateActivity import com.tommasoberlose.anotherwidget.ui.activities.MainActivity import com.tommasoberlose.anotherwidget.ui.viewmodels.MainViewModel import com.tommasoberlose.anotherwidget.utils.isDarkTheme import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.* class LayoutFragment : Fragment() { companion object { fun newInstance() = LayoutFragment() } private lateinit var viewModel: MainViewModel private lateinit var colors: IntArray private lateinit var binding: FragmentTabLayoutBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { viewModel = ViewModelProvider(activity as MainActivity).get(MainViewModel::class.java) binding = FragmentTabLayoutBinding.inflate(inflater) subscribeUi(viewModel) binding.lifecycleOwner = this binding.viewModel = viewModel binding.isDarkModeEnabled = requireActivity().isDarkTheme() return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) binding.showDividersToggle.setCheckedImmediatelyNoEvent(Preferences.showDividers) setupListener() lifecycleScope.launch(Dispatchers.IO) { val lazyColors = requireContext().resources.getIntArray(R.array.material_colors) withContext(Dispatchers.Main) { colors = lazyColors } } binding.scrollView.viewTreeObserver?.addOnScrollChangedListener { viewModel.fragmentScrollY.value = binding.scrollView.scrollY } } @SuppressLint("DefaultLocale") private fun subscribeUi( viewModel: MainViewModel ) { viewModel.secondRowTopMargin.observe(viewLifecycleOwner) { maintainScrollPosition { binding.secondRowTopMarginLabel.text = when (it) { Constants.SecondRowTopMargin.NONE.value -> getString(R.string.settings_clock_bottom_margin_subtitle_none) Constants.SecondRowTopMargin.SMALL.value -> getString(R.string.settings_clock_bottom_margin_subtitle_small) Constants.SecondRowTopMargin.LARGE.value -> getString(R.string.settings_clock_bottom_margin_subtitle_large) else -> getString(R.string.settings_clock_bottom_margin_subtitle_medium) } } } viewModel.clockBottomMargin.observe(viewLifecycleOwner) { maintainScrollPosition { binding.clockBottomMarginLabel.text = when (it) { Constants.ClockBottomMargin.NONE.value -> getString(R.string.settings_clock_bottom_margin_subtitle_none) Constants.ClockBottomMargin.SMALL.value -> getString(R.string.settings_clock_bottom_margin_subtitle_small) Constants.ClockBottomMargin.LARGE.value -> getString(R.string.settings_clock_bottom_margin_subtitle_large) else -> getString(R.string.settings_clock_bottom_margin_subtitle_medium) } } } viewModel.backgroundCardColor.observe(viewLifecycleOwner) { maintainScrollPosition { if (Preferences.backgroundCardAlpha == "00") { binding.backgroundColorLabel.text = getString(R.string.transparent) } else { binding.backgroundColorLabel.text = "#%s".format(Integer.toHexString(ColorHelper.getBackgroundColor(requireActivity().isDarkTheme()))).toUpperCase() } } } viewModel.showDividers.observe(viewLifecycleOwner) { maintainScrollPosition { binding.showDividersLabel.text = if (it) getString(R.string.settings_visible) else getString(R.string.settings_not_visible) } } } private fun setupListener() { binding.actionSecondRowTopMarginSize.setOnClickListener { BottomSheetMenu<Int>( requireContext(), header = getString(R.string.settings_secondary_row_top_margin_title) ).setSelectedValue(Preferences.secondRowTopMargin) .addItem( getString(R.string.settings_clock_bottom_margin_subtitle_none), Constants.SecondRowTopMargin.NONE.value ) .addItem( getString(R.string.settings_clock_bottom_margin_subtitle_small), Constants.SecondRowTopMargin.SMALL.value ) .addItem( getString(R.string.settings_clock_bottom_margin_subtitle_medium), Constants.SecondRowTopMargin.MEDIUM.value ) .addItem( getString(R.string.settings_clock_bottom_margin_subtitle_large), Constants.SecondRowTopMargin.LARGE.value ) .addOnSelectItemListener { value -> Preferences.secondRowTopMargin = value }.show() } binding.actionClockBottomMarginSize.setOnClickListener { BottomSheetMenu<Int>( requireContext(), header = getString(R.string.settings_clock_bottom_margin_title) ).setSelectedValue(Preferences.clockBottomMargin) .addItem( getString(R.string.settings_clock_bottom_margin_subtitle_none), Constants.ClockBottomMargin.NONE.value ) .addItem( getString(R.string.settings_clock_bottom_margin_subtitle_small), Constants.ClockBottomMargin.SMALL.value ) .addItem( getString(R.string.settings_clock_bottom_margin_subtitle_medium), Constants.ClockBottomMargin.MEDIUM.value ) .addItem( getString(R.string.settings_clock_bottom_margin_subtitle_large), Constants.ClockBottomMargin.LARGE.value ) .addOnSelectItemListener { value -> Preferences.clockBottomMargin = value }.show() } binding.actionBackgroundColor.setOnClickListener { BottomSheetColorPicker(requireContext(), colors = colors, header = getString(R.string.settings_background_color_title), getSelected = { ColorHelper.getBackgroundColorRgb(requireActivity().isDarkTheme()) }, onColorSelected = { color: Int -> val colorString = Integer.toHexString(color) if (requireActivity().isDarkTheme()) { Preferences.backgroundCardColorDark = "#" + if (colorString.length > 6) colorString.substring(2) else colorString } else { Preferences.backgroundCardColor = "#" + if (colorString.length > 6) colorString.substring(2) else colorString } }, showAlphaSelector = true, alpha = if (requireActivity().isDarkTheme()) Preferences.backgroundCardAlphaDark.toIntValue() else Preferences.backgroundCardAlpha.toIntValue(), onAlphaChangeListener = { alpha -> if (requireActivity().isDarkTheme()) { Preferences.backgroundCardAlphaDark = alpha.toHexValue() } else { Preferences.backgroundCardAlpha = alpha.toHexValue() } } ).show() } binding.actionShowDividers.setOnClickListener { binding.showDividersToggle.isChecked = !binding.showDividersToggle.isChecked } binding.showDividersToggle.setOnCheckedChangeListener { _, isChecked -> Preferences.showDividers = isChecked } } private fun maintainScrollPosition(callback: () -> Unit) { binding.scrollView.isScrollable = false callback.invoke() lifecycleScope.launch { delay(200) binding.scrollView.isScrollable = true } } }
0
Kotlin
0
1
1ee25bcc89334af7ee17b8472fde6906299474ea
10,015
another-widget
MIT License
app/src/main/java/edu/amrita/amritacafe/model/OrderAdapter.kt
JayadevHaddadi
316,990,403
false
null
package edu.amrita.amritacafe.model import android.content.Context import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.BaseAdapter import edu.amrita.amritacafe.R import edu.amrita.amritacafe.menu.MenuItemUS import edu.amrita.amritacafe.menu.RegularOrderItem import kotlinx.android.synthetic.main.item_order.view.* class OrderAdapter(context: Context) : BaseAdapter() { private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater private val orderList: MutableList<RegularOrderItem> = mutableListOf() val orderItems: List<RegularOrderItem> = orderList var orderChanged: () -> Unit = {} // Replaced by correct callback in mainactivity override fun getCount(): Int { return orderList.size } override fun getItem(position: Int): Any { return orderList[position] } override fun getItemId(position: Int): Long { return position.toLong() } private fun remove(item: RegularOrderItem) { orderList.removeAll { it == item } updateAll() } fun add(addItem: MenuItemUS, weight: Float) { var found = false for (existingItem in orderList) { if(addItem.malaylamName == existingItem.menuItem.malaylamName && existingItem.comment == "") { existingItem.increment(weight) println("increasing! ${existingItem.quantity}") found = true break } } if(!found) { orderList.add(RegularOrderItem(addItem, quantity = weight)) } updateAll() } fun clear() { orderList.clear() updateAll() } fun lastItemCostMultiplier(percentCost: Float) { if (orderList.size > 0) { val lastOrder = orderList.last() if (percentCost == -1f) lastOrder.comment = "Refund" else lastOrder.comment = "Discount ${Math.round(100 - percentCost * 100)}%" lastOrder.priceMultiplier = percentCost updateAll() } } private fun updateAll() { notifyDataSetChanged() orderChanged() } private fun reuseOrInflate(view: View?, parent: ViewGroup) = view ?: inflater.inflate(R.layout.item_order, parent, false).apply { val orderItemView = this amount_TV.setOnClickListener { println("increasing amount of bla bla") val position = tag as Int orderList[position].increment() notifyDataSetChanged() orderChanged() } setOnClickListener { comment_ET.run { visibility = View.VISIBLE requestFocus() context.getSystemService(Context.INPUT_METHOD_SERVICE).also { (it as InputMethodManager).showSoftInput(this, 0) } } } cancel_button.setOnClickListener { remove(orderList[tag as Int]) } comment_ET.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) {} override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { val position = orderItemView.tag as Int orderList[position] = orderItems[position].editComment(p0.toString()) } }) } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { return reuseOrInflate(convertView, parent).apply { tag = position orderList[position].let { orderItem -> label.text = orderItem.menuItem.englishName amount_TV.text = orderItem.quantity.toString() price_TV.text = orderItem.finalPrice.toString() comment_ET.setText(orderItem.comment) comment_ET.visibility = if (orderItem.comment.isNotBlank()) View.VISIBLE else View.GONE } } } }
0
Kotlin
0
0
2de46b0d1bf8fdd045f0ca273a3839689f6cae82
4,452
Amrita-Vegetables
Apache License 2.0
adshelper/src/main/java/com/example/app/adshelper/openad/AppOpenApplication.kt
vickypathak123
499,269,903
false
{"Java": 486597, "Kotlin": 215177, "Assembly": 5}
package com.example.app.adshelper.openad import android.annotation.SuppressLint import android.app.Activity import android.app.ActivityManager import android.content.Context import android.os.Build import android.os.Process import android.os.SystemClock import android.provider.Settings import android.util.Log import android.webkit.WebView import androidx.multidex.MultiDex import androidx.multidex.MultiDexApplication import com.example.app.adshelper.isAppForeground import com.example.app.adshelper.isOpenAdEnable import com.example.app.adshelper.dialogs.FullScreenNativeAdDialog import com.example.app.adshelper.isAnyAdOpen import com.example.app.adshelper.isInterstitialAdShow import com.example.app.adshelper.setTestDeviceIds import com.google.android.gms.ads.AdActivity import com.google.android.gms.ads.MobileAds import java.security.MessageDigest import java.security.NoSuchAlgorithmException import kotlin.collections.ArrayList open class AppOpenApplication : MultiDexApplication(), androidx.lifecycle.DefaultLifecycleObserver { private val TAG: String = "AppOpenApplication" // variable to track pause event time private var isPause: Boolean = false private var mLastPauseTime: Long = 0 private val mMinPauseDuration = 100 private var mOpenAdManager: OpenAdManager? = null private val mTestDeviceIds: ArrayList<String> = ArrayList() interface AppLifecycleListener { fun onResumeApp(fCurrentActivity: Activity): Boolean } private var mAppLifecycleListener: AppLifecycleListener? = null override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) MultiDex.install(this) } override fun onCreate() { super<MultiDexApplication>.onCreate() Log.e(TAG, "onCreate: ") androidx.lifecycle.ProcessLifecycleOwner.get().lifecycle.addObserver(this) mOpenAdManager = OpenAdManager(this@AppOpenApplication) } fun setAppLifecycleListener(fAppLifecycleListener: AppLifecycleListener) { this.mAppLifecycleListener = fAppLifecycleListener } fun setDeviceId(vararg fTestDeviceIds: String) { mTestDeviceIds.addAll(fTestDeviceIds) } fun initMobileAds(isAppInTesting: Boolean) { setMobileAds(isAppInTesting = isAppInTesting) } private fun setDeviceIds(isAppInTesting: Boolean) { if (isAppInTesting) { mTestDeviceIds.add(getAdsTestDeviceId()) setTestDeviceIds(*mTestDeviceIds.toTypedArray()) } } private fun setMobileAds(isAppInTesting: Boolean) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { val processName = getProcessName(applicationContext) if (processName != null && packageName != processName) { WebView.setDataDirectorySuffix(processName) MobileAds.initialize(baseContext) { Log.d(TAG, "onInitializationComplete.1") setDeviceIds(isAppInTesting = isAppInTesting) } } else { MobileAds.initialize(baseContext) { Log.d(TAG, "onInitializationComplete.2") setDeviceIds(isAppInTesting = isAppInTesting) } } } else { MobileAds.initialize(baseContext) { Log.d(TAG, "onInitializationComplete.3") setDeviceIds(isAppInTesting = isAppInTesting) } } } private fun getProcessName(context: Context?): String? { if (context == null) return null val manager = (context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager) for (processInfo in manager.runningAppProcesses) { if (processInfo.pid == Process.myPid()) { return processInfo.processName } } return null } @SuppressLint("HardwareIds") private fun getAdsTestDeviceId(): String { return try { val androidId: String = Settings.Secure.getString(this.contentResolver, Settings.Secure.ANDROID_ID) val md5Data = customMD5(androidId) val deviceId = md5Data?.uppercase(java.util.Locale.ENGLISH) ?: "null" println("getDeviceId: $deviceId") deviceId } catch (e: Exception) { e.toString() } } private fun customMD5(md5: String): String? { try { val md = MessageDigest.getInstance("MD5") val array = md.digest(md5.toByteArray()) val sb = StringBuffer() for (i in array.indices) { sb.append(Integer.toHexString(array[i].toInt() and 0xFF or 0x100).substring(1, 3)) } return sb.toString() } catch (e: NoSuchAlgorithmException) { } return null } //<editor-fold desc="For Application Lifecycle"> override fun onPause(owner: androidx.lifecycle.LifecycleOwner) { super.onPause(owner) Log.e(TAG, "onPause: ") mLastPauseTime = SystemClock.elapsedRealtime() isPause = true } override fun onStart(owner: androidx.lifecycle.LifecycleOwner) { super.onStart(owner) Log.e(TAG, "onStart: onAppForegrounded: ") isAppForeground = true } override fun onStop(owner: androidx.lifecycle.LifecycleOwner) { super.onStop(owner) Log.e(TAG, "onStop: onAppBackgrounded: ") isAppForeground = false if (SystemClock.elapsedRealtime() - mLastPauseTime < mMinPauseDuration) { Log.e(TAG, "onStop: Reset Pause Flag") if (isPause) { isPause = false } } } override fun onDestroy(owner: androidx.lifecycle.LifecycleOwner) { super.onDestroy(owner) Log.e(TAG, "onDestroy: ") } override fun onResume(owner: androidx.lifecycle.LifecycleOwner) { super.onResume(owner) Log.e(TAG, "onResume") if (isOpenAdEnable) { mAppLifecycleListener?.let { lListener -> mOpenAdManager?.let { lOpenAdManager -> if (isAppForeground && !isPause) { lOpenAdManager.mCurrentActivity?.let { fCurrentActivity -> if (fCurrentActivity !is AdActivity) { if (isAnyAdOpen) { isAnyAdOpen = false } else { if (!FullScreenNativeAdDialog.isDialogShowing && !isInterstitialAdShow) { if (lListener.onResumeApp(fCurrentActivity)) { lOpenAdManager.showOpenAd() } } } } } } if (isPause) { isPause = false } } } } } //</editor-fold> }
0
Java
1
0
aa966b83f6dca0aa08261b8810a778e40d909d4b
7,105
AndroidAppCenter
MIT License
ktor-client/ktor-client-apache/jvm/src/io/ktor/client/engine/apache/ApacheRequestProducer.kt
ktorio
40,136,600
false
null
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.apache import io.ktor.client.call.* import io.ktor.client.engine.* import io.ktor.client.features.* import io.ktor.client.request.* import io.ktor.http.* import io.ktor.http.content.* import io.ktor.utils.io.* import kotlinx.coroutines.* import org.apache.http.* import org.apache.http.HttpHeaders import org.apache.http.HttpRequest import org.apache.http.client.config.* import org.apache.http.client.methods.* import org.apache.http.client.utils.* import org.apache.http.entity.* import org.apache.http.nio.* import org.apache.http.nio.protocol.* import org.apache.http.protocol.* import java.nio.* import kotlin.coroutines.* internal class ApacheRequestProducer( private val requestData: HttpRequestData, private val config: ApacheEngineConfig, callContext: CoroutineContext ) : HttpAsyncRequestProducer, CoroutineScope { private val request: HttpUriRequest = setupRequest() private val host = URIUtils.extractHost(request.uri) ?: throw IllegalArgumentException("Cannot extract host from URL ${request.uri}") private val interestController = InterestControllerHolder() private val producerJob = Job() override val coroutineContext: CoroutineContext = callContext + producerJob private val channel: ByteReadChannel = when (val body = requestData.body) { is OutgoingContent.ByteArrayContent -> ByteReadChannel(body.bytes()) is OutgoingContent.ProtocolUpgrade -> throw UnsupportedContentTypeException(body) is OutgoingContent.NoContent -> ByteReadChannel.Empty is OutgoingContent.ReadChannelContent -> body.readFrom() is OutgoingContent.WriteChannelContent -> GlobalScope.writer(callContext, autoFlush = true) { body.writeTo(channel) }.channel } init { producerJob.invokeOnCompletion { cause -> channel.cancel(cause) } } override fun isRepeatable(): Boolean = true override fun getTarget(): HttpHost = host override fun generateRequest(): HttpRequest = request override fun requestCompleted(context: HttpContext) { } override fun resetRequest() {} override fun failed(cause: Exception) { val mappedCause = mapCause(cause, requestData) channel.cancel(mappedCause) producerJob.completeExceptionally(mappedCause) } override fun produceContent(encoder: ContentEncoder, ioctrl: IOControl) { if (interestController.outputSuspended) { return } var result: Int do { result = channel.readAvailable { buffer: ByteBuffer -> encoder.write(buffer) } } while (result > 0) if (channel.isClosedForRead) { encoder.complete() return } if (result == -1) { interestController.suspendOutput(ioctrl) launch(Dispatchers.Unconfined) { try { channel.awaitContent() } finally { interestController.resumeOutputIfPossible() } } } } override fun close() { channel.cancel() producerJob.complete() } private fun setupRequest(): HttpUriRequest = with(requestData) { val builder = RequestBuilder.create(method.value)!! builder.uri = url.toURI() val content = requestData.body var length: String? = null var type: String? = null mergeHeaders(headers, content) { key, value -> when (key) { HttpHeaders.CONTENT_LENGTH -> length = value HttpHeaders.CONTENT_TYPE -> type = value else -> builder.addHeader(key, value) } } if ((method != HttpMethod.Get && method != HttpMethod.Head) || body !is OutgoingContent.NoContent) { builder.entity = BasicHttpEntity().apply { val lengthResult = length if (lengthResult == null || lengthResult.isBlank()) { isChunked = true } else { contentLength = lengthResult.toLong() } setContentType(type) } } with(config) { builder.config = RequestConfig.custom() .setRedirectsEnabled(followRedirects) .setSocketTimeout(socketTimeout) .setConnectTimeout(connectTimeout) .setConnectionRequestTimeout(connectionRequestTimeout) .customRequest() .setupTimeoutAttributes(requestData) .build() } return builder.build() } } private fun RequestConfig.Builder.setupTimeoutAttributes(requestData: HttpRequestData): RequestConfig.Builder = also { requestData.getCapabilityOrNull(HttpTimeout)?.let { timeoutAttributes -> timeoutAttributes.connectTimeoutMillis?.let { setConnectTimeout(convertLongTimeoutToIntWithInfiniteAsZero(it)) } timeoutAttributes.socketTimeoutMillis?.let { setSocketTimeout(convertLongTimeoutToIntWithInfiniteAsZero(it)) } } }
269
null
991
9,709
9e0eb99aa2a0a6bc095f162328525be1a76edb21
5,283
ktor
Apache License 2.0
core/src/main/kotlin/com/malinskiy/marathon/execution/queue/TestAction.kt
cdsap
134,924,816
true
{"Kotlin": 300576, "JavaScript": 33573, "CSS": 29044, "HTML": 2224, "Shell": 964}
package com.malinskiy.marathon.execution.queue import com.malinskiy.marathon.device.Device import com.malinskiy.marathon.execution.TestResult sealed class TestAction { data class SaveReport(val device: Device, val testResult: TestResult) : TestAction() }
1
Kotlin
0
1
ce6648774cd47c87f074ebdfdacbbcf781bdfdd4
261
marathon
Apache License 2.0
kord-extensions/src/main/kotlin/com/kotlindiscord/kord/extensions/pagination/MessageButtonPaginator.kt
Kord-Extensions
262,018,456
false
null
@file:OptIn(KordPreview::class) package com.kotlindiscord.kord.extensions.pagination import com.kotlindiscord.kord.extensions.pagination.builders.PaginatorBuilder import com.kotlindiscord.kord.extensions.pagination.pages.Pages import dev.kord.common.annotation.KordPreview import dev.kord.core.behavior.UserBehavior import dev.kord.core.behavior.channel.MessageChannelBehavior import dev.kord.core.behavior.channel.createMessage import dev.kord.core.behavior.edit import dev.kord.core.entity.Message import dev.kord.core.entity.ReactionEmoji import dev.kord.rest.builder.message.create.allowedMentions import dev.kord.rest.builder.message.create.embed import dev.kord.rest.builder.message.modify.allowedMentions import dev.kord.rest.builder.message.modify.embed import java.util.* /** * Class representing a button-based paginator that operates on standard messages. * * @param pingInReply Whether to ping the author of [targetMessage] in reply. * @param targetMessage Target message to reply to, overriding [targetChannel]. * @param targetChannel Target channel to send the paginator to, if [targetMessage] isn't provided. */ public class MessageButtonPaginator( pages: Pages, owner: UserBehavior? = null, timeoutSeconds: Long? = null, keepEmbed: Boolean = true, switchEmoji: ReactionEmoji = if (pages.groups.size == 2) EXPAND_EMOJI else SWITCH_EMOJI, bundle: String? = null, locale: Locale? = null, public val pingInReply: Boolean = true, public val targetChannel: MessageChannelBehavior? = null, public val targetMessage: Message? = null, ) : BaseButtonPaginator(pages, owner, timeoutSeconds, keepEmbed, switchEmoji, bundle, locale) { init { if (targetChannel == null && targetMessage == null) { throw IllegalArgumentException("Must provide either a target channel or target message") } } /** Specific channel to send the paginator to. **/ public val channel: MessageChannelBehavior = targetMessage?.channel ?: targetChannel!! /** Message containing the paginator. **/ public var message: Message? = null override suspend fun send() { if (message == null) { setup() message = channel.createMessage { this.messageReference = targetMessage?.id allowedMentions { repliedUser = pingInReply } embed { applyPage() } with(this@MessageButtonPaginator.components) { this@createMessage.applyToMessage() } } } else { updateButtons() message!!.edit { embed { applyPage() } with(this@MessageButtonPaginator.components) { this@edit.applyToMessage() } } } } override suspend fun destroy() { if (!active) { return } active = false if (!keepEmbed) { message!!.delete() } else { message!!.edit { allowedMentions { repliedUser = pingInReply } embed { applyPage() } this.components = mutableListOf() } } super.destroy() } } /** Convenience function for creating a message button paginator from a paginator builder. **/ @Suppress("FunctionNaming") // Factory function public fun MessageButtonPaginator( pingInReply: Boolean = true, targetChannel: MessageChannelBehavior? = null, targetMessage: Message? = null, builder: PaginatorBuilder ): MessageButtonPaginator = MessageButtonPaginator( pages = builder.pages, owner = builder.owner, timeoutSeconds = builder.timeoutSeconds, keepEmbed = builder.keepEmbed, bundle = builder.bundle, locale = builder.locale, pingInReply = pingInReply, targetChannel = targetChannel, targetMessage = targetMessage, switchEmoji = builder.switchEmoji ?: if (builder.pages.groups.size == 2) EXPAND_EMOJI else SWITCH_EMOJI, )
15
Kotlin
14
53
c4a5a8cc8a65c0bd0928a4dcc6c05e3fc4fd75cf
4,091
kord-extensions
MIT License
library/src/commonMain/kotlin/com/befrvnk/knotion/endpoints/databases/DatabasesEndpoint.kt
befrvnk
672,042,674
false
null
package com.befrvnk.knotion.endpoints.databases interface DatabasesEndpoint { suspend fun createDatabase() suspend fun filterDatabaseEntries() suspend fun sortDatabaseEntries() suspend fun queryDatabase() suspend fun retrieveDatabase() suspend fun updateDatabase() }
1
Kotlin
0
0
6271d06fc965de19f5449804b7a8e33648eec7f2
297
knotion
MIT License
app/src/main/java/com/hz/zxk/demo/interceptor/InterceptorTwo.kt
crazyxiaoke
223,301,380
false
null
package com.hz.zxk.demo.interceptor import android.util.Log import okhttp3.Interceptor import okhttp3.Response /** @author zhengxiaoke @date 2020/4/15 3:34 PM */ class InterceptorTwo : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { Log.d("TAG", "我是第二个拦截器") return chain.proceed(chain.request()) } }
0
Kotlin
0
0
e83ade5f8d0a859bbc0c8537f087e17fd2051bba
353
SuperFrame
Apache License 2.0
foundation/domain-model/main/ru/pixnews/domain/model/company/Company.kt
illarionov
305,333,284
false
{"Kotlin": 2008969, "FreeMarker": 2782, "Shell": 855, "Fluent": 72}
/* * Copyright (c) 2023, the Pixnews project authors and contributors. Please see the AUTHORS file for details. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package ru.pixnews.domain.model.company import kotlinx.collections.immutable.ImmutableList import ru.pixnews.domain.model.company.CompanyStatus.UNKNOWN import ru.pixnews.domain.model.datasource.DataSource import ru.pixnews.domain.model.datetime.Date import ru.pixnews.domain.model.id.CompanyId import ru.pixnews.domain.model.locale.Localized import ru.pixnews.domain.model.url.ExternalLink import ru.pixnews.domain.model.url.ExternalLinkType.OFFICIAL import ru.pixnews.domain.model.url.ImageUrl import ru.pixnews.domain.model.url.Url import ru.pixnews.domain.model.util.HasId import ru.pixnews.domain.model.util.Ref import ru.pixnews.domain.model.util.RichText import ru.pixnews.library.internationalization.country.CountryCode public data class Company( override val id: CompanyId, val name: String, val description: Localized<RichText>, val avatar: ImageUrl?, val foundingDate: Date?, val status: CompanyStatus = UNKNOWN, val country: CountryCode?, val parentCompany: Ref<Company>?, val dataSources: ImmutableList<DataSource>, val links: ImmutableList<ExternalLink>, ) : HasId<CompanyId> { val url: Url? = links.firstOrNull { it.type == OFFICIAL }?.url }
4
Kotlin
0
2
bbecb1df53a9a94f60e35a1bb2fc3522eddf8450
1,426
Pixnews
Apache License 2.0
app/src/main/java/br/com/quixada/trabalho1/PlacesPage.kt
eliabe71
537,668,883
false
null
package br.com.quixada.trabalho1 import android.R.* import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ListView class PlacesPage(array: ArrayList<String>): Fragment() { private val COUNTRIES = arrayOf( "626900-000", "62504-010", "63900-081" ) private val array = array override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { val view: View = inflater.inflate(R.layout.fragment_places_page, container, false) var bind = view.findViewById<ListView>(R.id.liste) val adapter = activity?.let { ArrayAdapter<String>(it, layout.simple_list_item_1, array)} bind.adapter = adapter return view } }
0
Kotlin
0
0
09cd80476f7f4cf67cc74fc853df3db5482299a2
899
mobile
MIT License
src/main/kotlin/me/bzvol/fifimod/data/ModBlockStateProvider.kt
bzvol
508,218,419
false
{"Kotlin": 162220}
package me.bzvol.fifimod.data import me.bzvol.fifimod.FifiMod import me.bzvol.fifimod.block.AquariumBlock import me.bzvol.fifimod.block.FifhranyBlock import me.bzvol.fifimod.block.ModBlocks import net.minecraft.client.renderer.RenderType import net.minecraft.data.DataGenerator import net.minecraft.resources.ResourceLocation import net.minecraft.world.level.block.state.properties.BlockStateProperties import net.minecraftforge.client.model.generators.BlockStateProvider import net.minecraftforge.client.model.generators.ConfiguredModel import net.minecraftforge.client.model.generators.ModelFile import net.minecraftforge.common.data.ExistingFileHelper class ModBlockStateProvider(generator: DataGenerator, private val existingFileHelper: ExistingFileHelper) : BlockStateProvider(generator, FifiMod.MOD_ID, existingFileHelper) { override fun registerStatesAndModels() { simpleBlock(ModBlocks.BISMUTH_ORE) simpleBlock(ModBlocks.DEEPSLATE_BISMUTH_ORE) simpleBlock(ModBlocks.POTATO_BLOCK) simpleBlock(ModBlocks.TIN_ORE) simpleBlock(ModBlocks.TIN_BLOCK) simpleBlock(ModBlocks.BRONZE_BLOCK) simpleBlock(ModBlocks.STEEL_BLOCK) simpleBlock(ModBlocks.FIFI_PLANKS) simpleBlock(ModBlocks.ASH_BLOCK) simpleBlock( ModBlocks.FIFI_SAPLING, models().withExistingParent("fifi_sapling", mcLoc("block/cross")) .texture("cross", ResourceLocation(FifiMod.MOD_ID, "block/fifi_sapling")) .renderType("cutout") ) simpleBlock( ModBlocks.FIFI_LEAVES, *ConfiguredModel.builder() .modelFile( models().withExistingParent("fifi_leaves", mcLoc("block/leaves")) .texture("all", ResourceLocation(FifiMod.MOD_ID, "block/fifi_leaves")) .renderType("cutout") ) .weight(90) .nextModel() .modelFile( models().withExistingParent("fifi_leaves_flower", mcLoc("block/leaves")) .texture("all", ResourceLocation(FifiMod.MOD_ID, "block/fifi_leaves_flower")) .renderType("cutout") ) .weight(10) .build() ) horizontalBlock( ModBlocks.CARVED_POTATO_BLOCK, ResourceLocation(FifiMod.MOD_ID, "block/potato_block"), ResourceLocation(FifiMod.MOD_ID, "block/carved_potato_block"), ResourceLocation(FifiMod.MOD_ID, "block/potato_block"), ) horizontalBlock(ModBlocks.BISMUTH_BLOCK, cubeAll(ModBlocks.BISMUTH_BLOCK)) horizontalBlock( ModBlocks.BURPBOX, ResourceLocation(FifiMod.MOD_ID, "block/burpbox_side"), ResourceLocation(FifiMod.MOD_ID, "block/burpbox_front"), ResourceLocation(FifiMod.MOD_ID, "block/burpbox_side") ) horizontalBlock( ModBlocks.FIFI_SPAWNER, ModelFile.ExistingModelFile( ResourceLocation(FifiMod.MOD_ID, "block/fifi_spawner"), existingFileHelper ) ) axisBlock(ModBlocks.FIFI_LOG) axisBlock(ModBlocks.FIFI_WOOD) axisBlock(ModBlocks.STRIPPED_FIFI_LOG) axisBlock(ModBlocks.STRIPPED_FIFI_WOOD) val fifiPlanksTexture = ResourceLocation(FifiMod.MOD_ID, "block/fifi_planks") stairsBlock(ModBlocks.FIFI_STAIRS, fifiPlanksTexture) slabBlock(ModBlocks.FIFI_SLAB, fifiPlanksTexture, fifiPlanksTexture) fenceBlock(ModBlocks.FIFI_FENCE, fifiPlanksTexture) fenceGateBlock(ModBlocks.FIFI_FENCE_GATE, fifiPlanksTexture) models().fenceInventory("fifi_fence_inventory", fifiPlanksTexture) getVariantBuilder(ModBlocks.FIFHRANY) .forAllStates { state -> val age = state.getValue(FifhranyBlock.AGE) ConfiguredModel.builder() .modelFile( models() .withExistingParent( "fifhrany_stage$age", mcLoc("block/crop") ) .texture("crop", ResourceLocation(FifiMod.MOD_ID, "block/fifhrany_stage$age")) .renderType("cutout") ) .build() } getVariantBuilder(ModBlocks.AQUARIUM) .forAllStates { state -> val facing = state.getValue(BlockStateProperties.HORIZONTAL_FACING) val fill = state.getValue(AquariumBlock.FILL) ConfiguredModel.builder() .modelFile( ModelFile.UncheckedModelFile( ResourceLocation(FifiMod.MOD_ID, "block/aquarium_${fill.modelName}"), ) ) .rotationY(((facing.toYRot() + 180) % 360).toInt()) .build() } } }
0
Kotlin
0
0
95903762a1876342bfeae2b11c272f71d97621a3
5,066
FifiMod
MIT License
src/main/kotlin/no/nav/familie/ba/sak/task/BehandleFødselshendelseTask.kt
navikt
224,639,942
false
null
package no.nav.familie.ba.sak.task import io.micrometer.core.instrument.DistributionSummary import io.micrometer.core.instrument.Metrics import no.nav.familie.ba.sak.integrasjoner.infotrygd.InfotrygdFeedService import no.nav.familie.ba.sak.kjerne.autovedtak.AutovedtakStegService import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.FagsystemRegelVurdering import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.VelgFagSystemService import no.nav.familie.ba.sak.kjerne.autovedtak.satsendring.StartSatsendring import no.nav.familie.ba.sak.kjerne.personident.PersonidentService import no.nav.familie.ba.sak.task.dto.BehandleFødselshendelseTaskDTO import no.nav.familie.kontrakter.felles.Fødselsnummer import no.nav.familie.kontrakter.felles.objectMapper import no.nav.familie.prosessering.AsyncTaskStep import no.nav.familie.prosessering.TaskStepBeskrivelse import no.nav.familie.prosessering.domene.Task import no.nav.familie.prosessering.error.RekjørSenereException import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.time.LocalDateTime import java.time.temporal.ChronoUnit import java.util.Properties @Service @TaskStepBeskrivelse( taskStepType = BehandleFødselshendelseTask.TASK_STEP_TYPE, beskrivelse = "Setter i gang behandlingsløp for fødselshendelse", maxAntallFeil = 3, ) class BehandleFødselshendelseTask( private val autovedtakStegService: AutovedtakStegService, private val velgFagsystemService: VelgFagSystemService, private val infotrygdFeedService: InfotrygdFeedService, private val personidentService: PersonidentService, private val startSatsendring: StartSatsendring, ) : AsyncTaskStep { private val dagerSidenBarnBleFødt: DistributionSummary = Metrics.summary("foedselshendelse.dagersidenbarnfoedt") override fun doTask(task: Task) { val behandleFødselshendelseTaskDTO = objectMapper.readValue(task.payload, BehandleFødselshendelseTaskDTO::class.java) val nyBehandling = behandleFødselshendelseTaskDTO.nyBehandling logger.info("Behandler fødselshendelse") secureLogger.info("Behandler fødselshendelse, mor=${nyBehandling.morsIdent}, barna=${nyBehandling.barnasIdenter}") nyBehandling.barnasIdenter.forEach { // En litt forenklet løsning for å hente fødselsdato uten å kalle PDL. Gir ikke helt riktige data, men godt nok. val dagerSidenBarnetBleFødt = ChronoUnit.DAYS.between( Fødselsnummer(it).fødselsdato, LocalDateTime.now(), ) dagerSidenBarnBleFødt.record(dagerSidenBarnetBleFødt.toDouble()) } when (velgFagsystemService.velgFagsystem(nyBehandling).first) { FagsystemRegelVurdering.SEND_TIL_BA -> { val harOpprettetSatsendring = startSatsendring.sjekkOgOpprettSatsendringVedGammelSats(nyBehandling.morsIdent) if (harOpprettetSatsendring) { throw RekjørSenereException( "Satsendring skal kjøre ferdig før man behandler fødselsehendelse", LocalDateTime.now().plusMinutes(60), ) } autovedtakStegService.kjørBehandlingFødselshendelse( mottakersAktør = personidentService.hentAktør( nyBehandling.morsIdent, ), behandlingsdata = nyBehandling, ) } FagsystemRegelVurdering.SEND_TIL_INFOTRYGD -> { infotrygdFeedService.sendTilInfotrygdFeed(nyBehandling.barnasIdenter) } } } companion object { const val TASK_STEP_TYPE = "behandleFødselshendelseTask" private val logger = LoggerFactory.getLogger(BehandleFødselshendelseTask::class.java) private val secureLogger = LoggerFactory.getLogger("secureLogger") fun opprettTask(behandleFødselshendelseTaskDTO: BehandleFødselshendelseTaskDTO): Task { val triggerTid = if (erKlokkenMellom21Og06()) kl06IdagEllerNesteDag() else LocalDateTime.now() return Task( type = TASK_STEP_TYPE, payload = objectMapper.writeValueAsString(behandleFødselshendelseTaskDTO), properties = Properties().apply { this["morsIdent"] = behandleFødselshendelseTaskDTO.nyBehandling.morsIdent }, ).copy( triggerTid = triggerTid.plusDays(7), ) } } }
8
null
1
9
1a1ad3043cb51c472577eaf23749d0e0bf54b261
4,599
familie-ba-sak
MIT License
react-query-kotlin/src/jsMain/kotlin/tanstack/query/core/RetryerConfig.kt
karakum-team
393,199,102
false
{"Kotlin": 6901677}
// Automatically generated - do not modify! package tanstack.query.core import js.promise.PromiseResult external interface RetryerConfig<TData, TError> { var fn: () -> PromiseResult<TData> var abort: () -> Unit var onError: (error: TError) -> Unit var onSuccess: (data: TData) -> Unit var onFail: (failureCount: Int, error: TError) -> Unit var onPause: () -> Unit var onContinue: () -> Unit var retry: RetryValue<TError> var retryDelay: RetryDelayValue<TError> var networkMode: NetworkMode? }
0
Kotlin
8
30
f37c55e72fd893d635d02033d10246ed6981eb96
536
types-kotlin
Apache License 2.0
app/src/main/java/com/netacom/vndirect/ChatSdkApplication.kt
Netacom-NetAlo
462,549,625
false
null
/* * *Created by NetaloTeamAndroid on 2020 * Company: Netacom. * * */ @file:OptIn(ObsoleteCoroutinesApi::class, ExperimentalCoroutinesApi::class, FlowPreview::class) package com.netacom.dlinksdkandroid import android.app.Application import android.content.Context import androidx.work.Configuration import com.asia.sdkcore.entity.ui.theme.NeTheme import com.asia.sdkcore.sdk.AccountKey import com.asia.sdkcore.sdk.AppID import com.asia.sdkcore.sdk.AppKey import com.asia.sdkcore.sdk.SdkConfig import com.asia.sdkui.ui.sdk.NetAloSDK import com.asia.sdkui.ui.sdk.NetAloSdkCore import dagger.hilt.android.HiltAndroidApp import io.realm.Realm import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.ObsoleteCoroutinesApi import javax.inject.Inject /**Created by vantoan on 23,July,2020 Company: Netacom. Email: <EMAIL> */ @HiltAndroidApp class ChatSdkApplication : Application(), Configuration.Provider { @Inject lateinit var netAloSdkCore: NetAloSdkCore override fun getWorkManagerConfiguration() = Configuration.Builder() .setWorkerFactory(netAloSdkCore.workerFactory) .build() private val sdkTheme = NeTheme( mainColor = "#FF9500", subColorLight = "#F9D9C9", subColorDark = "#ef5222", toolbarDrawable = "#FF9500" ) override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) Realm.init(this) } override fun onCreate() { super.onCreate() NetAloSDK.initNetAloSDK( context = this, netAloSdkCore = netAloSdkCore, sdkConfig = SdkConfig( appId = AppID.VNDIRECT, appKey = AppKey.VNDIRECT_PRO, accountKey = AccountKey.VNDIRECT_PRO, isSyncContact = false, hidePhone = true, hideCreateGroup = true, hideAddInfoInChat = true, hideInfoInChat = true, hideCallInChat = false, hideSearch = true, classMainActivity = MainActivity::class.java.name ), neTheme = sdkTheme ) } }
0
Kotlin
0
0
b2b581a9710068b8c7e14f5ca039e6c6a9320d2c
2,229
DLinkSDK-Android-Demo
MIT License
src/main/kotlin/me/senseiwells/essential_client/features/DisplayStartTime.kt
senseiwells
398,797,734
false
{"Kotlin": 68185, "Java": 34580}
package me.senseiwells.essential_client.features import kotlinx.datetime.Clock import me.senseiwells.essential_client.EssentialClientConfig import net.minecraft.client.gui.Font import net.minecraft.client.gui.GuiGraphics import org.apache.commons.lang3.time.DurationFormatUtils object DisplayStartTime { private val start = Clock.System.now() @JvmStatic fun render(graphics: GuiGraphics, font: Font) { if (EssentialClientConfig.instance.displayPlayTime) { val duration = Clock.System.now().minus(this.start).inWholeMilliseconds val formatted = DurationFormatUtils.formatDuration(duration, "H:mm:ss", true) graphics.drawString(font, formatted, 8, 8, 0xFFFFFF) } } internal fun load() { } }
1
Kotlin
14
77
7bcfedfb2df201f3389ce9819d1403a33837e3f5
769
EssentialClient
MIT License
app/src/main/java/com/example/android/dagger/di/AppComponent.kt
dlgockd54
244,119,560
true
{"Kotlin": 53626}
package com.example.android.dagger.di import android.content.Context import com.example.android.dagger.login.LoginComponent import com.example.android.dagger.main.MainActivity import com.example.android.dagger.registration.RegistrationActivity import com.example.android.dagger.registration.RegistrationComponent import com.example.android.dagger.registration.enterdetails.EnterDetailsFragment import com.example.android.dagger.registration.termsandconditions.TermsAndConditionsFragment import dagger.BindsInstance import dagger.Component import javax.inject.Singleton /** * Created by hclee on 02/03/2020 */ @Singleton @Component(modules = [StorageModule::class, AppSubComponents::class]) interface AppComponent { @Component.Builder interface Builder { @BindsInstance // With @BindsInstance, the Context passed in will be available in the graph fun context(context: Context): Builder fun build(): AppComponent } // Classes that can be injected by this component fun inject(activity: MainActivity) // Expose RegistrationComponent builder from the graph fun registrationComponent(): RegistrationComponent.Builder fun loginComponent(): LoginComponent.Builder }
0
Kotlin
0
0
25e93d1a02fa9e36e2a7063e2e6129cf6e38491e
1,225
android-dagger
Apache License 2.0
src/test/java/com/tutuland/aoc2017/TestDay1.kt
gacordeiro
115,743,800
false
null
package com.tutuland.aoc2017 import org.amshove.kluent.shouldEqual import org.junit.Test class TestDay1 { @Test fun `firstCaptchaSolution invalid cases validation`() { "abc".firstCaptchaSolution shouldEqual "0" "1".firstCaptchaSolution shouldEqual "0" "".firstCaptchaSolution shouldEqual "0" } @Test fun `firstCaptchaSolution valid cases validation`() { "1122".firstCaptchaSolution shouldEqual "3" "1111".firstCaptchaSolution shouldEqual "4" "1234".firstCaptchaSolution shouldEqual "0" "91212129".firstCaptchaSolution shouldEqual "9" } @Test fun `firstCaptchaSolution for inputForDay1`() { inputForDay1.firstCaptchaSolution shouldEqual "1047" } @Test fun `secondCaptchaSolution invalid cases validation`() { "abc".secondCaptchaSolution shouldEqual "0" "1".secondCaptchaSolution shouldEqual "0" "".secondCaptchaSolution shouldEqual "0" } @Test fun `secondCaptchaSolution valid cases validation`() { "1212".secondCaptchaSolution shouldEqual "6" "1221".secondCaptchaSolution shouldEqual "0" "123425".secondCaptchaSolution shouldEqual "4" "123123".secondCaptchaSolution shouldEqual "12" "12131415".secondCaptchaSolution shouldEqual "4" } @Test fun `secondCaptchaSolution for inputForDay1`() { inputForDay1.secondCaptchaSolution shouldEqual "982" } }
0
Kotlin
0
0
dc880decebe5bb1c3f297b9864c491e1cec616b5
1,437
aoc2017
MIT License
analysis/analysis-api-impl-base/src/org/jetbrains/kotlin/analysis/api/impl/base/util/threadUtils.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.fir.utils import com.intellij.openapi.application.ApplicationManager import org.jetbrains.kotlin.analysis.api.tokens.HackToForceAllowRunningAnalyzeOnEDT import org.jetbrains.kotlin.analysis.api.tokens.hackyAllowRunningOnEdt @HackToForceAllowRunningAnalyzeOnEDT internal inline fun <R> runInPossiblyEdtThread(action: () -> R): R = when { !ApplicationManager.getApplication().isDispatchThread -> action() else -> hackyAllowRunningOnEdt(action) }
132
null
5074
40,992
57fe6721e3afb154571eb36812fd8ef7ec9d2026
705
kotlin
Apache License 2.0
data/src/test/java/com/igorvd/baseproject/data/movies/repository/MovieCloudRepositoryTest.kt
igorvilela28
143,054,565
false
null
package com.igorvd.baseproject.data.movies.repository import com.igorvd.baseproject.data.network.ApiClientBuilder import com.igorvd.baseproject.data.network.MovieDbApi import com.igorvd.baseproject.domain.movies.MovieSortBy import com.prosegur.genesis.mobile.data.utils.enqueue200Response import com.prosegur.genesis.mobile.data.utils.loadJsonFromResources import junit.framework.Assert.assertEquals import junit.framework.Assert.assertTrue import kotlinx.coroutines.experimental.runBlocking import okhttp3.mockwebserver.MockWebServer import org.junit.After import org.junit.Before import org.junit.Test /** * @author <NAME> * @since 31/07/2018 */ class MovieCloudRepositoryTest { private lateinit var server: MockWebServer private lateinit var movieDbApi: MovieDbApi private lateinit var movieCloudRepository: MovieCloudRepository private lateinit var classLoader: ClassLoader @Before fun setUp() { server = MockWebServer() server.start() val url = server.url("/").toString() movieDbApi = ApiClientBuilder.createService(MovieDbApi::class.java, url) movieCloudRepository = MovieCloudRepository(movieDbApi) classLoader = javaClass.classLoader } @After fun tearDown() { server.shutdown() } @Test fun `load movies`() = runBlocking { //region: arrange val moviesResponse = loadJsonFromResources( javaClass.classLoader, "MoviesResponse.json") server.enqueue200Response(moviesResponse) val configurationResponse = loadJsonFromResources( javaClass.classLoader, "ConfigurationResponse.json") server.enqueue200Response(configurationResponse) val genresResponse = loadJsonFromResources( javaClass.classLoader, "GenresResponse.json") server.enqueue200Response(genresResponse) //endregion //region: act val movies = movieCloudRepository.getMovies(1, MovieSortBy.POPULARITY) //endregion //region: assert assertTrue(movies.isNotEmpty()) val movie = movies[0] assertEquals(249, movie.voteCount) assertEquals(353081, movie.id) assertEquals(false, movie.video) assertEquals(7.5, movie.voteAverage) assertEquals("Missao: Impossivel - Efeito Fallout", movie.title) assertEquals(465.786, movie.popularity) assertEquals("https://image.tmdb.org/t/p/w92/kVv60GGRuh3kF6KI5Hn2T7QWWx0.jpg", movie.posterUrl) assertEquals("Mission: Impossible - Fallout", movie.originalTitle) assertEquals(listOf("Aventura", "Acao", "Thriller"), movie.genres) assertEquals("https://image.tmdb.org/t/p/w300/5qxePyMYDisLe8rJiBYX8HKEyv2.jpg", movie.backdropUrl) assertEquals(false, movie.adult) assertEquals("Quando uma importante missao nao sai como o planejado, Ethan Hunt (Tom Cruise) salva o mundo", movie.overview) assertEquals("2018-07-25", movie.releaseDate) //endregion } @Test fun `load movie trailer`() = runBlocking { //region: arrange val moviesResponse = loadJsonFromResources( javaClass.classLoader, "MovieVideosResponse.json") server.enqueue200Response(moviesResponse) //endregion //region: act val trailers = movieCloudRepository.getMovieTrailers(1) //endregion //region: assert assertTrue(trailers.isNotEmpty()) val trailer = trailers[0] assertEquals(1, trailer.movieId) assertEquals("Missao: Impossivel - Efeito Fallout 2018 - Trailer Dublado", trailer.name) assertEquals("https://www.youtube.com/watch?v=O17-POymi38", trailer.url) //endregion } }
1
null
2
5
bd8115888f736faddce90bada2fdc90f8b7e933c
3,807
The-Movie-DB-Client
Apache License 2.0
src/test/kotlin/nl/deltadak/ktemplate/KotlinTest.kt
marcphilipp
128,016,142
true
{"Kotlin": 7215}
@file:Suppress("MemberVisibilityCanBePrivate") package nl.deltadak.ktemplate import io.kotlintest.matchers.exactly import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.FunSpec class KotlinTest: FunSpec() { init { testCalculate() } /** With kotlintest 3.0.2, this test is also run! Hooray! */ fun testCalculate() = test("one plus one is two") { HelloKotlin().calculate().toDouble() shouldBe exactly(2.0) } }
0
Kotlin
0
0
5ecfb9829a31b64a6f4f329290601e5b75bc131c
461
kotlin-template-project
MIT License
OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/service/UserRefreshService.kt
OneSignal
33,515,679
false
{"Kotlin": 1777984, "Java": 49349, "Shell": 748}
package com.onesignal.user.internal.service import com.onesignal.common.IDManager import com.onesignal.core.internal.application.IApplicationService import com.onesignal.core.internal.config.ConfigModelStore import com.onesignal.core.internal.operations.IOperationRepo import com.onesignal.core.internal.startup.IStartableService import com.onesignal.session.internal.session.ISessionLifecycleHandler import com.onesignal.session.internal.session.ISessionService import com.onesignal.user.internal.identity.IdentityModelStore import com.onesignal.user.internal.operations.RefreshUserOperation // Ensure user is refreshed only when app // is in the foreground. This saves resources as there are a number of // events (such as push received or non-OneSignal events) that start // the app in the background but will never read/write any user // properties. class UserRefreshService( private val _applicationService: IApplicationService, private val _sessionService: ISessionService, private val _operationRepo: IOperationRepo, private val _configModelStore: ConfigModelStore, private val _identityModelStore: IdentityModelStore, ) : IStartableService, ISessionLifecycleHandler { private fun refreshUser() { if (IDManager.isLocalId(_identityModelStore.model.onesignalId) || !_applicationService.isInForeground) { return } _operationRepo.enqueue( RefreshUserOperation( _configModelStore.model.appId, _identityModelStore.model.onesignalId, ), ) } override fun start() = _sessionService.subscribe(this) override fun onSessionStarted() = refreshUser() override fun onSessionActive() { } override fun onSessionEnded(duration: Long) { } }
70
Kotlin
368
604
7e68c1d6bdc48b1786926cc443dcf532d592e4ec
1,784
OneSignal-Android-SDK
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/digitalprisonreportinglib/controller/model/MetricDefinition.kt
ministryofjustice
697,333,274
false
{"Kotlin": 491558}
package uk.gov.justice.digital.hmpps.digitalprisonreportinglib.controller.model data class MetricDefinition( val id: String, val name: String, val display: String, val description: String, val visualisationType: List<DashboardChartTypeDefinition>, val specification: List<MetricSpecificationDefinition>, ) data class MetricSpecificationDefinition( val name: String, val display: String, val unit: String? = null, )
3
Kotlin
1
2
bdbfa4adfe0a687378b5607da31b9bc3b57fd0cf
435
hmpps-digital-prison-reporting-lib
MIT License
android/src/main/java/com/westmangaextensions/utils/PostsView.kt
khalisafkari
302,327,244
false
null
package com.westmangaextensions.utils import com.facebook.react.bridge.ReadableArray import com.facebook.react.bridge.ReadableMap import com.facebook.react.bridge.WritableNativeArray import com.facebook.react.bridge.WritableNativeMap import org.jsoup.Jsoup import org.jsoup.select.Elements import java.io.IOException class PostsView { private val url = API() @Throws(IOException::class) fun getPostsViewJSON(uri: String): ReadableMap { val map = WritableNativeMap() val html = url.run(uri) val document = Jsoup.parse(html) map.putArray("image",parseImageJSON(document.select("div[id=readerarea] p img"))) map.putString("prev", document.select(".nextprev a[rel=prev]").eq(0).attr("href")) map.putString("next", document.select(".nextprev a[rel=next]").eq(0).attr("href")) return map } private fun parseImageJSON(elements: Elements):ReadableArray { val array = WritableNativeArray() for (image in elements) { array.pushString(image.attr("src")) } return array } }
0
Kotlin
0
1
b172639b625a7dcf459ce9cc950d08170eb13d8a
1,044
westmanga-extensions
MIT License
platform/android/core-persistance/src/main/java/io/dotanuki/platform/android/core/persistance/LocalStorage.kt
dotanuki-labs
192,096,771
false
null
package io.dotanuki.platform.android.core.persistance interface LocalStorage { suspend fun lastSearches(): List<String> fun registerNewSearch(term: String) fun destroy() }
2
Kotlin
37
452
cb76e46a4199664868757892c9ca865bec90c6b9
188
norris
MIT License
app/src/main/kotlin/com/xiaocydx/sample/transition/enter/JankFragment.kt
xiaocydx
460,257,515
false
{"Kotlin": 1365337}
package com.xiaocydx.sample.transition.enter import android.os.Bundle import android.view.View import androidx.lifecycle.flowWithLifecycle import com.xiaocydx.sample.viewLifecycle import com.xiaocydx.sample.viewLifecycleScope import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach /** * 模拟加载列表数据的场景,复现Fragment过渡动画卡顿问题 * * @author xcc * @date 2023/5/21 */ class JankFragment : TransitionFragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.state .flowWithLifecycle(viewLifecycle) .distinctUntilChanged() .onEach { state -> when (state) { TransitionState.LOADING -> { loadingAdapter.show() } TransitionState.CONTENT -> { loadingAdapter.hide() contentAdapter.show() } } } .launchIn(viewLifecycleScope) } }
0
Kotlin
0
9
47debfb87a9d2834c04f69daa66a3cab63343ab2
1,139
CXRV
Apache License 2.0
client/slack-spring-api-client/src/test/kotlin/io/olaph/slack/client/spring/IntegrationTests.kt
gitter-badger
181,514,383
true
{"Kotlin": 338538}
package io.olaph.slack.client.spring import io.olaph.slack.dto.jackson.common.types.Conversation import io.olaph.slack.dto.jackson.group.conversations.ConversationCreateRequest import io.olaph.slack.dto.jackson.group.conversations.ConversationMembersRequest import io.olaph.slack.dto.jackson.group.conversations.ConversationsListRequest import io.olaph.slack.dto.jackson.group.conversations.ConversationsOpenRequest import io.olaph.slack.dto.jackson.group.conversations.SuccessfulConversationOpenResponse import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.slf4j.LoggerFactory class IntegrationTests { private val client = DefaultSlackClient() companion object { val LOG = LoggerFactory.getLogger(IntegrationTests::class.java) } @Test @DisplayName("Integration Suite") fun integrationSuite() { val channelId = createConversation() val memberIds = membersConversations(channelId) val listConversations = listConversations() val openConversation = openConversation(memberIds) } /** * returns a channel id */ fun createConversation(): String { val response = client.conversation().create(TestConfig.token()) .with(ConversationCreateRequest(name = "test-${TestConfig.buildNumber()}")) .onFailure { LOG.info("{}", it) } .onSuccess { LOG.info("{}", it) } .invoke() Assertions.assertNotNull(response.success) return response.success!!.channel.id } /** * returns memberIds */ fun membersConversations(channelId: String): List<String> { val response = client.conversation().members(TestConfig.token()) .with(ConversationMembersRequest(channelId = channelId)) .onFailure { LOG.info("{}", it) } .onSuccess { LOG.info("{}", it) } .invoke() Assertions.assertNotNull(response.success) return response.success!!.memberIds } /** * returns Conversations */ fun listConversations(): List<Conversation> { val response = client.conversation().list(TestConfig.token()) .with(ConversationsListRequest()) .onFailure { LOG.info("{}", it) } .onSuccess { LOG.info("{}", it) } .invoke() Assertions.assertNotNull(response.success) return response.success!!.channels } /** * returns channel */ fun openConversation(memberIds: List<String>): SuccessfulConversationOpenResponse.Channel { val response = client.conversation().open(TestConfig.token()) .with(ConversationsOpenRequest(users = memberIds)) .onFailure { LOG.info("{}", it) } .onSuccess { LOG.info("{}", it) } .invoke() Assertions.assertNotNull(response.success) return response.success!!.channel } }
0
Kotlin
0
0
429fa4293cb5c5bf67d7d543f92d4cc7a81eea4f
3,025
slack-spring-boot-starter
MIT License
src/main/kotlin/venus/assembler/pseudos/JR.kt
ics-jku
470,084,492
false
null
package venus.assembler.pseudos import venus.assembler.AssemblerPassOne import venus.assembler.LineTokens import venus.assembler.PseudoWriter /** Writes pseudoinstruction `jr register` */ object JR : PseudoWriter() { override operator fun invoke(args: LineTokens, state: AssemblerPassOne): List<LineTokens> { checkArgsLength(args, 2) return listOf(listOf("jalr", "x0", args[1], "0")) } }
1
null
1
4
429d323b98a33db67074e44f164c8d1044f406de
413
venus
MIT License
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/exception/http/CwaWebException.kt
covid-be-app
281,650,940
false
null
package de.rki.coronawarnapp.exception.http import de.rki.coronawarnapp.exception.reporting.ErrorCodes import de.rki.coronawarnapp.exception.reporting.ReportedIOException open class CwaWebException(statusCode: Int) : ReportedIOException( ErrorCodes.CWA_WEB_REQUEST_PROBLEM.code, "error during web request, http status $statusCode" ) open class CwaServerError(val statusCode: Int) : CwaWebException(statusCode) { init { if (statusCode !in 500..599) throw IllegalArgumentException("a server error has to have code 5xx") } } open class CwaClientError(val statusCode: Int) : CwaWebException(statusCode) { init { if (statusCode !in 400..499) throw IllegalArgumentException("a client error has to have code 4xx") } } open class CwaSuccessResponseWithCodeMismatchNotSupportedError(val statusCode: Int) : CwaWebException(statusCode) open class CwaInformationalNotSupportedError(val statusCode: Int) : CwaWebException(statusCode) open class CwaRedirectNotSupportedError(val statusCode: Int) : CwaWebException(statusCode) class CwaUnknownHostException : CwaWebException(901) class BadRequestException : CwaClientError(400) class UnauthorizedException : CwaClientError(401) class ForbiddenException : CwaClientError(403) class NotFoundException : CwaClientError(404) class ConflictException : CwaClientError(409) class GoneException : CwaClientError(410) class UnsupportedMediaTypeException : CwaClientError(415) class TooManyRequestsException : CwaClientError(429) class InternalServerErrorException : CwaServerError(500) class NotImplementedException : CwaServerError(501) class BadGatewayException : CwaServerError(502) class ServiceUnavailableException : CwaServerError(503) class GatewayTimeoutException : CwaServerError(504) class HTTPVersionNotSupported : CwaServerError(505) class NetworkAuthenticationRequiredException : CwaServerError(511) class NetworkReadTimeoutException : CwaServerError(598) class NetworkConnectTimeoutException : CwaServerError(599)
5
null
3
55
d556b0b9f29e76295b59be2a1ba89bc4cf6ec33b
2,026
cwa-app-android
Apache License 2.0
ktor-oauth2-react-client/ktor-oauth2-react-client-frontend-api/src/main/kotlin/com/onlyteo/sandbox/routes/GreetingRoutes.kt
onlyteo
798,100,309
false
{"Kotlin": 14112, "HTML": 9051, "CSS": 1817}
package com.onlyteo.sandbox.routes import com.onlyteo.sandbox.config.Config import com.onlyteo.sandbox.service.GreetingService import io.ktor.client.HttpClient import io.ktor.server.application.call import io.ktor.server.auth.authenticate import io.ktor.server.response.respond import io.ktor.server.routing.Route import io.ktor.server.routing.get fun Route.greetingRouting(config: Config, httpClient: HttpClient) { val greetingService = GreetingService(config.app.integrations.greetingService, httpClient) authenticate("spring-authorization-server") { get("/api/greeting") { val name = call.parameters["name"] val greeting = greetingService.getGreeting(name) call.respond(greeting) } } }
0
Kotlin
0
0
0b19285d6c6b5ab4da63c0a74cc6c48496856a95
756
ktor-sandbox
Apache License 2.0
app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/SectionViewHolder.kt
TachiWeb
66,624,691
true
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Markdown": 4, "Proguard": 1, "Kotlin": 253, "XML": 171, "Java": 9}
package eu.kanade.tachiyomi.ui.recent_updates import android.support.v7.widget.RecyclerView import android.text.format.DateUtils import android.text.format.DateUtils.DAY_IN_MILLIS import android.view.View import kotlinx.android.synthetic.main.item_recent_chapter_section.view.* import java.util.* class SectionViewHolder(private val view: View) : RecyclerView.ViewHolder(view) { /** * Current date */ private val now = Date().time /** * Set value of section header * * @param date of section header */ fun onSetValues(date: Date) { view.section_text.text = DateUtils.getRelativeTimeSpanString(date.time, now, DAY_IN_MILLIS) } }
0
Kotlin
0
5
9dac958ed1414338dfff825c8d7dbe78fb98209a
689
tachiyomi
Apache License 2.0
src/main/kotlin/dev/realmkit/game/domain/stat/extension/validator/StatValidator.kt
RealmKit
590,912,533
false
{"Kotlin": 376600}
/* * Copyright (c) 2023 RealmKit * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package dev.realmkit.game.domain.stat.extension.validator import dev.realmkit.game.domain.stat.document.Stat import io.konform.validation.Validation /** * # [StatValidator] * [Stat] validations */ object StatValidator { /** * ## [validation] * [Stat] -> [Validation] object */ val validation: Validation<Stat> = Validation { Stat::base required { run(StatBaseValidator.validation) } Stat::rate required { run(StatRateValidator.validation) } Stat::multiplier required { run(StatMultiplierValidator.validation) } Stat::progression required { run(StatProgressionValidator.validation) } } }
28
Kotlin
0
0
75824606b7edf018adf82af1cc588fe25c5f9de5
1,759
game
MIT License
src/test/java/guru/springframework/sfgpetclinic/services/map/OwnerMapServiceTest.kt
adrianbadarau
179,070,960
true
{"Kotlin": 47191, "Java": 2201}
package guru.springframework.sfgpetclinic.services.map import guru.springframework.sfgpetclinic.model.Owner import guru.springframework.sfgpetclinic.model.PetType import guru.springframework.sfgpetclinic.services.PetService import guru.springframework.sfgpetclinic.services.PetTypeService import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test internal class OwnerMapServiceTest { var petTypeService = PetTypeMapService() var petService = PetMapService() val ownerMapService = OwnerMapService(petTypeService, petService) @DisplayName("Verify Zero Owners") @Test fun ownersAreZero() { val ownerCount = ownerMapService.findAll().size assertThat(ownerCount).isZero() } @DisplayName("Pet Type - ") @Nested internal inner class TestCreatePetTypes { @BeforeEach fun setUp() { val petType = PetType(1L, "Dog") val petType2 = PetType(2L, "Cat") petTypeService.save(petType) petTypeService.save(petType2) } @DisplayName("Test Pet Count") @Test fun testPetCount() { val petTypeCount = petTypeService.findAll().size assertThat(petTypeCount).isNotZero().isEqualTo(2) } @DisplayName("Save Owners Tests - ") @Nested internal inner class SaveOwnersTests { @BeforeEach fun setUp() { ownerMapService.save(Owner(1L, "Before", "Each")) } @DisplayName("Save Owner") @Test fun saveOwner() { val owner = Owner(2L, "Joe", "Buck") val savedOwner = ownerMapService.save(owner) assertThat(savedOwner).isNotNull() } @DisplayName("Save Owners Tests - ") @Nested internal inner class FindOwnersTests { @DisplayName("Find Owner") @Test fun findOwner() { val foundOwner = ownerMapService.findById(1L) assertThat(foundOwner).isNotNull() } @DisplayName("Find Owner Not Found") @Test fun findOwnerNotFound() { val foundOwner:Owner? = ownerMapService.findById(2L) assertThat(foundOwner).isNull() } } } } @DisplayName("Verify Still Zero Owners") @Test fun ownersAreStillZero() { val ownerCount = ownerMapService.findAll().size assertThat(ownerCount).isZero() } }
0
Kotlin
0
0
cbd206ac8f44483ae573ab7f009dc239c9cea9b0
2,793
testing-java-junit5
Apache License 2.0
libnavigation-core/src/test/java/com/mapbox/navigation/core/routerefresh/RouteRefreshControllerTest.kt
k4anubhav
439,334,238
false
{"Gradle": 39, "Markdown": 14, "Java Properties": 2, "Shell": 5, "Ignore List": 24, "Batchfile": 2, "EditorConfig": 1, "Makefile": 1, "YAML": 3, "XML": 380, "INI": 33, "Proguard": 16, "Text": 32, "Kotlin": 754, "CODEOWNERS": 1, "JSON": 53, "Java": 5, "CSS": 1, "Python": 4}
package com.mapbox.navigation.core.routerefresh import com.mapbox.api.directions.v5.models.DirectionsRoute import com.mapbox.api.directions.v5.models.RouteOptions import com.mapbox.base.common.logger.Logger import com.mapbox.base.common.logger.model.Message import com.mapbox.geojson.Point import com.mapbox.navigation.base.route.RouteRefreshCallback import com.mapbox.navigation.base.route.RouteRefreshOptions import com.mapbox.navigation.core.directions.session.DirectionsSession import com.mapbox.navigation.core.trip.session.TripSession import com.mapbox.navigation.navigator.internal.MapboxNativeNavigatorImpl.OFFLINE_UUID import com.mapbox.navigation.testing.MainCoroutineRule import io.mockk.Runs import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.slot import io.mockk.unmockkStatic import io.mockk.verify import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @ExperimentalCoroutinesApi class RouteRefreshControllerTest { @get:Rule val coroutineRule = MainCoroutineRule() private val routeRefreshCallbackSlot = slot<RouteRefreshCallback>() private val directionsSession: DirectionsSession = mockk(relaxUnitFun = true) { every { routes } returns listOf(mockk()) } private val tripSession: TripSession = mockk() private val logger: Logger = mockk { every { w(any(), any()) } just Runs every { i(any(), any()) } just Runs every { e(any(), any()) } just Runs every { e(any(), any(), any()) } just Runs } private val routeOptions: RouteOptions = mockk { every { coordinatesList() } returns listOf(Point.fromLngLat(0.0, 0.0), Point.fromLngLat(1.1, 1.1)) } private val validRoute: DirectionsRoute = mockk { every { routeOptions() } returns routeOptions every { requestUuid() } returns "test_uuid" } private val routeRefreshOptions = RouteRefreshOptions.Builder().build() private val routeRefreshController = RouteRefreshController( routeRefreshOptions, directionsSession, tripSession, logger ) private val requestId = 1L @Before fun setup() { mockkStatic("com.mapbox.navigation.base.extensions.RouteOptionsExtensions") every { tripSession.getRouteProgress() } returns mockk { every { currentLegProgress } returns mockk { every { legIndex } returns 0 } } every { tripSession.route } returns validRoute every { directionsSession.requestRouteRefresh(any(), any(), capture(routeRefreshCallbackSlot)) } returns requestId } @Test fun `should refresh route every 5 minutes by default`() = coroutineRule.runBlockingTest { every { routeOptions.enableRefresh() } returns true routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(15)) routeRefreshController.stop() verify(exactly = 3) { directionsSession.requestRouteRefresh(any(), any(), any()) } } @Test fun `should refresh route according to options`() = coroutineRule.runBlockingTest { val routeRefreshController = RouteRefreshController( RouteRefreshOptions.Builder() .intervalMillis(TimeUnit.MINUTES.toMillis(1)) .build(), directionsSession, tripSession, logger ) every { routeOptions.enableRefresh() } returns true routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(15)) routeRefreshController.stop() verify(exactly = 15) { directionsSession.requestRouteRefresh(any(), any(), any()) } } @Test fun `should refresh route with correct properties`() = coroutineRule.runBlockingTest { every { routeOptions.enableRefresh() } returns true routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(6)) routeRefreshController.stop() verify(exactly = 1) { directionsSession.requestRouteRefresh(any(), any(), any()) } } @Test fun `should refresh route with any annotation`() = coroutineRule.runBlockingTest { every { routeOptions.enableRefresh() } returns true routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(6)) routeRefreshController.stop() verify(exactly = 1) { directionsSession.requestRouteRefresh(any(), any(), any()) } } @Test fun `should log warning when route is not supported`() = coroutineRule.runBlockingTest { every { routeOptions.enableRefresh() } returns true every { validRoute.requestUuid() } returns null routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(6)) routeRefreshController.stop() verify(exactly = 0) { directionsSession.requestRouteRefresh(any(), any(), any()) } verify(exactly = 1) { logger.w(RouteRefreshController.TAG, any()) } } @Test fun `cancel request when stopped (nothing started)`() { routeRefreshController.stop() verify(exactly = 0) { directionsSession.cancelRouteRefreshRequest(any()) } } @Test fun `cancel request when stopped`() = coroutineRule.runBlockingTest { every { routeOptions.enableRefresh() } returns true routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(6)) routeRefreshController.stop() verify(exactly = 1) { directionsSession.cancelRouteRefreshRequest(requestId) } } @Test fun `do not send a request when route options is null`() { every { validRoute.routeOptions() } returns null routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(routeRefreshOptions.intervalMillis * 2) routeRefreshController.stop() verify(exactly = 0) { directionsSession.requestRouteRefresh(any(), any(), any()) } } @Test fun `do not send a request when uuid is empty`() { every { routeOptions.enableRefresh() } returns true every { validRoute.requestUuid() } returns "" routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(routeRefreshOptions.intervalMillis * 2) routeRefreshController.stop() verify(exactly = 0) { directionsSession.requestRouteRefresh(any(), any(), any()) } } @Test fun `do not send a request when uuid is offline`() { every { routeOptions.enableRefresh() } returns true every { validRoute.requestUuid() } returns OFFLINE_UUID routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(routeRefreshOptions.intervalMillis * 2) routeRefreshController.stop() verify(exactly = 0) { directionsSession.requestRouteRefresh(any(), any(), any()) } } @Test fun `should cancel the previous request before starting a new one`() { every { routeOptions.enableRefresh() } returns true // Create 2 requests. // Let the first one create a requestId equal to 1. // Cancel during the second call, and then we expect the first request to be canceled. val countDownLatch = CountDownLatch(2) every { directionsSession.requestRouteRefresh(any(), any(), any()) } answers { if (countDownLatch.count == 1L) { routeRefreshController.restart() } countDownLatch.countDown() countDownLatch.count } routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(routeRefreshOptions.intervalMillis * 2) countDownLatch.await() routeRefreshController.stop() verify(exactly = 2) { directionsSession.requestRouteRefresh(any(), any(), any()) } verify { directionsSession.cancelRouteRefreshRequest(1) } } @Test fun `restart should cancel outgoing requests and restart the refresh interval`() { every { routeOptions.enableRefresh() } returns true // We're expecting 2 requests in this test. The interruptions will // happen in between the requests. val countDownLatch = CountDownLatch(2) every { directionsSession.requestRouteRefresh(any(), any(), any()) } answers { countDownLatch.countDown() countDownLatch.count } routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy( (routeRefreshOptions.intervalMillis * 1.9).toLong() ) routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy( (routeRefreshOptions.intervalMillis * 1.9).toLong() ) countDownLatch.await() // If the timer did not restart, the count would be 3. verify(exactly = 2) { directionsSession.requestRouteRefresh(any(), any(), any()) } verify { directionsSession.cancelRouteRefreshRequest(1) } // Clean up coroutines routeRefreshController.stop() } @Test fun `clear the request when there is a successful response`() { every { routeOptions.enableRefresh() } returns true routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(routeRefreshOptions.intervalMillis) routeRefreshCallbackSlot.captured.onRefresh(mockk()) routeRefreshController.stop() verify(exactly = 1) { directionsSession.requestRouteRefresh(any(), any(), any()) } verify(exactly = 0) { directionsSession.cancelRouteRefreshRequest(any()) } } @Test fun `clear the request when there is a failure response`() { every { routeOptions.enableRefresh() } returns true routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(routeRefreshOptions.intervalMillis) routeRefreshCallbackSlot.captured.onError( mockk { every { message } returns "test error" every { throwable } returns mockk() } ) routeRefreshController.stop() verify(exactly = 1) { directionsSession.requestRouteRefresh(any(), any(), any()) } verify(exactly = 0) { directionsSession.cancelRouteRefreshRequest(any()) } } @Test fun `should log warning when route options are null`() = coroutineRule.runBlockingTest { every { validRoute.routeOptions() } returns null routeRefreshController.restart() coroutineRule.testDispatcher.advanceTimeBy(TimeUnit.MINUTES.toMillis(6)) routeRefreshController.stop() verify(exactly = 0) { directionsSession.requestRouteRefresh(any(), any(), any()) } verify(exactly = 1) { logger.w( RouteRefreshController.TAG, Message( """ Unable to refresh the route because routeOptions are missing. Use #fromJson(json, routeOptions, requestUuid) when deserializing the route or route response. """.trimIndent() ) ) } } @After fun tearDown() { unmockkStatic("com.mapbox.navigation.base.extensions.RouteOptionsExtensions") } }
1
null
1
1
c7fd13f6c363e0902cf2e12d55d4bc3647700400
11,737
mapbox-navigation-android
Apache License 2.0
app/src/main/java/com/oxyethylene/easynote/common/arrays/SpinnerItemTexts.kt
PolyOxyethylene
738,671,054
false
{"Kotlin": 336864, "Java": 106555, "JavaScript": 10698, "CSS": 1739, "HTML": 414}
package com.oxyethylene.easynote.common.arrays import com.oxyethylene.easynote.R /** * Created with IntelliJ IDEA. * @Project : EasyNoteDemo * @Package : com.oxyethylene.easynote.common.arrays * @ClassName : SpinnerItemTexts.java * @createTime : 2024/2/19 13:55 * @version : 1.0 * @author : Polyoxyethylene * @Description : */ /** * 设置标题文字大小的菜单的选项 */ val headerSizeList = ArrayList<Pair<Int, String>>().apply { add(Pair(R.mipmap.ic_set_heading_btn, "默认图标")) add(Pair(R.mipmap.ic_set_heading_1, "一号标题")) add(Pair(R.mipmap.ic_set_heading_2, "二号标题")) add(Pair(R.mipmap.ic_set_heading_3, "三号标题")) add(Pair(R.mipmap.ic_set_heading_4, "四号标题")) add(Pair(R.mipmap.ic_set_heading_5, "五号标题")) add(Pair(R.mipmap.ic_set_heading_6, "六号标题")) } /** * 设置文本对齐方式的菜单选项 */ val textAlignList = ArrayList<Pair<Int, String>>().apply { add(Pair(R.mipmap.ic_set_align_justify, "默认图标")) add(Pair(R.mipmap.ic_set_align_center, "居中对齐")) add(Pair(R.mipmap.ic_set_align_justify, "两端对齐")) add(Pair(R.mipmap.ic_set_align_left, "左对齐")) add(Pair(R.mipmap.ic_set_align_right, "右对齐")) } /** * 插入列表的菜单选项 */ val listInsertList = ArrayList<Pair<Int, String>>().apply { add(Pair(R.mipmap.ic_insert_list, "默认图标")) add(Pair(R.mipmap.ic_insert_list_ul, "无序列表")) add(Pair(R.mipmap.ic_insert_list_ol, "有序列表")) }
0
Kotlin
0
1
97992bfe8eeb4aa6d4ea69a98971422e8700ec9f
1,456
EasyNote
Apache License 2.0
wearApp/src/main/java/dev/johnoreilly/confetti/wear/sessions/navigation/sessionsDestination.kt
joreilly
436,024,503
false
null
@file:OptIn(ExperimentalHorologistApi::class) package dev.johnoreilly.confetti.wear.sessions.navigation import androidx.lifecycle.SavedStateHandle import androidx.navigation.NavBackStackEntry import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.navArgument import androidx.navigation.navDeepLink import com.google.android.horologist.annotations.ExperimentalHorologistApi import com.google.android.horologist.compose.navscaffold.scrollable import dev.johnoreilly.confetti.navigation.ConferenceDayKey import dev.johnoreilly.confetti.navigation.SessionDetailsKey import dev.johnoreilly.confetti.wear.navigation.ConfettiNavigationDestination import dev.johnoreilly.confetti.wear.sessiondetails.navigation.SessionDetailsDestination import dev.johnoreilly.confetti.wear.sessions.SessionsRoute import kotlinx.datetime.LocalDate import kotlinx.datetime.toLocalDate object SessionsDestination : ConfettiNavigationDestination { const val dateArg = "date" const val conferenceArg = "conference" override val route = "sessions_route/{$conferenceArg}/{${dateArg}}" override val destination = "sessions_destination" fun createNavigationRoute(date: ConferenceDayKey): String { return "sessions_route/${date.conference}/${date.date}" } fun fromNavArgs(entry: NavBackStackEntry): ConferenceDayKey { val arguments = entry.arguments!! val dateString = entry.arguments?.getString(dateArg)!! return ConferenceDayKey( arguments.getString(SessionDetailsDestination.conferenceArg)!!, LocalDate.parse(dateString) ) } fun fromNavArgs(savedStateHandle: SavedStateHandle): ConferenceDayKey { return ConferenceDayKey( savedStateHandle[conferenceArg]!!, savedStateHandle.get<String>(dateArg)!!.toLocalDate() ) } } fun NavGraphBuilder.sessionsGraph( navigateToSession: (SessionDetailsKey) -> Unit ) { scrollable( route = SessionsDestination.route, arguments = listOf( navArgument(SessionsDestination.dateArg) { type = NavType.StringType } ), deepLinks = listOf( navDeepLink { uriPattern = "confetti://confetti/sessions/{${SessionsDestination.dateArg}}" } ) ) { SessionsRoute( navigateToSession = navigateToSession, columnState = it.columnState ) } }
36
Kotlin
44
443
039c4aadd82f7029df027a6332a4743a4470dbc8
2,489
Confetti
Apache License 2.0
build-logic/build-update-utils/src/main/kotlin/gradlebuild/buildutils/tasks/SubprojectsInfo.kt
gradle
302,322
false
{"Groovy": 33309780, "Java": 30797028, "Kotlin": 3552953, "C++": 888505, "JavaScript": 76180, "HTML": 15779, "CSS": 13668, "Shell": 12214, "XSLT": 7121, "C": 5785, "Scala": 2817, "Gherkin": 192, "Python": 58, "Brainfuck": 54}
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gradlebuild.buildutils.tasks import com.google.gson.GsonBuilder import gradlebuild.buildutils.model.GradleSubproject import org.gradle.api.DefaultTask import org.gradle.api.tasks.Internal import org.gradle.work.DisableCachingByDefault import java.io.File @DisableCachingByDefault(because = "Abstract super-class, not to be instantiated directly") abstract class SubprojectsInfo : DefaultTask() { private val subprojectsFolder = project.layout.projectDirectory.dir("subprojects") @get:Internal protected val subprojectsJson = project.layout.projectDirectory.file(".teamcity/subprojects.json") protected fun generateSubprojectsJson(): String { val subprojects = generateSubprojects() val gson = GsonBuilder().setPrettyPrinting().create() return gson.toJson(subprojects) + '\n' } private fun generateSubprojects(): List<GradleSubproject> { return subprojectsFolder.asFile.listFiles(File::isDirectory)!! .filter { File(it, "build.gradle.kts").exists() || File(it, "build.gradle").exists() } .sorted() .map(this::generateSubproject) } private fun generateSubproject(subprojectDir: File): GradleSubproject { return GradleSubproject( subprojectDir.name, subprojectDir.name, subprojectDir.hasDescendantDir("src/test"), subprojectDir.hasDescendantDir("src/integTest"), subprojectDir.hasDescendantDir("src/crossVersionTest") ) } private fun File.hasDescendantDir(descendant: String) = resolve(descendant).isDirectory }
2,663
Groovy
4552
15,640
3fde2e4dd65124d0f3b2ef42f7e93446ccd7cced
2,300
gradle
Apache License 2.0
api/src/main/kotlin/br/com/strn/erp/api/database/entities/financeiro/MovConta.kt
IvoSestren
331,951,557
false
null
package br.com.strn.erp.api.database.entities.financeiro import br.com.strn.erp.api.database.entities.BaseEntity import br.com.strn.erp.api.database.util.newHandle import org.hibernate.annotations.Where import java.time.LocalDateTime import javax.persistence.* @Entity @Table(name = "movconta") @Where(clause = "deleted_at is null") class MovConta( var data: LocalDateTime?, var descricao: String?, @OneToMany var divisoes: List<MovContaDiv>? = null, @Id @SequenceGenerator(name = "sq_movconta", sequenceName = "sq_movconta", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sq_movconta") @Column(name = "id", unique = true, nullable = false) var id: Long? = null, override var handle: String? = newHandle() ) : BaseEntity(handle = handle)
0
Kotlin
0
0
a955b4a4b8b4e4f2b746bbe5bc4fe3674ab9caf1
861
erp_001
The Unlicense
protocol/osrs-221-desktop/src/main/kotlin/net/rsprot/protocol/game/incoming/codec/misc/client/MembershipPromotionEligibilityDecoder.kt
blurite
771,753,685
false
{"Kotlin": 1458066}
package net.rsprot.protocol.game.incoming.codec.misc.client import net.rsprot.buffer.JagByteBuf import net.rsprot.protocol.ClientProt import net.rsprot.protocol.game.incoming.misc.client.MembershipPromotionEligibility import net.rsprot.protocol.game.incoming.prot.GameClientProt import net.rsprot.protocol.message.codec.MessageDecoder import net.rsprot.protocol.metadata.Consistent import net.rsprot.protocol.tools.MessageDecodingTools @Consistent public class MembershipPromotionEligibilityDecoder : MessageDecoder<MembershipPromotionEligibility> { override val prot: ClientProt = GameClientProt.MEMBERSHIP_PROMOTION_ELIGIBILITY override fun decode( buffer: JagByteBuf, tools: MessageDecodingTools, ): MembershipPromotionEligibility { val eligibleForIntroductoryPrice = buffer.g1() val eligibleForTrialPurchase = buffer.g1() return MembershipPromotionEligibility( eligibleForIntroductoryPrice, eligibleForTrialPurchase, ) } }
4
Kotlin
6
7
b72a9ddbbf607e357b783c4c8a1f5dc91b5de4f0
1,018
rsprot
MIT License
app/src/main/java/com/example/cetl/settingScreen/myTeam/teamInspection/MemberStats.kt
Bhavyansh03-tech
840,319,498
false
{"Kotlin": 596261}
package com.example.cetl.settingScreen.myTeam.teamInspection import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import com.example.cetl.adapter.teamAdapter.TeamPlayerCardAdapter import com.example.cetl.databinding.FragmentMemberStatsBinding import com.example.cetl.model.user.PlayerCardList import com.example.cetl.settingScreen.myTeam.teamLeader.TeamLeaderActivity import com.google.firebase.firestore.FirebaseFirestore class MemberStats : Fragment() { private lateinit var binding: FragmentMemberStatsBinding private lateinit var adapter : TeamPlayerCardAdapter private lateinit var memberList: ArrayList<PlayerCardList> private var db = FirebaseFirestore.getInstance() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentMemberStatsBinding.inflate(layoutInflater, container, false) memberList = arrayListOf() // Access the parent teamMemberActivity val teamMember = activity as? TeamMember // Check if the parent activity is actually a teamMemberActivity and if data is available if (teamMember != null) { val teamId = teamMember.intent.getStringExtra("teamId").toString() loadTeamMemberData(teamId) } // Access the parent TeamLeaderActivity val teamLeader = activity as? TeamLeaderActivity // Check if the parent activity is actually a TeamLeaderActivity and if data is available if (teamLeader != null) { val teamId = teamLeader.intent.getStringExtra("teamId").toString() loadTeamLeaderData(teamId) } return binding.root } private fun loadTeamLeaderData(teamId: String) { db.collection("teams").document(teamId).collection("team_members") .get() .addOnSuccessListener { documents -> memberList.clear() for (document in documents) { val teamMember = document.toObject(PlayerCardList::class.java) memberList.add(teamMember) } adapter = TeamPlayerCardAdapter(memberList) binding.recyclerView.layoutManager = LinearLayoutManager(requireContext()) binding.recyclerView.adapter = adapter adapter.notifyDataSetChanged() } .addOnFailureListener { // Handle the error in retrieving the data from Firestore // Log or display the error message } } private fun loadTeamMemberData(teamId: String) { db.collection("teams").document(teamId).collection("team_members") .get() .addOnSuccessListener { documents -> memberList.clear() for (document in documents) { val teamMember = document.toObject(PlayerCardList::class.java) memberList.add(teamMember) } adapter = TeamPlayerCardAdapter(memberList) binding.recyclerView.layoutManager = LinearLayoutManager(requireContext()) binding.recyclerView.adapter = adapter adapter.notifyDataSetChanged() } .addOnFailureListener { // Handle the error in retrieving the data from Firestore // Log or display the error message } } }
0
Kotlin
0
0
ea288888f95b0465b4af79d26ce2b5baa1258c61
3,624
CETL
MIT License
vscode/src/jsMain/kotlin/vscode/window/createTextEditorDecorationType.kt
lppedd
761,812,661
false
{"Kotlin": 1887051}
@file:JsModule("vscode") @file:JsQualifier("window") package vscode.window import vscode.DecorationRenderOptions import vscode.TextEditorDecorationType /** * Create a TextEditorDecorationType that can be used to add decorations to text editors. * * @param options Rendering options for the decoration type. * @return A new decoration type instance. */ external fun createTextEditorDecorationType(options: DecorationRenderOptions): TextEditorDecorationType
0
Kotlin
0
3
0f493d3051afa3de2016e5425a708c7a9ed6699a
464
kotlin-externals
MIT License
app/src/main/java/com/image/mozaic/genericRecyclerView/GenericRecyclerAdapter.kt
mihaigabriel1992
138,795,805
false
{"Kotlin": 20542}
package com.image.mozaic.genericRecyclerView import android.databinding.DataBindingUtil import android.databinding.ViewDataBinding import android.support.v7.util.DiffUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup /** * Default Adapter should be used for most recyclerviews lists * */ class GenericRecyclerViewAdapter<T : BaseRecyclerViewItem>(private val loadingItem: LoadingItem? = LoadingItem()) : RecyclerView.Adapter<BaseViewHolder>() { private val data = mutableListOf<T>() private var isLoading: Boolean = false var clickListener: ((T) -> Unit)? = null @Suppress("UNCHECKED_CAST") private val LOADING_ITEM = loadingItem as T override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder { val binding: ViewDataBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), viewType, parent, false) val viewHolder = BaseViewHolder(binding) viewHolder.itemView.isFocusableInTouchMode = false viewHolder.itemView.isFocusable = false viewHolder.itemView.setOnClickListener { val position = viewHolder.adapterPosition if (position != RecyclerView.NO_POSITION && position < data.size) { val item = data[position] if (!item.shouldIgnoreClickListener()) { clickListener?.invoke(item) } } } return viewHolder } override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { val obj = data[position] holder.bind(obj) } override fun getItemCount(): Int { return data.size } override fun getItemViewType(position: Int) = data[position].provideLayout() fun prepareToLoadNextPage() { if (!isLoading) { isLoading = true data.add(LOADING_ITEM) this.notifyItemInserted(data.size - 1) } } fun loadingNextPageFinished() { if (isLoading) { isLoading = false val lastIndex = data.indexOf(LOADING_ITEM) data.remove(LOADING_ITEM) this.notifyItemRemoved(lastIndex) } } fun setItems(items: List<T>) { loadingNextPageFinished() val diffCallback = DiffCallback(data, items) val diffResult = DiffUtil.calculateDiff(diffCallback) data.clear() data.addAll(items) diffResult.dispatchUpdatesTo(this) } fun getData(): List<T> = data /** * TODO be careful when using this method */ fun clearData() { data.clear() this.notifyDataSetChanged() } private class DiffCallback( private val oldList: List<BaseRecyclerViewItem>, private val newList: List<BaseRecyclerViewItem> ) : DiffUtil.Callback() { override fun getOldListSize() = oldList.size override fun getNewListSize() = newList.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition].id == newList[newItemPosition].id } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition] == newList[newItemPosition] } } }
0
Kotlin
0
0
fd831ca6347bfc69eb085206dc66367af6d0f7e6
3,402
android-upstack
MIT License
domain/src/commonMain/kotlin/com/br/kmmdemo/models/Daily.kt
BottleRocketStudios
663,198,654
false
{"Kotlin": 57148, "Swift": 412}
package com.br.kmmdemo.models import com.br.kmmdemo.models.domainmodelinterface.DomainModel import kotlinx.serialization.Serializable @Serializable data class Daily( val time: String?, val dailyValues: DailyValues? ): DomainModel
0
Kotlin
0
0
250456862dcedf3ff73775b7f0f8e1086c1620fa
240
Kmp-demo
Apache License 2.0
core/src/debug/kotlin/ru/mobileup/template/core/debug_tools/RealDebugTools.kt
MobileUpLLC
485,284,340
false
null
package ru.mobileup.template.core.debug_tools import android.content.Context import com.chuckerteam.chucker.api.ChuckerCollector import com.chuckerteam.chucker.api.ChuckerInterceptor import com.chuckerteam.chucker.api.RetentionManager import me.aartikov.replica.client.ReplicaClient import me.aartikov.replica.devtools.ReplicaDevTools import me.nemiron.hyperion.networkemulation.NetworkEmulatorInterceptor import okhttp3.Interceptor import ru.mobileup.template.core.error_handling.ServerException import java.io.IOException class RealDebugTools( context: Context, replicaClient: ReplicaClient ) : DebugTools { private val networkEmulatorInterceptor = NetworkEmulatorInterceptor( context, failureExceptionProvider = { IOException(ServerException(cause = null)) } ) private val replicaDebugTools = ReplicaDevTools(replicaClient, context) private val chuckerCollector = ChuckerCollector( context = context, showNotification = false, retentionPeriod = RetentionManager.Period.ONE_HOUR ) private val chuckerInterceptor = ChuckerInterceptor .Builder(context) .collector(chuckerCollector) .build() override val interceptors: List<Interceptor> = listOf( networkEmulatorInterceptor, chuckerInterceptor ) override fun launch() { replicaDebugTools.launch() } @Suppress("DEPRECATION") override fun collectNetworkError(exception: Exception) { chuckerCollector.onError("DebugTools", exception) } }
1
null
2
8
75c3350979d4d2a92d8b685194b80ef3747201e9
1,547
MobileUp-Android-Template
MIT License