summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibPDF/Value.h
blob: efce1a30b0bad2ba2fa237943fdc80130b6c17fe (plain)
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
93
94
/*
 * Copyright (c) 2021, Matthew Olsson <mattco@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Format.h>
#include <AK/RefPtr.h>
#include <AK/String.h>
#include <AK/Variant.h>
#include <LibPDF/Forward.h>
#include <LibPDF/Object.h>
#include <LibPDF/Reference.h>

namespace PDF {

class Value : public Variant<Empty, std::nullptr_t, bool, int, float, Reference, NonnullRefPtr<Object>> {
public:
    using Variant::Variant;

    template<IsObject T>
    Value(RefPtr<T> const& refptr)
        : Variant(nullptr)
    {
        if (refptr)
            set<NonnullRefPtr<Object>>(*refptr);
    }

    [[nodiscard]] String to_string(int indent = 0) const;

    [[nodiscard]] ALWAYS_INLINE bool has_number() const { return has<int>() || has<float>(); }

    [[nodiscard]] ALWAYS_INLINE bool has_u32() const
    {
        return has<int>() && get<int>() >= 0;
    }

    [[nodiscard]] ALWAYS_INLINE bool has_u16() const
    {
        return has<int>() && get<int>() >= 0 && get<int>() < 65536;
    }

    [[nodiscard]] ALWAYS_INLINE u32 get_u32() const
    {
        VERIFY(has_u32());
        return get<int>();
    }

    [[nodiscard]] ALWAYS_INLINE u16 get_u16() const
    {
        VERIFY(has_u16());
        return get<int>();
    }

    [[nodiscard]] ALWAYS_INLINE int to_int() const
    {
        if (has<int>())
            return get<int>();
        return static_cast<int>(get<float>());
    }

    [[nodiscard]] ALWAYS_INLINE float to_float() const
    {
        if (has<float>())
            return get<float>();
        return static_cast<float>(get<int>());
    }

    [[nodiscard]] ALWAYS_INLINE u32 as_ref_index() const
    {
        return get<Reference>().as_ref_index();
    }

    [[nodiscard]] ALWAYS_INLINE u32 as_ref_generation_index() const
    {
        return get<Reference>().as_ref_generation_index();
    }
};

}

namespace AK {

template<>
struct Formatter<PDF::Value> : Formatter<StringView> {
    ErrorOr<void> format(FormatBuilder& builder, PDF::Value const& value)
    {
        return Formatter<StringView>::format(builder, value.to_string());
    }
};

}