File tree Expand file tree Collapse file tree 3 files changed +42
-0
lines changed
Expand file tree Collapse file tree 3 files changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -829,6 +829,16 @@ inline std::size_t dynamic::count(StringPiece key) const {
829829 return find (key) != items ().end () ? 1u : 0u ;
830830}
831831
832+ template <typename K>
833+ dynamic::IfIsNonStringDynamicConvertible<K, bool > dynamic::contains (
834+ K&& key) const {
835+ return count (key);
836+ }
837+
838+ inline bool dynamic::contains (StringPiece key) const {
839+ return count (key);
840+ }
841+
832842template <class K , class V >
833843inline dynamic::IfNotIterator<K, void > dynamic::insert (K&& key, V&& val) {
834844 auto & obj = get<ObjectImpl>();
Original file line number Diff line number Diff line change @@ -650,6 +650,18 @@ struct dynamic {
650650 IfIsNonStringDynamicConvertible<K, std::size_t > count (K&&) const ;
651651 std::size_t count (StringPiece) const ;
652652
653+ /* *
654+ * Check if key exists.
655+ *
656+ * If this is an object, returns whether it contains a field with
657+ * the given name. Otherwise throws TypeError.
658+ *
659+ * @methodset Object
660+ */
661+ template <typename K>
662+ IfIsNonStringDynamicConvertible<K, bool > contains (K&&) const ;
663+ bool contains (StringPiece) const ;
664+
653665 private:
654666 dynamic const & atImpl (dynamic const &) const &;
655667
Original file line number Diff line number Diff line change @@ -414,6 +414,26 @@ TEST(Dynamic, ObjectHeterogeneousAccess) {
414414 EXPECT_EQ (obj.count (StringPiece{b}), 0 );
415415 EXPECT_EQ (obj.count (StaticStrings::kBar ), 0 );
416416
417+ // contains()
418+ EXPECT_TRUE (obj.contains (empty));
419+ EXPECT_TRUE (obj.contains (nullptr ));
420+ EXPECT_TRUE (obj.contains (foo));
421+
422+ EXPECT_TRUE (obj.contains (a));
423+ EXPECT_TRUE (obj.contains (StaticStrings::kA ));
424+ EXPECT_TRUE (obj.contains (" a" ));
425+
426+ EXPECT_TRUE (obj.contains (sp));
427+ EXPECT_TRUE (obj.contains (StringPiece{" a" }));
428+ EXPECT_TRUE (obj.contains (StaticStrings::kFoo ));
429+
430+ EXPECT_TRUE (obj.contains (std::string{" a" }));
431+ EXPECT_TRUE (obj.contains (str));
432+
433+ EXPECT_FALSE (obj.contains (b));
434+ EXPECT_FALSE (obj.contains (StringPiece{b}));
435+ EXPECT_FALSE (obj.contains (StaticStrings::kBar ));
436+
417437 // operator[]
418438 EXPECT_EQ (obj[empty], 456 );
419439 EXPECT_EQ (obj[nullptr ], 456 );
You can’t perform that action at this time.
0 commit comments