Skip to content

Commit

Permalink
fix: ElectronBrowserContext::PartitionKey comparisons (#41055)
Browse files Browse the repository at this point in the history
* fix: ElectronBrowserContext::PartitionKey comparisons

Use c++20 default comparisons to simplify + fix PartitionKey sorting:

- The equality operator is broken. `PartitionKey{"foo", false}` is both
  equal, to and less than, `PartitionKey{"foo", true}`

- For some keys, the same session can be retrieved via both `fromPath()`
  and `fromPartition()`. This use case was discussed and removed from
  the original PR after code review said "always returning different
  sessions feels lower maintenance." The current behavior is a bug that
  comes from the comparison operators not checking the keys' types.

Xref: 3f1aea9#r1099745359

Xref: https://chromium.googlesource.com/chromium/src/+/main/styleguide/c++/c++-features.md#Default-comparisons-allowed

* fixup! fix: ElectronBrowserContext::PartitionKey comparisons
  • Loading branch information
ckerr committed Jan 23, 2024
1 parent 1300e83 commit 1af9612
Showing 1 changed file with 16 additions and 34 deletions.
50 changes: 16 additions & 34 deletions shell/browser/electron_browser_context.h
Expand Up @@ -9,6 +9,7 @@
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <variant>
#include <vector>

Expand Down Expand Up @@ -80,41 +81,22 @@ class ElectronBrowserContext : public content::BrowserContext {

// partition_id => browser_context
struct PartitionKey {
enum class KeyType { Partition, FilePath };
std::string location;
bool in_memory;
KeyType partition_type;

PartitionKey(const std::string& partition, bool in_memory)
: location(partition),
in_memory(in_memory),
partition_type(KeyType::Partition) {}
PartitionKey(const std::string_view partition, bool in_memory)
: type_{Type::Partition}, location_{partition}, in_memory_{in_memory} {}

explicit PartitionKey(const base::FilePath& file_path)
: location(file_path.AsUTF8Unsafe()),
in_memory(false),
partition_type(KeyType::FilePath) {}

bool operator<(const PartitionKey& other) const {
if (partition_type == KeyType::Partition) {
if (location == other.location)
return in_memory < other.in_memory;
return location < other.location;
} else {
if (location == other.location)
return false;
return location < other.location;
}
}

bool operator==(const PartitionKey& other) const {
if (partition_type == KeyType::Partition) {
return (location == other.location) && (in_memory < other.in_memory);
} else {
if (location == other.location)
return true;
return false;
}
}
: type_{Type::Path},
location_{file_path.AsUTF8Unsafe()},
in_memory_{false} {}

friend auto operator<=>(const PartitionKey&, const PartitionKey&) = default;

private:
enum class Type { Partition, Path };

Type type_;
std::string location_;
bool in_memory_;
};

using BrowserContextMap =
Expand Down

0 comments on commit 1af9612

Please sign in to comment.