1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.libraries.pcc.chronicle.api.cantrip
18 
19 /**
20  * A [Cantrip] is a transformation of [Data], represented as a function mapping that data to a
21  * mutated or null version of itself.
22  */
23 interface Cantrip<Data> {
24   /** Applies the [Cantrip] across a single [datum]. */
invokenull25   operator fun invoke(datum: Data): Data?
26 }
27 
28 /**
29  * Applies the [Cantrip] across all items in the [sequence].
30  *
31  * If a given return value from the [Cantrip] is null, the data is omitted from the sequence.
32  */
33 operator fun <Data> Cantrip<Data>.invoke(sequence: Sequence<Data>): Sequence<Data> =
34   sequence.mapNotNull(::invoke)
35 
36 /** Applies the [Cantrip] across all items in the [List]. */
37 operator fun <Data> Cantrip<Data>.invoke(list: List<Data>): List<Data> =
38   invoke(list.asSequence()).toList()
39 
40 /** Applies the [Cantrip] across all items in the [Set]. */
41 operator fun <Data> Cantrip<Data>.invoke(set: Set<Data>): Set<Data> =
42   invoke(set.asSequence()).toSet()
43