user_note_metadata_snapshot.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2022 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef COMPONENTS_USER_NOTES_INTERFACES_USER_NOTE_METADATA_SNAPSHOT_H_
  5. #define COMPONENTS_USER_NOTES_INTERFACES_USER_NOTE_METADATA_SNAPSHOT_H_
  6. #include <memory>
  7. #include <string>
  8. #include <unordered_map>
  9. #include "base/unguessable_token.h"
  10. #include "url/gurl.h"
  11. namespace user_notes {
  12. class UserNoteMetadata;
  13. // In order to have GURL as a key in a hashmap, GURL hashing mechanism is
  14. // needed.
  15. struct GURLHash {
  16. size_t operator()(const GURL& url) const {
  17. return std::hash<std::string>()(url.spec());
  18. }
  19. };
  20. // A class that encapsulates an
  21. // `unordered_map<GURL, unordered_map<ID, UserNoteMetadata>>`. This represents
  22. // a snapshot of the note metadata contained in the database for a set of URLs.
  23. // The first map is to group metadata by URL, which makes it easy to look up
  24. // what notes are attached to that URL. The second map is for quick lookup of a
  25. // note's metadata by its ID. Using this class makes code simpler and clearer
  26. // than if using the raw type.
  27. class UserNoteMetadataSnapshot {
  28. public:
  29. using IdToMetadataMap = std::unordered_map<base::UnguessableToken,
  30. std::unique_ptr<UserNoteMetadata>,
  31. base::UnguessableTokenHash>;
  32. using UrlToIdToMetadataMap =
  33. std::unordered_map<GURL, IdToMetadataMap, GURLHash>;
  34. UserNoteMetadataSnapshot();
  35. UserNoteMetadataSnapshot(UserNoteMetadataSnapshot&& other);
  36. UserNoteMetadataSnapshot(const UserNoteMetadataSnapshot&) = delete;
  37. UserNoteMetadataSnapshot& operator=(const UserNoteMetadataSnapshot&) = delete;
  38. ~UserNoteMetadataSnapshot();
  39. // Returns false if there's at least one entry in the snapshot, true
  40. // otherwise.
  41. bool IsEmpty();
  42. // Adds a metadata entry to this class, based on the URL the note is attached
  43. // to and its ID.
  44. void AddEntry(const GURL& url,
  45. const base::UnguessableToken& id,
  46. std::unique_ptr<UserNoteMetadata> metadata);
  47. // Returns a raw pointer to the Note ID -> Metadata hash map for the given
  48. // URL, or nullptr if the URL does not have any notes associated with it.
  49. const IdToMetadataMap* GetMapForUrl(const GURL& url) const;
  50. private:
  51. UrlToIdToMetadataMap url_map_;
  52. };
  53. } // namespace user_notes
  54. #endif // COMPONENTS_USER_NOTES_INTERFACES_USER_NOTE_METADATA_SNAPSHOT_H_