Przeglądaj źródła

added hashed_string::to_value for direct computation

Michele Caini 7 lat temu
rodzic
commit
c639cb5285
3 zmienionych plików z 39 dodań i 2 usunięć
  1. 0 2
      TODO
  2. 29 0
      src/entt/core/hashed_string.hpp
  3. 10 0
      test/entt/core/hashed_string.cpp

+ 0 - 2
TODO

@@ -23,7 +23,5 @@
 * monostate: make constraint trivially copyable due to atomic optional
 * monostate: use template variable to avoid {}
 * travis + windows is now available, try it
-* hashed string: static (constexpr) member function to_value for direct hashing
-* entity: simplify get functions so as to generate less symbols for multiple components
 * events on replace, so that one can track updated components? indagate impact
 * allow to bind values to delegate on connect with free functions (sbo + check size on costruction to guarantee a zero allocation abstraction)

+ 29 - 0
src/entt/core/hashed_string.hpp

@@ -38,6 +38,35 @@ public:
     /*! @brief Unsigned integer type. */
     using hash_type = std::uint64_t;
 
+    /**
+     * @brief Returns directly the numeric representation of a string.
+     *
+     * Forcing template resolution avoids implicit conversions. An
+     * human-readable identifier can be anything but a plain, old bunch of
+     * characters.<br/>
+     * Example of use:
+     * @code{.cpp}
+     * const auto value = hashed_string::to_value("my.png");
+     * @endcode
+     *
+     * @tparam N Number of characters of the identifier.
+     * @param str Human-readable identifer.
+     * @return The numeric representation of the string.
+     */
+    template<std::size_t N>
+    inline static constexpr hash_type to_value(const char (&str)[N]) ENTT_NOEXCEPT {
+        return helper(offset, str);
+    }
+
+    /**
+     * @brief Returns directly the numeric representation of a string.
+     * @param wrapper Helps achieving the purpose by relying on overloading.
+     * @return The numeric representation of the string.
+     */
+    inline static hash_type to_value(const_wrapper wrapper) ENTT_NOEXCEPT {
+        return helper(offset, wrapper.str);
+    }
+
     /*! @brief Constructs an empty hashed string. */
     constexpr hashed_string() ENTT_NOEXCEPT
         : hash{}, str{nullptr}

+ 10 - 0
test/entt/core/hashed_string.cpp

@@ -44,3 +44,13 @@ TEST(HashedString, Constexprness) {
     (void)std::integral_constant<hash_type, "quux"_hs>{};
     ASSERT_TRUE(true);
 }
+
+TEST(HashedString, ToValue) {
+    using hash_type = entt::hashed_string::hash_type;
+
+    const char *foobar = "foobar";
+
+    ASSERT_EQ(entt::hashed_string::to_value(foobar), 0x85944171f73967e8);
+    // how would you test a constexpr otherwise?
+    (void)std::integral_constant<hash_type, entt::hashed_string::to_value("quux")>{};
+}