-
Notifications
You must be signed in to change notification settings - Fork 35
/
ConversionExtensions.kt
46 lines (42 loc) · 1.54 KB
/
ConversionExtensions.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.crdt.extension
import arcs.core.common.Referencable
import arcs.core.crdt.CrdtEntity
import arcs.core.crdt.VersionMap
import arcs.core.data.RawEntity
import arcs.core.data.util.ReferencablePrimitive
import arcs.core.util.Base64
/** Converts the [RawEntity] into a [CrdtEntity.Data] model, at the given version. */
fun RawEntity.toCrdtEntityData(
versionMap: VersionMap,
referenceBuilder: (Referencable) -> CrdtEntity.Reference = { CrdtEntity.ReferenceImpl(it.id) }
): CrdtEntity.Data = CrdtEntity.Data(versionMap.copy(), this, referenceBuilder)
private fun Any?.toReferencable(): Referencable {
requireNotNull(this) { "Cannot create a referencable from a null value." }
return when {
ReferencablePrimitive.isSupportedPrimitive(this::class) -> {
if (this is ByteArray) {
ReferencablePrimitive(
ByteArray::class,
this,
valueRepr = Base64.encode(this)
)
} else {
ReferencablePrimitive(this::class, this)
}
}
this is Referencable -> this
else -> throw IllegalArgumentException(
"Entity contains non-referencable non-primitive values."
)
}
}