File: numeric.h

package info (click to toggle)
intel-compute-runtime 25.35.35096.9-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 79,324 kB
  • sloc: cpp: 926,243; lisp: 3,433; sh: 715; makefile: 162; python: 21
file content (92 lines) | stat: -rw-r--r-- 2,256 bytes parent folder | download | duplicates (2)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
 * Copyright (C) 2018-2023 Intel Corporation
 *
 * SPDX-License-Identifier: MIT
 *
 */

#pragma once

#include "shared/source/helpers/constants.h"

#include <cstdint>

namespace NEO {

template <uint8_t numBits>
struct StorageType;

template <>
struct StorageType<8> {
    using Type = uint8_t;
};

template <>
struct StorageType<16> {
    using Type = uint16_t;
};

template <>
struct StorageType<32> {
    using Type = uint32_t;
};

template <>
struct StorageType<64> {
    using Type = uint64_t;
};

template <uint8_t numBits>
struct StorageType {
    using Type = typename StorageType<numBits + 1>::Type;
};

template <uint8_t numBits>
using StorageTypeT = typename StorageType<numBits>::Type;

template <uint8_t integerBits, uint8_t fractionalBits, uint8_t totalBits = integerBits + fractionalBits>
struct UnsignedFixedPointValue {
    UnsignedFixedPointValue(float v) {
        fromFloatingPoint(v);
    }

    StorageTypeT<totalBits> &getRawAccess() {
        return storage;
    }

    static constexpr float getMaxRepresentableFloat() {
        return getMaxRepresentableFloatingPointValue<float>();
    }

    float asFloat() {
        return asFloatPointType<float>();
    }

  protected:
    template <typename FloatingType>
    static constexpr FloatingType getMaxRepresentableFloatingPointValue() {
        return static_cast<FloatingType>(
            static_cast<FloatingType>(maxNBitValue(integerBits)) + (static_cast<FloatingType>(maxNBitValue(fractionalBits)) / (1U << fractionalBits)));
    }

    template <typename FloatingType>
    void fromFloatingPoint(FloatingType val) {
        auto maxFloatVal = getMaxRepresentableFloatingPointValue<FloatingType>();
        // clamp to [0, maxFloatVal]
        val = (val < FloatingType{0}) ? FloatingType{0} : val;
        val = (val > maxFloatVal) ? maxFloatVal : val;

        // scale to fixed point representation
        this->storage = static_cast<StorageTypeT<totalBits>>(val * (1U << fractionalBits));
    }

    template <typename FloatingType>
    FloatingType asFloatPointType() {
        return static_cast<FloatingType>(storage) / (1U << fractionalBits);
    }

    StorageTypeT<totalBits> storage = 0;
};

using FixedU4D8 = UnsignedFixedPointValue<4, 8>;
} // namespace NEO