1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
45/// Rounds the given volume level to the nearest 1%. Input should be a float between 0.0 and 1.0 and
6/// the result will also be clamped to this range.
7///
8/// Rounding should be applied to audio levels handled by settings service that come from external
9/// sources.
10pub(crate) fn round_volume_level(volume: f32) -> f32 {
11#[allow(clippy::manual_clamp)]
12((volume * 100.0).round() / 100.0).max(0.0).min(1.0)
13}
1415#[cfg(test)]
16mod tests {
17use super::round_volume_level;
1819// Various tests to verify rounding works as expected.
20#[fuchsia::test]
21// We're testing rounding so we want explicit float comparisons.
22#[allow(clippy::float_cmp)]
23fn test_round_volume() {
24assert_eq!(round_volume_level(1.0), 1.0);
25assert_eq!(round_volume_level(0.0), 0.0);
26assert_eq!(round_volume_level(0.222222), 0.22);
27assert_eq!(round_volume_level(0.349), 0.35);
28assert_eq!(round_volume_level(0.995), 1.0);
29assert_eq!(round_volume_level(0.994), 0.99);
30 }
3132// Verifies that values below 0.0 round to 0.0.
33#[fuchsia::test]
34// We're testing rounding so we want explicit float comparisons.
35#[allow(clippy::float_cmp)]
36fn test_round_volume_below_range() {
37assert_eq!(round_volume_level(-1.0), 0.0);
38assert_eq!(round_volume_level(-0.1), 0.0);
39assert_eq!(round_volume_level(-0.0), 0.0);
40assert_eq!(round_volume_level(std::f32::MIN), 0.0);
41 }
4243// Verifies that values above 1.0 round to 1.0.
44#[fuchsia::test]
45// We're testing rounding so we want explicit float comparisons.
46#[allow(clippy::float_cmp)]
47fn test_round_volume_above_range() {
48assert_eq!(round_volume_level(2.0), 1.0);
49assert_eq!(round_volume_level(1.1), 1.0);
50assert_eq!(round_volume_level(std::f32::MAX), 1.0);
51 }
52}