\brief Stores \a value into \a key, replacing the existing value if \a key is already present. If \a key is not yet in the map and the map is already full (containing \a NumEntries active entries), this operation silently fails. \param[in] key The key to store. This must not be `nullptr`, nor an empty string. It must not contain embedded `NUL`s. \param[in] value The value to store. If `nullptr`,
| 160 | //! \param[in] value The value to store. If `nullptr`, \a key is removed from |
| 161 | //! the map. Must not contain embedded `NUL`s. |
| 162 | void SetKeyValue(std::string_view key, std::string_view value) { |
| 163 | if (!value.data()) { |
| 164 | RemoveKey(key); |
| 165 | return; |
| 166 | } |
| 167 | |
| 168 | DCHECK(key.data()); |
| 169 | DCHECK(key.size()); |
| 170 | DCHECK_EQ(key.find('\0', 0), std::string_view::npos); |
| 171 | if (!key.data() || !key.size()) { |
| 172 | return; |
| 173 | } |
| 174 | |
| 175 | // |key| must not be an empty string. |
| 176 | DCHECK_NE(key[0], '\0'); |
| 177 | if (key[0] == '\0') { |
| 178 | return; |
| 179 | } |
| 180 | |
| 181 | // |value| must not contain embedded NULs. |
| 182 | DCHECK_EQ(value.find('\0', 0), std::string_view::npos); |
| 183 | |
| 184 | Entry* entry = GetEntryForKey(key); |
| 185 | |
| 186 | // If it does not yet exist, attempt to insert it. |
| 187 | if (!entry) { |
| 188 | for (size_t i = 0; i < num_entries; ++i) { |
| 189 | if (!entries_[i].is_active()) { |
| 190 | entry = &entries_[i]; |
| 191 | SetFromStringView(key, entry->key, key_size); |
| 192 | break; |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | // If the map is out of space, |entry| will be nullptr. |
| 198 | if (!entry) { |
| 199 | return; |
| 200 | } |
| 201 | |
| 202 | #ifndef NDEBUG |
| 203 | // Sanity check that the key only appears once. |
| 204 | int count = 0; |
| 205 | for (size_t i = 0; i < num_entries; ++i) { |
| 206 | if (EntryKeyEquals(key, entries_[i])) { |
| 207 | ++count; |
| 208 | } |
| 209 | } |
| 210 | DCHECK_EQ(count, 1); |
| 211 | #endif |
| 212 | |
| 213 | SetFromStringView(value, entry->value, value_size); |
| 214 | } |
| 215 | |
| 216 | //! \brief Removes \a key from the map. |
| 217 | //! |