1 /* <lambda>null2 * Copyright 2023 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 androidx.graphics.shapes 18 19 import androidx.test.filters.SmallTest 20 import org.junit.Assert.assertThrows 21 import org.junit.Test 22 23 @SmallTest 24 class FloatMappingTest { 25 @Test fun identityMappingTest() = validateMapping(DoubleMapper.Identity) { it } 26 27 @Test 28 fun simpleMappingTest() = 29 validateMapping( 30 // Map the first half of the start source to the first quarter of the target. 31 mapper = DoubleMapper(0f to 0f, 0.5f to 0.25f) 32 ) { x -> 33 if (x < 0.5f) x / 2 else (3 * x - 1) / 2 34 } 35 36 @Test 37 fun targetWrapsTest() = 38 validateMapping( 39 // mapping applies a "+ 0.5f" 40 mapper = DoubleMapper(0f to 0.5f, 0.1f to 0.6f) 41 ) { x -> 42 (x + 0.5f) % 1f 43 } 44 45 @Test 46 fun sourceWrapsTest() = 47 validateMapping( 48 // Values on the source wrap (this is still the "+ 0.5f" function) 49 mapper = DoubleMapper(0.5f to 0f, 0.1f to 0.6f) 50 ) { x -> 51 (x + 0.5f) % 1f 52 } 53 54 @Test 55 fun bothWrapTest() = 56 validateMapping( 57 // Just the identity function 58 mapper = DoubleMapper(0.5f to 0.5f, 0.75f to 0.75f, 0.1f to 0.1f, 0.49f to 0.49f) 59 ) { 60 it 61 } 62 63 @Test 64 fun multiplePointTest() = 65 validateMapping(mapper = DoubleMapper(0.4f to 0.2f, 0.5f to 0.22f, 0f to 0.8f)) { x -> 66 if (x < 0.4f) { 67 (0.8f + x) % 1f 68 } else if (x < 0.5f) { 69 0.2f + (x - 0.4f) / 5 70 } else { 71 // maps a change of 0.5 in the source to a change 0.58 in the target, hence the 1.16 72 0.22f + (x - 0.5f) * 1.16f 73 } 74 } 75 76 @Test 77 fun targetDoubleWrapThrows() { 78 assertThrows(IllegalArgumentException::class.java) { 79 DoubleMapper(0.0f to 0.0f, 0.3f to 0.6f, 0.6f to 0.3f, 0.9f to 0.9f) 80 } 81 } 82 83 @Test 84 fun sourceDoubleWrapThrows() { 85 assertThrows(IllegalArgumentException::class.java) { 86 DoubleMapper(0.0f to 0.0f, 0.6f to 0.3f, 0.3f to 0.6f, 0.9f to 0.9f) 87 } 88 } 89 90 private fun validateMapping(mapper: DoubleMapper, expectedFunction: (Float) -> Float) { 91 (0..9999).forEach { i -> 92 val source = i / 10000f 93 val target = expectedFunction(source) 94 95 assertEqualish(target, mapper.map(source)) 96 assertEqualish(source, mapper.mapBack(target)) 97 } 98 } 99 } 100