From 4fad7262291a8af1415fb9a3693678bd9610f0d6 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 24 Feb 2020 17:46:10 +0100 Subject: Make map_pointer typesafe Instead of just using uint32_t, which would allow you to assign e.g. a map_pointer to a map_pointer, use our own smarter struct that has strict type checking. We allow creating a map_pointer from a nullptr, and we allow comparing map_pointer to nullptr, which also deals with comparisons against 0 which are often used, as 0 will be implictly converted to nullptr. --- apt-pkg/pkgcache.h | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'apt-pkg/pkgcache.h') diff --git a/apt-pkg/pkgcache.h b/apt-pkg/pkgcache.h index e5a1a81eb..ef22a78a0 100644 --- a/apt-pkg/pkgcache.h +++ b/apt-pkg/pkgcache.h @@ -77,6 +77,7 @@ #include #include +#include // required for nullptr_t #include #include #include @@ -92,10 +93,29 @@ typedef uint32_t map_filesize_small_t; typedef uint32_t map_id_t; // some files get an id, too, but in far less absolute numbers typedef uint16_t map_fileid_t; + // relative pointer from cache start -template using map_pointer = uint32_t; +template class map_pointer { + uint32_t val; +public: + map_pointer() noexcept : val(0) {} + map_pointer(nullptr_t) noexcept : val(0) {} + explicit map_pointer(uint32_t n) noexcept : val(n) {} + explicit operator uint32_t() noexcept { return val; } +}; + +template inline T *operator +(T *p, map_pointer m) { return p + uint32_t(m); } +template inline bool operator ==(map_pointer u, map_pointer m) { return uint32_t(u) == uint32_t(m); } +template inline bool operator !=(map_pointer u, map_pointer m) { return uint32_t(u) != uint32_t(m); } +template inline bool operator <(map_pointer u, map_pointer m) { return uint32_t(u) < uint32_t(m); } +template inline bool operator >(map_pointer u, map_pointer m) { return uint32_t(u) > uint32_t(m); } +template inline uint32_t operator -(map_pointer u, map_pointer m) { return uint32_t(u) - uint32_t(m); } +template bool operator ==(map_pointer m, nullptr_t) { return uint32_t(m) == 0; } +template bool operator !=(map_pointer m, nullptr_t) { return uint32_t(m) != 0; } + // same as the previous, but documented to be to a string item typedef map_pointer map_stringitem_t; + // we have only a small amount of flags for each item typedef uint8_t map_flags_t; typedef uint8_t map_number_t; -- cgit v1.2.3