appdimens-dynamic

//AppDimens SDP, HDP, WDP: Scalable Width and Height Dimensions/com.appdimens.dynamic.core/DimenCache

DimenCache

object DimenCache

EN Global, lock-free, shared cache for all AppDimens dimension calculations.

Thread Safety: Completely thread-safe. All reads and writes are lock-free using AtomicLongArray / AtomicIntegerArray. If two threads write identically-keyed entries simultaneously, the last write wins — always correct because both computed the same value.

PT Cache global, lock-free e compartilhado para todos os cálculos de dimensão do AppDimens.

data class CacheStats(val capacity: Int, val populated: Int, val fillRatio: Float, val hits: Long = 0, val misses: Long = 0, val evictions: Long = 0, val hitRate: Float = 0.0f)

EN Cache usage statistics snapshot. The hits, misses, evictions, and hitRate fields are only meaningful when diagnosticsEnabled is true.

@PublishedApiinternal enum CalcType : Enum<DimenCache.CalcType>

EN Calculation types based on the library’s package structure. PT Tipos de cálculo baseados na estrutura de pacotes da biblioteca.

internal class ScreenFactors

EN Holds all screen-derived scaling factors in an object padded to exceed two ARM64 cache lines (2 × 64 bytes = 128 bytes), ensuring that writes during updateFactors do not invalidate unrelated reads on sibling CPU cores.

@PublishedApiinternal class ShardWrapper(shardSize: Int)

EN Padded cache shard wrapper that prevents false sharing between shards across CPU cores on ARM64 (cache line = 64 bytes).

@PublishedApiinternal enum ValueType : Enum<DimenCache.ValueType>

EN Dimension type discriminator for the cache key. PT Discriminador de tipo de dimensão para a chave de cache.

@Volatileprivate var _scope: CoroutineScope?

@PublishedApiinternal const val ADJUSTMENT_SCALE: Float

@PublishedApiinternal const val CACHE_SIZE: Int = 2048

Number of slots in the primary (Tier-1) fast cache. Must be a power of 2 so that key and MASK is a fast modulo.

@JvmField@Volatileinternal var cachedUiMode: UiModeType

@Volatileprivate var cachedUiModeConfigHash: Int

@PublishedApi@JvmFieldinternal val CT_ASPECT_RATIO: Int

@PublishedApi@JvmFieldinternal val CT_DENSITY: Int

@PublishedApi@JvmFieldinternal val CT_DIAGONAL: Int

@PublishedApi@JvmFieldinternal val CT_INTERPOLATED: Int

@PublishedApi@JvmFieldinternal val CT_PERCENT: Int

@PublishedApi@JvmFieldinternal val CT_PERIMETER: Int

@PublishedApi@JvmFieldinternal val CT_SCALED: Int

@PublishedApiinternal val currentArMultiplier: Float

@PublishedApiinternal val currentAspectRatioMul: Float

@PublishedApiinternal val currentDensity: Float

@PublishedApiinternal val currentDiagonalScale: Float

@PublishedApiinternal val currentInterpolatedScale: Float

@PublishedApiinternal val currentLogNormalizedAr: Float

@PublishedApiinternal val currentLogScale: Float

@PublishedApiinternal val currentNormalizedAr: Float

@PublishedApiinternal val currentPerimeterScale: Float

@PublishedApiinternal val currentPowerScale: Float

@PublishedApiinternal val currentScale: Float

@PublishedApiinternal val currentSmallestWidthDp: Int

internal val Context.dataStore: ERROR CLASS: Symbol not found for DataStore<ERROR CLASS: Symbol not found for Preferences>

@JvmStatic@PublishedApi@Volatileinternal var diagnosticsEnabled: Boolean

EN When true, hit/miss/eviction counters are incremented on every cache operation. Uses LongAdder for low-contention counting. Disabled by default so production apps pay zero overhead.

@PublishedApi@JvmFieldinternal val evictionCount: LongAdder

@PublishedApi@JvmFieldinternal val factors: DimenCache.ScreenFactors

@PublishedApi@JvmFieldinternal val hitCount: LongAdder

@PublishedApiinternal const val INV_BASE_RATIO: Float = 0.0033333334f

@JvmStatic@PublishedApi@Volatileinternal var isEnabled: Boolean

EN Master switch for the cache system. If disabled, all calls will recompute. PT Chave mestre para o sistema de cache. Se desativado, todos os cálculos são refeitos.

@PublishedApiinternal val isInitialized: AtomicBoolean

@PublishedApi@Volatileinternal var isInitializedFast: Boolean

Internal flag to avoid AtomicBoolean.get overhead on every hot-path call.

internal val isInitializing: AtomicBoolean

internal val KEY_CACHE_DATA: ERROR CLASS: Unresolved name: byteArrayPreferencesKey

internal val KEY_SW_DP: ERROR CLASS: Unresolved name: intPreferencesKey

@PublishedApiinternal val keysArray: Array<AtomicLongArray>

EN Backward-compatible accessors — still referenced by DimenCacheTest. These are thin aliases into shards; no extra memory is allocated.

@PublishedApi@JvmFieldinternal val missCount: LongAdder

private val resetListeners: CopyOnWriteArrayList<() -> Unit>

private val saveFlow: MutableSharedFlow<Context>

internal val scope: CoroutineScope

private val scopeLock: Any

@PublishedApiinternal const val SENSITIVITY_DEFAULT: Float

@PublishedApiinternal const val SHARD_COUNT: Int = 4

EN Cache Sharding (Concurrency Partitioning) Split the cache into 4 shards to reduce false sharing and bus contention.

@PublishedApiinternal const val SHARD_MASK: Int

@PublishedApiinternal const val SHARD_SIZE: Int

@PublishedApiinternal const val SHARD_SIZE_MASK: Int

@PublishedApi@JvmFieldinternal val shards: Array<DimenCache.ShardWrapper>

EN Sharded, padded primitive cache storage. Replaces the previous keysArray / valueBitsArray pair. Each shard is wrapped in a ShardWrapper with 128-byte padding.

@PublishedApiinternal val valueBitsArray: Array<AtomicIntegerArray>

@JvmStaticfun addResetListener(listener: () -> Unit)

EN Registers a listener to be notified when the cache is cleared. PT Registra um listener para ser notificado quando o cache for limpo.

@JvmStatic@PublishedApiinternal fun buildKey(baseValue: Float, isLandscape: Boolean, ignoreMultiWindows: Boolean, calcType: DimenCache.CalcType, qualifier: DpQualifier, inverter: Inverter, applyAspectRatio: Boolean, valueType: DimenCache.ValueType, customSensitivityK: Float? = null): Long

Packs all dimension-calculation parameters into a single 64-bit Long key.

@PublishedApiinternal fun calculateRawScaling(baseValue: Float, applyAspectRatio: Boolean, customSensitivityK: Float?): Float

EN Unified high-performance scaling engine. Reads from factors — padded object, guaranteeing that the read of scale and arMultiplier land on the same cache line as all other factor fields.

@JvmStaticfun clear(context: Context? = null)

EN Clears all cache slots. Java-compatible alias.

@JvmStatic@JvmOverloadsfun clearAll(context: Context? = null)

EN Clears all cache entries using AtomicLongArray.lazySet / AtomicIntegerArray.lazySet with 4× manual loop unrolling. This avoids issuing a full memory barrier on every element, which is safe because the next getOrPut will provide the required acquire/release semantics. Thread-safe.

@JvmStaticfun getBatch(keys: LongArray, context: Context? = null, compute: (Int) -> Float): FloatArray

EN SIMD-friendly batch resolution.

@JvmStaticinternal fun getCachedUiModeType(context: Context): UiModeType

@JvmStaticinline fun getOrPut(key: Long, crossinline compute: () -> Float): Float

Backward compatibility for non-context calls.

EN Reads from the cache or computes (and stores) a new value. Lock-free.

@JvmStatic@PublishedApiinternal fun getOrPutAspectRatio(normalizedAr: Float, context: Context? = null): Float

@JvmStatic@PublishedApiinternal fun getOrPutInternal(key: Long, context: Context?, compute: () -> Float): Float

EN Non-inline core logic for getOrPut. Separated so that the public inline function does not need access to internal fields of ShardWrapper directly. This function is @PublishedApi, making it visible to the inlined call-sites.

@JvmStatic@PublishedApiinternal fun init(context: Context)

@JvmStaticfun invalidateOnConfigChange(new: Configuration)

EN Selectively invalidates the cache based on what actually changed in Configuration. The previous configuration is tracked internally.

private fun launchSaveCollector(target: CoroutineScope)

internal fun loadFromByteArray(data: ByteArray)

@JvmStaticfun peek(key: Long): Float?

EN Reads a stored cache value without computing a fallback. Returns null on a miss.

private suspend fun performSave(context: Context)

@JvmStaticfun removeResetListener(listener: () -> Unit)

EN Removes a previously registered reset listener. PT Remove um listener de reset previamente registrado.

@JvmStaticfun resetDiagnostics()

EN Resets the diagnostic counters (hit, miss, eviction) to zero. PT Zera os contadores de diagnóstico (hit, miss, eviction).

@JvmStatic@PublishedApiinternal fun saveToPersistence(context: Context)

internal fun serializeToByteArray(): ByteArray

@JvmStaticfun shutdown()

EN Cancels the background persistence scope. Intended for test teardown. The scope is automatically re-created on next use (e.g. saveToPersistence).

@JvmStaticfun stats(): DimenCache.CacheStats

private fun updateFactors(config: Configuration)

Types

Name Summary
CacheStats  
CalcType  
ScreenFactors  
ShardWrapper  
ValueType  

Properties

Name Summary
_scope  
ADJUSTMENT_SCALE  
CACHE_SIZE  
cachedUiMode  
cachedUiModeConfigHash  
CT_ASPECT_RATIO  
CT_DENSITY  
CT_DIAGONAL  
CT_INTERPOLATED  
CT_PERCENT  
CT_PERIMETER  
CT_SCALED  
currentArMultiplier  
currentAspectRatioMul  
currentDensity  
currentDiagonalScale  
currentInterpolatedScale  
currentLogNormalizedAr  
currentLogScale  
currentNormalizedAr  
currentPerimeterScale  
currentPowerScale  
currentScale  
currentSmallestWidthDp  
dataStore  
diagnosticsEnabled  
evictionCount  
factors  
hitCount  
INV_BASE_RATIO  
isEnabled  
isInitialized  
isInitializedFast  
isInitializing  
KEY_CACHE_DATA  
KEY_SW_DP  
keysArray  
missCount  
resetListeners  
saveFlow  
scope  
scopeLock  
SENSITIVITY_DEFAULT  
SHARD_COUNT  
SHARD_MASK  
SHARD_SIZE  
SHARD_SIZE_MASK  
shards  
valueBitsArray  

Functions

Name Summary
addResetListener  
buildKey  
calculateRawScaling  
clear  
clearAll  
getBatch  
getCachedUiModeType  
getOrPut  
getOrPutAspectRatio  
getOrPutInternal  
init  
invalidateOnConfigChange  
launchSaveCollector  
loadFromByteArray  
peek  
performSave  
removeResetListener  
resetDiagnostics  
saveToPersistence  
serializeToByteArray  
shutdown  
stats  
updateFactors