authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-06-04 01:12:38-04:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2021-06-04 01:12:38-04:00
log7d15a3ac71c5d8dc8c08dfd8ea8ad43d4eae188a
treeae007106526e300bb7143be003fe8d847ba7230c
parent87dae0ce98fde1957a9290c22866b3101ce419d8
parent6953c8544b68c788dca4ed065e4a15eccbd4446b
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #8975 from SpexGuy/hash-map-updates

Breaking hash map changes for 0.8.0

49 files changed, 3210 insertions(+), 1528 deletions(-)

doc/docgen.zig+3-3
......@@ -404,9 +404,9 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
404404 .n = header_stack_size,
405405 },
406406 });
407 if (try urls.fetchPut(urlized, tag_token)) |entry| {
407 if (try urls.fetchPut(urlized, tag_token)) |kv| {
408408 parseError(tokenizer, tag_token, "duplicate header url: #{s}", .{urlized}) catch {};
409 parseError(tokenizer, entry.value, "other tag here", .{}) catch {};
409 parseError(tokenizer, kv.value, "other tag here", .{}) catch {};
410410 return error.ParseError;
411411 }
412412 if (last_action == Action.Open) {
......@@ -1023,7 +1023,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
10231023 defer root_node.end();
10241024
10251025 var env_map = try process.getEnvMap(allocator);
1026 try env_map.set("ZIG_DEBUG_COLOR", "1");
1026 try env_map.put("ZIG_DEBUG_COLOR", "1");
10271027
10281028 const builtin_code = try getBuiltinCode(allocator, &env_map, zig_exe);
10291029
lib/std/array_hash_map.zig+1286-500
......@@ -17,23 +17,36 @@ const Allocator = mem.Allocator;
1717const builtin = std.builtin;
1818const hash_map = @This();
1919
20/// An ArrayHashMap with default hash and equal functions.
21/// See AutoContext for a description of the hash and equal implementations.
2022pub fn AutoArrayHashMap(comptime K: type, comptime V: type) type {
21 return ArrayHashMap(K, V, getAutoHashFn(K), getAutoEqlFn(K), !autoEqlIsCheap(K));
23 return ArrayHashMap(K, V, AutoContext(K), !autoEqlIsCheap(K));
2224}
2325
26/// An ArrayHashMapUnmanaged with default hash and equal functions.
27/// See AutoContext for a description of the hash and equal implementations.
2428pub fn AutoArrayHashMapUnmanaged(comptime K: type, comptime V: type) type {
25 return ArrayHashMapUnmanaged(K, V, getAutoHashFn(K), getAutoEqlFn(K), !autoEqlIsCheap(K));
29 return ArrayHashMapUnmanaged(K, V, AutoContext(K), !autoEqlIsCheap(K));
2630}
2731
2832/// Builtin hashmap for strings as keys.
2933pub fn StringArrayHashMap(comptime V: type) type {
30 return ArrayHashMap([]const u8, V, hashString, eqlString, true);
34 return ArrayHashMap([]const u8, V, StringContext, true);
3135}
3236
3337pub fn StringArrayHashMapUnmanaged(comptime V: type) type {
34 return ArrayHashMapUnmanaged([]const u8, V, hashString, eqlString, true);
38 return ArrayHashMapUnmanaged([]const u8, V, StringContext, true);
3539}
3640
41pub const StringContext = struct {
42 pub fn hash(self: @This(), s: []const u8) u32 {
43 return hashString(s);
44 }
45 pub fn eql(self: @This(), a: []const u8, b: []const u8) bool {
46 return eqlString(a, b);
47 }
48};
49
3750pub fn eqlString(a: []const u8, b: []const u8) bool {
3851 return mem.eql(u8, a, b);
3952}
......@@ -54,83 +67,112 @@ pub fn hashString(s: []const u8) u32 {
5467/// but only has to call `eql` for hash collisions.
5568/// If typical operations (except iteration over entries) need to be faster, prefer
5669/// the alternative `std.HashMap`.
70/// Context must be a struct type with two member functions:
71/// hash(self, K) u32
72/// eql(self, K, K) bool
73/// Adapted variants of many functions are provided. These variants
74/// take a pseudo key instead of a key. Their context must have the functions:
75/// hash(self, PseudoKey) u32
76/// eql(self, PseudoKey, K) bool
5777pub fn ArrayHashMap(
5878 comptime K: type,
5979 comptime V: type,
60 comptime hash: fn (key: K) u32,
61 comptime eql: fn (a: K, b: K) bool,
80 comptime Context: type,
6281 comptime store_hash: bool,
6382) type {
83 comptime std.hash_map.verifyContext(Context, K, K, u32);
6484 return struct {
6585 unmanaged: Unmanaged,
6686 allocator: *Allocator,
87 ctx: Context,
88
89 /// The ArrayHashMapUnmanaged type using the same settings as this managed map.
90 pub const Unmanaged = ArrayHashMapUnmanaged(K, V, Context, store_hash);
6791
68 pub const Unmanaged = ArrayHashMapUnmanaged(K, V, hash, eql, store_hash);
92 /// Pointers to a key and value in the backing store of this map.
93 /// Modifying the key is allowed only if it does not change the hash.
94 /// Modifying the value is allowed.
95 /// Entry pointers become invalid whenever this ArrayHashMap is modified,
96 /// unless `ensureCapacity` was previously used.
6997 pub const Entry = Unmanaged.Entry;
70 pub const Hash = Unmanaged.Hash;
71 pub const GetOrPutResult = Unmanaged.GetOrPutResult;
7298
73 /// Deprecated. Iterate using `items`.
74 pub const Iterator = struct {
75 hm: *const Self,
76 /// Iterator through the entry array.
77 index: usize,
99 /// A KV pair which has been copied out of the backing store
100 pub const KV = Unmanaged.KV;
78101
79 pub fn next(it: *Iterator) ?*Entry {
80 if (it.index >= it.hm.unmanaged.entries.items.len) return null;
81 const result = &it.hm.unmanaged.entries.items[it.index];
82 it.index += 1;
83 return result;
84 }
102 /// The Data type used for the MultiArrayList backing this map
103 pub const Data = Unmanaged.Data;
104 /// The MultiArrayList type backing this map
105 pub const DataList = Unmanaged.DataList;
85106
86 /// Reset the iterator to the initial index
87 pub fn reset(it: *Iterator) void {
88 it.index = 0;
89 }
90 };
107 /// The stored hash type, either u32 or void.
108 pub const Hash = Unmanaged.Hash;
109
110 /// getOrPut variants return this structure, with pointers
111 /// to the backing store and a flag to indicate whether an
112 /// existing entry was found.
113 /// Modifying the key is allowed only if it does not change the hash.
114 /// Modifying the value is allowed.
115 /// Entry pointers become invalid whenever this ArrayHashMap is modified,
116 /// unless `ensureCapacity` was previously used.
117 pub const GetOrPutResult = Unmanaged.GetOrPutResult;
118
119 /// An Iterator over Entry pointers.
120 pub const Iterator = Unmanaged.Iterator;
91121
92122 const Self = @This();
93 const Index = Unmanaged.Index;
94123
124 /// Create an ArrayHashMap instance which will use a specified allocator.
95125 pub fn init(allocator: *Allocator) Self {
126 if (@sizeOf(Context) != 0)
127 @compileError("Cannot infer context "++@typeName(Context)++", call initContext instead.");
128 return initContext(allocator, undefined);
129 }
130 pub fn initContext(allocator: *Allocator, ctx: Context) Self {
96131 return .{
97132 .unmanaged = .{},
98133 .allocator = allocator,
134 .ctx = ctx,
99135 };
100136 }
101137
102 /// `ArrayHashMap` takes ownership of the passed in array list. The array list must have
103 /// been allocated with `allocator`.
104 /// Deinitialize with `deinit`.
105 pub fn fromOwnedArrayList(allocator: *Allocator, entries: std.ArrayListUnmanaged(Entry)) !Self {
106 return Self{
107 .unmanaged = try Unmanaged.fromOwnedArrayList(allocator, entries),
108 .allocator = allocator,
109 };
110 }
111
138 /// Frees the backing allocation and leaves the map in an undefined state.
139 /// Note that this does not free keys or values. You must take care of that
140 /// before calling this function, if it is needed.
112141 pub fn deinit(self: *Self) void {
113142 self.unmanaged.deinit(self.allocator);
114143 self.* = undefined;
115144 }
116145
146 /// Clears the map but retains the backing allocation for future use.
117147 pub fn clearRetainingCapacity(self: *Self) void {
118148 return self.unmanaged.clearRetainingCapacity();
119149 }
120150
151 /// Clears the map and releases the backing allocation
121152 pub fn clearAndFree(self: *Self) void {
122153 return self.unmanaged.clearAndFree(self.allocator);
123154 }
124155
156 /// Returns the number of KV pairs stored in this map.
125157 pub fn count(self: Self) usize {
126158 return self.unmanaged.count();
127159 }
128160
161 /// Returns the backing array of keys in this map.
162 /// Modifying the map may invalidate this array.
163 pub fn keys(self: Self) []K {
164 return self.unmanaged.keys();
165 }
166 /// Returns the backing array of values in this map.
167 /// Modifying the map may invalidate this array.
168 pub fn values(self: Self) []V {
169 return self.unmanaged.values();
170 }
171
172 /// Returns an iterator over the pairs in this map.
173 /// Modifying the map may invalidate this iterator.
129174 pub fn iterator(self: *const Self) Iterator {
130 return Iterator{
131 .hm = self,
132 .index = 0,
133 };
175 return self.unmanaged.iterator();
134176 }
135177
136178 /// If key exists this function cannot fail.
......@@ -140,7 +182,10 @@ pub fn ArrayHashMap(
140182 /// the `Entry` pointer points to it. Caller should then initialize
141183 /// the value (but not the key).
142184 pub fn getOrPut(self: *Self, key: K) !GetOrPutResult {
143 return self.unmanaged.getOrPut(self.allocator, key);
185 return self.unmanaged.getOrPutContext(self.allocator, key, self.ctx);
186 }
187 pub fn getOrPutAdapted(self: *Self, key: anytype, ctx: anytype) !GetOrPutResult {
188 return self.unmanaged.getOrPutContextAdapted(key, ctx, self.ctx);
144189 }
145190
146191 /// If there is an existing item with `key`, then the result
......@@ -151,11 +196,13 @@ pub fn ArrayHashMap(
151196 /// If a new entry needs to be stored, this function asserts there
152197 /// is enough capacity to store it.
153198 pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult {
154 return self.unmanaged.getOrPutAssumeCapacity(key);
199 return self.unmanaged.getOrPutAssumeCapacityContext(key, self.ctx);
155200 }
156
157 pub fn getOrPutValue(self: *Self, key: K, value: V) !*Entry {
158 return self.unmanaged.getOrPutValue(self.allocator, key, value);
201 pub fn getOrPutAssumeCapacityAdapted(self: *Self, key: anytype, ctx: anytype) GetOrPutResult {
202 return self.unmanaged.getOrPutAssumeCapacityAdapted(key, ctx);
203 }
204 pub fn getOrPutValue(self: *Self, key: K, value: V) !GetOrPutResult {
205 return self.unmanaged.getOrPutValueContext(self.allocator, key, value, self.ctx);
159206 }
160207
161208 /// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`.
......@@ -164,14 +211,14 @@ pub fn ArrayHashMap(
164211 /// Increases capacity, guaranteeing that insertions up until the
165212 /// `expected_count` will not cause an allocation, and therefore cannot fail.
166213 pub fn ensureTotalCapacity(self: *Self, new_capacity: usize) !void {
167 return self.unmanaged.ensureTotalCapacity(self.allocator, new_capacity);
214 return self.unmanaged.ensureTotalCapacityContext(self.allocator, new_capacity, self.ctx);
168215 }
169216
170217 /// Increases capacity, guaranteeing that insertions up until
171218 /// `additional_count` **more** items will not cause an allocation, and
172219 /// therefore cannot fail.
173220 pub fn ensureUnusedCapacity(self: *Self, additional_count: usize) !void {
174 return self.unmanaged.ensureUnusedCapacity(self.allocator, additional_count);
221 return self.unmanaged.ensureUnusedCapacityContext(self.allocator, additional_count, self.ctx);
175222 }
176223
177224 /// Returns the number of total elements which may be present before it is
......@@ -183,119 +230,187 @@ pub fn ArrayHashMap(
183230 /// Clobbers any existing data. To detect if a put would clobber
184231 /// existing data, see `getOrPut`.
185232 pub fn put(self: *Self, key: K, value: V) !void {
186 return self.unmanaged.put(self.allocator, key, value);
233 return self.unmanaged.putContext(self.allocator, key, value, self.ctx);
187234 }
188235
189236 /// Inserts a key-value pair into the hash map, asserting that no previous
190237 /// entry with the same key is already present
191238 pub fn putNoClobber(self: *Self, key: K, value: V) !void {
192 return self.unmanaged.putNoClobber(self.allocator, key, value);
239 return self.unmanaged.putNoClobberContext(self.allocator, key, value, self.ctx);
193240 }
194241
195242 /// Asserts there is enough capacity to store the new key-value pair.
196243 /// Clobbers any existing data. To detect if a put would clobber
197244 /// existing data, see `getOrPutAssumeCapacity`.
198245 pub fn putAssumeCapacity(self: *Self, key: K, value: V) void {
199 return self.unmanaged.putAssumeCapacity(key, value);
246 return self.unmanaged.putAssumeCapacityContext(key, value, self.ctx);
200247 }
201248
202249 /// Asserts there is enough capacity to store the new key-value pair.
203250 /// Asserts that it does not clobber any existing data.
204251 /// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`.
205252 pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void {
206 return self.unmanaged.putAssumeCapacityNoClobber(key, value);
253 return self.unmanaged.putAssumeCapacityNoClobberContext(key, value, self.ctx);
207254 }
208255
209256 /// Inserts a new `Entry` into the hash map, returning the previous one, if any.
210 pub fn fetchPut(self: *Self, key: K, value: V) !?Entry {
211 return self.unmanaged.fetchPut(self.allocator, key, value);
257 pub fn fetchPut(self: *Self, key: K, value: V) !?KV {
258 return self.unmanaged.fetchPutContext(self.allocator, key, value, self.ctx);
212259 }
213260
214261 /// Inserts a new `Entry` into the hash map, returning the previous one, if any.
215262 /// If insertion happuns, asserts there is enough capacity without allocating.
216 pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?Entry {
217 return self.unmanaged.fetchPutAssumeCapacity(key, value);
263 pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?KV {
264 return self.unmanaged.fetchPutAssumeCapacityContext(key, value, self.ctx);
218265 }
219266
220 pub fn getEntry(self: Self, key: K) ?*Entry {
221 return self.unmanaged.getEntry(key);
267 /// Finds pointers to the key and value storage associated with a key.
268 pub fn getEntry(self: Self, key: K) ?Entry {
269 return self.unmanaged.getEntryContext(key, self.ctx);
270 }
271 pub fn getEntryAdapted(self: Self, key: anytype, ctx: anytype) ?Entry {
272 return self.unmanaged.getEntryAdapted(key, ctx);
222273 }
223274
275 /// Finds the index in the `entries` array where a key is stored
224276 pub fn getIndex(self: Self, key: K) ?usize {
225 return self.unmanaged.getIndex(key);
277 return self.unmanaged.getIndexContext(key, self.ctx);
278 }
279 pub fn getIndexAdapted(self: Self, key: anytype, ctx: anytype) ?usize {
280 return self.unmanaged.getIndexAdapted(key, ctx);
226281 }
227282
283 /// Find the value associated with a key
228284 pub fn get(self: Self, key: K) ?V {
229 return self.unmanaged.get(key);
285 return self.unmanaged.getContext(key, self.ctx);
286 }
287 pub fn getAdapted(self: Self, key: anytype, ctx: anytype) ?V {
288 return self.unmanaged.getAdapted(key, ctx);
230289 }
231290
291 /// Find a pointer to the value associated with a key
292 pub fn getPtr(self: Self, key: K) ?*V {
293 return self.unmanaged.getPtrContext(key, self.ctx);
294 }
295 pub fn getPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*V {
296 return self.unmanaged.getPtrAdapted(key, ctx);
297 }
298
299 /// Check whether a key is stored in the map
232300 pub fn contains(self: Self, key: K) bool {
233 return self.unmanaged.contains(key);
301 return self.unmanaged.containsContext(key, self.ctx);
302 }
303 pub fn containsAdapted(self: Self, key: anytype, ctx: anytype) bool {
304 return self.unmanaged.containsAdapted(key, ctx);
234305 }
235306
236307 /// If there is an `Entry` with a matching key, it is deleted from
237308 /// the hash map, and then returned from this function. The entry is
238309 /// removed from the underlying array by swapping it with the last
239310 /// element.
240 pub fn swapRemove(self: *Self, key: K) ?Entry {
241 return self.unmanaged.swapRemove(key);
311 pub fn fetchSwapRemove(self: *Self, key: K) ?KV {
312 return self.unmanaged.fetchSwapRemoveContext(key, self.ctx);
313 }
314 pub fn fetchSwapRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KV {
315 return self.unmanaged.fetchSwapRemoveContextAdapted(key, ctx, self.ctx);
242316 }
243317
244318 /// If there is an `Entry` with a matching key, it is deleted from
245319 /// the hash map, and then returned from this function. The entry is
246320 /// removed from the underlying array by shifting all elements forward
247321 /// thereby maintaining the current ordering.
248 pub fn orderedRemove(self: *Self, key: K) ?Entry {
249 return self.unmanaged.orderedRemove(key);
322 pub fn fetchOrderedRemove(self: *Self, key: K) ?KV {
323 return self.unmanaged.fetchOrderedRemoveContext(key, self.ctx);
324 }
325 pub fn fetchOrderedRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KV {
326 return self.unmanaged.fetchOrderedRemoveContextAdapted(key, ctx, self.ctx);
250327 }
251328
252 /// TODO: deprecated: call swapRemoveAssertDiscard instead.
253 pub fn removeAssertDiscard(self: *Self, key: K) void {
254 return self.unmanaged.removeAssertDiscard(key);
329 /// If there is an `Entry` with a matching key, it is deleted from
330 /// the hash map. The entry is removed from the underlying array
331 /// by swapping it with the last element. Returns true if an entry
332 /// was removed, false otherwise.
333 pub fn swapRemove(self: *Self, key: K) bool {
334 return self.unmanaged.swapRemoveContext(key, self.ctx);
335 }
336 pub fn swapRemoveAdapted(self: *Self, key: anytype, ctx: anytype) bool {
337 return self.unmanaged.swapRemoveContextAdapted(key, ctx, self.ctx);
255338 }
256339
257 /// Asserts there is an `Entry` with matching key, deletes it from the hash map
258 /// by swapping it with the last element, and discards it.
259 pub fn swapRemoveAssertDiscard(self: *Self, key: K) void {
260 return self.unmanaged.swapRemoveAssertDiscard(key);
340 /// If there is an `Entry` with a matching key, it is deleted from
341 /// the hash map. The entry is removed from the underlying array
342 /// by shifting all elements forward, thereby maintaining the
343 /// current ordering. Returns true if an entry was removed, false otherwise.
344 pub fn orderedRemove(self: *Self, key: K) bool {
345 return self.unmanaged.orderedRemoveContext(key, self.ctx);
346 }
347 pub fn orderedRemoveAdapted(self: *Self, key: anytype, ctx: anytype) bool {
348 return self.unmanaged.orderedRemoveContextAdapted(key, ctx, self.ctx);
261349 }
262350
263 /// Asserts there is an `Entry` with matching key, deletes it from the hash map
264 /// by by shifting all elements forward thereby maintaining the current ordering.
265 pub fn orderedRemoveAssertDiscard(self: *Self, key: K) void {
266 return self.unmanaged.orderedRemoveAssertDiscard(key);
351 /// Deletes the item at the specified index in `entries` from
352 /// the hash map. The entry is removed from the underlying array
353 /// by swapping it with the last element.
354 pub fn swapRemoveAt(self: *Self, index: usize) void {
355 self.unmanaged.swapRemoveAtContext(index, self.ctx);
267356 }
268357
269 pub fn items(self: Self) []Entry {
270 return self.unmanaged.items();
358 /// Deletes the item at the specified index in `entries` from
359 /// the hash map. The entry is removed from the underlying array
360 /// by shifting all elements forward, thereby maintaining the
361 /// current ordering.
362 pub fn orderedRemoveAt(self: *Self, index: usize) void {
363 self.unmanaged.orderedRemoveAtContext(index, self.ctx);
271364 }
272365
366 /// Create a copy of the hash map which can be modified separately.
367 /// The copy uses the same context and allocator as this instance.
273368 pub fn clone(self: Self) !Self {
274 var other = try self.unmanaged.clone(self.allocator);
275 return other.promote(self.allocator);
369 var other = try self.unmanaged.cloneContext(self.allocator, self.ctx);
370 return other.promoteContext(self.allocator, self.ctx);
371 }
372 /// Create a copy of the hash map which can be modified separately.
373 /// The copy uses the same context as this instance, but the specified
374 /// allocator.
375 pub fn cloneWithAllocator(self: Self, allocator: *Allocator) !Self {
376 var other = try self.unmanaged.cloneContext(allocator, self.ctx);
377 return other.promoteContext(allocator, self.ctx);
378 }
379 /// Create a copy of the hash map which can be modified separately.
380 /// The copy uses the same allocator as this instance, but the
381 /// specified context.
382 pub fn cloneWithContext(self: Self, ctx: anytype) !ArrayHashMap(K, V, @TypeOf(ctx), store_hash) {
383 var other = try self.unmanaged.cloneContext(self.allocator, ctx);
384 return other.promoteContext(self.allocator, ctx);
385 }
386 /// Create a copy of the hash map which can be modified separately.
387 /// The copy uses the specified allocator and context.
388 pub fn cloneWithAllocatorAndContext(self: Self, allocator: *Allocator, ctx: anytype) !ArrayHashMap(K, V, @TypeOf(ctx), store_hash) {
389 var other = try self.unmanaged.cloneContext(allocator, ctx);
390 return other.promoteContext(allocator, ctx);
276391 }
277392
278393 /// Rebuilds the key indexes. If the underlying entries has been modified directly, users
279394 /// can call `reIndex` to update the indexes to account for these new entries.
280395 pub fn reIndex(self: *Self) !void {
281 return self.unmanaged.reIndex(self.allocator);
396 return self.unmanaged.reIndexContext(self.allocator, self.ctx);
282397 }
283398
284399 /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated
285400 /// index entries. Keeps capacity the same.
286401 pub fn shrinkRetainingCapacity(self: *Self, new_len: usize) void {
287 return self.unmanaged.shrinkRetainingCapacity(new_len);
402 return self.unmanaged.shrinkRetainingCapacityContext(new_len, self.ctx);
288403 }
289404
290405 /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated
291406 /// index entries. Reduces allocated capacity.
292407 pub fn shrinkAndFree(self: *Self, new_len: usize) void {
293 return self.unmanaged.shrinkAndFree(self.allocator, new_len);
408 return self.unmanaged.shrinkAndFreeContext(self.allocator, new_len, self.ctx);
294409 }
295410
296411 /// Removes the last inserted `Entry` in the hash map and returns it.
297 pub fn pop(self: *Self) Entry {
298 return self.unmanaged.pop();
412 pub fn pop(self: *Self) KV {
413 return self.unmanaged.popContext(self.ctx);
299414 }
300415 };
301416}
......@@ -317,16 +432,23 @@ pub fn ArrayHashMap(
317432/// functions. It does not store each item's hash in the table. Setting `store_hash`
318433/// to `true` incurs slightly more memory cost by storing each key's hash in the table
319434/// but guarantees only one call to `eql` per insertion/deletion.
435/// Context must be a struct type with two member functions:
436/// hash(self, K) u32
437/// eql(self, K, K) bool
438/// Adapted variants of many functions are provided. These variants
439/// take a pseudo key instead of a key. Their context must have the functions:
440/// hash(self, PseudoKey) u32
441/// eql(self, PseudoKey, K) bool
320442pub fn ArrayHashMapUnmanaged(
321443 comptime K: type,
322444 comptime V: type,
323 comptime hash: fn (key: K) u32,
324 comptime eql: fn (a: K, b: K) bool,
445 comptime Context: type,
325446 comptime store_hash: bool,
326447) type {
448 comptime std.hash_map.verifyContext(Context, K, K, u32);
327449 return struct {
328450 /// It is permitted to access this field directly.
329 entries: std.ArrayListUnmanaged(Entry) = .{},
451 entries: DataList = .{},
330452
331453 /// When entries length is less than `linear_scan_max`, this remains `null`.
332454 /// Once entries length grows big enough, this field is allocated. There is
......@@ -334,26 +456,54 @@ pub fn ArrayHashMapUnmanaged(
334456 /// by how many total indexes there are.
335457 index_header: ?*IndexHeader = null,
336458
337 /// Modifying the key is illegal behavior.
459 /// Modifying the key is allowed only if it does not change the hash.
338460 /// Modifying the value is allowed.
339461 /// Entry pointers become invalid whenever this ArrayHashMap is modified,
340462 /// unless `ensureCapacity` was previously used.
341463 pub const Entry = struct {
342 /// This field is `void` if `store_hash` is `false`.
464 key_ptr: *K,
465 value_ptr: *V,
466 };
467
468 /// A KV pair which has been copied out of the backing store
469 pub const KV = struct {
470 key: K,
471 value: V,
472 };
473
474 /// The Data type used for the MultiArrayList backing this map
475 pub const Data = struct {
343476 hash: Hash,
344477 key: K,
345478 value: V,
346479 };
347480
481 /// The MultiArrayList type backing this map
482 pub const DataList = std.MultiArrayList(Data);
483
484 /// The stored hash type, either u32 or void.
348485 pub const Hash = if (store_hash) u32 else void;
349486
487 /// getOrPut variants return this structure, with pointers
488 /// to the backing store and a flag to indicate whether an
489 /// existing entry was found.
490 /// Modifying the key is allowed only if it does not change the hash.
491 /// Modifying the value is allowed.
492 /// Entry pointers become invalid whenever this ArrayHashMap is modified,
493 /// unless `ensureCapacity` was previously used.
350494 pub const GetOrPutResult = struct {
351 entry: *Entry,
495 key_ptr: *K,
496 value_ptr: *V,
352497 found_existing: bool,
353498 index: usize,
354499 };
355500
356 pub const Managed = ArrayHashMap(K, V, hash, eql, store_hash);
501 /// The ArrayHashMap type using the same settings as this managed map.
502 pub const Managed = ArrayHashMap(K, V, Context, store_hash);
503
504 /// Some functions require a context only if hashes are not stored.
505 /// To keep the api simple, this type is only used internally.
506 const ByIndexContext = if (store_hash) void else Context;
357507
358508 const Self = @This();
359509
......@@ -362,25 +512,26 @@ pub fn ArrayHashMapUnmanaged(
362512 const RemovalType = enum {
363513 swap,
364514 ordered,
365 index_only,
366515 };
367516
517 /// Convert from an unmanaged map to a managed map. After calling this,
518 /// the promoted map should no longer be used.
368519 pub fn promote(self: Self, allocator: *Allocator) Managed {
520 if (@sizeOf(Context) != 0)
521 @compileError("Cannot infer context "++@typeName(Context)++", call promoteContext instead.");
522 return self.promoteContext(allocator, undefined);
523 }
524 pub fn promoteContext(self: Self, allocator: *Allocator, ctx: Context) Managed {
369525 return .{
370526 .unmanaged = self,
371527 .allocator = allocator,
528 .ctx = ctx,
372529 };
373530 }
374531
375 /// `ArrayHashMapUnmanaged` takes ownership of the passed in array list. The array list must
376 /// have been allocated with `allocator`.
377 /// Deinitialize with `deinit`.
378 pub fn fromOwnedArrayList(allocator: *Allocator, entries: std.ArrayListUnmanaged(Entry)) !Self {
379 var array_hash_map = Self{ .entries = entries };
380 try array_hash_map.reIndex(allocator);
381 return array_hash_map;
382 }
383
532 /// Frees the backing allocation and leaves the map in an undefined state.
533 /// Note that this does not free keys or values. You must take care of that
534 /// before calling this function, if it is needed.
384535 pub fn deinit(self: *Self, allocator: *Allocator) void {
385536 self.entries.deinit(allocator);
386537 if (self.index_header) |header| {
......@@ -389,19 +540,19 @@ pub fn ArrayHashMapUnmanaged(
389540 self.* = undefined;
390541 }
391542
543 /// Clears the map but retains the backing allocation for future use.
392544 pub fn clearRetainingCapacity(self: *Self) void {
393 self.entries.items.len = 0;
545 self.entries.len = 0;
394546 if (self.index_header) |header| {
395 header.max_distance_from_start_index = 0;
396547 switch (header.capacityIndexType()) {
397548 .u8 => mem.set(Index(u8), header.indexes(u8), Index(u8).empty),
398549 .u16 => mem.set(Index(u16), header.indexes(u16), Index(u16).empty),
399550 .u32 => mem.set(Index(u32), header.indexes(u32), Index(u32).empty),
400 .usize => mem.set(Index(usize), header.indexes(usize), Index(usize).empty),
401551 }
402552 }
403553 }
404554
555 /// Clears the map and releases the backing allocation
405556 pub fn clearAndFree(self: *Self, allocator: *Allocator) void {
406557 self.entries.shrinkAndFree(allocator, 0);
407558 if (self.index_header) |header| {
......@@ -410,9 +561,54 @@ pub fn ArrayHashMapUnmanaged(
410561 }
411562 }
412563
564 /// Returns the number of KV pairs stored in this map.
413565 pub fn count(self: Self) usize {
414 return self.entries.items.len;
566 return self.entries.len;
567 }
568
569 /// Returns the backing array of keys in this map.
570 /// Modifying the map may invalidate this array.
571 pub fn keys(self: Self) []K {
572 return self.entries.items(.key);
573 }
574 /// Returns the backing array of values in this map.
575 /// Modifying the map may invalidate this array.
576 pub fn values(self: Self) []V {
577 return self.entries.items(.value);
578 }
579
580 /// Returns an iterator over the pairs in this map.
581 /// Modifying the map may invalidate this iterator.
582 pub fn iterator(self: Self) Iterator {
583 const slice = self.entries.slice();
584 return .{
585 .keys = slice.items(.key).ptr,
586 .values = slice.items(.value).ptr,
587 .len = @intCast(u32, slice.len),
588 };
415589 }
590 pub const Iterator = struct {
591 keys: [*]K,
592 values: [*]V,
593 len: u32,
594 index: u32 = 0,
595
596 pub fn next(it: *Iterator) ?Entry {
597 if (it.index >= it.len) return null;
598 const result = Entry{
599 .key_ptr = &it.keys[it.index],
600 // workaround for #6974
601 .value_ptr = if (@sizeOf(*V) == 0) undefined else &it.values[it.index],
602 };
603 it.index += 1;
604 return result;
605 }
606
607 /// Reset the iterator to the initial index
608 pub fn reset(it: *Iterator) void {
609 it.index = 0;
610 }
611 };
416612
417613 /// If key exists this function cannot fail.
418614 /// If there is an existing item with `key`, then the result
......@@ -421,16 +617,36 @@ pub fn ArrayHashMapUnmanaged(
421617 /// the `Entry` pointer points to it. Caller should then initialize
422618 /// the value (but not the key).
423619 pub fn getOrPut(self: *Self, allocator: *Allocator, key: K) !GetOrPutResult {
424 self.ensureCapacity(allocator, self.entries.items.len + 1) catch |err| {
620 if (@sizeOf(Context) != 0)
621 @compileError("Cannot infer context "++@typeName(Context)++", call getOrPutContext instead.");
622 return self.getOrPutContext(allocator, key, undefined);
623 }
624 pub fn getOrPutContext(self: *Self, allocator: *Allocator, key: K, ctx: Context) !GetOrPutResult {
625 const gop = try self.getOrPutContextAdapted(allocator, key, ctx, ctx);
626 if (!gop.found_existing) {
627 gop.key_ptr.* = key;
628 }
629 return gop;
630 }
631 pub fn getOrPutAdapted(self: *Self, allocator: *Allocator, key: anytype, key_ctx: anytype) !GetOrPutResult {
632 if (@sizeOf(Context) != 0)
633 @compileError("Cannot infer context "++@typeName(Context)++", call getOrPutContextAdapted instead.");
634 return self.getOrPutContextAdapted(allocator, key, key_ctx, undefined);
635 }
636 pub fn getOrPutContextAdapted(self: *Self, allocator: *Allocator, key: anytype, key_ctx: anytype, ctx: Context) !GetOrPutResult {
637 self.ensureTotalCapacityContext(allocator, self.entries.len + 1, ctx) catch |err| {
425638 // "If key exists this function cannot fail."
426 const index = self.getIndex(key) orelse return err;
639 const index = self.getIndexAdapted(key, key_ctx) orelse return err;
640 const slice = self.entries.slice();
427641 return GetOrPutResult{
428 .entry = &self.entries.items[index],
642 .key_ptr = &slice.items(.key)[index],
643 // workaround for #6974
644 .value_ptr = if (@sizeOf(*V) == 0) undefined else &slice.items(.value)[index],
429645 .found_existing = true,
430646 .index = index,
431647 };
432648 };
433 return self.getOrPutAssumeCapacity(key);
649 return self.getOrPutAssumeCapacityAdapted(key, key_ctx);
434650 }
435651
436652 /// If there is an existing item with `key`, then the result
......@@ -441,45 +657,75 @@ pub fn ArrayHashMapUnmanaged(
441657 /// If a new entry needs to be stored, this function asserts there
442658 /// is enough capacity to store it.
443659 pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult {
660 if (@sizeOf(Context) != 0)
661 @compileError("Cannot infer context "++@typeName(Context)++", call getOrPutAssumeCapacityContext instead.");
662 return self.getOrPutAssumeCapacityContext(key, undefined);
663 }
664 pub fn getOrPutAssumeCapacityContext(self: *Self, key: K, ctx: Context) GetOrPutResult {
665 const gop = self.getOrPutAssumeCapacityAdapted(key, ctx);
666 if (!gop.found_existing) {
667 gop.key_ptr.* = key;
668 }
669 return gop;
670 }
671 /// If there is an existing item with `key`, then the result
672 /// `Entry` pointers point to it, and found_existing is true.
673 /// Otherwise, puts a new item with undefined key and value, and
674 /// the `Entry` pointers point to it. Caller must then initialize
675 /// both the key and the value.
676 /// If a new entry needs to be stored, this function asserts there
677 /// is enough capacity to store it.
678 pub fn getOrPutAssumeCapacityAdapted(self: *Self, key: anytype, ctx: anytype) GetOrPutResult {
444679 const header = self.index_header orelse {
445680 // Linear scan.
446 const h = if (store_hash) hash(key) else {};
447 for (self.entries.items) |*item, i| {
448 if (item.hash == h and eql(key, item.key)) {
681 const h = if (store_hash) checkedHash(ctx, key) else {};
682 const slice = self.entries.slice();
683 const hashes_array = slice.items(.hash);
684 const keys_array = slice.items(.key);
685 for (keys_array) |*item_key, i| {
686 if (hashes_array[i] == h and checkedEql(ctx, key, item_key.*)) {
449687 return GetOrPutResult{
450 .entry = item,
688 .key_ptr = item_key,
689 // workaround for #6974
690 .value_ptr = if (@sizeOf(*V) == 0) undefined else &slice.items(.value)[i],
451691 .found_existing = true,
452692 .index = i,
453693 };
454694 }
455695 }
456 const new_entry = self.entries.addOneAssumeCapacity();
457 new_entry.* = .{
458 .hash = if (store_hash) h else {},
459 .key = key,
460 .value = undefined,
461 };
696
697 const index = self.entries.addOneAssumeCapacity();
698 // unsafe indexing because the length changed
699 if (store_hash) hashes_array.ptr[index] = h;
700
462701 return GetOrPutResult{
463 .entry = new_entry,
702 .key_ptr = &keys_array.ptr[index],
703 // workaround for #6974
704 .value_ptr = if (@sizeOf(*V) == 0) undefined else &slice.items(.value).ptr[index],
464705 .found_existing = false,
465 .index = self.entries.items.len - 1,
706 .index = index,
466707 };
467708 };
468709
469710 switch (header.capacityIndexType()) {
470 .u8 => return self.getOrPutInternal(key, header, u8),
471 .u16 => return self.getOrPutInternal(key, header, u16),
472 .u32 => return self.getOrPutInternal(key, header, u32),
473 .usize => return self.getOrPutInternal(key, header, usize),
711 .u8 => return self.getOrPutInternal(key, ctx, header, u8),
712 .u16 => return self.getOrPutInternal(key, ctx, header, u16),
713 .u32 => return self.getOrPutInternal(key, ctx, header, u32),
474714 }
475715 }
476716
477 pub fn getOrPutValue(self: *Self, allocator: *Allocator, key: K, value: V) !*Entry {
478 const res = try self.getOrPut(allocator, key);
479 if (!res.found_existing)
480 res.entry.value = value;
481
482 return res.entry;
717 pub fn getOrPutValue(self: *Self, allocator: *Allocator, key: K, value: V) !GetOrPutResult {
718 if (@sizeOf(Context) != 0)
719 @compileError("Cannot infer context "++@typeName(Context)++", call getOrPutValueContext instead.");
720 return self.getOrPutValueContext(allocator, key, value, undefined);
721 }
722 pub fn getOrPutValueContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !GetOrPutResult {
723 const res = try self.getOrPutContextAdapted(allocator, key, ctx, ctx);
724 if (!res.found_existing) {
725 res.key_ptr.* = key;
726 res.value_ptr.* = value;
727 }
728 return res;
483729 }
484730
485731 /// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`.
......@@ -488,30 +734,30 @@ pub fn ArrayHashMapUnmanaged(
488734 /// Increases capacity, guaranteeing that insertions up until the
489735 /// `expected_count` will not cause an allocation, and therefore cannot fail.
490736 pub fn ensureTotalCapacity(self: *Self, allocator: *Allocator, new_capacity: usize) !void {
491 try self.entries.ensureTotalCapacity(allocator, new_capacity);
492 if (new_capacity <= linear_scan_max) return;
737 if (@sizeOf(ByIndexContext) != 0)
738 @compileError("Cannot infer context "++@typeName(Context)++", call ensureTotalCapacityContext instead.");
739 return self.ensureTotalCapacityContext(allocator, new_capacity, undefined);
740 }
741 pub fn ensureTotalCapacityContext(self: *Self, allocator: *Allocator, new_capacity: usize, ctx: Context) !void {
742 if (new_capacity <= linear_scan_max) {
743 try self.entries.ensureCapacity(allocator, new_capacity);
744 return;
745 }
493746
494 // Ensure that the indexes will be at most 60% full if
495 // `new_capacity` items are put into it.
496 const needed_len = new_capacity * 5 / 3;
497747 if (self.index_header) |header| {
498 if (needed_len > header.indexes_len) {
499 // An overflow here would mean the amount of memory required would not
500 // be representable in the address space.
501 const new_indexes_len = math.ceilPowerOfTwo(usize, needed_len) catch unreachable;
502 const new_header = try IndexHeader.alloc(allocator, new_indexes_len);
503 self.insertAllEntriesIntoNewHeader(new_header);
504 header.free(allocator);
505 self.index_header = new_header;
748 if (new_capacity <= header.capacity()) {
749 try self.entries.ensureCapacity(allocator, new_capacity);
750 return;
506751 }
507 } else {
508 // An overflow here would mean the amount of memory required would not
509 // be representable in the address space.
510 const new_indexes_len = math.ceilPowerOfTwo(usize, needed_len) catch unreachable;
511 const header = try IndexHeader.alloc(allocator, new_indexes_len);
512 self.insertAllEntriesIntoNewHeader(header);
513 self.index_header = header;
514752 }
753
754 const new_bit_index = try IndexHeader.findBitIndex(new_capacity);
755 const new_header = try IndexHeader.alloc(allocator, new_bit_index);
756 try self.entries.ensureCapacity(allocator, new_capacity);
757
758 if (self.index_header) |old_header| old_header.free(allocator);
759 self.insertAllEntriesIntoNewHeader(if (store_hash) {} else ctx, new_header);
760 self.index_header = new_header;
515761 }
516762
517763 /// Increases capacity, guaranteeing that insertions up until
......@@ -522,7 +768,17 @@ pub fn ArrayHashMapUnmanaged(
522768 allocator: *Allocator,
523769 additional_capacity: usize,
524770 ) !void {
525 return self.ensureTotalCapacity(allocator, self.count() + additional_capacity);
771 if (@sizeOf(ByIndexContext) != 0)
772 @compileError("Cannot infer context "++@typeName(Context)++", call ensureTotalCapacityContext instead.");
773 return self.ensureUnusedCapacityContext(allocator, additional_capacity, undefined);
774 }
775 pub fn ensureUnusedCapacityContext(
776 self: *Self,
777 allocator: *Allocator,
778 additional_capacity: usize,
779 ctx: Context,
780 ) !void {
781 return self.ensureTotalCapacityContext(allocator, self.count() + additional_capacity, ctx);
526782 }
527783
528784 /// Returns the number of total elements which may be present before it is
......@@ -530,141 +786,321 @@ pub fn ArrayHashMapUnmanaged(
530786 pub fn capacity(self: Self) usize {
531787 const entry_cap = self.entries.capacity;
532788 const header = self.index_header orelse return math.min(linear_scan_max, entry_cap);
533 const indexes_cap = (header.indexes_len + 1) * 3 / 4;
789 const indexes_cap = header.capacity();
534790 return math.min(entry_cap, indexes_cap);
535791 }
536792
537793 /// Clobbers any existing data. To detect if a put would clobber
538794 /// existing data, see `getOrPut`.
539795 pub fn put(self: *Self, allocator: *Allocator, key: K, value: V) !void {
540 const result = try self.getOrPut(allocator, key);
541 result.entry.value = value;
796 if (@sizeOf(Context) != 0)
797 @compileError("Cannot infer context "++@typeName(Context)++", call putContext instead.");
798 return self.putContext(allocator, key, value, undefined);
799 }
800 pub fn putContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !void {
801 const result = try self.getOrPutContext(allocator, key, ctx);
802 result.value_ptr.* = value;
542803 }
543804
544805 /// Inserts a key-value pair into the hash map, asserting that no previous
545806 /// entry with the same key is already present
546807 pub fn putNoClobber(self: *Self, allocator: *Allocator, key: K, value: V) !void {
547 const result = try self.getOrPut(allocator, key);
808 if (@sizeOf(Context) != 0)
809 @compileError("Cannot infer context "++@typeName(Context)++", call putNoClobberContext instead.");
810 return self.putNoClobberContext(allocator, key, value, undefined);
811 }
812 pub fn putNoClobberContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !void {
813 const result = try self.getOrPutContext(allocator, key, ctx);
548814 assert(!result.found_existing);
549 result.entry.value = value;
815 result.value_ptr.* = value;
550816 }
551817
552818 /// Asserts there is enough capacity to store the new key-value pair.
553819 /// Clobbers any existing data. To detect if a put would clobber
554820 /// existing data, see `getOrPutAssumeCapacity`.
555821 pub fn putAssumeCapacity(self: *Self, key: K, value: V) void {
556 const result = self.getOrPutAssumeCapacity(key);
557 result.entry.value = value;
822 if (@sizeOf(Context) != 0)
823 @compileError("Cannot infer context "++@typeName(Context)++", call putAssumeCapacityContext instead.");
824 return self.putAssumeCapacityContext(key, value, undefined);
825 }
826 pub fn putAssumeCapacityContext(self: *Self, key: K, value: V, ctx: Context) void {
827 const result = self.getOrPutAssumeCapacityContext(key, ctx);
828 result.value_ptr.* = value;
558829 }
559830
560831 /// Asserts there is enough capacity to store the new key-value pair.
561832 /// Asserts that it does not clobber any existing data.
562833 /// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`.
563834 pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void {
564 const result = self.getOrPutAssumeCapacity(key);
835 if (@sizeOf(Context) != 0)
836 @compileError("Cannot infer context "++@typeName(Context)++", call putAssumeCapacityNoClobberContext instead.");
837 return self.putAssumeCapacityNoClobberContext(key, value, undefined);
838 }
839 pub fn putAssumeCapacityNoClobberContext(self: *Self, key: K, value: V, ctx: Context) void {
840 const result = self.getOrPutAssumeCapacityContext(key, ctx);
565841 assert(!result.found_existing);
566 result.entry.value = value;
842 result.value_ptr.* = value;
567843 }
568844
569845 /// Inserts a new `Entry` into the hash map, returning the previous one, if any.
570 pub fn fetchPut(self: *Self, allocator: *Allocator, key: K, value: V) !?Entry {
571 const gop = try self.getOrPut(allocator, key);
572 var result: ?Entry = null;
846 pub fn fetchPut(self: *Self, allocator: *Allocator, key: K, value: V) !?KV {
847 if (@sizeOf(Context) != 0)
848 @compileError("Cannot infer context "++@typeName(Context)++", call fetchPutContext instead.");
849 return self.fetchPutContext(allocator, key, value, undefined);
850 }
851 pub fn fetchPutContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !?KV {
852 const gop = try self.getOrPutContext(allocator, key, ctx);
853 var result: ?KV = null;
573854 if (gop.found_existing) {
574 result = gop.entry.*;
855 result = KV{
856 .key = gop.key_ptr.*,
857 .value = gop.value_ptr.*,
858 };
575859 }
576 gop.entry.value = value;
860 gop.value_ptr.* = value;
577861 return result;
578862 }
579863
580864 /// Inserts a new `Entry` into the hash map, returning the previous one, if any.
581865 /// If insertion happens, asserts there is enough capacity without allocating.
582 pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?Entry {
583 const gop = self.getOrPutAssumeCapacity(key);
584 var result: ?Entry = null;
866 pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?KV {
867 if (@sizeOf(Context) != 0)
868 @compileError("Cannot infer context "++@typeName(Context)++", call fetchPutAssumeCapacityContext instead.");
869 return self.fetchPutAssumeCapacityContext(key, value, undefined);
870 }
871 pub fn fetchPutAssumeCapacityContext(self: *Self, key: K, value: V, ctx: Context) ?KV {
872 const gop = self.getOrPutAssumeCapacityContext(key, ctx);
873 var result: ?KV = null;
585874 if (gop.found_existing) {
586 result = gop.entry.*;
875 result = KV{
876 .key = gop.key_ptr.*,
877 .value = gop.value_ptr.*,
878 };
587879 }
588 gop.entry.value = value;
880 gop.value_ptr.* = value;
589881 return result;
590882 }
591883
592 pub fn getEntry(self: Self, key: K) ?*Entry {
593 const index = self.getIndex(key) orelse return null;
594 return &self.entries.items[index];
884 /// Finds pointers to the key and value storage associated with a key.
885 pub fn getEntry(self: Self, key: K) ?Entry {
886 if (@sizeOf(Context) != 0)
887 @compileError("Cannot infer context "++@typeName(Context)++", call getEntryContext instead.");
888 return self.getEntryContext(key, undefined);
889 }
890 pub fn getEntryContext(self: Self, key: K, ctx: Context) ?Entry {
891 return self.getEntryAdapted(key, ctx);
892 }
893 pub fn getEntryAdapted(self: Self, key: anytype, ctx: anytype) ?Entry {
894 const index = self.getIndexAdapted(key, ctx) orelse return null;
895 const slice = self.entries.slice();
896 return Entry{
897 .key_ptr = &slice.items(.key)[index],
898 // workaround for #6974
899 .value_ptr = if (@sizeOf(*V) == 0) undefined else &slice.items(.value)[index],
900 };
595901 }
596902
903 /// Finds the index in the `entries` array where a key is stored
597904 pub fn getIndex(self: Self, key: K) ?usize {
905 if (@sizeOf(Context) != 0)
906 @compileError("Cannot infer context "++@typeName(Context)++", call getIndexContext instead.");
907 return self.getIndexContext(key, undefined);
908 }
909 pub fn getIndexContext(self: Self, key: K, ctx: Context) ?usize {
910 return self.getIndexAdapted(key, ctx);
911 }
912 pub fn getIndexAdapted(self: Self, key: anytype, ctx: anytype) ?usize {
598913 const header = self.index_header orelse {
599914 // Linear scan.
600 const h = if (store_hash) hash(key) else {};
601 for (self.entries.items) |*item, i| {
602 if (item.hash == h and eql(key, item.key)) {
915 const h = if (store_hash) checkedHash(ctx, key) else {};
916 const slice = self.entries.slice();
917 const hashes_array = slice.items(.hash);
918 const keys_array = slice.items(.key);
919 for (keys_array) |*item_key, i| {
920 if (hashes_array[i] == h and checkedEql(ctx, key, item_key.*)) {
603921 return i;
604922 }
605923 }
606924 return null;
607925 };
608926 switch (header.capacityIndexType()) {
609 .u8 => return self.getInternal(key, header, u8),
610 .u16 => return self.getInternal(key, header, u16),
611 .u32 => return self.getInternal(key, header, u32),
612 .usize => return self.getInternal(key, header, usize),
927 .u8 => return self.getIndexWithHeaderGeneric(key, ctx, header, u8),
928 .u16 => return self.getIndexWithHeaderGeneric(key, ctx, header, u16),
929 .u32 => return self.getIndexWithHeaderGeneric(key, ctx, header, u32),
613930 }
614931 }
932 fn getIndexWithHeaderGeneric(self: Self, key: anytype, ctx: anytype, header: *IndexHeader, comptime I: type) ?usize {
933 const indexes = header.indexes(I);
934 const slot = self.getSlotByKey(key, ctx, header, I, indexes) orelse return null;
935 return indexes[slot].entry_index;
936 }
615937
938 /// Find the value associated with a key
616939 pub fn get(self: Self, key: K) ?V {
617 return if (self.getEntry(key)) |entry| entry.value else null;
940 if (@sizeOf(Context) != 0)
941 @compileError("Cannot infer context "++@typeName(Context)++", call getContext instead.");
942 return self.getContext(key, undefined);
943 }
944 pub fn getContext(self: Self, key: K, ctx: Context) ?V {
945 return self.getAdapted(key, ctx);
946 }
947 pub fn getAdapted(self: Self, key: anytype, ctx: anytype) ?V {
948 const index = self.getIndexAdapted(key, ctx) orelse return null;
949 return self.values()[index];
950 }
951
952 /// Find a pointer to the value associated with a key
953 pub fn getPtr(self: Self, key: K) ?*V {
954 if (@sizeOf(Context) != 0)
955 @compileError("Cannot infer context "++@typeName(Context)++", call getPtrContext instead.");
956 return self.getPtrContext(key, undefined);
957 }
958 pub fn getPtrContext(self: Self, key: K, ctx: Context) ?*V {
959 return self.getPtrAdapted(key, ctx);
960 }
961 pub fn getPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*V {
962 const index = self.getIndexAdapted(key, ctx) orelse return null;
963 // workaround for #6974
964 return if (@sizeOf(*V) == 0) @as(*V, undefined) else &self.values()[index];
618965 }
619966
967 /// Check whether a key is stored in the map
620968 pub fn contains(self: Self, key: K) bool {
621 return self.getEntry(key) != null;
969 if (@sizeOf(Context) != 0)
970 @compileError("Cannot infer context "++@typeName(Context)++", call containsContext instead.");
971 return self.containsContext(key, undefined);
972 }
973 pub fn containsContext(self: Self, key: K, ctx: Context) bool {
974 return self.containsAdapted(key, ctx);
975 }
976 pub fn containsAdapted(self: Self, key: anytype, ctx: anytype) bool {
977 return self.getIndexAdapted(key, ctx) != null;
622978 }
623979
624980 /// If there is an `Entry` with a matching key, it is deleted from
625981 /// the hash map, and then returned from this function. The entry is
626982 /// removed from the underlying array by swapping it with the last
627983 /// element.
628 pub fn swapRemove(self: *Self, key: K) ?Entry {
629 return self.removeInternal(key, .swap);
984 pub fn fetchSwapRemove(self: *Self, key: K) ?KV {
985 if (@sizeOf(Context) != 0)
986 @compileError("Cannot infer context "++@typeName(Context)++", call fetchSwapRemoveContext instead.");
987 return self.fetchSwapRemoveContext(key, undefined);
988 }
989 pub fn fetchSwapRemoveContext(self: *Self, key: K, ctx: Context) ?KV {
990 return self.fetchSwapRemoveContextAdapted(key, ctx, ctx);
991 }
992 pub fn fetchSwapRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KV {
993 if (@sizeOf(ByIndexContext) != 0)
994 @compileError("Cannot infer context "++@typeName(Context)++", call fetchSwapRemoveContextAdapted instead.");
995 return self.fetchSwapRemoveContextAdapted(key, ctx, undefined);
996 }
997 pub fn fetchSwapRemoveContextAdapted(self: *Self, key: anytype, key_ctx: anytype, ctx: Context) ?KV {
998 return self.fetchRemoveByKey(key, key_ctx, if (store_hash) {} else ctx, .swap);
630999 }
6311000
6321001 /// If there is an `Entry` with a matching key, it is deleted from
6331002 /// the hash map, and then returned from this function. The entry is
6341003 /// removed from the underlying array by shifting all elements forward
6351004 /// thereby maintaining the current ordering.
636 pub fn orderedRemove(self: *Self, key: K) ?Entry {
637 return self.removeInternal(key, .ordered);
1005 pub fn fetchOrderedRemove(self: *Self, key: K) ?KV {
1006 if (@sizeOf(Context) != 0)
1007 @compileError("Cannot infer context "++@typeName(Context)++", call fetchOrderedRemoveContext instead.");
1008 return self.fetchOrderedRemoveContext(key, undefined);
1009 }
1010 pub fn fetchOrderedRemoveContext(self: *Self, key: K, ctx: Context) ?KV {
1011 return self.fetchOrderedRemoveContextAdapted(key, ctx, ctx);
1012 }
1013 pub fn fetchOrderedRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KV {
1014 if (@sizeOf(ByIndexContext) != 0)
1015 @compileError("Cannot infer context "++@typeName(Context)++", call fetchOrderedRemoveContextAdapted instead.");
1016 return self.fetchOrderedRemoveContextAdapted(key, ctx, undefined);
1017 }
1018 pub fn fetchOrderedRemoveContextAdapted(self: *Self, key: anytype, key_ctx: anytype, ctx: Context) ?KV {
1019 return self.fetchRemoveByKey(key, key_ctx, if (store_hash) {} else ctx, .ordered);
6381020 }
6391021
640 /// TODO deprecated: call swapRemoveAssertDiscard instead.
641 pub fn removeAssertDiscard(self: *Self, key: K) void {
642 return self.swapRemoveAssertDiscard(key);
1022 /// If there is an `Entry` with a matching key, it is deleted from
1023 /// the hash map. The entry is removed from the underlying array
1024 /// by swapping it with the last element. Returns true if an entry
1025 /// was removed, false otherwise.
1026 pub fn swapRemove(self: *Self, key: K) bool {
1027 if (@sizeOf(Context) != 0)
1028 @compileError("Cannot infer context "++@typeName(Context)++", call swapRemoveContext instead.");
1029 return self.swapRemoveContext(key, undefined);
1030 }
1031 pub fn swapRemoveContext(self: *Self, key: K, ctx: Context) bool {
1032 return self.swapRemoveContextAdapted(key, ctx, ctx);
1033 }
1034 pub fn swapRemoveAdapted(self: *Self, key: anytype, ctx: anytype) bool {
1035 if (@sizeOf(ByIndexContext) != 0)
1036 @compileError("Cannot infer context "++@typeName(Context)++", call swapRemoveContextAdapted instead.");
1037 return self.swapRemoveContextAdapted(key, ctx, undefined);
1038 }
1039 pub fn swapRemoveContextAdapted(self: *Self, key: anytype, key_ctx: anytype, ctx: Context) bool {
1040 return self.removeByKey(key, key_ctx, if (store_hash) {} else ctx, .swap);
6431041 }
6441042
645 /// Asserts there is an `Entry` with matching key, deletes it from the hash map
646 /// by swapping it with the last element, and discards it.
647 pub fn swapRemoveAssertDiscard(self: *Self, key: K) void {
648 assert(self.swapRemove(key) != null);
1043 /// If there is an `Entry` with a matching key, it is deleted from
1044 /// the hash map. The entry is removed from the underlying array
1045 /// by shifting all elements forward, thereby maintaining the
1046 /// current ordering. Returns true if an entry was removed, false otherwise.
1047 pub fn orderedRemove(self: *Self, key: K) bool {
1048 if (@sizeOf(Context) != 0)
1049 @compileError("Cannot infer context "++@typeName(Context)++", call orderedRemoveContext instead.");
1050 return self.orderedRemoveContext(key, undefined);
1051 }
1052 pub fn orderedRemoveContext(self: *Self, key: K, ctx: Context) bool {
1053 return self.orderedRemoveContextAdapted(key, ctx, ctx);
1054 }
1055 pub fn orderedRemoveAdapted(self: *Self, key: anytype, ctx: anytype) bool {
1056 if (@sizeOf(ByIndexContext) != 0)
1057 @compileError("Cannot infer context "++@typeName(Context)++", call orderedRemoveContextAdapted instead.");
1058 return self.orderedRemoveContextAdapted(key, ctx, undefined);
1059 }
1060 pub fn orderedRemoveContextAdapted(self: *Self, key: anytype, key_ctx: anytype, ctx: Context) bool {
1061 return self.removeByKey(key, key_ctx, if (store_hash) {} else ctx, .ordered);
6491062 }
6501063
651 /// Asserts there is an `Entry` with matching key, deletes it from the hash map
652 /// by by shifting all elements forward thereby maintaining the current ordering.
653 pub fn orderedRemoveAssertDiscard(self: *Self, key: K) void {
654 assert(self.orderedRemove(key) != null);
1064 /// Deletes the item at the specified index in `entries` from
1065 /// the hash map. The entry is removed from the underlying array
1066 /// by swapping it with the last element.
1067 pub fn swapRemoveAt(self: *Self, index: usize) void {
1068 if (@sizeOf(ByIndexContext) != 0)
1069 @compileError("Cannot infer context "++@typeName(Context)++", call swapRemoveAtContext instead.");
1070 return self.swapRemoveAtContext(index, undefined);
1071 }
1072 pub fn swapRemoveAtContext(self: *Self, index: usize, ctx: Context) void {
1073 self.removeByIndex(index, if (store_hash) {} else ctx, .swap);
6551074 }
6561075
657 pub fn items(self: Self) []Entry {
658 return self.entries.items;
1076 /// Deletes the item at the specified index in `entries` from
1077 /// the hash map. The entry is removed from the underlying array
1078 /// by shifting all elements forward, thereby maintaining the
1079 /// current ordering.
1080 pub fn orderedRemoveAt(self: *Self, index: usize) void {
1081 if (@sizeOf(ByIndexContext) != 0)
1082 @compileError("Cannot infer context "++@typeName(Context)++", call orderedRemoveAtContext instead.");
1083 return self.orderedRemoveAtContext(index, undefined);
1084 }
1085 pub fn orderedRemoveAtContext(self: *Self, index: usize, ctx: Context) void {
1086 self.removeByIndex(index, if (store_hash) {} else ctx, .ordered);
6591087 }
6601088
1089 /// Create a copy of the hash map which can be modified separately.
1090 /// The copy uses the same context and allocator as this instance.
6611091 pub fn clone(self: Self, allocator: *Allocator) !Self {
1092 if (@sizeOf(ByIndexContext) != 0)
1093 @compileError("Cannot infer context "++@typeName(Context)++", call cloneContext instead.");
1094 return self.cloneContext(allocator, undefined);
1095 }
1096 pub fn cloneContext(self: Self, allocator: *Allocator, ctx: Context) !Self {
6621097 var other: Self = .{};
663 try other.entries.appendSlice(allocator, self.entries.items);
1098 other.entries = try self.entries.clone(allocator);
1099 errdefer other.entries.deinit(allocator);
6641100
6651101 if (self.index_header) |header| {
666 const new_header = try IndexHeader.alloc(allocator, header.indexes_len);
667 other.insertAllEntriesIntoNewHeader(new_header);
1102 const new_header = try IndexHeader.alloc(allocator, header.bit_index);
1103 other.insertAllEntriesIntoNewHeader(if (store_hash) {} else ctx, new_header);
6681104 other.index_header = new_header;
6691105 }
6701106 return other;
......@@ -673,135 +1109,197 @@ pub fn ArrayHashMapUnmanaged(
6731109 /// Rebuilds the key indexes. If the underlying entries has been modified directly, users
6741110 /// can call `reIndex` to update the indexes to account for these new entries.
6751111 pub fn reIndex(self: *Self, allocator: *Allocator) !void {
1112 if (@sizeOf(ByIndexContext) != 0)
1113 @compileError("Cannot infer context "++@typeName(Context)++", call reIndexContext instead.");
1114 return self.reIndexContext(allocator, undefined);
1115 }
1116 pub fn reIndexContext(self: *Self, allocator: *Allocator, ctx: Context) !void {
6761117 if (self.entries.capacity <= linear_scan_max) return;
6771118 // We're going to rebuild the index header and replace the existing one (if any). The
6781119 // indexes should sized such that they will be at most 60% full.
679 const needed_len = self.entries.capacity * 5 / 3;
680 const new_indexes_len = math.ceilPowerOfTwo(usize, needed_len) catch unreachable;
681 const new_header = try IndexHeader.alloc(allocator, new_indexes_len);
682 self.insertAllEntriesIntoNewHeader(new_header);
683 if (self.index_header) |header|
684 header.free(allocator);
1120 const bit_index = try IndexHeader.findBitIndex(self.entries.capacity);
1121 const new_header = try IndexHeader.alloc(allocator, bit_index);
1122 if (self.index_header) |header| header.free(allocator);
1123 self.insertAllEntriesIntoNewHeader(if (store_hash) {} else ctx, new_header);
6851124 self.index_header = new_header;
6861125 }
6871126
6881127 /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated
6891128 /// index entries. Keeps capacity the same.
6901129 pub fn shrinkRetainingCapacity(self: *Self, new_len: usize) void {
1130 if (@sizeOf(ByIndexContext) != 0)
1131 @compileError("Cannot infer context "++@typeName(Context)++", call shrinkRetainingCapacityContext instead.");
1132 return self.shrinkRetainingCapacityContext(new_len, undefined);
1133 }
1134 pub fn shrinkRetainingCapacityContext(self: *Self, new_len: usize, ctx: Context) void {
6911135 // Remove index entries from the new length onwards.
6921136 // Explicitly choose to ONLY remove index entries and not the underlying array list
6931137 // entries as we're going to remove them in the subsequent shrink call.
694 var i: usize = new_len;
695 while (i < self.entries.items.len) : (i += 1)
696 _ = self.removeWithHash(self.entries.items[i].key, self.entries.items[i].hash, .index_only);
1138 if (self.index_header) |header| {
1139 var i: usize = new_len;
1140 while (i < self.entries.len) : (i += 1)
1141 self.removeFromIndexByIndex(i, if (store_hash) {} else ctx, header);
1142 }
6971143 self.entries.shrinkRetainingCapacity(new_len);
6981144 }
6991145
7001146 /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated
7011147 /// index entries. Reduces allocated capacity.
7021148 pub fn shrinkAndFree(self: *Self, allocator: *Allocator, new_len: usize) void {
1149 if (@sizeOf(ByIndexContext) != 0)
1150 @compileError("Cannot infer context "++@typeName(Context)++", call shrinkAndFreeContext instead.");
1151 return self.shrinkAndFreeContext(allocator, new_len, undefined);
1152 }
1153 pub fn shrinkAndFreeContext(self: *Self, allocator: *Allocator, new_len: usize, ctx: Context) void {
7031154 // Remove index entries from the new length onwards.
7041155 // Explicitly choose to ONLY remove index entries and not the underlying array list
7051156 // entries as we're going to remove them in the subsequent shrink call.
706 var i: usize = new_len;
707 while (i < self.entries.items.len) : (i += 1)
708 _ = self.removeWithHash(self.entries.items[i].key, self.entries.items[i].hash, .index_only);
1157 if (self.index_header) |header| {
1158 var i: usize = new_len;
1159 while (i < self.entries.len) : (i += 1)
1160 self.removeFromIndexByIndex(i, if (store_hash) {} else ctx, header);
1161 }
7091162 self.entries.shrinkAndFree(allocator, new_len);
7101163 }
7111164
7121165 /// Removes the last inserted `Entry` in the hash map and returns it.
713 pub fn pop(self: *Self) Entry {
714 const top = self.entries.items[self.entries.items.len - 1];
715 _ = self.removeWithHash(top.key, top.hash, .index_only);
716 self.entries.items.len -= 1;
717 return top;
1166 pub fn pop(self: *Self) KV {
1167 if (@sizeOf(ByIndexContext) != 0)
1168 @compileError("Cannot infer context "++@typeName(Context)++", call popContext instead.");
1169 return self.popContext(undefined);
7181170 }
719
720 fn removeInternal(self: *Self, key: K, comptime removal_type: RemovalType) ?Entry {
721 const key_hash = if (store_hash) hash(key) else {};
722 return self.removeWithHash(key, key_hash, removal_type);
1171 pub fn popContext(self: *Self, ctx: Context) KV {
1172 const item = self.entries.get(self.entries.len-1);
1173 if (self.index_header) |header|
1174 self.removeFromIndexByIndex(self.entries.len-1, if (store_hash) {} else ctx, header);
1175 self.entries.len -= 1;
1176 return .{
1177 .key = item.key,
1178 .value = item.value,
1179 };
7231180 }
7241181
725 fn removeWithHash(self: *Self, key: K, key_hash: Hash, comptime removal_type: RemovalType) ?Entry {
1182 // ------------------ No pub fns below this point ------------------
1183
1184 fn fetchRemoveByKey(self: *Self, key: anytype, key_ctx: anytype, ctx: ByIndexContext, comptime removal_type: RemovalType) ?KV {
7261185 const header = self.index_header orelse {
727 // If we're only removing index entries and we have no index header, there's no need
728 // to continue.
729 if (removal_type == .index_only) return null;
7301186 // Linear scan.
731 for (self.entries.items) |item, i| {
732 if (item.hash == key_hash and eql(key, item.key)) {
1187 const key_hash = if (store_hash) key_ctx.hash(key) else {};
1188 const slice = self.entries.slice();
1189 const hashes_array = if (store_hash) slice.items(.hash) else {};
1190 const keys_array = slice.items(.key);
1191 for (keys_array) |*item_key, i| {
1192 const hash_match = if (store_hash) hashes_array[i] == key_hash else true;
1193 if (hash_match and key_ctx.eql(key, item_key.*)) {
1194 const removed_entry: KV = .{
1195 .key = keys_array[i],
1196 .value = slice.items(.value)[i],
1197 };
7331198 switch (removal_type) {
734 .swap => return self.entries.swapRemove(i),
735 .ordered => return self.entries.orderedRemove(i),
736 .index_only => unreachable,
1199 .swap => self.entries.swapRemove(i),
1200 .ordered => self.entries.orderedRemove(i),
7371201 }
1202 return removed_entry;
7381203 }
7391204 }
7401205 return null;
7411206 };
742 switch (header.capacityIndexType()) {
743 .u8 => return self.removeWithIndex(key, key_hash, header, u8, removal_type),
744 .u16 => return self.removeWithIndex(key, key_hash, header, u16, removal_type),
745 .u32 => return self.removeWithIndex(key, key_hash, header, u32, removal_type),
746 .usize => return self.removeWithIndex(key, key_hash, header, usize, removal_type),
747 }
1207 return switch (header.capacityIndexType()) {
1208 .u8 => self.fetchRemoveByKeyGeneric(key, key_ctx, ctx, header, u8, removal_type),
1209 .u16 => self.fetchRemoveByKeyGeneric(key, key_ctx, ctx, header, u16, removal_type),
1210 .u32 => self.fetchRemoveByKeyGeneric(key, key_ctx, ctx, header, u32, removal_type),
1211 };
7481212 }
749
750 fn removeWithIndex(self: *Self, key: K, key_hash: Hash, header: *IndexHeader, comptime I: type, comptime removal_type: RemovalType) ?Entry {
1213 fn fetchRemoveByKeyGeneric(self: *Self, key: anytype, key_ctx: anytype, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, comptime removal_type: RemovalType) ?KV {
7511214 const indexes = header.indexes(I);
752 const h = if (store_hash) key_hash else hash(key);
753 const start_index = header.constrainIndex(h);
754 var roll_over: usize = 0;
755 while (roll_over <= header.max_distance_from_start_index) : (roll_over += 1) {
756 const index_index = header.constrainIndex(start_index + roll_over);
757 var index = &indexes[index_index];
758 if (index.isEmpty())
759 return null;
760
761 const entry = &self.entries.items[index.entry_index];
762
763 const hash_match = if (store_hash) h == entry.hash else true;
764 if (!hash_match or !eql(key, entry.key))
765 continue;
1215 const entry_index = self.removeFromIndexByKey(key, key_ctx, header, I, indexes) orelse return null;
1216 const slice = self.entries.slice();
1217 const removed_entry: KV = .{
1218 .key = slice.items(.key)[entry_index],
1219 .value = slice.items(.value)[entry_index],
1220 };
1221 self.removeFromArrayAndUpdateIndex(entry_index, ctx, header, I, indexes, removal_type);
1222 return removed_entry;
1223 }
7661224
767 var removed_entry: ?Entry = undefined;
768 switch (removal_type) {
769 .swap => {
770 removed_entry = self.entries.swapRemove(index.entry_index);
771 if (self.entries.items.len > 0 and self.entries.items.len != index.entry_index) {
772 // Because of the swap remove, now we need to update the index that was
773 // pointing to the last entry and is now pointing to this removed item slot.
774 self.updateEntryIndex(header, self.entries.items.len, index.entry_index, I, indexes);
775 }
776 },
777 .ordered => {
778 removed_entry = self.entries.orderedRemove(index.entry_index);
779 var i: usize = index.entry_index;
780 while (i < self.entries.items.len) : (i += 1) {
781 // Because of the ordered remove, everything from the entry index onwards has
782 // been shifted forward so we'll need to update the index entries.
783 self.updateEntryIndex(header, i + 1, i, I, indexes);
1225 fn removeByKey(self: *Self, key: anytype, key_ctx: anytype, ctx: ByIndexContext, comptime removal_type: RemovalType) bool {
1226 const header = self.index_header orelse {
1227 // Linear scan.
1228 const key_hash = if (store_hash) key_ctx.hash(key) else {};
1229 const slice = self.entries.slice();
1230 const hashes_array = if (store_hash) slice.items(.hash) else {};
1231 const keys_array = slice.items(.key);
1232 for (keys_array) |*item_key, i| {
1233 const hash_match = if (store_hash) hashes_array[i] == key_hash else true;
1234 if (hash_match and key_ctx.eql(key, item_key.*)) {
1235 switch (removal_type) {
1236 .swap => self.entries.swapRemove(i),
1237 .ordered => self.entries.orderedRemove(i),
7841238 }
785 },
786 .index_only => removed_entry = null,
1239 return true;
1240 }
7871241 }
1242 return false;
1243 };
1244 return switch (header.capacityIndexType()) {
1245 .u8 => self.removeByKeyGeneric(key, key_ctx, ctx, header, u8, removal_type),
1246 .u16 => self.removeByKeyGeneric(key, key_ctx, ctx, header, u16, removal_type),
1247 .u32 => self.removeByKeyGeneric(key, key_ctx, ctx, header, u32, removal_type),
1248 };
1249 }
1250 fn removeByKeyGeneric(self: *Self, key: anytype, key_ctx: anytype, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, comptime removal_type: RemovalType) bool {
1251 const indexes = header.indexes(I);
1252 const entry_index = self.removeFromIndexByKey(key, key_ctx, header, I, indexes) orelse return false;
1253 self.removeFromArrayAndUpdateIndex(entry_index, ctx, header, I, indexes, removal_type);
1254 return true;
1255 }
7881256
789 // Now we have to shift over the following indexes.
790 roll_over += 1;
791 while (roll_over < header.indexes_len) : (roll_over += 1) {
792 const next_index_index = header.constrainIndex(start_index + roll_over);
793 const next_index = &indexes[next_index_index];
794 if (next_index.isEmpty() or next_index.distance_from_start_index == 0) {
795 index.setEmpty();
796 return removed_entry;
797 }
798 index.* = next_index.*;
799 index.distance_from_start_index -= 1;
800 index = next_index;
1257 fn removeByIndex(self: *Self, entry_index: usize, ctx: ByIndexContext, comptime removal_type: RemovalType) void {
1258 assert(entry_index < self.entries.len);
1259 const header = self.index_header orelse {
1260 switch (removal_type) {
1261 .swap => self.entries.swapRemove(entry_index),
1262 .ordered => self.entries.orderedRemove(entry_index),
8011263 }
802 unreachable;
1264 return;
1265 };
1266 switch (header.capacityIndexType()) {
1267 .u8 => self.removeByIndexGeneric(entry_index, ctx, header, u8, removal_type),
1268 .u16 => self.removeByIndexGeneric(entry_index, ctx, header, u16, removal_type),
1269 .u32 => self.removeByIndexGeneric(entry_index, ctx, header, u32, removal_type),
1270 }
1271 }
1272 fn removeByIndexGeneric(self: *Self, entry_index: usize, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, comptime removal_type: RemovalType) void {
1273 const indexes = header.indexes(I);
1274 self.removeFromIndexByIndexGeneric(entry_index, ctx, header, I, indexes);
1275 self.removeFromArrayAndUpdateIndex(entry_index, ctx, header, I, indexes, removal_type);
1276 }
1277
1278 fn removeFromArrayAndUpdateIndex(self: *Self, entry_index: usize, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, indexes: []Index(I), comptime removal_type: RemovalType) void {
1279 const last_index = self.entries.len-1; // overflow => remove from empty map
1280 switch (removal_type) {
1281 .swap => {
1282 if (last_index != entry_index) {
1283 // Because of the swap remove, now we need to update the index that was
1284 // pointing to the last entry and is now pointing to this removed item slot.
1285 self.updateEntryIndex(header, last_index, entry_index, ctx, I, indexes);
1286 }
1287 // updateEntryIndex reads from the old entry index,
1288 // so it needs to run before removal.
1289 self.entries.swapRemove(entry_index);
1290 },
1291 .ordered => {
1292 var i: usize = entry_index;
1293 while (i < last_index) : (i += 1) {
1294 // Because of the ordered remove, everything from the entry index onwards has
1295 // been shifted forward so we'll need to update the index entries.
1296 self.updateEntryIndex(header, i + 1, i, ctx, I, indexes);
1297 }
1298 // updateEntryIndex reads from the old entry index,
1299 // so it needs to run before removal.
1300 self.entries.orderedRemove(entry_index);
1301 },
8031302 }
804 return null;
8051303 }
8061304
8071305 fn updateEntryIndex(
......@@ -809,116 +1307,188 @@ pub fn ArrayHashMapUnmanaged(
8091307 header: *IndexHeader,
8101308 old_entry_index: usize,
8111309 new_entry_index: usize,
1310 ctx: ByIndexContext,
8121311 comptime I: type,
8131312 indexes: []Index(I),
8141313 ) void {
815 const h = if (store_hash) self.entries.items[new_entry_index].hash else hash(self.entries.items[new_entry_index].key);
816 const start_index = header.constrainIndex(h);
817 var roll_over: usize = 0;
818 while (roll_over <= header.max_distance_from_start_index) : (roll_over += 1) {
819 const index_index = header.constrainIndex(start_index + roll_over);
820 const index = &indexes[index_index];
821 if (index.entry_index == old_entry_index) {
822 index.entry_index = @intCast(I, new_entry_index);
1314 const slot = self.getSlotByIndex(old_entry_index, ctx, header, I, indexes);
1315 indexes[slot].entry_index = @intCast(I, new_entry_index);
1316 }
1317
1318 fn removeFromIndexByIndex(self: *Self, entry_index: usize, ctx: ByIndexContext, header: *IndexHeader) void {
1319 switch (header.capacityIndexType()) {
1320 .u8 => self.removeFromIndexByIndexGeneric(entry_index, ctx, header, u8, header.indexes(u8)),
1321 .u16 => self.removeFromIndexByIndexGeneric(entry_index, ctx, header, u16, header.indexes(u16)),
1322 .u32 => self.removeFromIndexByIndexGeneric(entry_index, ctx, header, u32, header.indexes(u32)),
1323 }
1324 }
1325 fn removeFromIndexByIndexGeneric(self: *Self, entry_index: usize, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, indexes: []Index(I)) void {
1326 const slot = self.getSlotByIndex(entry_index, ctx, header, I, indexes);
1327 self.removeSlot(slot, header, I, indexes);
1328 }
1329
1330 fn removeFromIndexByKey(self: *Self, key: anytype, ctx: anytype, header: *IndexHeader, comptime I: type, indexes: []Index(I)) ?usize {
1331 const slot = self.getSlotByKey(key, ctx, header, I, indexes) orelse return null;
1332 const removed_entry_index = indexes[slot].entry_index;
1333 self.removeSlot(slot, header, I, indexes);
1334 return removed_entry_index;
1335 }
1336
1337 fn removeSlot(self: *Self, removed_slot: usize, header: *IndexHeader, comptime I: type, indexes: []Index(I)) void {
1338 const start_index = removed_slot +% 1;
1339 const end_index = start_index +% indexes.len;
1340
1341 var last_slot = removed_slot;
1342 var index: usize = start_index;
1343 while (index != end_index) : (index +%= 1) {
1344 const slot = header.constrainIndex(index);
1345 const slot_data = indexes[slot];
1346 if (slot_data.isEmpty() or slot_data.distance_from_start_index == 0) {
1347 indexes[last_slot].setEmpty();
8231348 return;
8241349 }
1350 indexes[last_slot] = .{
1351 .entry_index = slot_data.entry_index,
1352 .distance_from_start_index = slot_data.distance_from_start_index - 1,
1353 };
1354 last_slot = slot;
1355 }
1356 unreachable;
1357 }
1358
1359 fn getSlotByIndex(self: *Self, entry_index: usize, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, indexes: []Index(I)) usize {
1360 const slice = self.entries.slice();
1361 const h = if (store_hash) slice.items(.hash)[entry_index]
1362 else checkedHash(ctx, slice.items(.key)[entry_index]);
1363 const start_index = safeTruncate(usize, h);
1364 const end_index = start_index +% indexes.len;
1365
1366 var index = start_index;
1367 var distance_from_start_index: I = 0;
1368 while (index != end_index) : ({
1369 index +%= 1;
1370 distance_from_start_index += 1;
1371 }) {
1372 const slot = header.constrainIndex(index);
1373 const slot_data = indexes[slot];
1374
1375 // This is the fundamental property of the array hash map index. If this
1376 // assert fails, it probably means that the entry was not in the index.
1377 assert(!slot_data.isEmpty());
1378 assert(slot_data.distance_from_start_index >= distance_from_start_index);
1379
1380 if (slot_data.entry_index == entry_index) {
1381 return slot;
1382 }
8251383 }
8261384 unreachable;
8271385 }
8281386
8291387 /// Must ensureCapacity before calling this.
830 fn getOrPutInternal(self: *Self, key: K, header: *IndexHeader, comptime I: type) GetOrPutResult {
1388 fn getOrPutInternal(self: *Self, key: anytype, ctx: anytype, header: *IndexHeader, comptime I: type) GetOrPutResult {
1389 const slice = self.entries.slice();
1390 const hashes_array = if (store_hash) slice.items(.hash) else {};
1391 const keys_array = slice.items(.key);
1392 const values_array = slice.items(.value);
8311393 const indexes = header.indexes(I);
832 const h = hash(key);
833 const start_index = header.constrainIndex(h);
834 var roll_over: usize = 0;
835 var distance_from_start_index: usize = 0;
836 while (roll_over <= header.indexes_len) : ({
837 roll_over += 1;
1394
1395 const h = checkedHash(ctx, key);
1396 const start_index = safeTruncate(usize, h);
1397 const end_index = start_index +% indexes.len;
1398
1399 var index = start_index;
1400 var distance_from_start_index: I = 0;
1401 while (index != end_index) : ({
1402 index +%= 1;
8381403 distance_from_start_index += 1;
8391404 }) {
840 const index_index = header.constrainIndex(start_index + roll_over);
841 const index = indexes[index_index];
842 if (index.isEmpty()) {
843 indexes[index_index] = .{
844 .distance_from_start_index = @intCast(I, distance_from_start_index),
845 .entry_index = @intCast(I, self.entries.items.len),
846 };
847 header.maybeBumpMax(distance_from_start_index);
848 const new_entry = self.entries.addOneAssumeCapacity();
849 new_entry.* = .{
850 .hash = if (store_hash) h else {},
851 .key = key,
852 .value = undefined,
1405 var slot = header.constrainIndex(index);
1406 var slot_data = indexes[slot];
1407
1408 // If the slot is empty, there can be no more items in this run.
1409 // We didn't find a matching item, so this must be new.
1410 // Put it in the empty slot.
1411 if (slot_data.isEmpty()) {
1412 const new_index = self.entries.addOneAssumeCapacity();
1413 indexes[slot] = .{
1414 .distance_from_start_index = distance_from_start_index,
1415 .entry_index = @intCast(I, new_index),
8531416 };
1417
1418 // update the hash if applicable
1419 if (store_hash) hashes_array.ptr[new_index] = h;
1420
8541421 return .{
8551422 .found_existing = false,
856 .entry = new_entry,
857 .index = self.entries.items.len - 1,
1423 .key_ptr = &keys_array.ptr[new_index],
1424 // workaround for #6974
1425 .value_ptr = if (@sizeOf(*V) == 0) undefined else &values_array.ptr[new_index],
1426 .index = new_index,
8581427 };
8591428 }
8601429
8611430 // This pointer survives the following append because we call
8621431 // entries.ensureCapacity before getOrPutInternal.
863 const entry = &self.entries.items[index.entry_index];
864 const hash_match = if (store_hash) h == entry.hash else true;
865 if (hash_match and eql(key, entry.key)) {
1432 const hash_match = if (store_hash) h == hashes_array[slot_data.entry_index] else true;
1433 if (hash_match and checkedEql(ctx, key, keys_array[slot_data.entry_index])) {
8661434 return .{
8671435 .found_existing = true,
868 .entry = entry,
869 .index = index.entry_index,
1436 .key_ptr = &keys_array[slot_data.entry_index],
1437 // workaround for #6974
1438 .value_ptr = if (@sizeOf(*V) == 0) undefined else &values_array[slot_data.entry_index],
1439 .index = slot_data.entry_index,
8701440 };
8711441 }
872 if (index.distance_from_start_index < distance_from_start_index) {
1442
1443 // If the entry is closer to its target than our current distance,
1444 // the entry we are looking for does not exist. It would be in
1445 // this slot instead if it was here. So stop looking, and switch
1446 // to insert mode.
1447 if (slot_data.distance_from_start_index < distance_from_start_index) {
8731448 // In this case, we did not find the item. We will put a new entry.
8741449 // However, we will use this index for the new entry, and move
875 // the previous index down the line, to keep the max_distance_from_start_index
1450 // the previous index down the line, to keep the max distance_from_start_index
8761451 // as small as possible.
877 indexes[index_index] = .{
878 .distance_from_start_index = @intCast(I, distance_from_start_index),
879 .entry_index = @intCast(I, self.entries.items.len),
1452 const new_index = self.entries.addOneAssumeCapacity();
1453 if (store_hash) hashes_array.ptr[new_index] = h;
1454 indexes[slot] = .{
1455 .entry_index = @intCast(I, new_index),
1456 .distance_from_start_index = distance_from_start_index,
8801457 };
881 header.maybeBumpMax(distance_from_start_index);
882 const new_entry = self.entries.addOneAssumeCapacity();
883 new_entry.* = .{
884 .hash = if (store_hash) h else {},
885 .key = key,
886 .value = undefined,
887 };
888
889 distance_from_start_index = index.distance_from_start_index;
890 var prev_entry_index = index.entry_index;
1458 distance_from_start_index = slot_data.distance_from_start_index;
1459 var displaced_index = slot_data.entry_index;
8911460
8921461 // Find somewhere to put the index we replaced by shifting
8931462 // following indexes backwards.
894 roll_over += 1;
1463 index +%= 1;
8951464 distance_from_start_index += 1;
896 while (roll_over < header.indexes_len) : ({
897 roll_over += 1;
1465 while (index != end_index) : ({
1466 index +%= 1;
8981467 distance_from_start_index += 1;
8991468 }) {
900 const next_index_index = header.constrainIndex(start_index + roll_over);
901 const next_index = indexes[next_index_index];
902 if (next_index.isEmpty()) {
903 header.maybeBumpMax(distance_from_start_index);
904 indexes[next_index_index] = .{
905 .entry_index = prev_entry_index,
906 .distance_from_start_index = @intCast(I, distance_from_start_index),
1469 slot = header.constrainIndex(index);
1470 slot_data = indexes[slot];
1471 if (slot_data.isEmpty()) {
1472 indexes[slot] = .{
1473 .entry_index = displaced_index,
1474 .distance_from_start_index = distance_from_start_index,
9071475 };
9081476 return .{
9091477 .found_existing = false,
910 .entry = new_entry,
911 .index = self.entries.items.len - 1,
1478 .key_ptr = &keys_array.ptr[new_index],
1479 // workaround for #6974
1480 .value_ptr = if (@sizeOf(*V) == 0) undefined else &values_array.ptr[new_index],
1481 .index = new_index,
9121482 };
9131483 }
914 if (next_index.distance_from_start_index < distance_from_start_index) {
915 header.maybeBumpMax(distance_from_start_index);
916 indexes[next_index_index] = .{
917 .entry_index = prev_entry_index,
918 .distance_from_start_index = @intCast(I, distance_from_start_index),
1484
1485 if (slot_data.distance_from_start_index < distance_from_start_index) {
1486 indexes[slot] = .{
1487 .entry_index = displaced_index,
1488 .distance_from_start_index = distance_from_start_index,
9191489 };
920 distance_from_start_index = next_index.distance_from_start_index;
921 prev_entry_index = next_index.entry_index;
1490 displaced_index = slot_data.entry_index;
1491 distance_from_start_index = slot_data.distance_from_start_index;
9221492 }
9231493 }
9241494 unreachable;
......@@ -927,61 +1497,69 @@ pub fn ArrayHashMapUnmanaged(
9271497 unreachable;
9281498 }
9291499
930 fn getInternal(self: Self, key: K, header: *IndexHeader, comptime I: type) ?usize {
931 const indexes = header.indexes(I);
932 const h = hash(key);
933 const start_index = header.constrainIndex(h);
934 var roll_over: usize = 0;
935 while (roll_over <= header.max_distance_from_start_index) : (roll_over += 1) {
936 const index_index = header.constrainIndex(start_index + roll_over);
937 const index = indexes[index_index];
938 if (index.isEmpty())
1500 fn getSlotByKey(self: Self, key: anytype, ctx: anytype, header: *IndexHeader, comptime I: type, indexes: []Index(I)) ?usize {
1501 const slice = self.entries.slice();
1502 const hashes_array = if (store_hash) slice.items(.hash) else {};
1503 const keys_array = slice.items(.key);
1504 const h = checkedHash(ctx, key);
1505
1506 const start_index = safeTruncate(usize, h);
1507 const end_index = start_index +% indexes.len;
1508
1509 var index = start_index;
1510 var distance_from_start_index: I = 0;
1511 while (index != end_index) : ({
1512 index +%= 1;
1513 distance_from_start_index += 1;
1514 }) {
1515 const slot = header.constrainIndex(index);
1516 const slot_data = indexes[slot];
1517 if (slot_data.isEmpty() or slot_data.distance_from_start_index < distance_from_start_index)
9391518 return null;
9401519
941 const entry = &self.entries.items[index.entry_index];
942 const hash_match = if (store_hash) h == entry.hash else true;
943 if (hash_match and eql(key, entry.key))
944 return index.entry_index;
1520 const hash_match = if (store_hash) h == hashes_array[slot_data.entry_index] else true;
1521 if (hash_match and checkedEql(ctx, key, keys_array[slot_data.entry_index]))
1522 return slot;
9451523 }
946 return null;
1524 unreachable;
9471525 }
9481526
949 fn insertAllEntriesIntoNewHeader(self: *Self, header: *IndexHeader) void {
1527 fn insertAllEntriesIntoNewHeader(self: *Self, ctx: ByIndexContext, header: *IndexHeader) void {
9501528 switch (header.capacityIndexType()) {
951 .u8 => return self.insertAllEntriesIntoNewHeaderGeneric(header, u8),
952 .u16 => return self.insertAllEntriesIntoNewHeaderGeneric(header, u16),
953 .u32 => return self.insertAllEntriesIntoNewHeaderGeneric(header, u32),
954 .usize => return self.insertAllEntriesIntoNewHeaderGeneric(header, usize),
1529 .u8 => return self.insertAllEntriesIntoNewHeaderGeneric(ctx, header, u8),
1530 .u16 => return self.insertAllEntriesIntoNewHeaderGeneric(ctx, header, u16),
1531 .u32 => return self.insertAllEntriesIntoNewHeaderGeneric(ctx, header, u32),
9551532 }
9561533 }
957
958 fn insertAllEntriesIntoNewHeaderGeneric(self: *Self, header: *IndexHeader, comptime I: type) void {
1534 fn insertAllEntriesIntoNewHeaderGeneric(self: *Self, ctx: ByIndexContext, header: *IndexHeader, comptime I: type) void {
1535 const slice = self.entries.slice();
1536 const items = if (store_hash) slice.items(.hash) else slice.items(.key);
9591537 const indexes = header.indexes(I);
960 entry_loop: for (self.entries.items) |entry, i| {
961 const h = if (store_hash) entry.hash else hash(entry.key);
962 const start_index = header.constrainIndex(h);
963 var entry_index = i;
964 var roll_over: usize = 0;
965 var distance_from_start_index: usize = 0;
966 while (roll_over < header.indexes_len) : ({
967 roll_over += 1;
1538
1539 entry_loop: for (items) |key, i| {
1540 const h = if (store_hash) key else checkedHash(ctx, key);
1541 const start_index = safeTruncate(usize, h);
1542 const end_index = start_index +% indexes.len;
1543 var index = start_index;
1544 var entry_index = @intCast(I, i);
1545 var distance_from_start_index: I = 0;
1546 while (index != end_index) : ({
1547 index +%= 1;
9681548 distance_from_start_index += 1;
9691549 }) {
970 const index_index = header.constrainIndex(start_index + roll_over);
971 const next_index = indexes[index_index];
1550 const slot = header.constrainIndex(index);
1551 const next_index = indexes[slot];
9721552 if (next_index.isEmpty()) {
973 header.maybeBumpMax(distance_from_start_index);
974 indexes[index_index] = .{
975 .distance_from_start_index = @intCast(I, distance_from_start_index),
976 .entry_index = @intCast(I, entry_index),
1553 indexes[slot] = .{
1554 .distance_from_start_index = distance_from_start_index,
1555 .entry_index = entry_index,
9771556 };
9781557 continue :entry_loop;
9791558 }
9801559 if (next_index.distance_from_start_index < distance_from_start_index) {
981 header.maybeBumpMax(distance_from_start_index);
982 indexes[index_index] = .{
983 .distance_from_start_index = @intCast(I, distance_from_start_index),
984 .entry_index = @intCast(I, entry_index),
1560 indexes[slot] = .{
1561 .distance_from_start_index = distance_from_start_index,
1562 .entry_index = entry_index,
9851563 };
9861564 distance_from_start_index = next_index.distance_from_start_index;
9871565 entry_index = next_index.entry_index;
......@@ -990,98 +1568,255 @@ pub fn ArrayHashMapUnmanaged(
9901568 unreachable;
9911569 }
9921570 }
1571
1572 fn checkedHash(ctx: anytype, key: anytype) callconv(.Inline) u32 {
1573 comptime std.hash_map.verifyContext(@TypeOf(ctx), @TypeOf(key), K, u32);
1574 // If you get a compile error on the next line, it means that
1575 const hash = ctx.hash(key); // your generic hash function doesn't accept your key
1576 if (@TypeOf(hash) != u32) {
1577 @compileError("Context "++@typeName(@TypeOf(ctx))++" has a generic hash function that returns the wrong type!\n"++
1578 @typeName(u32)++" was expected, but found "++@typeName(@TypeOf(hash)));
1579 }
1580 return hash;
1581 }
1582 fn checkedEql(ctx: anytype, a: anytype, b: K) callconv(.Inline) bool {
1583 comptime std.hash_map.verifyContext(@TypeOf(ctx), @TypeOf(a), K, u32);
1584 // If you get a compile error on the next line, it means that
1585 const eql = ctx.eql(a, b); // your generic eql function doesn't accept (self, adapt key, K)
1586 if (@TypeOf(eql) != bool) {
1587 @compileError("Context "++@typeName(@TypeOf(ctx))++" has a generic eql function that returns the wrong type!\n"++
1588 @typeName(bool)++" was expected, but found "++@typeName(@TypeOf(eql)));
1589 }
1590 return eql;
1591 }
1592
1593 fn dumpState(self: Self, comptime keyFmt: []const u8, comptime valueFmt: []const u8) void {
1594 if (@sizeOf(ByIndexContext) != 0)
1595 @compileError("Cannot infer context "++@typeName(Context)++", call dumpStateContext instead.");
1596 self.dumpStateContext(keyFmt, valueFmt, undefined);
1597 }
1598 fn dumpStateContext(self: Self, comptime keyFmt: []const u8, comptime valueFmt: []const u8, ctx: Context) void {
1599 const p = std.debug.print;
1600 p("{s}:\n", .{@typeName(Self)});
1601 const slice = self.entries.slice();
1602 const hash_status = if (store_hash) "stored" else "computed";
1603 p(" len={} capacity={} hashes {s}\n", .{slice.len, slice.capacity, hash_status});
1604 var i: usize = 0;
1605 const mask: u32 = if (self.index_header) |header| header.mask() else ~@as(u32, 0);
1606 while (i < slice.len) : (i += 1) {
1607 const hash = if (store_hash) slice.items(.hash)[i]
1608 else checkedHash(ctx, slice.items(.key)[i]);
1609 if (store_hash) {
1610 p(
1611 " [{}]: key="++keyFmt++" value="++valueFmt++" hash=0x{x} slot=[0x{x}]\n",
1612 .{i, slice.items(.key)[i], slice.items(.value)[i], hash, hash & mask},
1613 );
1614 } else {
1615 p(
1616 " [{}]: key="++keyFmt++" value="++valueFmt++" slot=[0x{x}]\n",
1617 .{i, slice.items(.key)[i], slice.items(.value)[i], hash & mask},
1618 );
1619 }
1620 }
1621 if (self.index_header) |header| {
1622 p("\n", .{});
1623 switch (header.capacityIndexType()) {
1624 .u8 => self.dumpIndex(header, u8),
1625 .u16 => self.dumpIndex(header, u16),
1626 .u32 => self.dumpIndex(header, u32),
1627 }
1628 }
1629 }
1630 fn dumpIndex(self: Self, header: *IndexHeader, comptime I: type) void {
1631 const p = std.debug.print;
1632 p(" index len=0x{x} type={}\n", .{header.length(), header.capacityIndexType()});
1633 const indexes = header.indexes(I);
1634 if (indexes.len == 0) return;
1635 var is_empty = false;
1636 for (indexes) |idx, i| {
1637 if (idx.isEmpty()) {
1638 is_empty = true;
1639 } else {
1640 if (is_empty) {
1641 is_empty = false;
1642 p(" ...\n", .{});
1643 }
1644 p(" [0x{x}]: [{}] +{}\n", .{i, idx.entry_index, idx.distance_from_start_index});
1645 }
1646 }
1647 if (is_empty) {
1648 p(" ...\n", .{});
1649 }
1650 }
9931651 };
9941652}
9951653
996const CapacityIndexType = enum { u8, u16, u32, usize };
1654const CapacityIndexType = enum { u8, u16, u32 };
9971655
998fn capacityIndexType(indexes_len: usize) CapacityIndexType {
999 if (indexes_len < math.maxInt(u8))
1656fn capacityIndexType(bit_index: u8) CapacityIndexType {
1657 if (bit_index <= 8)
10001658 return .u8;
1001 if (indexes_len < math.maxInt(u16))
1659 if (bit_index <= 16)
10021660 return .u16;
1003 if (indexes_len < math.maxInt(u32))
1004 return .u32;
1005 return .usize;
1661 assert(bit_index <= 32);
1662 return .u32;
10061663}
10071664
1008fn capacityIndexSize(indexes_len: usize) usize {
1009 switch (capacityIndexType(indexes_len)) {
1665fn capacityIndexSize(bit_index: u8) usize {
1666 switch (capacityIndexType(bit_index)) {
10101667 .u8 => return @sizeOf(Index(u8)),
10111668 .u16 => return @sizeOf(Index(u16)),
10121669 .u32 => return @sizeOf(Index(u32)),
1013 .usize => return @sizeOf(Index(usize)),
10141670 }
10151671}
10161672
1673/// @truncate fails if the target type is larger than the
1674/// target value. This causes problems when one of the types
1675/// is usize, which may be larger or smaller than u32 on different
1676/// systems. This version of truncate is safe to use if either
1677/// parameter has dynamic size, and will perform widening conversion
1678/// when needed. Both arguments must have the same signedness.
1679fn safeTruncate(comptime T: type, val: anytype) T {
1680 if (@bitSizeOf(T) >= @bitSizeOf(@TypeOf(val)))
1681 return val;
1682 return @truncate(T, val);
1683}
1684
1685/// A single entry in the lookup acceleration structure. These structs
1686/// are found in an array after the IndexHeader. Hashes index into this
1687/// array, and linear probing is used for collisions.
10171688fn Index(comptime I: type) type {
10181689 return extern struct {
1690 const Self = @This();
1691
1692 /// The index of this entry in the backing store. If the index is
1693 /// empty, this is empty_sentinel.
10191694 entry_index: I,
1695
1696 /// The distance between this slot and its ideal placement. This is
1697 /// used to keep maximum scan length small. This value is undefined
1698 /// if the index is empty.
10201699 distance_from_start_index: I,
10211700
1022 const Self = @This();
1701 /// The special entry_index value marking an empty slot.
1702 const empty_sentinel = ~@as(I, 0);
10231703
1704 /// A constant empty index
10241705 const empty = Self{
1025 .entry_index = math.maxInt(I),
1706 .entry_index = empty_sentinel,
10261707 .distance_from_start_index = undefined,
10271708 };
10281709
1710 /// Checks if a slot is empty
10291711 fn isEmpty(idx: Self) bool {
1030 return idx.entry_index == math.maxInt(I);
1712 return idx.entry_index == empty_sentinel;
10311713 }
10321714
1715 /// Sets a slot to empty
10331716 fn setEmpty(idx: *Self) void {
1034 idx.entry_index = math.maxInt(I);
1717 idx.entry_index = empty_sentinel;
1718 idx.distance_from_start_index = undefined;
10351719 }
10361720 };
10371721}
10381722
1039/// This struct is trailed by an array of `Index(I)`, where `I`
1040/// and the array length are determined by `indexes_len`.
1723/// the byte size of the index must fit in a usize. This is a power of two
1724/// length * the size of an Index(u32). The index is 8 bytes (3 bits repr)
1725/// and max_usize + 1 is not representable, so we need to subtract out 4 bits.
1726const max_representable_index_len = @bitSizeOf(usize) - 4;
1727const max_bit_index = math.min(32, max_representable_index_len);
1728const min_bit_index = 5;
1729const max_capacity = (1 << max_bit_index) - 1;
1730const index_capacities = blk: {
1731 var caps: [max_bit_index + 1]u32 = undefined;
1732 for (caps[0..max_bit_index]) |*item, i| {
1733 item.* = (1<<i) * 3 / 5;
1734 }
1735 caps[max_bit_index] = max_capacity;
1736 break :blk caps;
1737};
1738
1739/// This struct is trailed by two arrays of length indexes_len
1740/// of integers, whose integer size is determined by indexes_len.
1741/// These arrays are indexed by constrainIndex(hash). The
1742/// entryIndexes array contains the index in the dense backing store
1743/// where the entry's data can be found. Entries which are not in
1744/// use have their index value set to emptySentinel(I).
1745/// The entryDistances array stores the distance between an entry
1746/// and its ideal hash bucket. This is used when adding elements
1747/// to balance the maximum scan length.
10411748const IndexHeader = struct {
1042 max_distance_from_start_index: usize,
1043 indexes_len: usize,
1749 /// This field tracks the total number of items in the arrays following
1750 /// this header. It is the bit index of the power of two number of indices.
1751 /// This value is between min_bit_index and max_bit_index, inclusive.
1752 bit_index: u8 align(@alignOf(u32)),
10441753
1754 /// Map from an incrementing index to an index slot in the attached arrays.
10451755 fn constrainIndex(header: IndexHeader, i: usize) usize {
10461756 // This is an optimization for modulo of power of two integers;
10471757 // it requires `indexes_len` to always be a power of two.
1048 return i & (header.indexes_len - 1);
1758 return @intCast(usize, i & header.mask());
10491759 }
10501760
1761 /// Returns the attached array of indexes. I must match the type
1762 /// returned by capacityIndexType.
10511763 fn indexes(header: *IndexHeader, comptime I: type) []Index(I) {
1052 const start = @ptrCast([*]Index(I), @ptrCast([*]u8, header) + @sizeOf(IndexHeader));
1053 return start[0..header.indexes_len];
1764 const start_ptr = @ptrCast([*]Index(I), @ptrCast([*]u8, header) + @sizeOf(IndexHeader));
1765 return start_ptr[0..header.length()];
10541766 }
10551767
1768 /// Returns the type used for the index arrays.
10561769 fn capacityIndexType(header: IndexHeader) CapacityIndexType {
1057 return hash_map.capacityIndexType(header.indexes_len);
1770 return hash_map.capacityIndexType(header.bit_index);
10581771 }
10591772
1060 fn maybeBumpMax(header: *IndexHeader, distance_from_start_index: usize) void {
1061 if (distance_from_start_index > header.max_distance_from_start_index) {
1062 header.max_distance_from_start_index = distance_from_start_index;
1063 }
1773 fn capacity(self: IndexHeader) u32 {
1774 return index_capacities[self.bit_index];
1775 }
1776 fn length(self: IndexHeader) usize {
1777 return @as(usize, 1) << @intCast(math.Log2Int(usize), self.bit_index);
1778 }
1779 fn mask(self: IndexHeader) u32 {
1780 return @intCast(u32, self.length() - 1);
1781 }
1782
1783 fn findBitIndex(desired_capacity: usize) !u8 {
1784 if (desired_capacity > max_capacity) return error.OutOfMemory;
1785 var new_bit_index = @intCast(u8, std.math.log2_int_ceil(usize, desired_capacity));
1786 if (desired_capacity > index_capacities[new_bit_index]) new_bit_index += 1;
1787 if (new_bit_index < min_bit_index) new_bit_index = min_bit_index;
1788 assert(desired_capacity <= index_capacities[new_bit_index]);
1789 return new_bit_index;
10641790 }
10651791
1066 fn alloc(allocator: *Allocator, len: usize) !*IndexHeader {
1067 const index_size = hash_map.capacityIndexSize(len);
1792 /// Allocates an index header, and fills the entryIndexes array with empty.
1793 /// The distance array contents are undefined.
1794 fn alloc(allocator: *Allocator, new_bit_index: u8) !*IndexHeader {
1795 const len = @as(usize, 1) << @intCast(math.Log2Int(usize), new_bit_index);
1796 const index_size = hash_map.capacityIndexSize(new_bit_index);
10681797 const nbytes = @sizeOf(IndexHeader) + index_size * len;
10691798 const bytes = try allocator.allocAdvanced(u8, @alignOf(IndexHeader), nbytes, .exact);
10701799 @memset(bytes.ptr + @sizeOf(IndexHeader), 0xff, bytes.len - @sizeOf(IndexHeader));
10711800 const result = @ptrCast(*IndexHeader, bytes.ptr);
10721801 result.* = .{
1073 .max_distance_from_start_index = 0,
1074 .indexes_len = len,
1802 .bit_index = new_bit_index,
10751803 };
10761804 return result;
10771805 }
10781806
1807 /// Releases the memory for a header and its associated arrays.
10791808 fn free(header: *IndexHeader, allocator: *Allocator) void {
1080 const index_size = hash_map.capacityIndexSize(header.indexes_len);
1081 const ptr = @ptrCast([*]u8, header);
1082 const slice = ptr[0 .. @sizeOf(IndexHeader) + header.indexes_len * index_size];
1809 const index_size = hash_map.capacityIndexSize(header.bit_index);
1810 const ptr = @ptrCast([*]align(@alignOf(IndexHeader)) u8, header);
1811 const slice = ptr[0 .. @sizeOf(IndexHeader) + header.length() * index_size];
10831812 allocator.free(slice);
10841813 }
1814
1815 // Verify that the header has sufficient alignment to produce aligned arrays.
1816 comptime {
1817 if (@alignOf(u32) > @alignOf(IndexHeader))
1818 @compileError("IndexHeader must have a larger alignment than its indexes!");
1819 }
10851820};
10861821
10871822test "basic hash map usage" {
......@@ -1099,31 +1834,32 @@ test "basic hash map usage" {
10991834
11001835 const gop1 = try map.getOrPut(5);
11011836 try testing.expect(gop1.found_existing == true);
1102 try testing.expect(gop1.entry.value == 55);
1837 try testing.expect(gop1.value_ptr.* == 55);
11031838 try testing.expect(gop1.index == 4);
1104 gop1.entry.value = 77;
1105 try testing.expect(map.getEntry(5).?.value == 77);
1839 gop1.value_ptr.* = 77;
1840 try testing.expect(map.getEntry(5).?.value_ptr.* == 77);
11061841
11071842 const gop2 = try map.getOrPut(99);
11081843 try testing.expect(gop2.found_existing == false);
11091844 try testing.expect(gop2.index == 5);
1110 gop2.entry.value = 42;
1111 try testing.expect(map.getEntry(99).?.value == 42);
1845 gop2.value_ptr.* = 42;
1846 try testing.expect(map.getEntry(99).?.value_ptr.* == 42);
11121847
11131848 const gop3 = try map.getOrPutValue(5, 5);
1114 try testing.expect(gop3.value == 77);
1849 try testing.expect(gop3.value_ptr.* == 77);
11151850
11161851 const gop4 = try map.getOrPutValue(100, 41);
1117 try testing.expect(gop4.value == 41);
1852 try testing.expect(gop4.value_ptr.* == 41);
11181853
11191854 try testing.expect(map.contains(2));
1120 try testing.expect(map.getEntry(2).?.value == 22);
1855 try testing.expect(map.getEntry(2).?.value_ptr.* == 22);
11211856 try testing.expect(map.get(2).? == 22);
11221857
1123 const rmv1 = map.swapRemove(2);
1858 const rmv1 = map.fetchSwapRemove(2);
11241859 try testing.expect(rmv1.?.key == 2);
11251860 try testing.expect(rmv1.?.value == 22);
1126 try testing.expect(map.swapRemove(2) == null);
1861 try testing.expect(map.fetchSwapRemove(2) == null);
1862 try testing.expect(map.swapRemove(2) == false);
11271863 try testing.expect(map.getEntry(2) == null);
11281864 try testing.expect(map.get(2) == null);
11291865
......@@ -1131,22 +1867,23 @@ test "basic hash map usage" {
11311867 try testing.expect(map.getIndex(100).? == 1);
11321868 const gop5 = try map.getOrPut(5);
11331869 try testing.expect(gop5.found_existing == true);
1134 try testing.expect(gop5.entry.value == 77);
1870 try testing.expect(gop5.value_ptr.* == 77);
11351871 try testing.expect(gop5.index == 4);
11361872
11371873 // Whereas, if we do an `orderedRemove`, it should move the index forward one spot.
1138 const rmv2 = map.orderedRemove(100);
1874 const rmv2 = map.fetchOrderedRemove(100);
11391875 try testing.expect(rmv2.?.key == 100);
11401876 try testing.expect(rmv2.?.value == 41);
1141 try testing.expect(map.orderedRemove(100) == null);
1877 try testing.expect(map.fetchOrderedRemove(100) == null);
1878 try testing.expect(map.orderedRemove(100) == false);
11421879 try testing.expect(map.getEntry(100) == null);
11431880 try testing.expect(map.get(100) == null);
11441881 const gop6 = try map.getOrPut(5);
11451882 try testing.expect(gop6.found_existing == true);
1146 try testing.expect(gop6.entry.value == 77);
1883 try testing.expect(gop6.value_ptr.* == 77);
11471884 try testing.expect(gop6.index == 3);
11481885
1149 map.removeAssertDiscard(3);
1886 try testing.expect(map.swapRemove(3));
11501887}
11511888
11521889test "iterator hash map" {
......@@ -1154,7 +1891,7 @@ test "iterator hash map" {
11541891 defer reset_map.deinit();
11551892
11561893 // test ensureCapacity with a 0 parameter
1157 try reset_map.ensureCapacity(0);
1894 try reset_map.ensureTotalCapacity(0);
11581895
11591896 try reset_map.putNoClobber(0, 11);
11601897 try reset_map.putNoClobber(1, 22);
......@@ -1178,7 +1915,7 @@ test "iterator hash map" {
11781915
11791916 var count: usize = 0;
11801917 while (it.next()) |entry| : (count += 1) {
1181 buffer[@intCast(usize, entry.key)] = entry.value;
1918 buffer[@intCast(usize, entry.key_ptr.*)] = entry.value_ptr.*;
11821919 }
11831920 try testing.expect(count == 3);
11841921 try testing.expect(it.next() == null);
......@@ -1190,7 +1927,7 @@ test "iterator hash map" {
11901927 it.reset();
11911928 count = 0;
11921929 while (it.next()) |entry| {
1193 buffer[@intCast(usize, entry.key)] = entry.value;
1930 buffer[@intCast(usize, entry.key_ptr.*)] = entry.value_ptr.*;
11941931 count += 1;
11951932 if (count >= 2) break;
11961933 }
......@@ -1201,15 +1938,15 @@ test "iterator hash map" {
12011938
12021939 it.reset();
12031940 var entry = it.next().?;
1204 try testing.expect(entry.key == first_entry.key);
1205 try testing.expect(entry.value == first_entry.value);
1941 try testing.expect(entry.key_ptr.* == first_entry.key_ptr.*);
1942 try testing.expect(entry.value_ptr.* == first_entry.value_ptr.*);
12061943}
12071944
12081945test "ensure capacity" {
12091946 var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator);
12101947 defer map.deinit();
12111948
1212 try map.ensureCapacity(20);
1949 try map.ensureTotalCapacity(20);
12131950 const initial_capacity = map.capacity();
12141951 try testing.expect(initial_capacity >= 20);
12151952 var i: i32 = 0;
......@@ -1220,6 +1957,59 @@ test "ensure capacity" {
12201957 try testing.expect(initial_capacity == map.capacity());
12211958}
12221959
1960test "big map" {
1961 var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator);
1962 defer map.deinit();
1963
1964 var i: i32 = 0;
1965 while (i < 8) : (i += 1) {
1966 try map.put(i, i + 10);
1967 }
1968
1969 i = 0;
1970 while (i < 8) : (i += 1) {
1971 try testing.expectEqual(@as(?i32, i + 10), map.get(i));
1972 }
1973 while (i < 16) : (i += 1) {
1974 try testing.expectEqual(@as(?i32, null), map.get(i));
1975 }
1976
1977 i = 4;
1978 while (i < 12) : (i += 1) {
1979 try map.put(i, i + 12);
1980 }
1981
1982 i = 0;
1983 while (i < 4) : (i += 1) {
1984 try testing.expectEqual(@as(?i32, i + 10), map.get(i));
1985 }
1986 while (i < 12) : (i += 1) {
1987 try testing.expectEqual(@as(?i32, i + 12), map.get(i));
1988 }
1989 while (i < 16) : (i += 1) {
1990 try testing.expectEqual(@as(?i32, null), map.get(i));
1991 }
1992
1993 i = 0;
1994 while (i < 4) : (i += 1) {
1995 try testing.expect(map.orderedRemove(i));
1996 }
1997 while (i < 8) : (i += 1) {
1998 try testing.expect(map.swapRemove(i));
1999 }
2000
2001 i = 0;
2002 while (i < 8) : (i += 1) {
2003 try testing.expectEqual(@as(?i32, null), map.get(i));
2004 }
2005 while (i < 12) : (i += 1) {
2006 try testing.expectEqual(@as(?i32, i + 12), map.get(i));
2007 }
2008 while (i < 16) : (i += 1) {
2009 try testing.expectEqual(@as(?i32, null), map.get(i));
2010 }
2011}
2012
12232013test "clone" {
12242014 var original = AutoArrayHashMap(i32, i32).init(std.testing.allocator);
12252015 defer original.deinit();
......@@ -1235,7 +2025,14 @@ test "clone" {
12352025
12362026 i = 0;
12372027 while (i < 10) : (i += 1) {
2028 try testing.expect(original.get(i).? == i * 10);
12382029 try testing.expect(copy.get(i).? == i * 10);
2030 try testing.expect(original.getPtr(i).? != copy.getPtr(i).?);
2031 }
2032
2033 while (i < 20) : (i += 1) {
2034 try testing.expect(original.get(i) == null);
2035 try testing.expect(copy.get(i) == null);
12392036 }
12402037}
12412038
......@@ -1261,7 +2058,7 @@ test "shrink" {
12612058 const gop = try map.getOrPut(i);
12622059 if (i < 17) {
12632060 try testing.expect(gop.found_existing == true);
1264 try testing.expect(gop.entry.value == i * 10);
2061 try testing.expect(gop.value_ptr.* == i * 10);
12652062 } else try testing.expect(gop.found_existing == false);
12662063 }
12672064
......@@ -1274,7 +2071,7 @@ test "shrink" {
12742071 const gop = try map.getOrPut(i);
12752072 if (i < 15) {
12762073 try testing.expect(gop.found_existing == true);
1277 try testing.expect(gop.entry.value == i * 10);
2074 try testing.expect(gop.value_ptr.* == i * 10);
12782075 } else try testing.expect(gop.found_existing == false);
12792076 }
12802077}
......@@ -1298,7 +2095,7 @@ test "pop" {
12982095}
12992096
13002097test "reIndex" {
1301 var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator);
2098 var map = ArrayHashMap(i32, i32, AutoContext(i32), true).init(std.testing.allocator);
13022099 defer map.deinit();
13032100
13042101 // Populate via the API.
......@@ -1312,13 +2109,13 @@ test "reIndex" {
13122109
13132110 // Now write to the underlying array list directly.
13142111 const num_unindexed_entries = 20;
1315 const hash = getAutoHashFn(i32);
2112 const hash = getAutoHashFn(i32, void);
13162113 var al = &map.unmanaged.entries;
13172114 while (i < num_indexed_entries + num_unindexed_entries) : (i += 1) {
13182115 try al.append(std.testing.allocator, .{
13192116 .key = i,
13202117 .value = i * 10,
1321 .hash = {},
2118 .hash = hash({}, i),
13222119 });
13232120 }
13242121
......@@ -1328,36 +2125,7 @@ test "reIndex" {
13282125 while (i < num_indexed_entries + num_unindexed_entries) : (i += 1) {
13292126 const gop = try map.getOrPut(i);
13302127 try testing.expect(gop.found_existing == true);
1331 try testing.expect(gop.entry.value == i * 10);
1332 try testing.expect(gop.index == i);
1333 }
1334}
1335
1336test "fromOwnedArrayList" {
1337 const array_hash_map_type = AutoArrayHashMap(i32, i32);
1338 var al = std.ArrayListUnmanaged(array_hash_map_type.Entry){};
1339 const hash = getAutoHashFn(i32);
1340
1341 // Populate array list.
1342 const num_entries = 20;
1343 var i: i32 = 0;
1344 while (i < num_entries) : (i += 1) {
1345 try al.append(std.testing.allocator, .{
1346 .key = i,
1347 .value = i * 10,
1348 .hash = {},
1349 });
1350 }
1351
1352 // Now instantiate using `fromOwnedArrayList`.
1353 var map = try array_hash_map_type.fromOwnedArrayList(std.testing.allocator, al);
1354 defer map.deinit();
1355
1356 i = 0;
1357 while (i < num_entries) : (i += 1) {
1358 const gop = try map.getOrPut(i);
1359 try testing.expect(gop.found_existing == true);
1360 try testing.expect(gop.entry.value == i * 10);
2128 try testing.expect(gop.value_ptr.* == i * 10);
13612129 try testing.expect(gop.index == i);
13622130 }
13632131}
......@@ -1365,34 +2133,52 @@ test "fromOwnedArrayList" {
13652133test "auto store_hash" {
13662134 const HasCheapEql = AutoArrayHashMap(i32, i32);
13672135 const HasExpensiveEql = AutoArrayHashMap([32]i32, i32);
1368 try testing.expect(meta.fieldInfo(HasCheapEql.Entry, .hash).field_type == void);
1369 try testing.expect(meta.fieldInfo(HasExpensiveEql.Entry, .hash).field_type != void);
2136 try testing.expect(meta.fieldInfo(HasCheapEql.Data, .hash).field_type == void);
2137 try testing.expect(meta.fieldInfo(HasExpensiveEql.Data, .hash).field_type != void);
13702138
13712139 const HasCheapEqlUn = AutoArrayHashMapUnmanaged(i32, i32);
13722140 const HasExpensiveEqlUn = AutoArrayHashMapUnmanaged([32]i32, i32);
1373 try testing.expect(meta.fieldInfo(HasCheapEqlUn.Entry, .hash).field_type == void);
1374 try testing.expect(meta.fieldInfo(HasExpensiveEqlUn.Entry, .hash).field_type != void);
2141 try testing.expect(meta.fieldInfo(HasCheapEqlUn.Data, .hash).field_type == void);
2142 try testing.expect(meta.fieldInfo(HasExpensiveEqlUn.Data, .hash).field_type != void);
2143}
2144
2145test "compile everything" {
2146 std.testing.refAllDecls(AutoArrayHashMap(i32, i32));
2147 std.testing.refAllDecls(StringArrayHashMap([]const u8));
2148 std.testing.refAllDecls(AutoArrayHashMap(i32, void));
2149 std.testing.refAllDecls(StringArrayHashMap(u0));
2150 std.testing.refAllDecls(AutoArrayHashMapUnmanaged(i32, i32));
2151 std.testing.refAllDecls(StringArrayHashMapUnmanaged([]const u8));
2152 std.testing.refAllDecls(AutoArrayHashMapUnmanaged(i32, void));
2153 std.testing.refAllDecls(StringArrayHashMapUnmanaged(u0));
13752154}
13762155
1377pub fn getHashPtrAddrFn(comptime K: type) (fn (K) u32) {
2156pub fn getHashPtrAddrFn(comptime K: type, comptime Context: type) (fn (Context, K) u32) {
13782157 return struct {
1379 fn hash(key: K) u32 {
1380 return getAutoHashFn(usize)(@ptrToInt(key));
2158 fn hash(ctx: Context, key: K) u32 {
2159 return getAutoHashFn(usize, void)({}, @ptrToInt(key));
13812160 }
13822161 }.hash;
13832162}
13842163
1385pub fn getTrivialEqlFn(comptime K: type) (fn (K, K) bool) {
2164pub fn getTrivialEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K) bool) {
13862165 return struct {
1387 fn eql(a: K, b: K) bool {
2166 fn eql(ctx: Context, a: K, b: K) bool {
13882167 return a == b;
13892168 }
13902169 }.eql;
13912170}
13922171
1393pub fn getAutoHashFn(comptime K: type) (fn (K) u32) {
2172pub fn AutoContext(comptime K: type) type {
2173 return struct {
2174 pub const hash = getAutoHashFn(K, @This());
2175 pub const eql = getAutoEqlFn(K, @This());
2176 };
2177}
2178
2179pub fn getAutoHashFn(comptime K: type, comptime Context: type) (fn (Context, K) u32) {
13942180 return struct {
1395 fn hash(key: K) u32 {
2181 fn hash(ctx: Context, key: K) u32 {
13962182 if (comptime trait.hasUniqueRepresentation(K)) {
13972183 return @truncate(u32, Wyhash.hash(0, std.mem.asBytes(&key)));
13982184 } else {
......@@ -1404,9 +2190,9 @@ pub fn getAutoHashFn(comptime K: type) (fn (K) u32) {
14042190 }.hash;
14052191}
14062192
1407pub fn getAutoEqlFn(comptime K: type) (fn (K, K) bool) {
2193pub fn getAutoEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K) bool) {
14082194 return struct {
1409 fn eql(a: K, b: K) bool {
2195 fn eql(ctx: Context, a: K, b: K) bool {
14102196 return meta.eql(a, b);
14112197 }
14122198 }.eql;
......@@ -1430,9 +2216,9 @@ pub fn autoEqlIsCheap(comptime K: type) bool {
14302216 };
14312217}
14322218
1433pub fn getAutoHashStratFn(comptime K: type, comptime strategy: std.hash.Strategy) (fn (K) u32) {
2219pub fn getAutoHashStratFn(comptime K: type, comptime Context: type, comptime strategy: std.hash.Strategy) (fn (Context, K) u32) {
14342220 return struct {
1435 fn hash(key: K) u32 {
2221 fn hash(ctx: Context, key: K) u32 {
14362222 var hasher = Wyhash.init(0);
14372223 std.hash.autoHashStrat(&hasher, key, strategy);
14382224 return @truncate(u32, hasher.final());
lib/std/buf_map.zig+42-25
......@@ -16,65 +16,82 @@ pub const BufMap = struct {
1616
1717 const BufMapHashMap = StringHashMap([]const u8);
1818
19 /// Create a BufMap backed by a specific allocator.
20 /// That allocator will be used for both backing allocations
21 /// and string deduplication.
1922 pub fn init(allocator: *Allocator) BufMap {
2023 var self = BufMap{ .hash_map = BufMapHashMap.init(allocator) };
2124 return self;
2225 }
2326
27 /// Free the backing storage of the map, as well as all
28 /// of the stored keys and values.
2429 pub fn deinit(self: *BufMap) void {
2530 var it = self.hash_map.iterator();
26 while (true) {
27 const entry = it.next() orelse break;
28 self.free(entry.key);
29 self.free(entry.value);
31 while (it.next()) |entry| {
32 self.free(entry.key_ptr.*);
33 self.free(entry.value_ptr.*);
3034 }
3135
3236 self.hash_map.deinit();
3337 }
3438
35 /// Same as `set` but the key and value become owned by the BufMap rather
39 /// Same as `put` but the key and value become owned by the BufMap rather
3640 /// than being copied.
37 /// If `setMove` fails, the ownership of key and value does not transfer.
38 pub fn setMove(self: *BufMap, key: []u8, value: []u8) !void {
41 /// If `putMove` fails, the ownership of key and value does not transfer.
42 pub fn putMove(self: *BufMap, key: []u8, value: []u8) !void {
3943 const get_or_put = try self.hash_map.getOrPut(key);
4044 if (get_or_put.found_existing) {
41 self.free(get_or_put.entry.key);
42 self.free(get_or_put.entry.value);
43 get_or_put.entry.key = key;
45 self.free(get_or_put.key_ptr.*);
46 self.free(get_or_put.value_ptr.*);
47 get_or_put.key_ptr.* = key;
4448 }
45 get_or_put.entry.value = value;
49 get_or_put.value_ptr.* = value;
4650 }
4751
4852 /// `key` and `value` are copied into the BufMap.
49 pub fn set(self: *BufMap, key: []const u8, value: []const u8) !void {
53 pub fn put(self: *BufMap, key: []const u8, value: []const u8) !void {
5054 const value_copy = try self.copy(value);
5155 errdefer self.free(value_copy);
5256 const get_or_put = try self.hash_map.getOrPut(key);
5357 if (get_or_put.found_existing) {
54 self.free(get_or_put.entry.value);
58 self.free(get_or_put.value_ptr.*);
5559 } else {
56 get_or_put.entry.key = self.copy(key) catch |err| {
60 get_or_put.key_ptr.* = self.copy(key) catch |err| {
5761 _ = self.hash_map.remove(key);
5862 return err;
5963 };
6064 }
61 get_or_put.entry.value = value_copy;
65 get_or_put.value_ptr.* = value_copy;
6266 }
6367
68 /// Find the address of the value associated with a key.
69 /// The returned pointer is invalidated if the map resizes.
70 pub fn getPtr(self: BufMap, key: []const u8) ?*[]const u8 {
71 return self.hash_map.getPtr(key);
72 }
73
74 /// Return the map's copy of the value associated with
75 /// a key. The returned string is invalidated if this
76 /// key is removed from the map.
6477 pub fn get(self: BufMap, key: []const u8) ?[]const u8 {
6578 return self.hash_map.get(key);
6679 }
6780
68 pub fn delete(self: *BufMap, key: []const u8) void {
69 const entry = self.hash_map.remove(key) orelse return;
70 self.free(entry.key);
71 self.free(entry.value);
81 /// Removes the item from the map and frees its value.
82 /// This invalidates the value returned by get() for this key.
83 pub fn remove(self: *BufMap, key: []const u8) void {
84 const kv = self.hash_map.fetchRemove(key) orelse return;
85 self.free(kv.key);
86 self.free(kv.value);
7287 }
7388
89 /// Returns the number of KV pairs stored in the map.
7490 pub fn count(self: BufMap) usize {
7591 return self.hash_map.count();
7692 }
7793
94 /// Returns an iterator over entries in the map.
7895 pub fn iterator(self: *const BufMap) BufMapHashMap.Iterator {
7996 return self.hash_map.iterator();
8097 }
......@@ -93,21 +110,21 @@ test "BufMap" {
93110 var bufmap = BufMap.init(allocator);
94111 defer bufmap.deinit();
95112
96 try bufmap.set("x", "1");
113 try bufmap.put("x", "1");
97114 try testing.expect(mem.eql(u8, bufmap.get("x").?, "1"));
98115 try testing.expect(1 == bufmap.count());
99116
100 try bufmap.set("x", "2");
117 try bufmap.put("x", "2");
101118 try testing.expect(mem.eql(u8, bufmap.get("x").?, "2"));
102119 try testing.expect(1 == bufmap.count());
103120
104 try bufmap.set("x", "3");
121 try bufmap.put("x", "3");
105122 try testing.expect(mem.eql(u8, bufmap.get("x").?, "3"));
106123 try testing.expect(1 == bufmap.count());
107124
108 bufmap.delete("x");
125 bufmap.remove("x");
109126 try testing.expect(0 == bufmap.count());
110127
111 try bufmap.setMove(try allocator.dupe(u8, "k"), try allocator.dupe(u8, "v1"));
112 try bufmap.setMove(try allocator.dupe(u8, "k"), try allocator.dupe(u8, "v2"));
128 try bufmap.putMove(try allocator.dupe(u8, "k"), try allocator.dupe(u8, "v1"));
129 try bufmap.putMove(try allocator.dupe(u8, "k"), try allocator.dupe(u8, "v2"));
113130}
lib/std/buf_set.zig+39-20
......@@ -9,50 +9,69 @@ const mem = @import("mem.zig");
99const Allocator = mem.Allocator;
1010const testing = std.testing;
1111
12/// A BufSet is a set of strings. The BufSet duplicates
13/// strings internally, and never takes ownership of strings
14/// which are passed to it.
1215pub const BufSet = struct {
1316 hash_map: BufSetHashMap,
1417
1518 const BufSetHashMap = StringHashMap(void);
19 pub const Iterator = BufSetHashMap.KeyIterator;
1620
21 /// Create a BufSet using an allocator. The allocator will
22 /// be used internally for both backing allocations and
23 /// string duplication.
1724 pub fn init(a: *Allocator) BufSet {
1825 var self = BufSet{ .hash_map = BufSetHashMap.init(a) };
1926 return self;
2027 }
2128
29 /// Free a BufSet along with all stored keys.
2230 pub fn deinit(self: *BufSet) void {
23 var it = self.hash_map.iterator();
24 while (it.next()) |entry| {
25 self.free(entry.key);
31 var it = self.hash_map.keyIterator();
32 while (it.next()) |key_ptr| {
33 self.free(key_ptr.*);
2634 }
2735 self.hash_map.deinit();
2836 self.* = undefined;
2937 }
3038
31 pub fn put(self: *BufSet, key: []const u8) !void {
32 if (self.hash_map.get(key) == null) {
33 const key_copy = try self.copy(key);
34 errdefer self.free(key_copy);
35 try self.hash_map.put(key_copy, {});
39 /// Insert an item into the BufSet. The item will be
40 /// copied, so the caller may delete or reuse the
41 /// passed string immediately.
42 pub fn insert(self: *BufSet, value: []const u8) !void {
43 const gop = try self.hash_map.getOrPut(value);
44 if (!gop.found_existing) {
45 gop.key_ptr.* = self.copy(value) catch |err| {
46 _ = self.hash_map.remove(value);
47 return err;
48 };
3649 }
3750 }
3851
39 pub fn exists(self: BufSet, key: []const u8) bool {
40 return self.hash_map.get(key) != null;
52 /// Check if the set contains an item matching the passed string
53 pub fn contains(self: BufSet, value: []const u8) bool {
54 return self.hash_map.contains(value);
4155 }
4256
43 pub fn delete(self: *BufSet, key: []const u8) void {
44 const entry = self.hash_map.remove(key) orelse return;
45 self.free(entry.key);
57 /// Remove an item from the set.
58 pub fn remove(self: *BufSet, value: []const u8) void {
59 const kv = self.hash_map.fetchRemove(value) orelse return;
60 self.free(kv.key);
4661 }
4762
63 /// Returns the number of items stored in the set
4864 pub fn count(self: *const BufSet) usize {
4965 return self.hash_map.count();
5066 }
5167
52 pub fn iterator(self: *const BufSet) BufSetHashMap.Iterator {
53 return self.hash_map.iterator();
68 /// Returns an iterator over the items stored in the set.
69 /// Iteration order is arbitrary.
70 pub fn iterator(self: *const BufSet) Iterator {
71 return self.hash_map.keyIterator();
5472 }
5573
74 /// Get the allocator used by this set
5675 pub fn allocator(self: *const BufSet) *Allocator {
5776 return self.hash_map.allocator;
5877 }
......@@ -72,12 +91,12 @@ test "BufSet" {
7291 var bufset = BufSet.init(std.testing.allocator);
7392 defer bufset.deinit();
7493
75 try bufset.put("x");
94 try bufset.insert("x");
7695 try testing.expect(bufset.count() == 1);
77 bufset.delete("x");
96 bufset.remove("x");
7897 try testing.expect(bufset.count() == 0);
7998
80 try bufset.put("x");
81 try bufset.put("y");
82 try bufset.put("z");
99 try bufset.insert("x");
100 try bufset.insert("y");
101 try bufset.insert("z");
83102}
lib/std/build.zig+21-21
......@@ -504,10 +504,10 @@ pub const Builder = struct {
504504 }
505505 self.available_options_list.append(available_option) catch unreachable;
506506
507 const entry = self.user_input_options.getEntry(name) orelse return null;
508 entry.value.used = true;
507 const option_ptr = self.user_input_options.getPtr(name) orelse return null;
508 option_ptr.used = true;
509509 switch (type_id) {
510 .Bool => switch (entry.value.value) {
510 .Bool => switch (option_ptr.value) {
511511 .Flag => return true,
512512 .Scalar => |s| {
513513 if (mem.eql(u8, s, "true")) {
......@@ -526,7 +526,7 @@ pub const Builder = struct {
526526 return null;
527527 },
528528 },
529 .Int => switch (entry.value.value) {
529 .Int => switch (option_ptr.value) {
530530 .Flag => {
531531 warn("Expected -D{s} to be an integer, but received a boolean.\n\n", .{name});
532532 self.markInvalidUserInput();
......@@ -553,7 +553,7 @@ pub const Builder = struct {
553553 return null;
554554 },
555555 },
556 .Float => switch (entry.value.value) {
556 .Float => switch (option_ptr.value) {
557557 .Flag => {
558558 warn("Expected -D{s} to be a float, but received a boolean.\n\n", .{name});
559559 self.markInvalidUserInput();
......@@ -573,7 +573,7 @@ pub const Builder = struct {
573573 return null;
574574 },
575575 },
576 .Enum => switch (entry.value.value) {
576 .Enum => switch (option_ptr.value) {
577577 .Flag => {
578578 warn("Expected -D{s} to be a string, but received a boolean.\n\n", .{name});
579579 self.markInvalidUserInput();
......@@ -594,7 +594,7 @@ pub const Builder = struct {
594594 return null;
595595 },
596596 },
597 .String => switch (entry.value.value) {
597 .String => switch (option_ptr.value) {
598598 .Flag => {
599599 warn("Expected -D{s} to be a string, but received a boolean.\n\n", .{name});
600600 self.markInvalidUserInput();
......@@ -607,7 +607,7 @@ pub const Builder = struct {
607607 },
608608 .Scalar => |s| return s,
609609 },
610 .List => switch (entry.value.value) {
610 .List => switch (option_ptr.value) {
611611 .Flag => {
612612 warn("Expected -D{s} to be a list, but received a boolean.\n\n", .{name});
613613 self.markInvalidUserInput();
......@@ -769,7 +769,7 @@ pub const Builder = struct {
769769 const value = self.dupe(value_raw);
770770 const gop = try self.user_input_options.getOrPut(name);
771771 if (!gop.found_existing) {
772 gop.entry.value = UserInputOption{
772 gop.value_ptr.* = UserInputOption{
773773 .name = name,
774774 .value = UserValue{ .Scalar = value },
775775 .used = false,
......@@ -778,7 +778,7 @@ pub const Builder = struct {
778778 }
779779
780780 // option already exists
781 switch (gop.entry.value.value) {
781 switch (gop.value_ptr.value) {
782782 UserValue.Scalar => |s| {
783783 // turn it into a list
784784 var list = ArrayList([]const u8).init(self.allocator);
......@@ -811,7 +811,7 @@ pub const Builder = struct {
811811 const name = self.dupe(name_raw);
812812 const gop = try self.user_input_options.getOrPut(name);
813813 if (!gop.found_existing) {
814 gop.entry.value = UserInputOption{
814 gop.value_ptr.* = UserInputOption{
815815 .name = name,
816816 .value = UserValue{ .Flag = {} },
817817 .used = false,
......@@ -820,7 +820,7 @@ pub const Builder = struct {
820820 }
821821
822822 // option already exists
823 switch (gop.entry.value.value) {
823 switch (gop.value_ptr.value) {
824824 UserValue.Scalar => |s| {
825825 warn("Flag '-D{s}' conflicts with option '-D{s}={s}'.\n", .{ name, name, s });
826826 return true;
......@@ -866,10 +866,9 @@ pub const Builder = struct {
866866 pub fn validateUserInputDidItFail(self: *Builder) bool {
867867 // make sure all args are used
868868 var it = self.user_input_options.iterator();
869 while (true) {
870 const entry = it.next() orelse break;
871 if (!entry.value.used) {
872 warn("Invalid option: -D{s}\n\n", .{entry.key});
869 while (it.next()) |entry| {
870 if (!entry.value_ptr.used) {
871 warn("Invalid option: -D{s}\n\n", .{entry.key_ptr.*});
873872 self.markInvalidUserInput();
874873 }
875874 }
......@@ -1653,7 +1652,8 @@ pub const LibExeObjStep = struct {
16531652
16541653 pub fn linkFramework(self: *LibExeObjStep, framework_name: []const u8) void {
16551654 assert(self.target.isDarwin());
1656 self.frameworks.put(self.builder.dupe(framework_name)) catch unreachable;
1655 // Note: No need to dupe because frameworks dupes internally.
1656 self.frameworks.insert(framework_name) catch unreachable;
16571657 }
16581658
16591659 /// Returns whether the library, executable, or object depends on a particular system library.
......@@ -2155,8 +2155,8 @@ pub const LibExeObjStep = struct {
21552155 // Inherit dependencies on darwin frameworks
21562156 if (self.target.isDarwin() and !other.isDynamicLibrary()) {
21572157 var it = other.frameworks.iterator();
2158 while (it.next()) |entry| {
2159 self.frameworks.put(entry.key) catch unreachable;
2158 while (it.next()) |framework| {
2159 self.frameworks.insert(framework.*) catch unreachable;
21602160 }
21612161 }
21622162 }
......@@ -2591,9 +2591,9 @@ pub const LibExeObjStep = struct {
25912591 }
25922592
25932593 var it = self.frameworks.iterator();
2594 while (it.next()) |entry| {
2594 while (it.next()) |framework| {
25952595 zig_args.append("-framework") catch unreachable;
2596 zig_args.append(entry.key) catch unreachable;
2596 zig_args.append(framework.*) catch unreachable;
25972597 }
25982598 }
25992599
lib/std/build/run.zig+4-6
......@@ -117,9 +117,9 @@ pub const RunStep = struct {
117117
118118 if (prev_path) |pp| {
119119 const new_path = self.builder.fmt("{s}" ++ [1]u8{fs.path.delimiter} ++ "{s}", .{ pp, search_path });
120 env_map.set(key, new_path) catch unreachable;
120 env_map.put(key, new_path) catch unreachable;
121121 } else {
122 env_map.set(key, self.builder.dupePath(search_path)) catch unreachable;
122 env_map.put(key, self.builder.dupePath(search_path)) catch unreachable;
123123 }
124124 }
125125
......@@ -134,10 +134,8 @@ pub const RunStep = struct {
134134
135135 pub fn setEnvironmentVariable(self: *RunStep, key: []const u8, value: []const u8) void {
136136 const env_map = self.getEnvMap();
137 env_map.set(
138 self.builder.dupe(key),
139 self.builder.dupe(value),
140 ) catch unreachable;
137 // Note: no need to dupe these strings because BufMap does it internally.
138 env_map.put(key, value) catch unreachable;
141139 }
142140
143141 pub fn expectStdErrEqual(self: *RunStep, bytes: []const u8) void {
lib/std/child_process.zig+12-12
......@@ -955,7 +955,7 @@ pub fn createWindowsEnvBlock(allocator: *mem.Allocator, env_map: *const BufMap)
955955 while (it.next()) |pair| {
956956 // +1 for '='
957957 // +1 for null byte
958 max_chars_needed += pair.key.len + pair.value.len + 2;
958 max_chars_needed += pair.key_ptr.len + pair.value_ptr.len + 2;
959959 }
960960 break :x max_chars_needed;
961961 };
......@@ -965,10 +965,10 @@ pub fn createWindowsEnvBlock(allocator: *mem.Allocator, env_map: *const BufMap)
965965 var it = env_map.iterator();
966966 var i: usize = 0;
967967 while (it.next()) |pair| {
968 i += try unicode.utf8ToUtf16Le(result[i..], pair.key);
968 i += try unicode.utf8ToUtf16Le(result[i..], pair.key_ptr.*);
969969 result[i] = '=';
970970 i += 1;
971 i += try unicode.utf8ToUtf16Le(result[i..], pair.value);
971 i += try unicode.utf8ToUtf16Le(result[i..], pair.value_ptr.*);
972972 result[i] = 0;
973973 i += 1;
974974 }
......@@ -990,10 +990,10 @@ pub fn createNullDelimitedEnvMap(arena: *mem.Allocator, env_map: *const std.BufM
990990 var it = env_map.iterator();
991991 var i: usize = 0;
992992 while (it.next()) |pair| : (i += 1) {
993 const env_buf = try arena.allocSentinel(u8, pair.key.len + pair.value.len + 1, 0);
994 mem.copy(u8, env_buf, pair.key);
995 env_buf[pair.key.len] = '=';
996 mem.copy(u8, env_buf[pair.key.len + 1 ..], pair.value);
993 const env_buf = try arena.allocSentinel(u8, pair.key_ptr.len + pair.value_ptr.len + 1, 0);
994 mem.copy(u8, env_buf, pair.key_ptr.*);
995 env_buf[pair.key_ptr.len] = '=';
996 mem.copy(u8, env_buf[pair.key_ptr.len + 1 ..], pair.value_ptr.*);
997997 envp_buf[i] = env_buf.ptr;
998998 }
999999 assert(i == envp_count);
......@@ -1007,11 +1007,11 @@ test "createNullDelimitedEnvMap" {
10071007 var envmap = BufMap.init(allocator);
10081008 defer envmap.deinit();
10091009
1010 try envmap.set("HOME", "/home/ifreund");
1011 try envmap.set("WAYLAND_DISPLAY", "wayland-1");
1012 try envmap.set("DISPLAY", ":1");
1013 try envmap.set("DEBUGINFOD_URLS", " ");
1014 try envmap.set("XCURSOR_SIZE", "24");
1010 try envmap.put("HOME", "/home/ifreund");
1011 try envmap.put("WAYLAND_DISPLAY", "wayland-1");
1012 try envmap.put("DISPLAY", ":1");
1013 try envmap.put("DEBUGINFOD_URLS", " ");
1014 try envmap.put("XCURSOR_SIZE", "24");
10151015
10161016 var arena = std.heap.ArenaAllocator.init(allocator);
10171017 defer arena.deinit();
lib/std/fs/watch.zig+58-56
......@@ -165,11 +165,13 @@ pub fn Watch(comptime V: type) type {
165165 .macos, .freebsd, .netbsd, .dragonfly, .openbsd => {
166166 var it = self.os_data.file_table.iterator();
167167 while (it.next()) |entry| {
168 entry.value.cancelled = true;
168 const key = entry.key_ptr.*;
169 const value = entry.value_ptr.*;
170 value.cancelled = true;
169171 // @TODO Close the fd here?
170 await entry.value.putter_frame;
171 self.allocator.free(entry.key);
172 self.allocator.destroy(entry.value);
172 await value.putter_frame;
173 self.allocator.free(key);
174 self.allocator.destroy(value);
173175 }
174176 },
175177 .linux => {
......@@ -177,9 +179,9 @@ pub fn Watch(comptime V: type) type {
177179 {
178180 // Remove all directory watches linuxEventPutter will take care of
179181 // cleaning up the memory and closing the inotify fd.
180 var dir_it = self.os_data.wd_table.iterator();
181 while (dir_it.next()) |wd_entry| {
182 const rc = os.linux.inotify_rm_watch(self.os_data.inotify_fd, wd_entry.key);
182 var dir_it = self.os_data.wd_table.keyIterator();
183 while (dir_it.next()) |wd_key| {
184 const rc = os.linux.inotify_rm_watch(self.os_data.inotify_fd, wd_key.*);
183185 // Errno can only be EBADF, EINVAL if either the inotify fs or the wd are invalid
184186 std.debug.assert(rc == 0);
185187 }
......@@ -202,13 +204,13 @@ pub fn Watch(comptime V: type) type {
202204 await dir_entry.value.putter_frame;
203205 }
204206
205 self.allocator.free(dir_entry.key);
206 var file_it = dir_entry.value.file_table.iterator();
207 self.allocator.free(dir_entry.key_ptr.*);
208 var file_it = dir_entry.value.file_table.keyIterator();
207209 while (file_it.next()) |file_entry| {
208 self.allocator.free(file_entry.key);
210 self.allocator.free(file_entry.*);
209211 }
210212 dir_entry.value.file_table.deinit(self.allocator);
211 self.allocator.destroy(dir_entry.value);
213 self.allocator.destroy(dir_entry.value_ptr.*);
212214 }
213215 self.os_data.dir_table.deinit(self.allocator);
214216 },
......@@ -236,18 +238,18 @@ pub fn Watch(comptime V: type) type {
236238 defer held.release();
237239
238240 const gop = try self.os_data.file_table.getOrPut(self.allocator, realpath);
239 errdefer self.os_data.file_table.removeAssertDiscard(realpath);
241 errdefer assert(self.os_data.file_table.remove(realpath));
240242 if (gop.found_existing) {
241 const prev_value = gop.entry.value.value;
242 gop.entry.value.value = value;
243 const prev_value = gop.value_ptr.value;
244 gop.value_ptr.value = value;
243245 return prev_value;
244246 }
245247
246 gop.entry.key = try self.allocator.dupe(u8, realpath);
247 errdefer self.allocator.free(gop.entry.key);
248 gop.entry.value = try self.allocator.create(OsData.Put);
249 errdefer self.allocator.destroy(gop.entry.value);
250 gop.entry.value.* = .{
248 gop.key_ptr.* = try self.allocator.dupe(u8, realpath);
249 errdefer self.allocator.free(gop.key_ptr.*);
250 gop.value_ptr.* = try self.allocator.create(OsData.Put);
251 errdefer self.allocator.destroy(gop.value_ptr.*);
252 gop.value_ptr.* = .{
251253 .putter_frame = undefined,
252254 .value = value,
253255 };
......@@ -255,7 +257,7 @@ pub fn Watch(comptime V: type) type {
255257 // @TODO Can I close this fd and get an error from bsdWaitKev?
256258 const flags = if (comptime std.Target.current.isDarwin()) os.O_SYMLINK | os.O_EVTONLY else 0;
257259 const fd = try os.open(realpath, flags, 0);
258 gop.entry.value.putter_frame = async self.kqPutEvents(fd, gop.entry.key, gop.entry.value);
260 gop.value_ptr.putter_frame = async self.kqPutEvents(fd, gop.key_ptr.*, gop.value_ptr.*);
259261 return null;
260262 }
261263
......@@ -345,24 +347,24 @@ pub fn Watch(comptime V: type) type {
345347 defer held.release();
346348
347349 const gop = try self.os_data.wd_table.getOrPut(self.allocator, wd);
348 errdefer self.os_data.wd_table.removeAssertDiscard(wd);
350 errdefer assert(self.os_data.wd_table.remove(wd));
349351 if (!gop.found_existing) {
350 gop.entry.value = OsData.Dir{
352 gop.value_ptr.* = OsData.Dir{
351353 .dirname = try self.allocator.dupe(u8, dirname),
352354 .file_table = OsData.FileTable.init(self.allocator),
353355 };
354356 }
355357
356 const dir = &gop.entry.value;
358 const dir = gop.value_ptr;
357359 const file_table_gop = try dir.file_table.getOrPut(self.allocator, basename);
358 errdefer dir.file_table.removeAssertDiscard(basename);
360 errdefer assert(dir.file_table.remove(basename));
359361 if (file_table_gop.found_existing) {
360 const prev_value = file_table_gop.entry.value;
361 file_table_gop.entry.value = value;
362 const prev_value = file_table_gop.value_ptr.*;
363 file_table_gop.value_ptr.* = value;
362364 return prev_value;
363365 } else {
364 file_table_gop.entry.key = try self.allocator.dupe(u8, basename);
365 file_table_gop.entry.value = value;
366 file_table_gop.key_ptr.* = try self.allocator.dupe(u8, basename);
367 file_table_gop.value_ptr.* = value;
366368 return null;
367369 }
368370 }
......@@ -383,19 +385,19 @@ pub fn Watch(comptime V: type) type {
383385 defer held.release();
384386
385387 const gop = try self.os_data.dir_table.getOrPut(self.allocator, dirname);
386 errdefer self.os_data.dir_table.removeAssertDiscard(dirname);
388 errdefer assert(self.os_data.dir_table.remove(dirname));
387389 if (gop.found_existing) {
388 const dir = gop.entry.value;
390 const dir = gop.value_ptr.*;
389391
390392 const file_gop = try dir.file_table.getOrPut(self.allocator, basename);
391 errdefer dir.file_table.removeAssertDiscard(basename);
393 errdefer assert(dir.file_table.remove(basename));
392394 if (file_gop.found_existing) {
393 const prev_value = file_gop.entry.value;
394 file_gop.entry.value = value;
395 const prev_value = file_gop.value_ptr.*;
396 file_gop.value_ptr.* = value;
395397 return prev_value;
396398 } else {
397 file_gop.entry.value = value;
398 file_gop.entry.key = try self.allocator.dupe(u8, basename);
399 file_gop.value_ptr.* = value;
400 file_gop.key_ptr.* = try self.allocator.dupe(u8, basename);
399401 return null;
400402 }
401403 } else {
......@@ -411,17 +413,17 @@ pub fn Watch(comptime V: type) type {
411413 const dir = try self.allocator.create(OsData.Dir);
412414 errdefer self.allocator.destroy(dir);
413415
414 gop.entry.key = try self.allocator.dupe(u8, dirname);
415 errdefer self.allocator.free(gop.entry.key);
416 gop.key_ptr.* = try self.allocator.dupe(u8, dirname);
417 errdefer self.allocator.free(gop.key_ptr.*);
416418
417419 dir.* = OsData.Dir{
418420 .file_table = OsData.FileTable.init(self.allocator),
419421 .putter_frame = undefined,
420422 .dir_handle = dir_handle,
421423 };
422 gop.entry.value = dir;
424 gop.value_ptr.* = dir;
423425 try dir.file_table.put(self.allocator, try self.allocator.dupe(u8, basename), value);
424 dir.putter_frame = async self.windowsDirReader(dir, gop.entry.key);
426 dir.putter_frame = async self.windowsDirReader(dir, gop.key_ptr.*);
425427 return null;
426428 }
427429 }
......@@ -501,9 +503,9 @@ pub fn Watch(comptime V: type) type {
501503 if (dir.file_table.getEntry(basename)) |entry| {
502504 self.channel.put(Event{
503505 .id = id,
504 .data = entry.value,
506 .data = entry.value_ptr.*,
505507 .dirname = dirname,
506 .basename = entry.key,
508 .basename = entry.key_ptr.*,
507509 });
508510 }
509511 }
......@@ -525,7 +527,7 @@ pub fn Watch(comptime V: type) type {
525527 defer held.release();
526528
527529 const dir = self.os_data.wd_table.get(dirname) orelse return null;
528 if (dir.file_table.remove(basename)) |file_entry| {
530 if (dir.file_table.fetchRemove(basename)) |file_entry| {
529531 self.allocator.free(file_entry.key);
530532 return file_entry.value;
531533 }
......@@ -539,7 +541,7 @@ pub fn Watch(comptime V: type) type {
539541 defer held.release();
540542
541543 const dir = self.os_data.dir_table.get(dirname) orelse return null;
542 if (dir.file_table.remove(basename)) |file_entry| {
544 if (dir.file_table.fetchRemove(basename)) |file_entry| {
543545 self.allocator.free(file_entry.key);
544546 return file_entry.value;
545547 }
......@@ -552,14 +554,14 @@ pub fn Watch(comptime V: type) type {
552554 const held = self.os_data.table_lock.acquire();
553555 defer held.release();
554556
555 const entry = self.os_data.file_table.get(realpath) orelse return null;
556 entry.value.cancelled = true;
557 const entry = self.os_data.file_table.getEntry(realpath) orelse return null;
558 entry.value_ptr.cancelled = true;
557559 // @TODO Close the fd here?
558 await entry.value.putter_frame;
559 self.allocator.free(entry.key);
560 self.allocator.destroy(entry.value);
560 await entry.value_ptr.putter_frame;
561 self.allocator.free(entry.key_ptr.*);
562 self.allocator.destroy(entry.value_ptr.*);
561563
562 self.os_data.file_table.removeAssertDiscard(realpath);
564 assert(self.os_data.file_table.remove(realpath));
563565 },
564566 else => @compileError("Unsupported OS"),
565567 }
......@@ -594,19 +596,19 @@ pub fn Watch(comptime V: type) type {
594596 if (dir.file_table.getEntry(basename)) |file_value| {
595597 self.channel.put(Event{
596598 .id = .CloseWrite,
597 .data = file_value.value,
599 .data = file_value.value_ptr.*,
598600 .dirname = dir.dirname,
599 .basename = file_value.key,
601 .basename = file_value.key_ptr.*,
600602 });
601603 }
602604 } else if (ev.mask & os.linux.IN_IGNORED == os.linux.IN_IGNORED) {
603605 // Directory watch was removed
604606 const held = self.os_data.table_lock.acquire();
605607 defer held.release();
606 if (self.os_data.wd_table.remove(ev.wd)) |*wd_entry| {
607 var file_it = wd_entry.value.file_table.iterator();
608 if (self.os_data.wd_table.fetchRemove(ev.wd)) |wd_entry| {
609 var file_it = wd_entry.value.file_table.keyIterator();
608610 while (file_it.next()) |file_entry| {
609 self.allocator.free(file_entry.key);
611 self.allocator.free(file_entry.*);
610612 }
611613 self.allocator.free(wd_entry.value.dirname);
612614 wd_entry.value.file_table.deinit(self.allocator);
......@@ -620,9 +622,9 @@ pub fn Watch(comptime V: type) type {
620622 if (dir.file_table.getEntry(basename)) |file_value| {
621623 self.channel.put(Event{
622624 .id = .Delete,
623 .data = file_value.value,
625 .data = file_value.value_ptr.*,
624626 .dirname = dir.dirname,
625 .basename = file_value.key,
627 .basename = file_value.key_ptr.*,
626628 });
627629 }
628630 }
lib/std/hash_map.zig+872-225
......@@ -15,7 +15,7 @@ const trait = meta.trait;
1515const Allocator = mem.Allocator;
1616const Wyhash = std.hash.Wyhash;
1717
18pub fn getAutoHashFn(comptime K: type) (fn (K) u64) {
18pub fn getAutoHashFn(comptime K: type, comptime Context: type) (fn (Context, K) u64) {
1919 comptime {
2020 assert(@hasDecl(std, "StringHashMap")); // detect when the following message needs updated
2121 if (K == []const u8) {
......@@ -28,7 +28,7 @@ pub fn getAutoHashFn(comptime K: type) (fn (K) u64) {
2828 }
2929
3030 return struct {
31 fn hash(key: K) u64 {
31 fn hash(ctx: Context, key: K) u64 {
3232 if (comptime trait.hasUniqueRepresentation(K)) {
3333 return Wyhash.hash(0, std.mem.asBytes(&key));
3434 } else {
......@@ -40,31 +40,51 @@ pub fn getAutoHashFn(comptime K: type) (fn (K) u64) {
4040 }.hash;
4141}
4242
43pub fn getAutoEqlFn(comptime K: type) (fn (K, K) bool) {
43pub fn getAutoEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K) bool) {
4444 return struct {
45 fn eql(a: K, b: K) bool {
45 fn eql(ctx: Context, a: K, b: K) bool {
4646 return meta.eql(a, b);
4747 }
4848 }.eql;
4949}
5050
5151pub fn AutoHashMap(comptime K: type, comptime V: type) type {
52 return HashMap(K, V, getAutoHashFn(K), getAutoEqlFn(K), default_max_load_percentage);
52 return HashMap(K, V, AutoContext(K), default_max_load_percentage);
5353}
5454
5555pub fn AutoHashMapUnmanaged(comptime K: type, comptime V: type) type {
56 return HashMapUnmanaged(K, V, getAutoHashFn(K), getAutoEqlFn(K), default_max_load_percentage);
56 return HashMapUnmanaged(K, V, AutoContext(K), default_max_load_percentage);
57}
58
59pub fn AutoContext(comptime K: type) type {
60 return struct {
61 pub const hash = getAutoHashFn(K, @This());
62 pub const eql = getAutoEqlFn(K, @This());
63 };
5764}
5865
5966/// Builtin hashmap for strings as keys.
67/// Key memory is managed by the caller. Keys and values
68/// will not automatically be freed.
6069pub fn StringHashMap(comptime V: type) type {
61 return HashMap([]const u8, V, hashString, eqlString, default_max_load_percentage);
70 return HashMap([]const u8, V, StringContext, default_max_load_percentage);
6271}
6372
73/// Key memory is managed by the caller. Keys and values
74/// will not automatically be freed.
6475pub fn StringHashMapUnmanaged(comptime V: type) type {
65 return HashMapUnmanaged([]const u8, V, hashString, eqlString, default_max_load_percentage);
76 return HashMapUnmanaged([]const u8, V, StringContext, default_max_load_percentage);
6677}
6778
79pub const StringContext = struct {
80 pub fn hash(self: @This(), s: []const u8) u64 {
81 return hashString(s);
82 }
83 pub fn eql(self: @This(), a: []const u8, b: []const u8) bool {
84 return eqlString(a, b);
85 }
86};
87
6888pub fn eqlString(a: []const u8, b: []const u8) bool {
6989 return mem.eql(u8, a, b);
7090}
......@@ -78,6 +98,222 @@ pub const DefaultMaxLoadPercentage = default_max_load_percentage;
7898
7999pub const default_max_load_percentage = 80;
80100
101/// This function issues a compile error with a helpful message if there
102/// is a problem with the provided context type. A context must have the following
103/// member functions:
104/// - hash(self, PseudoKey) Hash
105/// - eql(self, PseudoKey, Key) bool
106/// If you are passing a context to a *Adapted function, PseudoKey is the type
107/// of the key parameter. Otherwise, when creating a HashMap or HashMapUnmanaged
108/// type, PseudoKey = Key = K.
109pub fn verifyContext(comptime RawContext: type, comptime PseudoKey: type, comptime Key: type, comptime Hash: type) void {
110 comptime {
111 var allow_const_ptr = false;
112 var allow_mutable_ptr = false;
113 // Context is the actual namespace type. RawContext may be a pointer to Context.
114 var Context = RawContext;
115 // Make sure the context is a namespace type which may have member functions
116 switch (@typeInfo(Context)) {
117 .Struct, .Union, .Enum => {},
118 // Special-case .Opaque for a better error message
119 .Opaque => @compileError("Hash context must be a type with hash and eql member functions. Cannot use "++@typeName(Context)++" because it is opaque. Use a pointer instead."),
120 .Pointer => |ptr| {
121 if (ptr.size != .One) {
122 @compileError("Hash context must be a type with hash and eql member functions. Cannot use "++@typeName(Context)++" because it is not a single pointer.");
123 }
124 Context = ptr.child;
125 allow_const_ptr = true;
126 allow_mutable_ptr = !ptr.is_const;
127 switch (@typeInfo(Context)) {
128 .Struct, .Union, .Enum, .Opaque => {},
129 else => @compileError("Hash context must be a type with hash and eql member functions. Cannot use "++@typeName(Context)),
130 }
131 },
132 else => @compileError("Hash context must be a type with hash and eql member functions. Cannot use "++@typeName(Context)),
133 }
134
135 // Keep track of multiple errors so we can report them all.
136 var errors: []const u8 = "";
137
138 // Put common errors here, they will only be evaluated
139 // if the error is actually triggered.
140 const lazy = struct {
141 const prefix = "\n ";
142 const deep_prefix = prefix ++ " ";
143 const hash_signature = "fn (self, "++@typeName(PseudoKey)++") "++@typeName(Hash);
144 const eql_signature = "fn (self, "++@typeName(PseudoKey)++", "++@typeName(Key)++") bool";
145 const err_invalid_hash_signature = prefix ++ @typeName(Context) ++ ".hash must be " ++ hash_signature ++
146 deep_prefix ++ "but is actually " ++ @typeName(@TypeOf(Context.hash));
147 const err_invalid_eql_signature = prefix ++ @typeName(Context) ++ ".eql must be " ++ eql_signature ++
148 deep_prefix ++ "but is actually " ++ @typeName(@TypeOf(Context.eql));
149 };
150
151 // Verify Context.hash(self, PseudoKey) => Hash
152 if (@hasDecl(Context, "hash")) {
153 const hash = Context.hash;
154 const info = @typeInfo(@TypeOf(hash));
155 if (info == .Fn) {
156 const func = info.Fn;
157 if (func.args.len != 2) {
158 errors = errors ++ lazy.err_invalid_hash_signature;
159 } else {
160 var emitted_signature = false;
161 if (func.args[0].arg_type) |Self| {
162 if (Self == Context) {
163 // pass, this is always fine.
164 } else if (Self == *const Context) {
165 if (!allow_const_ptr) {
166 if (!emitted_signature) {
167 errors = errors ++ lazy.err_invalid_hash_signature;
168 emitted_signature = true;
169 }
170 errors = errors ++ lazy.deep_prefix ++ "First parameter must be "++@typeName(Context)++", but is "++@typeName(Self);
171 errors = errors ++ lazy.deep_prefix ++ "Note: Cannot be a pointer because it is passed by value.";
172 }
173 } else if (Self == *Context) {
174 if (!allow_mutable_ptr) {
175 if (!emitted_signature) {
176 errors = errors ++ lazy.err_invalid_hash_signature;
177 emitted_signature = true;
178 }
179 if (!allow_const_ptr) {
180 errors = errors ++ lazy.deep_prefix ++ "First parameter must be "++@typeName(Context)++", but is "++@typeName(Self);
181 errors = errors ++ lazy.deep_prefix ++ "Note: Cannot be a pointer because it is passed by value.";
182 } else {
183 errors = errors ++ lazy.deep_prefix ++ "First parameter must be "++@typeName(Context)++" or "++@typeName(*const Context)++", but is "++@typeName(Self);
184 errors = errors ++ lazy.deep_prefix ++ "Note: Cannot be non-const because it is passed by const pointer.";
185 }
186 }
187 } else {
188 if (!emitted_signature) {
189 errors = errors ++ lazy.err_invalid_hash_signature;
190 emitted_signature = true;
191 }
192 errors = errors ++ lazy.deep_prefix ++ "First parameter must be "++@typeName(Context);
193 if (allow_const_ptr) {
194 errors = errors++" or "++@typeName(*const Context);
195 if (allow_mutable_ptr) {
196 errors = errors++" or "++@typeName(*Context);
197 }
198 }
199 errors = errors++", but is "++@typeName(Self);
200 }
201 }
202 if (func.args[1].arg_type != null and func.args[1].arg_type.? != PseudoKey) {
203 if (!emitted_signature) {
204 errors = errors ++ lazy.err_invalid_hash_signature;
205 emitted_signature = true;
206 }
207 errors = errors ++ lazy.deep_prefix ++ "Second parameter must be "++@typeName(PseudoKey)++", but is "++@typeName(func.args[1].arg_type.?);
208 }
209 if (func.return_type != null and func.return_type.? != Hash) {
210 if (!emitted_signature) {
211 errors = errors ++ lazy.err_invalid_hash_signature;
212 emitted_signature = true;
213 }
214 errors = errors ++ lazy.deep_prefix ++ "Return type must be "++@typeName(Hash)++", but was "++@typeName(func.return_type.?);
215 }
216 // If any of these are generic (null), we cannot verify them.
217 // The call sites check the return type, but cannot check the
218 // parameters. This may cause compile errors with generic hash/eql functions.
219 }
220 } else {
221 errors = errors ++ lazy.err_invalid_hash_signature;
222 }
223 } else {
224 errors = errors ++ lazy.prefix ++ @typeName(Context) ++ " must declare a hash function with signature " ++ lazy.hash_signature;
225 }
226
227 // Verify Context.eql(self, PseudoKey, Key) => bool
228 if (@hasDecl(Context, "eql")) {
229 const eql = Context.eql;
230 const info = @typeInfo(@TypeOf(eql));
231 if (info == .Fn) {
232 const func = info.Fn;
233 if (func.args.len != 3) {
234 errors = errors ++ lazy.err_invalid_eql_signature;
235 } else {
236 var emitted_signature = false;
237 if (func.args[0].arg_type) |Self| {
238 if (Self == Context) {
239 // pass, this is always fine.
240 } else if (Self == *const Context) {
241 if (!allow_const_ptr) {
242 if (!emitted_signature) {
243 errors = errors ++ lazy.err_invalid_eql_signature;
244 emitted_signature = true;
245 }
246 errors = errors ++ lazy.deep_prefix ++ "First parameter must be "++@typeName(Context)++", but is "++@typeName(Self);
247 errors = errors ++ lazy.deep_prefix ++ "Note: Cannot be a pointer because it is passed by value.";
248 }
249 } else if (Self == *Context) {
250 if (!allow_mutable_ptr) {
251 if (!emitted_signature) {
252 errors = errors ++ lazy.err_invalid_eql_signature;
253 emitted_signature = true;
254 }
255 if (!allow_const_ptr) {
256 errors = errors ++ lazy.deep_prefix ++ "First parameter must be "++@typeName(Context)++", but is "++@typeName(Self);
257 errors = errors ++ lazy.deep_prefix ++ "Note: Cannot be a pointer because it is passed by value.";
258 } else {
259 errors = errors ++ lazy.deep_prefix ++ "First parameter must be "++@typeName(Context)++" or "++@typeName(*const Context)++", but is "++@typeName(Self);
260 errors = errors ++ lazy.deep_prefix ++ "Note: Cannot be non-const because it is passed by const pointer.";
261 }
262 }
263 } else {
264 if (!emitted_signature) {
265 errors = errors ++ lazy.err_invalid_eql_signature;
266 emitted_signature = true;
267 }
268 errors = errors ++ lazy.deep_prefix ++ "First parameter must be "++@typeName(Context);
269 if (allow_const_ptr) {
270 errors = errors++" or "++@typeName(*const Context);
271 if (allow_mutable_ptr) {
272 errors = errors++" or "++@typeName(*Context);
273 }
274 }
275 errors = errors++", but is "++@typeName(Self);
276 }
277 }
278 if (func.args[1].arg_type.? != PseudoKey) {
279 if (!emitted_signature) {
280 errors = errors ++ lazy.err_invalid_eql_signature;
281 emitted_signature = true;
282 }
283 errors = errors ++ lazy.deep_prefix ++ "Second parameter must be "++@typeName(PseudoKey)++", but is "++@typeName(func.args[1].arg_type.?);
284 }
285 if (func.args[2].arg_type.? != Key) {
286 if (!emitted_signature) {
287 errors = errors ++ lazy.err_invalid_eql_signature;
288 emitted_signature = true;
289 }
290 errors = errors ++ lazy.deep_prefix ++ "Third parameter must be "++@typeName(Key)++", but is "++@typeName(func.args[2].arg_type.?);
291 }
292 if (func.return_type.? != bool) {
293 if (!emitted_signature) {
294 errors = errors ++ lazy.err_invalid_eql_signature;
295 emitted_signature = true;
296 }
297 errors = errors ++ lazy.deep_prefix ++ "Return type must be bool, but was "++@typeName(func.return_type.?);
298 }
299 // If any of these are generic (null), we cannot verify them.
300 // The call sites check the return type, but cannot check the
301 // parameters. This may cause compile errors with generic hash/eql functions.
302 }
303 } else {
304 errors = errors ++ lazy.err_invalid_eql_signature;
305 }
306 } else {
307 errors = errors ++ lazy.prefix ++ @typeName(Context) ++ " must declare a eql function with signature " ++ lazy.eql_signature;
308 }
309
310 if (errors.len != 0) {
311 // errors begins with a newline (from lazy.prefix)
312 @compileError("Problems found with hash context type "++@typeName(Context)++":"++errors);
313 }
314 }
315}
316
81317/// General purpose hash table.
82318/// No order is guaranteed and any modification invalidates live iterators.
83319/// It provides fast operations (lookup, insertion, deletion) with quite high
......@@ -86,83 +322,167 @@ pub const default_max_load_percentage = 80;
86322/// field, see `HashMapUnmanaged`.
87323/// If iterating over the table entries is a strong usecase and needs to be fast,
88324/// prefer the alternative `std.ArrayHashMap`.
325/// Context must be a struct type with two member functions:
326/// hash(self, K) u64
327/// eql(self, K, K) bool
328/// Adapted variants of many functions are provided. These variants
329/// take a pseudo key instead of a key. Their context must have the functions:
330/// hash(self, PseudoKey) u64
331/// eql(self, PseudoKey, K) bool
89332pub fn HashMap(
90333 comptime K: type,
91334 comptime V: type,
92 comptime hashFn: fn (key: K) u64,
93 comptime eqlFn: fn (a: K, b: K) bool,
335 comptime Context: type,
94336 comptime max_load_percentage: u64,
95337) type {
338 comptime verifyContext(Context, K, K, u64);
96339 return struct {
97340 unmanaged: Unmanaged,
98341 allocator: *Allocator,
342 ctx: Context,
99343
100 pub const Unmanaged = HashMapUnmanaged(K, V, hashFn, eqlFn, max_load_percentage);
344 /// The type of the unmanaged hash map underlying this wrapper
345 pub const Unmanaged = HashMapUnmanaged(K, V, Context, max_load_percentage);
346 /// An entry, containing pointers to a key and value stored in the map
101347 pub const Entry = Unmanaged.Entry;
348 /// A copy of a key and value which are no longer in the map
349 pub const KV = Unmanaged.KV;
350 /// The integer type that is the result of hashing
102351 pub const Hash = Unmanaged.Hash;
352 /// The iterator type returned by iterator()
103353 pub const Iterator = Unmanaged.Iterator;
354
355 pub const KeyIterator = Unmanaged.KeyIterator;
356 pub const ValueIterator = Unmanaged.ValueIterator;
357
358 /// The integer type used to store the size of the map
104359 pub const Size = Unmanaged.Size;
360 /// The type returned from getOrPut and variants
105361 pub const GetOrPutResult = Unmanaged.GetOrPutResult;
106362
107363 const Self = @This();
108364
365 /// Create a managed hash map with an empty context.
366 /// If the context is not zero-sized, you must use
367 /// initContext(allocator, ctx) instead.
109368 pub fn init(allocator: *Allocator) Self {
369 if (@sizeOf(Context) != 0) {
370 @compileError("Context must be specified! Call initContext(allocator, ctx) instead.");
371 }
372 return .{
373 .unmanaged = .{},
374 .allocator = allocator,
375 .ctx = undefined, // ctx is zero-sized so this is safe.
376 };
377 }
378
379 /// Create a managed hash map with a context
380 pub fn initContext(allocator: *Allocator, ctx: Context) Self {
110381 return .{
111382 .unmanaged = .{},
112383 .allocator = allocator,
384 .ctx = ctx,
113385 };
114386 }
115387
388 /// Release the backing array and invalidate this map.
389 /// This does *not* deinit keys, values, or the context!
390 /// If your keys or values need to be released, ensure
391 /// that that is done before calling this function.
116392 pub fn deinit(self: *Self) void {
117393 self.unmanaged.deinit(self.allocator);
118394 self.* = undefined;
119395 }
120396
397 /// Empty the map, but keep the backing allocation for future use.
398 /// This does *not* free keys or values! Be sure to
399 /// release them if they need deinitialization before
400 /// calling this function.
121401 pub fn clearRetainingCapacity(self: *Self) void {
122402 return self.unmanaged.clearRetainingCapacity();
123403 }
124404
405 /// Empty the map and release the backing allocation.
406 /// This does *not* free keys or values! Be sure to
407 /// release them if they need deinitialization before
408 /// calling this function.
125409 pub fn clearAndFree(self: *Self) void {
126410 return self.unmanaged.clearAndFree(self.allocator);
127411 }
128412
413 /// Return the number of items in the map.
129414 pub fn count(self: Self) Size {
130415 return self.unmanaged.count();
131416 }
132417
418 /// Create an iterator over the entries in the map.
419 /// The iterator is invalidated if the map is modified.
133420 pub fn iterator(self: *const Self) Iterator {
134421 return self.unmanaged.iterator();
135422 }
136423
424 /// Create an iterator over the keys in the map.
425 /// The iterator is invalidated if the map is modified.
426 pub fn keyIterator(self: *const Self) KeyIterator {
427 return self.unmanaged.keyIterator();
428 }
429
430 /// Create an iterator over the values in the map.
431 /// The iterator is invalidated if the map is modified.
432 pub fn valueIterator(self: *const Self) ValueIterator {
433 return self.unmanaged.valueIterator();
434 }
435
137436 /// If key exists this function cannot fail.
138437 /// If there is an existing item with `key`, then the result
139 /// `Entry` pointer points to it, and found_existing is true.
438 /// `Entry` pointers point to it, and found_existing is true.
140439 /// Otherwise, puts a new item with undefined value, and
141 /// the `Entry` pointer points to it. Caller should then initialize
440 /// the `Entry` pointers point to it. Caller should then initialize
142441 /// the value (but not the key).
143442 pub fn getOrPut(self: *Self, key: K) !GetOrPutResult {
144 return self.unmanaged.getOrPut(self.allocator, key);
443 return self.unmanaged.getOrPutContext(self.allocator, key, self.ctx);
444 }
445
446 /// If key exists this function cannot fail.
447 /// If there is an existing item with `key`, then the result
448 /// `Entry` pointers point to it, and found_existing is true.
449 /// Otherwise, puts a new item with undefined key and value, and
450 /// the `Entry` pointers point to it. Caller must then initialize
451 /// the key and value.
452 pub fn getOrPutAdapted(self: *Self, key: anytype, ctx: anytype) !GetOrPutResult {
453 return self.unmanaged.getOrPutContextAdapted(self.allocator, key, ctx, self.ctx);
145454 }
146455
147456 /// If there is an existing item with `key`, then the result
148 /// `Entry` pointer points to it, and found_existing is true.
457 /// `Entry` pointers point to it, and found_existing is true.
149458 /// Otherwise, puts a new item with undefined value, and
150 /// the `Entry` pointer points to it. Caller should then initialize
459 /// the `Entry` pointers point to it. Caller should then initialize
151460 /// the value (but not the key).
152461 /// If a new entry needs to be stored, this function asserts there
153462 /// is enough capacity to store it.
154463 pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult {
155 return self.unmanaged.getOrPutAssumeCapacity(key);
464 return self.unmanaged.getOrPutAssumeCapacityContext(key, self.ctx);
465 }
466
467 /// If there is an existing item with `key`, then the result
468 /// `Entry` pointers point to it, and found_existing is true.
469 /// Otherwise, puts a new item with undefined value, and
470 /// the `Entry` pointers point to it. Caller must then initialize
471 /// the key and value.
472 /// If a new entry needs to be stored, this function asserts there
473 /// is enough capacity to store it.
474 pub fn getOrPutAssumeCapacityAdapted(self: *Self, key: anytype, ctx: anytype) GetOrPutResult {
475 return self.unmanaged.getOrPutAssumeCapacityAdapted(self.allocator, key, ctx);
156476 }
157477
158 pub fn getOrPutValue(self: *Self, key: K, value: V) !*Entry {
159 return self.unmanaged.getOrPutValue(self.allocator, key, value);
478 pub fn getOrPutValue(self: *Self, key: K, value: V) !Entry {
479 return self.unmanaged.getOrPutValueContext(self.allocator, key, value, self.ctx);
160480 }
161481
162482 /// Increases capacity, guaranteeing that insertions up until the
163483 /// `expected_count` will not cause an allocation, and therefore cannot fail.
164484 pub fn ensureCapacity(self: *Self, expected_count: Size) !void {
165 return self.unmanaged.ensureCapacity(self.allocator, expected_count);
485 return self.unmanaged.ensureCapacityContext(self.allocator, expected_count, self.ctx);
166486 }
167487
168488 /// Returns the number of total elements which may be present before it is
......@@ -174,67 +494,114 @@ pub fn HashMap(
174494 /// Clobbers any existing data. To detect if a put would clobber
175495 /// existing data, see `getOrPut`.
176496 pub fn put(self: *Self, key: K, value: V) !void {
177 return self.unmanaged.put(self.allocator, key, value);
497 return self.unmanaged.putContext(self.allocator, key, value, self.ctx);
178498 }
179499
180500 /// Inserts a key-value pair into the hash map, asserting that no previous
181501 /// entry with the same key is already present
182502 pub fn putNoClobber(self: *Self, key: K, value: V) !void {
183 return self.unmanaged.putNoClobber(self.allocator, key, value);
503 return self.unmanaged.putNoClobberContext(self.allocator, key, value, self.ctx);
184504 }
185505
186506 /// Asserts there is enough capacity to store the new key-value pair.
187507 /// Clobbers any existing data. To detect if a put would clobber
188508 /// existing data, see `getOrPutAssumeCapacity`.
189509 pub fn putAssumeCapacity(self: *Self, key: K, value: V) void {
190 return self.unmanaged.putAssumeCapacity(key, value);
510 return self.unmanaged.putAssumeCapacityContext(key, value, self.ctx);
191511 }
192512
193513 /// Asserts there is enough capacity to store the new key-value pair.
194514 /// Asserts that it does not clobber any existing data.
195515 /// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`.
196516 pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void {
197 return self.unmanaged.putAssumeCapacityNoClobber(key, value);
517 return self.unmanaged.putAssumeCapacityNoClobberContext(key, value, self.ctx);
198518 }
199519
200520 /// Inserts a new `Entry` into the hash map, returning the previous one, if any.
201 pub fn fetchPut(self: *Self, key: K, value: V) !?Entry {
202 return self.unmanaged.fetchPut(self.allocator, key, value);
521 pub fn fetchPut(self: *Self, key: K, value: V) !?KV {
522 return self.unmanaged.fetchPutContext(self.allocator, key, value, self.ctx);
203523 }
204524
205525 /// Inserts a new `Entry` into the hash map, returning the previous one, if any.
206526 /// If insertion happuns, asserts there is enough capacity without allocating.
207 pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?Entry {
208 return self.unmanaged.fetchPutAssumeCapacity(key, value);
527 pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?KV {
528 return self.unmanaged.fetchPutAssumeCapacityContext(key, value, self.ctx);
209529 }
210530
531 /// Removes a value from the map and returns the removed kv pair.
532 pub fn fetchRemove(self: *Self, key: K) ?KV {
533 return self.unmanaged.fetchRemoveContext(key, self.ctx);
534 }
535
536 pub fn fetchRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KV {
537 return self.unmanaged.fetchRemoveAdapted(key, ctx);
538 }
539
540 /// Finds the value associated with a key in the map
211541 pub fn get(self: Self, key: K) ?V {
212 return self.unmanaged.get(key);
542 return self.unmanaged.getContext(key, self.ctx);
543 }
544 pub fn getAdapted(self: Self, key: anytype, ctx: anytype) ?V {
545 return self.unmanaged.getAdapted(key, ctx);
546 }
547
548 pub fn getPtr(self: Self, key: K) ?*V {
549 return self.unmanaged.getPtrContext(key, self.ctx);
550 }
551 pub fn getPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*V {
552 return self.unmanaged.getPtrAdapted(key, self.ctx);
553 }
554
555 /// Finds the key and value associated with a key in the map
556 pub fn getEntry(self: Self, key: K) ?Entry {
557 return self.unmanaged.getEntryContext(key, self.ctx);
213558 }
214559
215 pub fn getEntry(self: Self, key: K) ?*Entry {
216 return self.unmanaged.getEntry(key);
560 pub fn getEntryAdapted(self: Self, key: anytype, ctx: anytype) ?Entry {
561 return self.unmanaged.getEntryAdapted(key, ctx);
217562 }
218563
564 /// Check if the map contains a key
219565 pub fn contains(self: Self, key: K) bool {
220 return self.unmanaged.contains(key);
566 return self.unmanaged.containsContext(key, self.ctx);
567 }
568
569 pub fn containsAdapted(self: Self, key: anytype, ctx: anytype) bool {
570 return self.unmanaged.containsAdapted(key, ctx);
221571 }
222572
223573 /// If there is an `Entry` with a matching key, it is deleted from
224574 /// the hash map, and then returned from this function.
225 pub fn remove(self: *Self, key: K) ?Entry {
226 return self.unmanaged.remove(key);
575 pub fn remove(self: *Self, key: K) bool {
576 return self.unmanaged.removeContext(key, self.ctx);
227577 }
228578
229 /// Asserts there is an `Entry` with matching key, deletes it from the hash map,
230 /// and discards it.
231 pub fn removeAssertDiscard(self: *Self, key: K) void {
232 return self.unmanaged.removeAssertDiscard(key);
579 pub fn removeAdapted(self: *Self, key: anytype, ctx: anytype) bool {
580 return self.unmanaged.removeAdapted(key, ctx);
233581 }
234582
583 /// Creates a copy of this map, using the same allocator
235584 pub fn clone(self: Self) !Self {
236 var other = try self.unmanaged.clone(self.allocator);
237 return other.promote(self.allocator);
585 var other = try self.unmanaged.cloneContext(self.allocator, self.ctx);
586 return other.promoteContext(self.allocator, self.ctx);
587 }
588
589 /// Creates a copy of this map, using a specified allocator
590 pub fn cloneWithAllocator(self: Self, new_allocator: *Allocator) !Self {
591 var other = try self.unmanaged.cloneContext(new_allocator, self.ctx);
592 return other.promoteContext(new_allocator, self.ctx);
593 }
594
595 /// Creates a copy of this map, using a specified context
596 pub fn cloneWithContext(self: Self, new_ctx: anytype) !HashMap(K, V, @TypeOf(new_ctx), max_load_percentage) {
597 var other = try self.unmanaged.cloneContext(self.allocator, new_ctx);
598 return other.promoteContext(self.allocator, new_ctx);
599 }
600
601 /// Creates a copy of this map, using a specified allocator and context
602 pub fn cloneWithAllocatorAndContext(new_allocator: *Allocator, new_ctx: anytype) !HashMap(K, V, @TypeOf(new_ctx), max_load_percentage) {
603 var other = try self.unmanaged.cloneContext(new_allocator, new_ctx);
604 return other.promoteContext(new_allocator, new_ctx);
238605 }
239606 };
240607}
......@@ -251,11 +618,12 @@ pub fn HashMap(
251618pub fn HashMapUnmanaged(
252619 comptime K: type,
253620 comptime V: type,
254 hashFn: fn (key: K) u64,
255 eqlFn: fn (a: K, b: K) bool,
621 comptime Context: type,
256622 comptime max_load_percentage: u64,
257623) type {
258 comptime assert(max_load_percentage > 0 and max_load_percentage < 100);
624 if (max_load_percentage <= 0 or max_load_percentage >= 100)
625 @compileError("max_load_percentage must be between 0 and 100.");
626 comptime verifyContext(Context, K, K, u64);
259627
260628 return struct {
261629 const Self = @This();
......@@ -284,19 +652,25 @@ pub fn HashMapUnmanaged(
284652 const minimal_capacity = 8;
285653
286654 // This hashmap is specially designed for sizes that fit in a u32.
287 const Size = u32;
655 pub const Size = u32;
288656
289657 // u64 hashes guarantee us that the fingerprint bits will never be used
290658 // to compute the index of a slot, maximizing the use of entropy.
291 const Hash = u64;
659 pub const Hash = u64;
292660
293661 pub const Entry = struct {
662 key_ptr: *K,
663 value_ptr: *V,
664 };
665
666 pub const KV = struct {
294667 key: K,
295668 value: V,
296669 };
297670
298671 const Header = packed struct {
299 entries: [*]Entry,
672 values: [*]V,
673 keys: [*]K,
300674 capacity: Size,
301675 };
302676
......@@ -353,11 +727,11 @@ pub fn HashMapUnmanaged(
353727 assert(@alignOf(Metadata) == 1);
354728 }
355729
356 const Iterator = struct {
730 pub const Iterator = struct {
357731 hm: *const Self,
358732 index: Size = 0,
359733
360 pub fn next(it: *Iterator) ?*Entry {
734 pub fn next(it: *Iterator) ?Entry {
361735 assert(it.index <= it.hm.capacity());
362736 if (it.hm.size == 0) return null;
363737
......@@ -370,9 +744,10 @@ pub fn HashMapUnmanaged(
370744 it.index += 1;
371745 }) {
372746 if (metadata[0].isUsed()) {
373 const entry = &it.hm.entries()[it.index];
747 const key = &it.hm.keys()[it.index];
748 const value = &it.hm.values()[it.index];
374749 it.index += 1;
375 return entry;
750 return Entry{ .key_ptr = key, .value_ptr = value };
376751 }
377752 }
378753
......@@ -380,17 +755,50 @@ pub fn HashMapUnmanaged(
380755 }
381756 };
382757
758 pub const KeyIterator = FieldIterator(K);
759 pub const ValueIterator = FieldIterator(V);
760
761 fn FieldIterator(comptime T: type) type {
762 return struct {
763 len: usize,
764 metadata: [*]const Metadata,
765 items: [*]T,
766
767 pub fn next(self: *@This()) ?*T {
768 while (self.len > 0) {
769 self.len -= 1;
770 const used = self.metadata[0].isUsed();
771 const item = &self.items[0];
772 self.metadata += 1;
773 self.items += 1;
774 if (used) {
775 return item;
776 }
777 }
778 return null;
779 }
780 };
781 }
782
383783 pub const GetOrPutResult = struct {
384 entry: *Entry,
784 key_ptr: *K,
785 value_ptr: *V,
385786 found_existing: bool,
386787 };
387788
388 pub const Managed = HashMap(K, V, hashFn, eqlFn, max_load_percentage);
789 pub const Managed = HashMap(K, V, Context, max_load_percentage);
389790
390791 pub fn promote(self: Self, allocator: *Allocator) Managed {
792 if (@sizeOf(Context) != 0)
793 @compileError("Cannot infer context "++@typeName(Context)++", call promoteContext instead.");
794 return promoteContext(self, allocator, undefined);
795 }
796
797 pub fn promoteContext(self: Self, allocator: *Allocator, ctx: Context) Managed {
391798 return .{
392799 .unmanaged = self,
393800 .allocator = allocator,
801 .ctx = ctx,
394802 };
395803 }
396804
......@@ -403,26 +811,6 @@ pub fn HashMapUnmanaged(
403811 self.* = undefined;
404812 }
405813
406 fn deallocate(self: *Self, allocator: *Allocator) void {
407 if (self.metadata == null) return;
408
409 const cap = self.capacity();
410 const meta_size = @sizeOf(Header) + cap * @sizeOf(Metadata);
411
412 const alignment = @alignOf(Entry) - 1;
413 const entries_size = @as(usize, cap) * @sizeOf(Entry) + alignment;
414
415 const total_size = meta_size + entries_size;
416
417 var slice: []u8 = undefined;
418 slice.ptr = @intToPtr([*]u8, @ptrToInt(self.header()));
419 slice.len = total_size;
420 allocator.free(slice);
421
422 self.metadata = null;
423 self.available = 0;
424 }
425
426814 fn capacityForSize(size: Size) Size {
427815 var new_cap = @truncate(u32, (@as(u64, size) * 100) / max_load_percentage + 1);
428816 new_cap = math.ceilPowerOfTwo(u32, new_cap) catch unreachable;
......@@ -430,8 +818,13 @@ pub fn HashMapUnmanaged(
430818 }
431819
432820 pub fn ensureCapacity(self: *Self, allocator: *Allocator, new_size: Size) !void {
821 if (@sizeOf(Context) != 0)
822 @compileError("Cannot infer context "++@typeName(Context)++", call ensureCapacityContext instead.");
823 return ensureCapacityContext(self, allocator, new_size, undefined);
824 }
825 pub fn ensureCapacityContext(self: *Self, allocator: *Allocator, new_size: Size, ctx: Context) !void {
433826 if (new_size > self.size)
434 try self.growIfNeeded(allocator, new_size - self.size);
827 try self.growIfNeeded(allocator, new_size - self.size, ctx);
435828 }
436829
437830 pub fn clearRetainingCapacity(self: *Self) void {
......@@ -456,8 +849,12 @@ pub fn HashMapUnmanaged(
456849 return @ptrCast(*Header, @ptrCast([*]Header, self.metadata.?) - 1);
457850 }
458851
459 fn entries(self: *const Self) [*]Entry {
460 return self.header().entries;
852 fn keys(self: *const Self) [*]K {
853 return self.header().keys;
854 }
855
856 fn values(self: *const Self) [*]V {
857 return self.header().values;
461858 }
462859
463860 pub fn capacity(self: *const Self) Size {
......@@ -470,28 +867,75 @@ pub fn HashMapUnmanaged(
470867 return .{ .hm = self };
471868 }
472869
870 pub fn keyIterator(self: *const Self) KeyIterator {
871 if (self.metadata) |metadata| {
872 return .{
873 .len = self.capacity(),
874 .metadata = metadata,
875 .items = self.keys(),
876 };
877 } else {
878 return .{
879 .len = 0,
880 .metadata = undefined,
881 .items = undefined,
882 };
883 }
884 }
885
886 pub fn valueIterator(self: *const Self) ValueIterator {
887 if (self.metadata) |metadata| {
888 return .{
889 .len = self.capacity(),
890 .metadata = metadata,
891 .items = self.values(),
892 };
893 } else {
894 return .{
895 .len = 0,
896 .metadata = undefined,
897 .items = undefined,
898 };
899 }
900 }
901
473902 /// Insert an entry in the map. Assumes it is not already present.
474903 pub fn putNoClobber(self: *Self, allocator: *Allocator, key: K, value: V) !void {
475 assert(!self.contains(key));
476 try self.growIfNeeded(allocator, 1);
904 if (@sizeOf(Context) != 0)
905 @compileError("Cannot infer context "++@typeName(Context)++", call putNoClobberContext instead.");
906 return self.putNoClobberContext(allocator, key, value, undefined);
907 }
908 pub fn putNoClobberContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !void {
909 assert(!self.containsContext(key, ctx));
910 try self.growIfNeeded(allocator, 1, ctx);
477911
478 self.putAssumeCapacityNoClobber(key, value);
912 self.putAssumeCapacityNoClobberContext(key, value, ctx);
479913 }
480914
481915 /// Asserts there is enough capacity to store the new key-value pair.
482916 /// Clobbers any existing data. To detect if a put would clobber
483917 /// existing data, see `getOrPutAssumeCapacity`.
484918 pub fn putAssumeCapacity(self: *Self, key: K, value: V) void {
485 const gop = self.getOrPutAssumeCapacity(key);
486 gop.entry.value = value;
919 if (@sizeOf(Context) != 0)
920 @compileError("Cannot infer context "++@typeName(Context)++", call putAssumeCapacityContext instead.");
921 return self.putAssumeCapacityContext(key, value, undefined);
922 }
923 pub fn putAssumeCapacityContext(self: *Self, key: K, value: V, ctx: Context) void {
924 const gop = self.getOrPutAssumeCapacityContext(key, ctx);
925 gop.value_ptr.* = value;
487926 }
488927
489928 /// Insert an entry in the map. Assumes it is not already present,
490929 /// and that no allocation is needed.
491930 pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void {
492 assert(!self.contains(key));
931 if (@sizeOf(Context) != 0)
932 @compileError("Cannot infer context "++@typeName(Context)++", call putAssumeCapacityNoClobberContext instead.");
933 return self.putAssumeCapacityNoClobberContext(key, value, undefined);
934 }
935 pub fn putAssumeCapacityNoClobberContext(self: *Self, key: K, value: V, ctx: Context) void {
936 assert(!self.containsContext(key, ctx));
493937
494 const hash = hashFn(key);
938 const hash = ctx.hash(key);
495939 const mask = self.capacity() - 1;
496940 var idx = @truncate(usize, hash & mask);
497941
......@@ -508,40 +952,102 @@ pub fn HashMapUnmanaged(
508952
509953 const fingerprint = Metadata.takeFingerprint(hash);
510954 metadata[0].fill(fingerprint);
511 self.entries()[idx] = Entry{ .key = key, .value = value };
955 self.keys()[idx] = key;
956 self.values()[idx] = value;
512957
513958 self.size += 1;
514959 }
515960
516961 /// Inserts a new `Entry` into the hash map, returning the previous one, if any.
517 pub fn fetchPut(self: *Self, allocator: *Allocator, key: K, value: V) !?Entry {
518 const gop = try self.getOrPut(allocator, key);
519 var result: ?Entry = null;
962 pub fn fetchPut(self: *Self, allocator: *Allocator, key: K, value: V) !?KV {
963 if (@sizeOf(Context) != 0)
964 @compileError("Cannot infer context "++@typeName(Context)++", call fetchPutContext instead.");
965 return self.fetchPutContext(allocator, key, value, undefined);
966 }
967 pub fn fetchPutContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !?KV {
968 const gop = try self.getOrPutContext(allocator, key, ctx);
969 var result: ?KV = null;
520970 if (gop.found_existing) {
521 result = gop.entry.*;
971 result = KV{
972 .key = gop.key_ptr.*,
973 .value = gop.value_ptr.*,
974 };
522975 }
523 gop.entry.value = value;
976 gop.value_ptr.* = value;
524977 return result;
525978 }
526979
527980 /// Inserts a new `Entry` into the hash map, returning the previous one, if any.
528981 /// If insertion happens, asserts there is enough capacity without allocating.
529 pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?Entry {
530 const gop = self.getOrPutAssumeCapacity(key);
531 var result: ?Entry = null;
982 pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?KV {
983 if (@sizeOf(Context) != 0)
984 @compileError("Cannot infer context "++@typeName(Context)++", call fetchPutAssumeCapacityContext instead.");
985 return self.fetchPutAssumeCapacityContext(key, value, undefined);
986 }
987 pub fn fetchPutAssumeCapacityContext(self: *Self, key: K, value: V, ctx: Context) ?KV {
988 const gop = self.getOrPutAssumeCapacityContext(key, ctx);
989 var result: ?KV = null;
532990 if (gop.found_existing) {
533 result = gop.entry.*;
991 result = KV{
992 .key = gop.key_ptr.*,
993 .value = gop.value_ptr.*,
994 };
534995 }
535 gop.entry.value = value;
996 gop.value_ptr.* = value;
536997 return result;
537998 }
538999
539 pub fn getEntry(self: Self, key: K) ?*Entry {
1000 /// If there is an `Entry` with a matching key, it is deleted from
1001 /// the hash map, and then returned from this function.
1002 pub fn fetchRemove(self: *Self, key: K) ?KV {
1003 if (@sizeOf(Context) != 0)
1004 @compileError("Cannot infer context "++@typeName(Context)++", call fetchRemoveContext instead.");
1005 return self.fetchRemoveContext(key, undefined);
1006 }
1007 pub fn fetchRemoveContext(self: *Self, key: K, ctx: Context) ?KV {
1008 return self.fetchRemoveAdapted(key, ctx);
1009 }
1010 pub fn fetchRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KV {
1011 if (self.getIndex(key, ctx)) |idx| {
1012 const old_key = &self.keys()[idx];
1013 const old_val = &self.values()[idx];
1014 const result = KV{
1015 .key = old_key.*,
1016 .value = old_val.*,
1017 };
1018 self.metadata.?[idx].remove();
1019 old_key.* = undefined;
1020 old_val.* = undefined;
1021 self.size -= 1;
1022 return result;
1023 }
1024
1025 return null;
1026 }
1027
1028 /// Find the index containing the data for the given key.
1029 /// Whether this function returns null is almost always
1030 /// branched on after this function returns, and this function
1031 /// returns null/not null from separate code paths. We
1032 /// want the optimizer to remove that branch and instead directly
1033 /// fuse the basic blocks after the branch to the basic blocks
1034 /// from this function. To encourage that, this function is
1035 /// marked as inline.
1036 fn getIndex(self: Self, key: anytype, ctx: anytype) callconv(.Inline) ?usize {
1037 comptime verifyContext(@TypeOf(ctx), @TypeOf(key), K, Hash);
1038
5401039 if (self.size == 0) {
5411040 return null;
5421041 }
5431042
544 const hash = hashFn(key);
1043 // If you get a compile error on this line, it means that your generic hash
1044 // function is invalid for these parameters.
1045 const hash = ctx.hash(key);
1046 // verifyContext can't verify the return type of generic hash functions,
1047 // so we need to double-check it here.
1048 if (@TypeOf(hash) != Hash) {
1049 @compileError("Context "++@typeName(@TypeOf(ctx))++" has a generic hash function that returns the wrong type! "++@typeName(Hash)++" was expected, but found "++@typeName(@TypeOf(hash)));
1050 }
5451051 const mask = self.capacity() - 1;
5461052 const fingerprint = Metadata.takeFingerprint(hash);
5471053 var idx = @truncate(usize, hash & mask);
......@@ -549,11 +1055,20 @@ pub fn HashMapUnmanaged(
5491055 var metadata = self.metadata.? + idx;
5501056 while (metadata[0].isUsed() or metadata[0].isTombstone()) {
5511057 if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
552 const entry = &self.entries()[idx];
553 if (eqlFn(entry.key, key)) {
554 return entry;
1058 const test_key = &self.keys()[idx];
1059 // If you get a compile error on this line, it means that your generic eql
1060 // function is invalid for these parameters.
1061 const eql = ctx.eql(key, test_key.*);
1062 // verifyContext can't verify the return type of generic eql functions,
1063 // so we need to double-check it here.
1064 if (@TypeOf(eql) != bool) {
1065 @compileError("Context "++@typeName(@TypeOf(ctx))++" has a generic eql function that returns the wrong type! bool was expected, but found "++@typeName(@TypeOf(eql)));
1066 }
1067 if (eql) {
1068 return idx;
5551069 }
5561070 }
1071
5571072 idx = (idx + 1) & mask;
5581073 metadata = self.metadata.? + idx;
5591074 }
......@@ -561,46 +1076,122 @@ pub fn HashMapUnmanaged(
5611076 return null;
5621077 }
5631078
1079 pub fn getEntry(self: Self, key: K) ?Entry {
1080 if (@sizeOf(Context) != 0)
1081 @compileError("Cannot infer context "++@typeName(Context)++", call getEntryContext instead.");
1082 return self.getEntryContext(key, undefined);
1083 }
1084 pub fn getEntryContext(self: Self, key: K, ctx: Context) ?Entry {
1085 return self.getEntryAdapted(key, ctx);
1086 }
1087 pub fn getEntryAdapted(self: Self, key: anytype, ctx: anytype) ?Entry {
1088 if (self.getIndex(key, ctx)) |idx| {
1089 return Entry{
1090 .key_ptr = &self.keys()[idx],
1091 .value_ptr = &self.values()[idx],
1092 };
1093 }
1094 return null;
1095 }
1096
5641097 /// Insert an entry if the associated key is not already present, otherwise update preexisting value.
5651098 pub fn put(self: *Self, allocator: *Allocator, key: K, value: V) !void {
566 const result = try self.getOrPut(allocator, key);
567 result.entry.value = value;
1099 if (@sizeOf(Context) != 0)
1100 @compileError("Cannot infer context "++@typeName(Context)++", call putContext instead.");
1101 return self.putContext(allocator, key, value, undefined);
1102 }
1103 pub fn putContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !void {
1104 const result = try self.getOrPutContext(allocator, key, ctx);
1105 result.value_ptr.* = value;
5681106 }
5691107
5701108 /// Get an optional pointer to the value associated with key, if present.
571 pub fn get(self: Self, key: K) ?V {
572 if (self.size == 0) {
573 return null;
1109 pub fn getPtr(self: Self, key: K) ?*V {
1110 if (@sizeOf(Context) != 0)
1111 @compileError("Cannot infer context "++@typeName(Context)++", call getPtrContext instead.");
1112 return self.getPtrContext(key, undefined);
1113 }
1114 pub fn getPtrContext(self: Self, key: K, ctx: Context) ?*V {
1115 return self.getPtrAdapted(key, ctx);
1116 }
1117 pub fn getPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*V {
1118 if (self.getIndex(key, ctx)) |idx| {
1119 return &self.values()[idx];
5741120 }
1121 return null;
1122 }
5751123
576 const hash = hashFn(key);
577 const mask = self.capacity() - 1;
578 const fingerprint = Metadata.takeFingerprint(hash);
579 var idx = @truncate(usize, hash & mask);
580
581 var metadata = self.metadata.? + idx;
582 while (metadata[0].isUsed() or metadata[0].isTombstone()) {
583 if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
584 const entry = &self.entries()[idx];
585 if (eqlFn(entry.key, key)) {
586 return entry.value;
587 }
588 }
589 idx = (idx + 1) & mask;
590 metadata = self.metadata.? + idx;
1124 /// Get a copy of the value associated with key, if present.
1125 pub fn get(self: Self, key: K) ?V {
1126 if (@sizeOf(Context) != 0)
1127 @compileError("Cannot infer context "++@typeName(Context)++", call getContext instead.");
1128 return self.getContext(key, undefined);
1129 }
1130 pub fn getContext(self: Self, key: K, ctx: Context) ?V {
1131 return self.getAdapted(key, ctx);
1132 }
1133 pub fn getAdapted(self: Self, key: anytype, ctx: anytype) ?V {
1134 if (self.getIndex(key, ctx)) |idx| {
1135 return self.values()[idx];
5911136 }
592
5931137 return null;
5941138 }
5951139
5961140 pub fn getOrPut(self: *Self, allocator: *Allocator, key: K) !GetOrPutResult {
597 try self.growIfNeeded(allocator, 1);
598
599 return self.getOrPutAssumeCapacity(key);
1141 if (@sizeOf(Context) != 0)
1142 @compileError("Cannot infer context "++@typeName(Context)++", call getOrPutContext instead.");
1143 return self.getOrPutContext(allocator, key, undefined);
1144 }
1145 pub fn getOrPutContext(self: *Self, allocator: *Allocator, key: K, ctx: Context) !GetOrPutResult {
1146 const gop = try self.getOrPutContextAdapted(allocator, key, ctx, ctx);
1147 if (!gop.found_existing) {
1148 gop.key_ptr.* = key;
1149 }
1150 return gop;
1151 }
1152 pub fn getOrPutAdapted(self: *Self, allocator: *Allocator, key: anytype, key_ctx: anytype) !GetOrPutResult {
1153 if (@sizeOf(Context) != 0)
1154 @compileError("Cannot infer context "++@typeName(Context)++", call getOrPutContextAdapted instead.");
1155 return self.getOrPutContextAdapted(allocator, key, key_ctx, undefined);
1156 }
1157 pub fn getOrPutContextAdapted(self: *Self, allocator: *Allocator, key: anytype, key_ctx: anytype, ctx: Context) !GetOrPutResult {
1158 self.growIfNeeded(allocator, 1, ctx) catch |err| {
1159 // If allocation fails, try to do the lookup anyway.
1160 // If we find an existing item, we can return it.
1161 // Otherwise return the error, we could not add another.
1162 const index = self.getIndex(key, key_ctx) orelse return err;
1163 return GetOrPutResult{
1164 .key_ptr = &self.keys()[index],
1165 .value_ptr = &self.values()[index],
1166 .found_existing = true,
1167 };
1168 };
1169 return self.getOrPutAssumeCapacityAdapted(key, key_ctx);
6001170 }
6011171
6021172 pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult {
603 const hash = hashFn(key);
1173 if (@sizeOf(Context) != 0)
1174 @compileError("Cannot infer context "++@typeName(Context)++", call getOrPutAssumeCapacityContext instead.");
1175 return self.getOrPutAssumeCapacityContext(key, undefined);
1176 }
1177 pub fn getOrPutAssumeCapacityContext(self: *Self, key: K, ctx: Context) GetOrPutResult {
1178 const result = self.getOrPutAssumeCapacityAdapted(key, ctx);
1179 if (!result.found_existing) {
1180 result.key_ptr.* = key;
1181 }
1182 return result;
1183 }
1184 pub fn getOrPutAssumeCapacityAdapted(self: *Self, key: anytype, ctx: anytype) GetOrPutResult {
1185 comptime verifyContext(@TypeOf(ctx), @TypeOf(key), K, Hash);
1186
1187 // If you get a compile error on this line, it means that your generic hash
1188 // function is invalid for these parameters.
1189 const hash = ctx.hash(key);
1190 // verifyContext can't verify the return type of generic hash functions,
1191 // so we need to double-check it here.
1192 if (@TypeOf(hash) != Hash) {
1193 @compileError("Context "++@typeName(@TypeOf(ctx))++" has a generic hash function that returns the wrong type! "++@typeName(Hash)++" was expected, but found "++@typeName(@TypeOf(hash)));
1194 }
6041195 const mask = self.capacity() - 1;
6051196 const fingerprint = Metadata.takeFingerprint(hash);
6061197 var idx = @truncate(usize, hash & mask);
......@@ -609,9 +1200,21 @@ pub fn HashMapUnmanaged(
6091200 var metadata = self.metadata.? + idx;
6101201 while (metadata[0].isUsed() or metadata[0].isTombstone()) {
6111202 if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
612 const entry = &self.entries()[idx];
613 if (eqlFn(entry.key, key)) {
614 return GetOrPutResult{ .entry = entry, .found_existing = true };
1203 const test_key = &self.keys()[idx];
1204 // If you get a compile error on this line, it means that your generic eql
1205 // function is invalid for these parameters.
1206 const eql = ctx.eql(key, test_key.*);
1207 // verifyContext can't verify the return type of generic eql functions,
1208 // so we need to double-check it here.
1209 if (@TypeOf(eql) != bool) {
1210 @compileError("Context "++@typeName(@TypeOf(ctx))++" has a generic eql function that returns the wrong type! bool was expected, but found "++@typeName(@TypeOf(eql)));
1211 }
1212 if (eql) {
1213 return GetOrPutResult{
1214 .key_ptr = test_key,
1215 .value_ptr = &self.values()[idx],
1216 .found_existing = true,
1217 };
6151218 }
6161219 } else if (first_tombstone_idx == self.capacity() and metadata[0].isTombstone()) {
6171220 first_tombstone_idx = idx;
......@@ -631,79 +1234,67 @@ pub fn HashMapUnmanaged(
6311234 }
6321235
6331236 metadata[0].fill(fingerprint);
634 const entry = &self.entries()[idx];
635 entry.* = .{ .key = key, .value = undefined };
1237 const new_key = &self.keys()[idx];
1238 const new_value = &self.values()[idx];
1239 new_key.* = key;
1240 new_value.* = undefined;
6361241 self.size += 1;
6371242
638 return GetOrPutResult{ .entry = entry, .found_existing = false };
1243 return GetOrPutResult{
1244 .key_ptr = new_key,
1245 .value_ptr = new_value,
1246 .found_existing = false,
1247 };
6391248 }
6401249
641 pub fn getOrPutValue(self: *Self, allocator: *Allocator, key: K, value: V) !*Entry {
642 const res = try self.getOrPut(allocator, key);
643 if (!res.found_existing) res.entry.value = value;
644 return res.entry;
1250 pub fn getOrPutValue(self: *Self, allocator: *Allocator, key: K, value: V) !Entry {
1251 if (@sizeOf(Context) != 0)
1252 @compileError("Cannot infer context "++@typeName(Context)++", call getOrPutValueContext instead.");
1253 return self.getOrPutValueContext(allocator, key, value, undefined);
1254 }
1255 pub fn getOrPutValueContext(self: *Self, allocator: *Allocator, key: K, value: V, ctx: Context) !Entry {
1256 const res = try self.getOrPutAdapted(allocator, key, ctx);
1257 if (!res.found_existing) {
1258 res.key_ptr.* = key;
1259 res.value_ptr.* = value;
1260 }
1261 return Entry{ .key_ptr = res.key_ptr, .value_ptr = res.value_ptr };
6451262 }
6461263
6471264 /// Return true if there is a value associated with key in the map.
6481265 pub fn contains(self: *const Self, key: K) bool {
649 return self.get(key) != null;
1266 if (@sizeOf(Context) != 0)
1267 @compileError("Cannot infer context "++@typeName(Context)++", call containsContext instead.");
1268 return self.containsContext(key, undefined);
6501269 }
651
652 /// If there is an `Entry` with a matching key, it is deleted from
653 /// the hash map, and then returned from this function.
654 pub fn remove(self: *Self, key: K) ?Entry {
655 if (self.size == 0) return null;
656
657 const hash = hashFn(key);
658 const mask = self.capacity() - 1;
659 const fingerprint = Metadata.takeFingerprint(hash);
660 var idx = @truncate(usize, hash & mask);
661
662 var metadata = self.metadata.? + idx;
663 while (metadata[0].isUsed() or metadata[0].isTombstone()) {
664 if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
665 const entry = &self.entries()[idx];
666 if (eqlFn(entry.key, key)) {
667 const removed_entry = entry.*;
668 metadata[0].remove();
669 entry.* = undefined;
670 self.size -= 1;
671 return removed_entry;
672 }
673 }
674 idx = (idx + 1) & mask;
675 metadata = self.metadata.? + idx;
676 }
677
678 return null;
1270 pub fn containsContext(self: *const Self, key: K, ctx: Context) bool {
1271 return self.containsAdapted(key, ctx);
1272 }
1273 pub fn containsAdapted(self: *const Self, key: anytype, ctx: anytype) bool {
1274 return self.getIndex(key, ctx) != null;
6791275 }
6801276
681 /// Asserts there is an `Entry` with matching key, deletes it from the hash map,
682 /// and discards it.
683 pub fn removeAssertDiscard(self: *Self, key: K) void {
684 assert(self.contains(key));
685
686 const hash = hashFn(key);
687 const mask = self.capacity() - 1;
688 const fingerprint = Metadata.takeFingerprint(hash);
689 var idx = @truncate(usize, hash & mask);
690
691 var metadata = self.metadata.? + idx;
692 while (metadata[0].isUsed() or metadata[0].isTombstone()) {
693 if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
694 const entry = &self.entries()[idx];
695 if (eqlFn(entry.key, key)) {
696 metadata[0].remove();
697 entry.* = undefined;
698 self.size -= 1;
699 return;
700 }
701 }
702 idx = (idx + 1) & mask;
703 metadata = self.metadata.? + idx;
1277 /// If there is an `Entry` with a matching key, it is deleted from
1278 /// the hash map, and this function returns true. Otherwise this
1279 /// function returns false.
1280 pub fn remove(self: *Self, key: K) bool {
1281 if (@sizeOf(Context) != 0)
1282 @compileError("Cannot infer context "++@typeName(Context)++", call removeContext instead.");
1283 return self.removeContext(key, undefined);
1284 }
1285 pub fn removeContext(self: *Self, key: K, ctx: Context) bool {
1286 return self.removeAdapted(key, ctx);
1287 }
1288 pub fn removeAdapted(self: *Self, key: anytype, ctx: anytype) bool {
1289 if (self.getIndex(key, ctx)) |idx| {
1290 self.metadata.?[idx].remove();
1291 self.keys()[idx] = undefined;
1292 self.values()[idx] = undefined;
1293 self.size -= 1;
1294 return true;
7041295 }
7051296
706 unreachable;
1297 return false;
7071298 }
7081299
7091300 fn initMetadatas(self: *Self) void {
......@@ -718,14 +1309,19 @@ pub fn HashMapUnmanaged(
7181309 return @truncate(Size, max_load - self.available);
7191310 }
7201311
721 fn growIfNeeded(self: *Self, allocator: *Allocator, new_count: Size) !void {
1312 fn growIfNeeded(self: *Self, allocator: *Allocator, new_count: Size, ctx: Context) !void {
7221313 if (new_count > self.available) {
723 try self.grow(allocator, capacityForSize(self.load() + new_count));
1314 try self.grow(allocator, capacityForSize(self.load() + new_count), ctx);
7241315 }
7251316 }
7261317
7271318 pub fn clone(self: Self, allocator: *Allocator) !Self {
728 var other = Self{};
1319 if (@sizeOf(Context) != 0)
1320 @compileError("Cannot infer context "++@typeName(Context)++", call cloneContext instead.");
1321 return self.cloneContext(allocator, @as(Context, undefined));
1322 }
1323 pub fn cloneContext(self: Self, allocator: *Allocator, new_ctx: anytype) !HashMapUnmanaged(K, V, @TypeOf(new_ctx), max_load_percentage) {
1324 var other = HashMapUnmanaged(K, V, @TypeOf(new_ctx), max_load_percentage){};
7291325 if (self.size == 0)
7301326 return other;
7311327
......@@ -736,11 +1332,11 @@ pub fn HashMapUnmanaged(
7361332
7371333 var i: Size = 0;
7381334 var metadata = self.metadata.?;
739 var entr = self.entries();
1335 var keys_ptr = self.keys();
1336 var values_ptr = self.values();
7401337 while (i < self.capacity()) : (i += 1) {
7411338 if (metadata[i].isUsed()) {
742 const entry = &entr[i];
743 other.putAssumeCapacityNoClobber(entry.key, entry.value);
1339 other.putAssumeCapacityNoClobberContext(keys_ptr[i], values_ptr[i], new_ctx);
7441340 if (other.size == self.size)
7451341 break;
7461342 }
......@@ -749,7 +1345,8 @@ pub fn HashMapUnmanaged(
7491345 return other;
7501346 }
7511347
752 fn grow(self: *Self, allocator: *Allocator, new_capacity: Size) !void {
1348 fn grow(self: *Self, allocator: *Allocator, new_capacity: Size, ctx: Context) !void {
1349 @setCold(true);
7531350 const new_cap = std.math.max(new_capacity, minimal_capacity);
7541351 assert(new_cap > self.capacity());
7551352 assert(std.math.isPowerOfTwo(new_cap));
......@@ -764,11 +1361,11 @@ pub fn HashMapUnmanaged(
7641361 const old_capacity = self.capacity();
7651362 var i: Size = 0;
7661363 var metadata = self.metadata.?;
767 var entr = self.entries();
1364 var keys_ptr = self.keys();
1365 var values_ptr = self.values();
7681366 while (i < old_capacity) : (i += 1) {
7691367 if (metadata[i].isUsed()) {
770 const entry = &entr[i];
771 map.putAssumeCapacityNoClobber(entry.key, entry.value);
1368 map.putAssumeCapacityNoClobberContext(keys_ptr[i], values_ptr[i], ctx);
7721369 if (map.size == self.size)
7731370 break;
7741371 }
......@@ -780,26 +1377,64 @@ pub fn HashMapUnmanaged(
7801377 }
7811378
7821379 fn allocate(self: *Self, allocator: *Allocator, new_capacity: Size) !void {
1380 const header_align = @alignOf(Header);
1381 const key_align = if (@sizeOf(K) == 0) 1 else @alignOf(K);
1382 const val_align = if (@sizeOf(V) == 0) 1 else @alignOf(V);
1383 const max_align = comptime math.max3(header_align, key_align, val_align);
1384
7831385 const meta_size = @sizeOf(Header) + new_capacity * @sizeOf(Metadata);
1386 comptime assert(@alignOf(Metadata) == 1);
1387
1388 const keys_start = std.mem.alignForward(meta_size, key_align);
1389 const keys_end = keys_start + new_capacity * @sizeOf(K);
7841390
785 const alignment = @alignOf(Entry) - 1;
786 const entries_size = @as(usize, new_capacity) * @sizeOf(Entry) + alignment;
1391 const vals_start = std.mem.alignForward(keys_end, val_align);
1392 const vals_end = vals_start + new_capacity * @sizeOf(V);
7871393
788 const total_size = meta_size + entries_size;
1394 const total_size = std.mem.alignForward(vals_end, max_align);
7891395
790 const slice = try allocator.alignedAlloc(u8, @alignOf(Header), total_size);
1396 const slice = try allocator.alignedAlloc(u8, max_align, total_size);
7911397 const ptr = @ptrToInt(slice.ptr);
7921398
7931399 const metadata = ptr + @sizeOf(Header);
794 var entry_ptr = ptr + meta_size;
795 entry_ptr = (entry_ptr + alignment) & ~@as(usize, alignment);
796 assert(entry_ptr + @as(usize, new_capacity) * @sizeOf(Entry) <= ptr + total_size);
7971400
7981401 const hdr = @intToPtr(*Header, ptr);
799 hdr.entries = @intToPtr([*]Entry, entry_ptr);
1402 if (@sizeOf([*]V) != 0) {
1403 hdr.values = @intToPtr([*]V, ptr + vals_start);
1404 }
1405 if (@sizeOf([*]K) != 0) {
1406 hdr.keys = @intToPtr([*]K, ptr + keys_start);
1407 }
8001408 hdr.capacity = new_capacity;
8011409 self.metadata = @intToPtr([*]Metadata, metadata);
8021410 }
1411
1412 fn deallocate(self: *Self, allocator: *Allocator) void {
1413 if (self.metadata == null) return;
1414
1415 const header_align = @alignOf(Header);
1416 const key_align = if (@sizeOf(K) == 0) 1 else @alignOf(K);
1417 const val_align = if (@sizeOf(V) == 0) 1 else @alignOf(V);
1418 const max_align = comptime math.max3(header_align, key_align, val_align);
1419
1420 const cap = self.capacity();
1421 const meta_size = @sizeOf(Header) + cap * @sizeOf(Metadata);
1422 comptime assert(@alignOf(Metadata) == 1);
1423
1424 const keys_start = std.mem.alignForward(meta_size, key_align);
1425 const keys_end = keys_start + cap * @sizeOf(K);
1426
1427 const vals_start = std.mem.alignForward(keys_end, val_align);
1428 const vals_end = vals_start + cap * @sizeOf(V);
1429
1430 const total_size = std.mem.alignForward(vals_end, max_align);
1431
1432 const slice = @intToPtr([*]align(max_align) u8, @ptrToInt(self.header()))[0..total_size];
1433 allocator.free(slice);
1434
1435 self.metadata = null;
1436 self.available = 0;
1437 }
8031438 };
8041439}
8051440
......@@ -822,14 +1457,14 @@ test "std.hash_map basic usage" {
8221457 var sum: u32 = 0;
8231458 var it = map.iterator();
8241459 while (it.next()) |kv| {
825 sum += kv.key;
1460 sum += kv.key_ptr.*;
8261461 }
827 try expect(sum == total);
1462 try expectEqual(total, sum);
8281463
8291464 i = 0;
8301465 sum = 0;
8311466 while (i < count) : (i += 1) {
832 try expectEqual(map.get(i).?, i);
1467 try expectEqual(i, map.get(i).?);
8331468 sum += map.get(i).?;
8341469 }
8351470 try expectEqual(total, sum);
......@@ -903,7 +1538,7 @@ test "std.hash_map grow" {
9031538 i = 0;
9041539 var it = map.iterator();
9051540 while (it.next()) |kv| {
906 try expectEqual(kv.key, kv.value);
1541 try expectEqual(kv.key_ptr.*, kv.value_ptr.*);
9071542 i += 1;
9081543 }
9091544 try expectEqual(i, growTo);
......@@ -931,9 +1566,9 @@ test "std.hash_map clone" {
9311566 defer b.deinit();
9321567
9331568 try expectEqual(b.count(), 3);
934 try expectEqual(b.get(1), 1);
935 try expectEqual(b.get(2), 2);
936 try expectEqual(b.get(3), 3);
1569 try expectEqual(b.get(1).?, 1);
1570 try expectEqual(b.get(2).?, 2);
1571 try expectEqual(b.get(3).?, 3);
9371572}
9381573
9391574test "std.hash_map ensureCapacity with existing elements" {
......@@ -975,8 +1610,8 @@ test "std.hash_map remove" {
9751610 try expectEqual(map.count(), 10);
9761611 var it = map.iterator();
9771612 while (it.next()) |kv| {
978 try expectEqual(kv.key, kv.value);
979 try expect(kv.key % 3 != 0);
1613 try expectEqual(kv.key_ptr.*, kv.value_ptr.*);
1614 try expect(kv.key_ptr.* % 3 != 0);
9801615 }
9811616
9821617 i = 0;
......@@ -1146,7 +1781,7 @@ test "std.hash_map putAssumeCapacity" {
11461781 i = 0;
11471782 var sum = i;
11481783 while (i < 20) : (i += 1) {
1149 sum += map.get(i).?;
1784 sum += map.getPtr(i).?.*;
11501785 }
11511786 try expectEqual(sum, 190);
11521787
......@@ -1201,33 +1836,34 @@ test "std.hash_map basic hash map usage" {
12011836
12021837 const gop1 = try map.getOrPut(5);
12031838 try testing.expect(gop1.found_existing == true);
1204 try testing.expect(gop1.entry.value == 55);
1205 gop1.entry.value = 77;
1206 try testing.expect(map.getEntry(5).?.value == 77);
1839 try testing.expect(gop1.value_ptr.* == 55);
1840 gop1.value_ptr.* = 77;
1841 try testing.expect(map.getEntry(5).?.value_ptr.* == 77);
12071842
12081843 const gop2 = try map.getOrPut(99);
12091844 try testing.expect(gop2.found_existing == false);
1210 gop2.entry.value = 42;
1211 try testing.expect(map.getEntry(99).?.value == 42);
1845 gop2.value_ptr.* = 42;
1846 try testing.expect(map.getEntry(99).?.value_ptr.* == 42);
12121847
12131848 const gop3 = try map.getOrPutValue(5, 5);
1214 try testing.expect(gop3.value == 77);
1849 try testing.expect(gop3.value_ptr.* == 77);
12151850
12161851 const gop4 = try map.getOrPutValue(100, 41);
1217 try testing.expect(gop4.value == 41);
1852 try testing.expect(gop4.value_ptr.* == 41);
12181853
12191854 try testing.expect(map.contains(2));
1220 try testing.expect(map.getEntry(2).?.value == 22);
1855 try testing.expect(map.getEntry(2).?.value_ptr.* == 22);
12211856 try testing.expect(map.get(2).? == 22);
12221857
1223 const rmv1 = map.remove(2);
1858 const rmv1 = map.fetchRemove(2);
12241859 try testing.expect(rmv1.?.key == 2);
12251860 try testing.expect(rmv1.?.value == 22);
1226 try testing.expect(map.remove(2) == null);
1861 try testing.expect(map.fetchRemove(2) == null);
1862 try testing.expect(map.remove(2) == false);
12271863 try testing.expect(map.getEntry(2) == null);
12281864 try testing.expect(map.get(2) == null);
12291865
1230 map.removeAssertDiscard(3);
1866 try testing.expect(map.remove(3) == true);
12311867}
12321868
12331869test "std.hash_map clone" {
......@@ -1247,3 +1883,14 @@ test "std.hash_map clone" {
12471883 try testing.expect(copy.get(i).? == i * 10);
12481884 }
12491885}
1886
1887test "compile everything" {
1888 std.testing.refAllDecls(AutoHashMap(i32, i32));
1889 std.testing.refAllDecls(StringHashMap([]const u8));
1890 std.testing.refAllDecls(AutoHashMap(i32, void));
1891 std.testing.refAllDecls(StringHashMap(u0));
1892 std.testing.refAllDecls(AutoHashMapUnmanaged(i32, i32));
1893 std.testing.refAllDecls(StringHashMapUnmanaged([]const u8));
1894 std.testing.refAllDecls(AutoHashMapUnmanaged(i32, void));
1895 std.testing.refAllDecls(StringHashMapUnmanaged(u0));
1896}
lib/std/heap/general_purpose_allocator.zig+10-10
......@@ -346,10 +346,10 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
346346 break;
347347 }
348348 }
349 var it = self.large_allocations.iterator();
349 var it = self.large_allocations.valueIterator();
350350 while (it.next()) |large_alloc| {
351351 log.err("memory address 0x{x} leaked: {s}", .{
352 @ptrToInt(large_alloc.value.bytes.ptr), large_alloc.value.getStackTrace(),
352 @ptrToInt(large_alloc.bytes.ptr), large_alloc.getStackTrace(),
353353 });
354354 leaks = true;
355355 }
......@@ -444,7 +444,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
444444 }
445445 };
446446
447 if (config.safety and old_mem.len != entry.value.bytes.len) {
447 if (config.safety and old_mem.len != entry.value_ptr.bytes.len) {
448448 var addresses: [stack_n]usize = [1]usize{0} ** stack_n;
449449 var free_stack_trace = StackTrace{
450450 .instruction_addresses = &addresses,
......@@ -452,9 +452,9 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
452452 };
453453 std.debug.captureStackTrace(ret_addr, &free_stack_trace);
454454 log.err("Allocation size {d} bytes does not match free size {d}. Allocation: {s} Free: {s}", .{
455 entry.value.bytes.len,
455 entry.value_ptr.bytes.len,
456456 old_mem.len,
457 entry.value.getStackTrace(),
457 entry.value_ptr.getStackTrace(),
458458 free_stack_trace,
459459 });
460460 }
......@@ -466,7 +466,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
466466 log.info("large free {d} bytes at {*}", .{ old_mem.len, old_mem.ptr });
467467 }
468468
469 self.large_allocations.removeAssertDiscard(@ptrToInt(old_mem.ptr));
469 assert(self.large_allocations.remove(@ptrToInt(old_mem.ptr)));
470470 return 0;
471471 }
472472
......@@ -475,8 +475,8 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
475475 old_mem.len, old_mem.ptr, new_size,
476476 });
477477 }
478 entry.value.bytes = old_mem.ptr[0..result_len];
479 collectStackTrace(ret_addr, &entry.value.stack_addresses);
478 entry.value_ptr.bytes = old_mem.ptr[0..result_len];
479 collectStackTrace(ret_addr, &entry.value_ptr.stack_addresses);
480480 return result_len;
481481 }
482482
......@@ -645,8 +645,8 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
645645
646646 const gop = self.large_allocations.getOrPutAssumeCapacity(@ptrToInt(slice.ptr));
647647 assert(!gop.found_existing); // This would mean the kernel double-mapped pages.
648 gop.entry.value.bytes = slice;
649 collectStackTrace(ret_addr, &gop.entry.value.stack_addresses);
648 gop.value_ptr.bytes = slice;
649 collectStackTrace(ret_addr, &gop.value_ptr.stack_addresses);
650650
651651 if (config.verbose_log) {
652652 log.info("large alloc {d} bytes at {*}", .{ slice.len, slice.ptr });
lib/std/json.zig+2-2
......@@ -1303,14 +1303,14 @@ pub const Value = union(enum) {
13031303 try child_whitespace.outputIndent(out_stream);
13041304 }
13051305
1306 try stringify(entry.key, options, out_stream);
1306 try stringify(entry.key_ptr.*, options, out_stream);
13071307 try out_stream.writeByte(':');
13081308 if (child_options.whitespace) |child_whitespace| {
13091309 if (child_whitespace.separator) {
13101310 try out_stream.writeByte(' ');
13111311 }
13121312 }
1313 try stringify(entry.value, child_options, out_stream);
1313 try stringify(entry.value_ptr.*, child_options, out_stream);
13141314 }
13151315 if (field_output) {
13161316 if (options.whitespace) |whitespace| {
lib/std/math.zig+47-4
......@@ -380,12 +380,41 @@ test "math.min" {
380380 }
381381}
382382
383/// Finds the min of three numbers
384pub fn min3(x: anytype, y: anytype, z: anytype) @TypeOf(x, y, z) {
385 return min(x, min(y, z));
386}
387
388test "math.min3" {
389 try testing.expect(min3(@as(i32, 0), @as(i32, 1), @as(i32, 2)) == 0);
390 try testing.expect(min3(@as(i32, 0), @as(i32, 2), @as(i32, 1)) == 0);
391 try testing.expect(min3(@as(i32, 1), @as(i32, 0), @as(i32, 2)) == 0);
392 try testing.expect(min3(@as(i32, 1), @as(i32, 2), @as(i32, 0)) == 0);
393 try testing.expect(min3(@as(i32, 2), @as(i32, 0), @as(i32, 1)) == 0);
394 try testing.expect(min3(@as(i32, 2), @as(i32, 1), @as(i32, 0)) == 0);
395}
396
383397pub fn max(x: anytype, y: anytype) @TypeOf(x, y) {
384398 return if (x > y) x else y;
385399}
386400
387401test "math.max" {
388402 try testing.expect(max(@as(i32, -1), @as(i32, 2)) == 2);
403 try testing.expect(max(@as(i32, 2), @as(i32, -1)) == 2);
404}
405
406/// Finds the max of three numbers
407pub fn max3(x: anytype, y: anytype, z: anytype) @TypeOf(x, y, z) {
408 return max(x, max(y, z));
409}
410
411test "math.max3" {
412 try testing.expect(max3(@as(i32, 0), @as(i32, 1), @as(i32, 2)) == 2);
413 try testing.expect(max3(@as(i32, 0), @as(i32, 2), @as(i32, 1)) == 2);
414 try testing.expect(max3(@as(i32, 1), @as(i32, 0), @as(i32, 2)) == 2);
415 try testing.expect(max3(@as(i32, 1), @as(i32, 2), @as(i32, 0)) == 2);
416 try testing.expect(max3(@as(i32, 2), @as(i32, 0), @as(i32, 1)) == 2);
417 try testing.expect(max3(@as(i32, 2), @as(i32, 1), @as(i32, 0)) == 2);
389418}
390419
391420pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper) {
......@@ -581,6 +610,17 @@ pub fn Log2Int(comptime T: type) type {
581610 return std.meta.Int(.unsigned, count);
582611}
583612
613pub fn Log2IntCeil(comptime T: type) type {
614 // comptime ceil log2
615 comptime var count = 0;
616 comptime var s = @typeInfo(T).Int.bits;
617 inline while (s != 0) : (s >>= 1) {
618 count += 1;
619 }
620
621 return std.meta.Int(.unsigned, count);
622}
623
584624pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) type {
585625 assert(from <= to);
586626 if (from == 0 and to == 0) {
......@@ -1046,15 +1086,18 @@ fn testCeilPowerOfTwo() !void {
10461086}
10471087
10481088pub fn log2_int(comptime T: type, x: T) Log2Int(T) {
1089 if (@typeInfo(T) != .Int or @typeInfo(T).Int.signedness != .unsigned)
1090 @compileError("log2_int requires an unsigned integer, found "++@typeName(T));
10491091 assert(x != 0);
10501092 return @intCast(Log2Int(T), @typeInfo(T).Int.bits - 1 - @clz(T, x));
10511093}
10521094
1053pub fn log2_int_ceil(comptime T: type, x: T) Log2Int(T) {
1095pub fn log2_int_ceil(comptime T: type, x: T) Log2IntCeil(T) {
1096 if (@typeInfo(T) != .Int or @typeInfo(T).Int.signedness != .unsigned)
1097 @compileError("log2_int_ceil requires an unsigned integer, found "++@typeName(T));
10541098 assert(x != 0);
1055 const log2_val = log2_int(T, x);
1056 if (@as(T, 1) << log2_val == x)
1057 return log2_val;
1099 if (x == 1) return 0;
1100 const log2_val: Log2IntCeil(T) = log2_int(T, x - 1);
10581101 return log2_val + 1;
10591102}
10601103
lib/std/multi_array_list.zig+137-23
......@@ -10,6 +10,15 @@ const mem = std.mem;
1010const Allocator = mem.Allocator;
1111const testing = std.testing;
1212
13/// A MultiArrayList stores a list of a struct type.
14/// Instead of storing a single list of items, MultiArrayList
15/// stores separate lists for each field of the struct.
16/// This allows for memory savings if the struct has padding,
17/// and also improves cache usage if only some fields are needed
18/// for a computation. The primary API for accessing fields is
19/// the `slice()` function, which computes the start pointers
20/// for the array of each field. From the slice you can call
21/// `.items(.<field_name>)` to obtain a slice of field values.
1322pub fn MultiArrayList(comptime S: type) type {
1423 return struct {
1524 bytes: [*]align(@alignOf(S)) u8 = undefined,
......@@ -20,6 +29,10 @@ pub fn MultiArrayList(comptime S: type) type {
2029
2130 pub const Field = meta.FieldEnum(S);
2231
32 /// A MultiArrayList.Slice contains cached start pointers for each field in the list.
33 /// These pointers are not normally stored to reduce the size of the list in memory.
34 /// If you are accessing multiple fields, call slice() first to compute the pointers,
35 /// and then get the field arrays from the slice.
2336 pub const Slice = struct {
2437 /// This array is indexed by the field index which can be obtained
2538 /// by using @enumToInt() on the Field enum
......@@ -29,11 +42,12 @@ pub fn MultiArrayList(comptime S: type) type {
2942
3043 pub fn items(self: Slice, comptime field: Field) []FieldType(field) {
3144 const F = FieldType(field);
32 if (self.len == 0) {
45 if (self.capacity == 0) {
3346 return &[_]F{};
3447 }
3548 const byte_ptr = self.ptrs[@enumToInt(field)];
36 const casted_ptr = @ptrCast([*]F, @alignCast(@alignOf(F), byte_ptr));
49 const casted_ptr: [*]F = if (@sizeOf([*]F) == 0) undefined
50 else @ptrCast([*]F, @alignCast(@alignOf(F), byte_ptr));
3751 return casted_ptr[0..self.len];
3852 }
3953
......@@ -74,12 +88,12 @@ pub fn MultiArrayList(comptime S: type) type {
7488 data[i] = .{
7589 .size = @sizeOf(field_info.field_type),
7690 .size_index = i,
77 .alignment = field_info.alignment,
91 .alignment = if (@sizeOf(field_info.field_type) == 0) 1 else field_info.alignment,
7892 };
7993 }
8094 const Sort = struct {
8195 fn lessThan(trash: *i32, lhs: Data, rhs: Data) bool {
82 return lhs.alignment >= rhs.alignment;
96 return lhs.alignment > rhs.alignment;
8397 }
8498 };
8599 var trash: i32 = undefined; // workaround for stage1 compiler bug
......@@ -109,6 +123,9 @@ pub fn MultiArrayList(comptime S: type) type {
109123 return result;
110124 }
111125
126 /// Compute pointers to the start of each field of the array.
127 /// If you need to access multiple fields, calling this may
128 /// be more efficient than calling `items()` multiple times.
112129 pub fn slice(self: Self) Slice {
113130 var result: Slice = .{
114131 .ptrs = undefined,
......@@ -123,6 +140,9 @@ pub fn MultiArrayList(comptime S: type) type {
123140 return result;
124141 }
125142
143 /// Get the slice of values for a specified field.
144 /// If you need multiple fields, consider calling slice()
145 /// instead.
126146 pub fn items(self: Self, comptime field: Field) []FieldType(field) {
127147 return self.slice().items(field);
128148 }
......@@ -159,6 +179,72 @@ pub fn MultiArrayList(comptime S: type) type {
159179 self.set(self.len - 1, elem);
160180 }
161181
182 /// Extend the list by 1 element, asserting `self.capacity`
183 /// is sufficient to hold an additional item. Returns the
184 /// newly reserved index with uninitialized data.
185 pub fn addOneAssumeCapacity(self: *Self) usize {
186 assert(self.len < self.capacity);
187 const index = self.len;
188 self.len += 1;
189 return index;
190 }
191
192 /// Inserts an item into an ordered list. Shifts all elements
193 /// after and including the specified index back by one and
194 /// sets the given index to the specified element. May reallocate
195 /// and invalidate iterators.
196 pub fn insert(self: *Self, gpa: *Allocator, index: usize, elem: S) void {
197 try self.ensureCapacity(gpa, self.len + 1);
198 self.insertAssumeCapacity(index, elem);
199 }
200
201 /// Inserts an item into an ordered list which has room for it.
202 /// Shifts all elements after and including the specified index
203 /// back by one and sets the given index to the specified element.
204 /// Will not reallocate the array, does not invalidate iterators.
205 pub fn insertAssumeCapacity(self: *Self, index: usize, elem: S) void {
206 assert(self.len < self.capacity);
207 assert(index <= self.len);
208 self.len += 1;
209 const slices = self.slice();
210 inline for (fields) |field_info, field_index| {
211 const field_slice = slices.items(@intToEnum(Field, field_index));
212 var i: usize = self.len-1;
213 while (i > index) : (i -= 1) {
214 field_slice[i] = field_slice[i-1];
215 }
216 field_slice[index] = @field(elem, field_info.name);
217 }
218 }
219
220 /// Remove the specified item from the list, swapping the last
221 /// item in the list into its position. Fast, but does not
222 /// retain list ordering.
223 pub fn swapRemove(self: *Self, index: usize) void {
224 const slices = self.slice();
225 inline for (fields) |field_info, i| {
226 const field_slice = slices.items(@intToEnum(Field, i));
227 field_slice[index] = field_slice[self.len-1];
228 field_slice[self.len-1] = undefined;
229 }
230 self.len -= 1;
231 }
232
233 /// Remove the specified item from the list, shifting items
234 /// after it to preserve order.
235 pub fn orderedRemove(self: *Self, index: usize) void {
236 const slices = self.slice();
237 inline for (fields) |field_info, field_index| {
238 const field_slice = slices.items(@intToEnum(Field, field_index));
239 var i = index;
240 while (i < self.len-1) : (i += 1) {
241 field_slice[i] = field_slice[i+1];
242 }
243 field_slice[i] = undefined;
244 }
245 self.len -= 1;
246 }
247
162248 /// Adjust the list's length to `new_len`.
163249 /// Does not initialize added items, if any.
164250 pub fn resize(self: *Self, gpa: *Allocator, new_len: usize) !void {
......@@ -186,13 +272,15 @@ pub fn MultiArrayList(comptime S: type) type {
186272 ) catch {
187273 const self_slice = self.slice();
188274 inline for (fields) |field_info, i| {
189 const field = @intToEnum(Field, i);
190 const dest_slice = self_slice.items(field)[new_len..];
191 const byte_count = dest_slice.len * @sizeOf(field_info.field_type);
192 // We use memset here for more efficient codegen in safety-checked,
193 // valgrind-enabled builds. Otherwise the valgrind client request
194 // will be repeated for every element.
195 @memset(@ptrCast([*]u8, dest_slice.ptr), undefined, byte_count);
275 if (@sizeOf(field_info.field_type) != 0) {
276 const field = @intToEnum(Field, i);
277 const dest_slice = self_slice.items(field)[new_len..];
278 const byte_count = dest_slice.len * @sizeOf(field_info.field_type);
279 // We use memset here for more efficient codegen in safety-checked,
280 // valgrind-enabled builds. Otherwise the valgrind client request
281 // will be repeated for every element.
282 @memset(@ptrCast([*]u8, dest_slice.ptr), undefined, byte_count);
283 }
196284 }
197285 self.len = new_len;
198286 return;
......@@ -206,12 +294,14 @@ pub fn MultiArrayList(comptime S: type) type {
206294 const self_slice = self.slice();
207295 const other_slice = other.slice();
208296 inline for (fields) |field_info, i| {
209 const field = @intToEnum(Field, i);
210 // TODO we should be able to use std.mem.copy here but it causes a
211 // test failure on aarch64 with -OReleaseFast
212 const src_slice = mem.sliceAsBytes(self_slice.items(field));
213 const dst_slice = mem.sliceAsBytes(other_slice.items(field));
214 @memcpy(dst_slice.ptr, src_slice.ptr, src_slice.len);
297 if (@sizeOf(field_info.field_type) != 0) {
298 const field = @intToEnum(Field, i);
299 // TODO we should be able to use std.mem.copy here but it causes a
300 // test failure on aarch64 with -OReleaseFast
301 const src_slice = mem.sliceAsBytes(self_slice.items(field));
302 const dst_slice = mem.sliceAsBytes(other_slice.items(field));
303 @memcpy(dst_slice.ptr, src_slice.ptr, src_slice.len);
304 }
215305 }
216306 gpa.free(self.allocatedBytes());
217307 self.* = other;
......@@ -273,17 +363,41 @@ pub fn MultiArrayList(comptime S: type) type {
273363 const self_slice = self.slice();
274364 const other_slice = other.slice();
275365 inline for (fields) |field_info, i| {
276 const field = @intToEnum(Field, i);
277 // TODO we should be able to use std.mem.copy here but it causes a
278 // test failure on aarch64 with -OReleaseFast
279 const src_slice = mem.sliceAsBytes(self_slice.items(field));
280 const dst_slice = mem.sliceAsBytes(other_slice.items(field));
281 @memcpy(dst_slice.ptr, src_slice.ptr, src_slice.len);
366 if (@sizeOf(field_info.field_type) != 0) {
367 const field = @intToEnum(Field, i);
368 // TODO we should be able to use std.mem.copy here but it causes a
369 // test failure on aarch64 with -OReleaseFast
370 const src_slice = mem.sliceAsBytes(self_slice.items(field));
371 const dst_slice = mem.sliceAsBytes(other_slice.items(field));
372 @memcpy(dst_slice.ptr, src_slice.ptr, src_slice.len);
373 }
282374 }
283375 gpa.free(self.allocatedBytes());
284376 self.* = other;
285377 }
286378
379 /// Create a copy of this list with a new backing store,
380 /// using the specified allocator.
381 pub fn clone(self: Self, gpa: *Allocator) !Self {
382 var result = Self{};
383 errdefer result.deinit(gpa);
384 try result.ensureCapacity(gpa, self.len);
385 result.len = self.len;
386 const self_slice = self.slice();
387 const result_slice = result.slice();
388 inline for (fields) |field_info, i| {
389 if (@sizeOf(field_info.field_type) != 0) {
390 const field = @intToEnum(Field, i);
391 // TODO we should be able to use std.mem.copy here but it causes a
392 // test failure on aarch64 with -OReleaseFast
393 const src_slice = mem.sliceAsBytes(self_slice.items(field));
394 const dst_slice = mem.sliceAsBytes(result_slice.items(field));
395 @memcpy(dst_slice.ptr, src_slice.ptr, src_slice.len);
396 }
397 }
398 return result;
399 }
400
287401 fn capacityInBytes(capacity: usize) usize {
288402 const sizes_vector: std.meta.Vector(sizes.bytes.len, usize) = sizes.bytes;
289403 const capacity_vector = @splat(sizes.bytes.len, capacity);
lib/std/process.zig+4-4
......@@ -85,7 +85,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {
8585
8686 i += 1; // skip over null byte
8787
88 try result.setMove(key, value);
88 try result.putMove(key, value);
8989 }
9090 return result;
9191 } else if (builtin.os.tag == .wasi) {
......@@ -112,7 +112,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {
112112 var parts = mem.split(pair, "=");
113113 const key = parts.next().?;
114114 const value = parts.next().?;
115 try result.set(key, value);
115 try result.put(key, value);
116116 }
117117 return result;
118118 } else if (builtin.link_libc) {
......@@ -126,7 +126,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {
126126 while (line[end_i] != 0) : (end_i += 1) {}
127127 const value = line[line_i + 1 .. end_i];
128128
129 try result.set(key, value);
129 try result.put(key, value);
130130 }
131131 return result;
132132 } else {
......@@ -139,7 +139,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {
139139 while (line[end_i] != 0) : (end_i += 1) {}
140140 const value = line[line_i + 1 .. end_i];
141141
142 try result.set(key, value);
142 try result.put(key, value);
143143 }
144144 return result;
145145 }
src/AstGen.zig+9-11
......@@ -144,9 +144,7 @@ pub fn generate(gpa: *Allocator, tree: ast.Tree) InnerError!Zir {
144144 astgen.extra.items[imports_index] = astgen.addExtraAssumeCapacity(Zir.Inst.Imports{
145145 .imports_len = @intCast(u32, astgen.imports.count()),
146146 });
147 for (astgen.imports.items()) |entry| {
148 astgen.extra.appendAssumeCapacity(entry.key);
149 }
147 astgen.extra.appendSliceAssumeCapacity(astgen.imports.keys());
150148 }
151149
152150 return Zir{
......@@ -7932,13 +7930,13 @@ fn identAsString(astgen: *AstGen, ident_token: ast.TokenIndex) !u32 {
79327930 const gop = try astgen.string_table.getOrPut(gpa, key);
79337931 if (gop.found_existing) {
79347932 string_bytes.shrinkRetainingCapacity(str_index);
7935 return gop.entry.value;
7933 return gop.value_ptr.*;
79367934 } else {
79377935 // We have to dupe the key into the arena, otherwise the memory
79387936 // becomes invalidated when string_bytes gets data appended.
79397937 // TODO https://github.com/ziglang/zig/issues/8528
7940 gop.entry.key = try astgen.arena.dupe(u8, key);
7941 gop.entry.value = str_index;
7938 gop.key_ptr.* = try astgen.arena.dupe(u8, key);
7939 gop.value_ptr.* = str_index;
79427940 try string_bytes.append(gpa, 0);
79437941 return str_index;
79447942 }
......@@ -7957,15 +7955,15 @@ fn strLitAsString(astgen: *AstGen, str_lit_token: ast.TokenIndex) !IndexSlice {
79577955 if (gop.found_existing) {
79587956 string_bytes.shrinkRetainingCapacity(str_index);
79597957 return IndexSlice{
7960 .index = gop.entry.value,
7958 .index = gop.value_ptr.*,
79617959 .len = @intCast(u32, key.len),
79627960 };
79637961 } else {
79647962 // We have to dupe the key into the arena, otherwise the memory
79657963 // becomes invalidated when string_bytes gets data appended.
79667964 // TODO https://github.com/ziglang/zig/issues/8528
7967 gop.entry.key = try astgen.arena.dupe(u8, key);
7968 gop.entry.value = str_index;
7965 gop.key_ptr.* = try astgen.arena.dupe(u8, key);
7966 gop.value_ptr.* = str_index;
79697967 // Still need a null byte because we are using the same table
79707968 // to lookup null terminated strings, so if we get a match, it has to
79717969 // be null terminated for that to work.
......@@ -9122,10 +9120,10 @@ fn declareNewName(
91229120 return astgen.failNodeNotes(node, "redeclaration of '{s}'", .{
91239121 name,
91249122 }, &[_]u32{
9125 try astgen.errNoteNode(gop.entry.value, "other declaration here", .{}),
9123 try astgen.errNoteNode(gop.value_ptr.*, "other declaration here", .{}),
91269124 });
91279125 }
9128 gop.entry.value = node;
9126 gop.value_ptr.* = node;
91299127 break;
91309128 },
91319129 .top => break,
src/Cache.zig+4-4
......@@ -90,10 +90,10 @@ pub const HashHelper = struct {
9090 }
9191
9292 pub fn addStringSet(hh: *HashHelper, hm: std.StringArrayHashMapUnmanaged(void)) void {
93 const entries = hm.items();
94 hh.add(entries.len);
95 for (entries) |entry| {
96 hh.addBytes(entry.key);
93 const keys = hm.keys();
94 hh.add(keys.len);
95 for (keys) |key| {
96 hh.addBytes(key);
9797 }
9898 }
9999
src/Compilation.zig+107-89
......@@ -729,18 +729,21 @@ fn addPackageTableToCacheHash(
729729) (error{OutOfMemory} || std.os.GetCwdError)!void {
730730 const allocator = &arena.allocator;
731731
732 const packages = try allocator.alloc(Package.Table.Entry, pkg_table.count());
732 const packages = try allocator.alloc(Package.Table.KV, pkg_table.count());
733733 {
734734 // Copy over the hashmap entries to our slice
735735 var table_it = pkg_table.iterator();
736736 var idx: usize = 0;
737737 while (table_it.next()) |entry| : (idx += 1) {
738 packages[idx] = entry.*;
738 packages[idx] = .{
739 .key = entry.key_ptr.*,
740 .value = entry.value_ptr.*,
741 };
739742 }
740743 }
741744 // Sort the slice by package name
742 std.sort.sort(Package.Table.Entry, packages, {}, struct {
743 fn lessThan(_: void, lhs: Package.Table.Entry, rhs: Package.Table.Entry) bool {
745 std.sort.sort(Package.Table.KV, packages, {}, struct {
746 fn lessThan(_: void, lhs: Package.Table.KV, rhs: Package.Table.KV) bool {
744747 return std.mem.lessThan(u8, lhs.key, rhs.key);
745748 }
746749 }.lessThan);
......@@ -1525,8 +1528,8 @@ pub fn destroy(self: *Compilation) void {
15251528 {
15261529 var it = self.crt_files.iterator();
15271530 while (it.next()) |entry| {
1528 gpa.free(entry.key);
1529 entry.value.deinit(gpa);
1531 gpa.free(entry.key_ptr.*);
1532 entry.value_ptr.deinit(gpa);
15301533 }
15311534 self.crt_files.deinit(gpa);
15321535 }
......@@ -1554,14 +1557,14 @@ pub fn destroy(self: *Compilation) void {
15541557 glibc_file.deinit(gpa);
15551558 }
15561559
1557 for (self.c_object_table.items()) |entry| {
1558 entry.key.destroy(gpa);
1560 for (self.c_object_table.keys()) |key| {
1561 key.destroy(gpa);
15591562 }
15601563 self.c_object_table.deinit(gpa);
15611564 self.c_object_cache_digest_set.deinit(gpa);
15621565
1563 for (self.failed_c_objects.items()) |entry| {
1564 entry.value.destroy(gpa);
1566 for (self.failed_c_objects.values()) |value| {
1567 value.destroy(gpa);
15651568 }
15661569 self.failed_c_objects.deinit(gpa);
15671570
......@@ -1578,8 +1581,8 @@ pub fn destroy(self: *Compilation) void {
15781581}
15791582
15801583pub fn clearMiscFailures(comp: *Compilation) void {
1581 for (comp.misc_failures.items()) |*entry| {
1582 entry.value.deinit(comp.gpa);
1584 for (comp.misc_failures.values()) |*value| {
1585 value.deinit(comp.gpa);
15831586 }
15841587 comp.misc_failures.deinit(comp.gpa);
15851588 comp.misc_failures = .{};
......@@ -1599,9 +1602,10 @@ pub fn update(self: *Compilation) !void {
15991602
16001603 // For compiling C objects, we rely on the cache hash system to avoid duplicating work.
16011604 // Add a Job for each C object.
1602 try self.c_object_work_queue.ensureUnusedCapacity(self.c_object_table.items().len);
1603 for (self.c_object_table.items()) |entry| {
1604 self.c_object_work_queue.writeItemAssumeCapacity(entry.key);
1605 try self.c_object_work_queue.ensureUnusedCapacity(self.c_object_table.count());
1606 for (self.c_object_table.keys()) |key| {
1607 assert(@ptrToInt(key) != 0xaaaa_aaaa_aaaa_aaaa);
1608 self.c_object_work_queue.writeItemAssumeCapacity(key);
16051609 }
16061610
16071611 const use_stage1 = build_options.omit_stage2 or
......@@ -1620,8 +1624,8 @@ pub fn update(self: *Compilation) !void {
16201624 // it changed, and, if so, re-compute ZIR and then queue the job
16211625 // to update it.
16221626 try self.astgen_work_queue.ensureUnusedCapacity(module.import_table.count());
1623 for (module.import_table.items()) |entry| {
1624 self.astgen_work_queue.writeItemAssumeCapacity(entry.value);
1627 for (module.import_table.values()) |value| {
1628 self.astgen_work_queue.writeItemAssumeCapacity(value);
16251629 }
16261630
16271631 try self.work_queue.writeItem(.{ .analyze_pkg = std_pkg });
......@@ -1635,12 +1639,12 @@ pub fn update(self: *Compilation) !void {
16351639 // Process the deletion set. We use a while loop here because the
16361640 // deletion set may grow as we call `clearDecl` within this loop,
16371641 // and more unreferenced Decls are revealed.
1638 while (module.deletion_set.entries.items.len != 0) {
1639 const decl = module.deletion_set.entries.items[0].key;
1642 while (module.deletion_set.count() != 0) {
1643 const decl = module.deletion_set.keys()[0];
16401644 assert(decl.deletion_flag);
16411645 assert(decl.dependants.count() == 0);
16421646 const is_anon = if (decl.zir_decl_index == 0) blk: {
1643 break :blk decl.namespace.anon_decls.swapRemove(decl) != null;
1647 break :blk decl.namespace.anon_decls.swapRemove(decl);
16441648 } else false;
16451649
16461650 try module.clearDecl(decl, null);
......@@ -1677,8 +1681,7 @@ pub fn update(self: *Compilation) !void {
16771681 // to reference the ZIR.
16781682 if (self.totalErrorCount() == 0 and !self.keep_source_files_loaded) {
16791683 if (self.bin_file.options.module) |module| {
1680 for (module.import_table.items()) |entry| {
1681 const file = entry.value;
1684 for (module.import_table.values()) |file| {
16821685 file.unloadTree(self.gpa);
16831686 file.unloadSource(self.gpa);
16841687 }
......@@ -1702,18 +1705,21 @@ pub fn totalErrorCount(self: *Compilation) usize {
17021705 var total: usize = self.failed_c_objects.count() + self.misc_failures.count();
17031706
17041707 if (self.bin_file.options.module) |module| {
1705 total += module.failed_exports.items().len;
1708 total += module.failed_exports.count();
17061709
1707 for (module.failed_files.items()) |entry| {
1708 if (entry.value) |_| {
1709 total += 1;
1710 } else {
1711 const file = entry.key;
1712 assert(file.zir_loaded);
1713 const payload_index = file.zir.extra[@enumToInt(Zir.ExtraIndex.compile_errors)];
1714 assert(payload_index != 0);
1715 const header = file.zir.extraData(Zir.Inst.CompileErrors, payload_index);
1716 total += header.data.items_len;
1710 {
1711 var it = module.failed_files.iterator();
1712 while (it.next()) |entry| {
1713 if (entry.value_ptr.*) |_| {
1714 total += 1;
1715 } else {
1716 const file = entry.key_ptr.*;
1717 assert(file.zir_loaded);
1718 const payload_index = file.zir.extra[@enumToInt(Zir.ExtraIndex.compile_errors)];
1719 assert(payload_index != 0);
1720 const header = file.zir.extraData(Zir.Inst.CompileErrors, payload_index);
1721 total += header.data.items_len;
1722 }
17171723 }
17181724 }
17191725
......@@ -1721,14 +1727,14 @@ pub fn totalErrorCount(self: *Compilation) usize {
17211727 // When a parse error is introduced, we keep all the semantic analysis for
17221728 // the previous parse success, including compile errors, but we cannot
17231729 // emit them until the file succeeds parsing.
1724 for (module.failed_decls.items()) |entry| {
1725 if (entry.key.namespace.file_scope.okToReportErrors()) {
1730 for (module.failed_decls.keys()) |key| {
1731 if (key.namespace.file_scope.okToReportErrors()) {
17261732 total += 1;
17271733 }
17281734 }
17291735 if (module.emit_h) |emit_h| {
1730 for (emit_h.failed_decls.items()) |entry| {
1731 if (entry.key.namespace.file_scope.okToReportErrors()) {
1736 for (emit_h.failed_decls.keys()) |key| {
1737 if (key.namespace.file_scope.okToReportErrors()) {
17321738 total += 1;
17331739 }
17341740 }
......@@ -1743,7 +1749,7 @@ pub fn totalErrorCount(self: *Compilation) usize {
17431749 // Compile log errors only count if there are no other errors.
17441750 if (total == 0) {
17451751 if (self.bin_file.options.module) |module| {
1746 total += @boolToInt(module.compile_log_decls.items().len != 0);
1752 total += @boolToInt(module.compile_log_decls.count() != 0);
17471753 }
17481754 }
17491755
......@@ -1757,57 +1763,67 @@ pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors {
17571763 var errors = std.ArrayList(AllErrors.Message).init(self.gpa);
17581764 defer errors.deinit();
17591765
1760 for (self.failed_c_objects.items()) |entry| {
1761 const c_object = entry.key;
1762 const err_msg = entry.value;
1763 // TODO these fields will need to be adjusted when we have proper
1764 // C error reporting bubbling up.
1765 try errors.append(.{
1766 .src = .{
1767 .src_path = try arena.allocator.dupe(u8, c_object.src.src_path),
1768 .msg = try std.fmt.allocPrint(&arena.allocator, "unable to build C object: {s}", .{
1769 err_msg.msg,
1770 }),
1771 .byte_offset = 0,
1772 .line = err_msg.line,
1773 .column = err_msg.column,
1774 .source_line = null, // TODO
1775 },
1776 });
1766 {
1767 var it = self.failed_c_objects.iterator();
1768 while (it.next()) |entry| {
1769 const c_object = entry.key_ptr.*;
1770 const err_msg = entry.value_ptr.*;
1771 // TODO these fields will need to be adjusted when we have proper
1772 // C error reporting bubbling up.
1773 try errors.append(.{
1774 .src = .{
1775 .src_path = try arena.allocator.dupe(u8, c_object.src.src_path),
1776 .msg = try std.fmt.allocPrint(&arena.allocator, "unable to build C object: {s}", .{
1777 err_msg.msg,
1778 }),
1779 .byte_offset = 0,
1780 .line = err_msg.line,
1781 .column = err_msg.column,
1782 .source_line = null, // TODO
1783 },
1784 });
1785 }
17771786 }
1778 for (self.misc_failures.items()) |entry| {
1779 try AllErrors.addPlainWithChildren(&arena, &errors, entry.value.msg, entry.value.children);
1787 for (self.misc_failures.values()) |*value| {
1788 try AllErrors.addPlainWithChildren(&arena, &errors, value.msg, value.children);
17801789 }
17811790 if (self.bin_file.options.module) |module| {
1782 for (module.failed_files.items()) |entry| {
1783 if (entry.value) |msg| {
1784 try AllErrors.add(module, &arena, &errors, msg.*);
1785 } else {
1786 // Must be ZIR errors. In order for ZIR errors to exist, the parsing
1787 // must have completed successfully.
1788 const tree = try entry.key.getTree(module.gpa);
1789 assert(tree.errors.len == 0);
1790 try AllErrors.addZir(&arena.allocator, &errors, entry.key);
1791 {
1792 var it = module.failed_files.iterator();
1793 while (it.next()) |entry| {
1794 if (entry.value_ptr.*) |msg| {
1795 try AllErrors.add(module, &arena, &errors, msg.*);
1796 } else {
1797 // Must be ZIR errors. In order for ZIR errors to exist, the parsing
1798 // must have completed successfully.
1799 const tree = try entry.key_ptr.*.getTree(module.gpa);
1800 assert(tree.errors.len == 0);
1801 try AllErrors.addZir(&arena.allocator, &errors, entry.key_ptr.*);
1802 }
17911803 }
17921804 }
1793 for (module.failed_decls.items()) |entry| {
1794 // Skip errors for Decls within files that had a parse failure.
1795 // We'll try again once parsing succeeds.
1796 if (entry.key.namespace.file_scope.okToReportErrors()) {
1797 try AllErrors.add(module, &arena, &errors, entry.value.*);
1805 {
1806 var it = module.failed_decls.iterator();
1807 while (it.next()) |entry| {
1808 // Skip errors for Decls within files that had a parse failure.
1809 // We'll try again once parsing succeeds.
1810 if (entry.key_ptr.*.namespace.file_scope.okToReportErrors()) {
1811 try AllErrors.add(module, &arena, &errors, entry.value_ptr.*.*);
1812 }
17981813 }
17991814 }
18001815 if (module.emit_h) |emit_h| {
1801 for (emit_h.failed_decls.items()) |entry| {
1816 var it = emit_h.failed_decls.iterator();
1817 while (it.next()) |entry| {
18021818 // Skip errors for Decls within files that had a parse failure.
18031819 // We'll try again once parsing succeeds.
1804 if (entry.key.namespace.file_scope.okToReportErrors()) {
1805 try AllErrors.add(module, &arena, &errors, entry.value.*);
1820 if (entry.key_ptr.*.namespace.file_scope.okToReportErrors()) {
1821 try AllErrors.add(module, &arena, &errors, entry.value_ptr.*.*);
18061822 }
18071823 }
18081824 }
1809 for (module.failed_exports.items()) |entry| {
1810 try AllErrors.add(module, &arena, &errors, entry.value.*);
1825 for (module.failed_exports.values()) |value| {
1826 try AllErrors.add(module, &arena, &errors, value.*);
18111827 }
18121828 }
18131829
......@@ -1820,20 +1836,21 @@ pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors {
18201836 }
18211837
18221838 if (self.bin_file.options.module) |module| {
1823 const compile_log_items = module.compile_log_decls.items();
1824 if (errors.items.len == 0 and compile_log_items.len != 0) {
1839 if (errors.items.len == 0 and module.compile_log_decls.count() != 0) {
1840 const keys = module.compile_log_decls.keys();
1841 const values = module.compile_log_decls.values();
18251842 // First one will be the error; subsequent ones will be notes.
1826 const src_loc = compile_log_items[0].key.nodeOffsetSrcLoc(compile_log_items[0].value);
1843 const src_loc = keys[0].nodeOffsetSrcLoc(values[0]);
18271844 const err_msg = Module.ErrorMsg{
18281845 .src_loc = src_loc,
18291846 .msg = "found compile log statement",
1830 .notes = try self.gpa.alloc(Module.ErrorMsg, compile_log_items.len - 1),
1847 .notes = try self.gpa.alloc(Module.ErrorMsg, module.compile_log_decls.count() - 1),
18311848 };
18321849 defer self.gpa.free(err_msg.notes);
18331850
1834 for (compile_log_items[1..]) |entry, i| {
1851 for (keys[1..]) |key, i| {
18351852 err_msg.notes[i] = .{
1836 .src_loc = entry.key.nodeOffsetSrcLoc(entry.value),
1853 .src_loc = key.nodeOffsetSrcLoc(values[i+1]),
18371854 .msg = "also here",
18381855 };
18391856 }
......@@ -1898,6 +1915,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor
18981915 }
18991916
19001917 while (self.c_object_work_queue.readItem()) |c_object| {
1918 assert(@ptrToInt(c_object) != 0xaaaa_aaaa_aaaa_aaaa);
19011919 self.work_queue_wait_group.start();
19021920 try self.thread_pool.spawn(workerUpdateCObject, .{
19031921 self, c_object, &c_obj_prog_node, &self.work_queue_wait_group,
......@@ -1964,7 +1982,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor
19641982 continue;
19651983 },
19661984 else => {
1967 try module.failed_decls.ensureCapacity(module.gpa, module.failed_decls.items().len + 1);
1985 try module.failed_decls.ensureCapacity(module.gpa, module.failed_decls.count() + 1);
19681986 module.failed_decls.putAssumeCapacityNoClobber(decl, try Module.ErrorMsg.create(
19691987 module.gpa,
19701988 decl.srcLoc(),
......@@ -2036,7 +2054,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor
20362054 @panic("sadly stage2 is omitted from this build to save memory on the CI server");
20372055 const module = self.bin_file.options.module.?;
20382056 self.bin_file.updateDeclLineNumber(module, decl) catch |err| {
2039 try module.failed_decls.ensureCapacity(module.gpa, module.failed_decls.items().len + 1);
2057 try module.failed_decls.ensureCapacity(module.gpa, module.failed_decls.count() + 1);
20402058 module.failed_decls.putAssumeCapacityNoClobber(decl, try Module.ErrorMsg.create(
20412059 module.gpa,
20422060 decl.srcLoc(),
......@@ -2101,7 +2119,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor
21012119 };
21022120 },
21032121 .windows_import_lib => |index| {
2104 const link_lib = self.bin_file.options.system_libs.items()[index].key;
2122 const link_lib = self.bin_file.options.system_libs.keys()[index];
21052123 mingw.buildImportLib(self, link_lib) catch |err| {
21062124 // TODO Surface more error details.
21072125 try self.setMiscFailure(
......@@ -3023,7 +3041,7 @@ fn failCObjWithOwnedErrorMsg(
30233041 defer lock.release();
30243042 {
30253043 errdefer err_msg.destroy(comp.gpa);
3026 try comp.failed_c_objects.ensureCapacity(comp.gpa, comp.failed_c_objects.items().len + 1);
3044 try comp.failed_c_objects.ensureCapacity(comp.gpa, comp.failed_c_objects.count() + 1);
30273045 }
30283046 comp.failed_c_objects.putAssumeCapacityNoClobber(c_object, err_msg);
30293047 }
......@@ -3953,8 +3971,8 @@ fn updateStage1Module(comp: *Compilation, main_progress_node: *std.Progress.Node
39533971 // We need to save the inferred link libs to the cache, otherwise if we get a cache hit
39543972 // next time we will be missing these libs.
39553973 var libs_txt = std.ArrayList(u8).init(arena);
3956 for (comp.bin_file.options.system_libs.items()[inferred_lib_start_index..]) |entry| {
3957 try libs_txt.writer().print("{s}\n", .{entry.key});
3974 for (comp.bin_file.options.system_libs.keys()[inferred_lib_start_index..]) |key| {
3975 try libs_txt.writer().print("{s}\n", .{key});
39583976 }
39593977 try directory.handle.writeFile(libs_txt_basename, libs_txt.items);
39603978 }
......@@ -4017,7 +4035,7 @@ fn createStage1Pkg(
40174035 var children = std.ArrayList(*stage1.Pkg).init(arena);
40184036 var it = pkg.table.iterator();
40194037 while (it.next()) |entry| {
4020 try children.append(try createStage1Pkg(arena, entry.key, entry.value, child_pkg));
4038 try children.append(try createStage1Pkg(arena, entry.key_ptr.*, entry.value_ptr.*, child_pkg));
40214039 }
40224040 break :blk children.items;
40234041 };
src/Module.zig+113-122
......@@ -268,15 +268,7 @@ pub const Decl = struct {
268268 /// typed_value may need to be regenerated.
269269 dependencies: DepsTable = .{},
270270
271 /// The reason this is not `std.AutoArrayHashMapUnmanaged` is a workaround for
272 /// stage1 compiler giving me: `error: struct 'Module.Decl' depends on itself`
273 pub const DepsTable = std.ArrayHashMapUnmanaged(
274 *Decl,
275 void,
276 std.array_hash_map.getAutoHashFn(*Decl),
277 std.array_hash_map.getAutoEqlFn(*Decl),
278 false,
279 );
271 pub const DepsTable = std.AutoArrayHashMapUnmanaged(*Decl, void);
280272
281273 pub fn clearName(decl: *Decl, gpa: *Allocator) void {
282274 gpa.free(mem.spanZ(decl.name));
......@@ -287,7 +279,7 @@ pub const Decl = struct {
287279 const gpa = module.gpa;
288280 log.debug("destroy {*} ({s})", .{ decl, decl.name });
289281 if (decl.deletion_flag) {
290 module.deletion_set.swapRemoveAssertDiscard(decl);
282 assert(module.deletion_set.swapRemove(decl));
291283 }
292284 if (decl.has_tv) {
293285 if (decl.getInnerNamespace()) |namespace| {
......@@ -550,11 +542,11 @@ pub const Decl = struct {
550542 }
551543
552544 fn removeDependant(decl: *Decl, other: *Decl) void {
553 decl.dependants.removeAssertDiscard(other);
545 assert(decl.dependants.swapRemove(other));
554546 }
555547
556548 fn removeDependency(decl: *Decl, other: *Decl) void {
557 decl.dependencies.removeAssertDiscard(other);
549 assert(decl.dependencies.swapRemove(other));
558550 }
559551};
560552
......@@ -683,7 +675,7 @@ pub const EnumFull = struct {
683675 /// Offset from `owner_decl`, points to the enum decl AST node.
684676 node_offset: i32,
685677
686 pub const ValueMap = std.ArrayHashMapUnmanaged(Value, void, Value.hash_u32, Value.eql, false);
678 pub const ValueMap = std.ArrayHashMapUnmanaged(Value, void, Value.ArrayHashContext, false);
687679
688680 pub fn srcLoc(self: EnumFull) SrcLoc {
689681 return .{
......@@ -895,13 +887,13 @@ pub const Scope = struct {
895887 var anon_decls = ns.anon_decls;
896888 ns.anon_decls = .{};
897889
898 for (decls.items()) |entry| {
899 entry.value.destroy(mod);
890 for (decls.values()) |value| {
891 value.destroy(mod);
900892 }
901893 decls.deinit(gpa);
902894
903 for (anon_decls.items()) |entry| {
904 entry.key.destroy(mod);
895 for (anon_decls.keys()) |key| {
896 key.destroy(mod);
905897 }
906898 anon_decls.deinit(gpa);
907899 }
......@@ -924,15 +916,13 @@ pub const Scope = struct {
924916 // TODO rework this code to not panic on OOM.
925917 // (might want to coordinate with the clearDecl function)
926918
927 for (decls.items()) |entry| {
928 const child_decl = entry.value;
919 for (decls.values()) |child_decl| {
929920 mod.clearDecl(child_decl, outdated_decls) catch @panic("out of memory");
930921 child_decl.destroy(mod);
931922 }
932923 decls.deinit(gpa);
933924
934 for (anon_decls.items()) |entry| {
935 const child_decl = entry.key;
925 for (anon_decls.keys()) |child_decl| {
936926 mod.clearDecl(child_decl, outdated_decls) catch @panic("out of memory");
937927 child_decl.destroy(mod);
938928 }
......@@ -2120,9 +2110,11 @@ pub const InnerError = error{ OutOfMemory, AnalysisFail };
21202110pub fn deinit(mod: *Module) void {
21212111 const gpa = mod.gpa;
21222112
2123 for (mod.import_table.items()) |entry| {
2124 gpa.free(entry.key);
2125 entry.value.destroy(mod);
2113 for (mod.import_table.keys()) |key| {
2114 gpa.free(key);
2115 }
2116 for (mod.import_table.values()) |value| {
2117 value.destroy(mod);
21262118 }
21272119 mod.import_table.deinit(gpa);
21282120
......@@ -2130,16 +2122,16 @@ pub fn deinit(mod: *Module) void {
21302122
21312123 // The callsite of `Compilation.create` owns the `root_pkg`, however
21322124 // Module owns the builtin and std packages that it adds.
2133 if (mod.root_pkg.table.remove("builtin")) |entry| {
2134 gpa.free(entry.key);
2135 entry.value.destroy(gpa);
2125 if (mod.root_pkg.table.fetchRemove("builtin")) |kv| {
2126 gpa.free(kv.key);
2127 kv.value.destroy(gpa);
21362128 }
2137 if (mod.root_pkg.table.remove("std")) |entry| {
2138 gpa.free(entry.key);
2139 entry.value.destroy(gpa);
2129 if (mod.root_pkg.table.fetchRemove("std")) |kv| {
2130 gpa.free(kv.key);
2131 kv.value.destroy(gpa);
21402132 }
2141 if (mod.root_pkg.table.remove("root")) |entry| {
2142 gpa.free(entry.key);
2133 if (mod.root_pkg.table.fetchRemove("root")) |kv| {
2134 gpa.free(kv.key);
21432135 }
21442136
21452137 mod.compile_log_text.deinit(gpa);
......@@ -2148,46 +2140,45 @@ pub fn deinit(mod: *Module) void {
21482140 mod.local_zir_cache.handle.close();
21492141 mod.global_zir_cache.handle.close();
21502142
2151 for (mod.failed_decls.items()) |entry| {
2152 entry.value.destroy(gpa);
2143 for (mod.failed_decls.values()) |value| {
2144 value.destroy(gpa);
21532145 }
21542146 mod.failed_decls.deinit(gpa);
21552147
21562148 if (mod.emit_h) |emit_h| {
2157 for (emit_h.failed_decls.items()) |entry| {
2158 entry.value.destroy(gpa);
2149 for (emit_h.failed_decls.values()) |value| {
2150 value.destroy(gpa);
21592151 }
21602152 emit_h.failed_decls.deinit(gpa);
21612153 emit_h.decl_table.deinit(gpa);
21622154 gpa.destroy(emit_h);
21632155 }
21642156
2165 for (mod.failed_files.items()) |entry| {
2166 if (entry.value) |msg| msg.destroy(gpa);
2157 for (mod.failed_files.values()) |value| {
2158 if (value) |msg| msg.destroy(gpa);
21672159 }
21682160 mod.failed_files.deinit(gpa);
21692161
2170 for (mod.failed_exports.items()) |entry| {
2171 entry.value.destroy(gpa);
2162 for (mod.failed_exports.values()) |value| {
2163 value.destroy(gpa);
21722164 }
21732165 mod.failed_exports.deinit(gpa);
21742166
21752167 mod.compile_log_decls.deinit(gpa);
21762168
2177 for (mod.decl_exports.items()) |entry| {
2178 const export_list = entry.value;
2169 for (mod.decl_exports.values()) |export_list| {
21792170 gpa.free(export_list);
21802171 }
21812172 mod.decl_exports.deinit(gpa);
21822173
2183 for (mod.export_owners.items()) |entry| {
2184 freeExportList(gpa, entry.value);
2174 for (mod.export_owners.values()) |value| {
2175 freeExportList(gpa, value);
21852176 }
21862177 mod.export_owners.deinit(gpa);
21872178
2188 var it = mod.global_error_set.iterator();
2189 while (it.next()) |entry| {
2190 gpa.free(entry.key);
2179 var it = mod.global_error_set.keyIterator();
2180 while (it.next()) |key| {
2181 gpa.free(key.*);
21912182 }
21922183 mod.global_error_set.deinit(gpa);
21932184
......@@ -2670,12 +2661,10 @@ fn updateZirRefs(gpa: *Allocator, file: *Scope.File, old_zir: Zir) !void {
26702661 }
26712662
26722663 if (decl.getInnerNamespace()) |namespace| {
2673 for (namespace.decls.items()) |entry| {
2674 const sub_decl = entry.value;
2664 for (namespace.decls.values()) |sub_decl| {
26752665 try decl_stack.append(gpa, sub_decl);
26762666 }
2677 for (namespace.anon_decls.items()) |entry| {
2678 const sub_decl = entry.key;
2667 for (namespace.anon_decls.keys()) |sub_decl| {
26792668 try decl_stack.append(gpa, sub_decl);
26802669 }
26812670 }
......@@ -2769,8 +2758,7 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl: *Decl) InnerError!void {
27692758 // prior to re-analysis.
27702759 mod.deleteDeclExports(decl);
27712760 // Dependencies will be re-discovered, so we remove them here prior to re-analysis.
2772 for (decl.dependencies.items()) |entry| {
2773 const dep = entry.key;
2761 for (decl.dependencies.keys()) |dep| {
27742762 dep.removeDependant(decl);
27752763 if (dep.dependants.count() == 0 and !dep.deletion_flag) {
27762764 log.debug("insert {*} ({s}) dependant {*} ({s}) into deletion set", .{
......@@ -2817,8 +2805,7 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl: *Decl) InnerError!void {
28172805 // We may need to chase the dependants and re-analyze them.
28182806 // However, if the decl is a function, and the type is the same, we do not need to.
28192807 if (type_changed or decl.ty.zigTypeTag() != .Fn) {
2820 for (decl.dependants.items()) |entry| {
2821 const dep = entry.key;
2808 for (decl.dependants.keys()) |dep| {
28222809 switch (dep.analysis) {
28232810 .unreferenced => unreachable,
28242811 .in_progress => continue, // already doing analysis, ok
......@@ -3128,7 +3115,7 @@ pub fn declareDeclDependency(mod: *Module, depender: *Decl, dependee: *Decl) !vo
31283115
31293116 if (dependee.deletion_flag) {
31303117 dependee.deletion_flag = false;
3131 mod.deletion_set.removeAssertDiscard(dependee);
3118 assert(mod.deletion_set.swapRemove(dependee));
31323119 }
31333120
31343121 dependee.dependants.putAssumeCapacity(depender, {});
......@@ -3154,7 +3141,7 @@ pub fn importPkg(mod: *Module, cur_pkg: *Package, pkg: *Package) !ImportFileResu
31543141
31553142 const gop = try mod.import_table.getOrPut(gpa, resolved_path);
31563143 if (gop.found_existing) return ImportFileResult{
3157 .file = gop.entry.value,
3144 .file = gop.value_ptr.*,
31583145 .is_new = false,
31593146 };
31603147 keep_resolved_path = true; // It's now owned by import_table.
......@@ -3165,7 +3152,7 @@ pub fn importPkg(mod: *Module, cur_pkg: *Package, pkg: *Package) !ImportFileResu
31653152 const new_file = try gpa.create(Scope.File);
31663153 errdefer gpa.destroy(new_file);
31673154
3168 gop.entry.value = new_file;
3155 gop.value_ptr.* = new_file;
31693156 new_file.* = .{
31703157 .sub_file_path = sub_file_path,
31713158 .source = undefined,
......@@ -3209,7 +3196,7 @@ pub fn importFile(
32093196
32103197 const gop = try mod.import_table.getOrPut(gpa, resolved_path);
32113198 if (gop.found_existing) return ImportFileResult{
3212 .file = gop.entry.value,
3199 .file = gop.value_ptr.*,
32133200 .is_new = false,
32143201 };
32153202 keep_resolved_path = true; // It's now owned by import_table.
......@@ -3231,7 +3218,7 @@ pub fn importFile(
32313218 resolved_root_path, resolved_path, sub_file_path, import_string,
32323219 });
32333220
3234 gop.entry.value = new_file;
3221 gop.value_ptr.* = new_file;
32353222 new_file.* = .{
32363223 .sub_file_path = sub_file_path,
32373224 .source = undefined,
......@@ -3366,7 +3353,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) InnerError!vo
33663353 log.debug("scan new {*} ({s}) into {*}", .{ new_decl, decl_name, namespace });
33673354 new_decl.src_line = line;
33683355 new_decl.name = decl_name;
3369 gop.entry.value = new_decl;
3356 gop.value_ptr.* = new_decl;
33703357 // Exported decls, comptime decls, usingnamespace decls, and
33713358 // test decls if in test mode, get analyzed.
33723359 const want_analysis = is_exported or switch (decl_name_index) {
......@@ -3385,7 +3372,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) InnerError!vo
33853372 return;
33863373 }
33873374 gpa.free(decl_name);
3388 const decl = gop.entry.value;
3375 const decl = gop.value_ptr.*;
33893376 log.debug("scan existing {*} ({s}) of {*}", .{ decl, decl.name, namespace });
33903377 // Update the AST node of the decl; even if its contents are unchanged, it may
33913378 // have been re-ordered.
......@@ -3438,10 +3425,9 @@ pub fn clearDecl(
34383425 }
34393426
34403427 // Remove itself from its dependencies.
3441 for (decl.dependencies.items()) |entry| {
3442 const dep = entry.key;
3428 for (decl.dependencies.keys()) |dep| {
34433429 dep.removeDependant(decl);
3444 if (dep.dependants.items().len == 0 and !dep.deletion_flag) {
3430 if (dep.dependants.count() == 0 and !dep.deletion_flag) {
34453431 // We don't recursively perform a deletion here, because during the update,
34463432 // another reference to it may turn up.
34473433 dep.deletion_flag = true;
......@@ -3451,8 +3437,7 @@ pub fn clearDecl(
34513437 decl.dependencies.clearRetainingCapacity();
34523438
34533439 // Anything that depends on this deleted decl needs to be re-analyzed.
3454 for (decl.dependants.items()) |entry| {
3455 const dep = entry.key;
3440 for (decl.dependants.keys()) |dep| {
34563441 dep.removeDependency(decl);
34573442 if (outdated_decls) |map| {
34583443 map.putAssumeCapacity(dep, {});
......@@ -3467,14 +3452,14 @@ pub fn clearDecl(
34673452 }
34683453 decl.dependants.clearRetainingCapacity();
34693454
3470 if (mod.failed_decls.swapRemove(decl)) |entry| {
3471 entry.value.destroy(gpa);
3455 if (mod.failed_decls.fetchSwapRemove(decl)) |kv| {
3456 kv.value.destroy(gpa);
34723457 }
34733458 if (mod.emit_h) |emit_h| {
3474 if (emit_h.failed_decls.swapRemove(decl)) |entry| {
3475 entry.value.destroy(gpa);
3459 if (emit_h.failed_decls.fetchSwapRemove(decl)) |kv| {
3460 kv.value.destroy(gpa);
34763461 }
3477 emit_h.decl_table.removeAssertDiscard(decl);
3462 assert(emit_h.decl_table.swapRemove(decl));
34783463 }
34793464 _ = mod.compile_log_decls.swapRemove(decl);
34803465 mod.deleteDeclExports(decl);
......@@ -3510,7 +3495,7 @@ pub fn clearDecl(
35103495
35113496 if (decl.deletion_flag) {
35123497 decl.deletion_flag = false;
3513 mod.deletion_set.swapRemoveAssertDiscard(decl);
3498 assert(mod.deletion_set.swapRemove(decl));
35143499 }
35153500
35163501 decl.analysis = .unreferenced;
......@@ -3519,12 +3504,12 @@ pub fn clearDecl(
35193504/// Delete all the Export objects that are caused by this Decl. Re-analysis of
35203505/// this Decl will cause them to be re-created (or not).
35213506fn deleteDeclExports(mod: *Module, decl: *Decl) void {
3522 const kv = mod.export_owners.swapRemove(decl) orelse return;
3507 const kv = mod.export_owners.fetchSwapRemove(decl) orelse return;
35233508
35243509 for (kv.value) |exp| {
3525 if (mod.decl_exports.getEntry(exp.exported_decl)) |decl_exports_kv| {
3510 if (mod.decl_exports.getPtr(exp.exported_decl)) |value_ptr| {
35263511 // Remove exports with owner_decl matching the regenerating decl.
3527 const list = decl_exports_kv.value;
3512 const list = value_ptr.*;
35283513 var i: usize = 0;
35293514 var new_len = list.len;
35303515 while (i < new_len) {
......@@ -3535,9 +3520,9 @@ fn deleteDeclExports(mod: *Module, decl: *Decl) void {
35353520 i += 1;
35363521 }
35373522 }
3538 decl_exports_kv.value = mod.gpa.shrink(list, new_len);
3523 value_ptr.* = mod.gpa.shrink(list, new_len);
35393524 if (new_len == 0) {
3540 mod.decl_exports.removeAssertDiscard(exp.exported_decl);
3525 assert(mod.decl_exports.swapRemove(exp.exported_decl));
35413526 }
35423527 }
35433528 if (mod.comp.bin_file.cast(link.File.Elf)) |elf| {
......@@ -3546,8 +3531,8 @@ fn deleteDeclExports(mod: *Module, decl: *Decl) void {
35463531 if (mod.comp.bin_file.cast(link.File.MachO)) |macho| {
35473532 macho.deleteExport(exp.link.macho);
35483533 }
3549 if (mod.failed_exports.swapRemove(exp)) |entry| {
3550 entry.value.destroy(mod.gpa);
3534 if (mod.failed_exports.fetchSwapRemove(exp)) |failed_kv| {
3535 failed_kv.value.destroy(mod.gpa);
35513536 }
35523537 mod.gpa.free(exp.options.name);
35533538 mod.gpa.destroy(exp);
......@@ -3623,12 +3608,12 @@ pub fn analyzeFnBody(mod: *Module, decl: *Decl, func: *Fn) !void {
36233608fn markOutdatedDecl(mod: *Module, decl: *Decl) !void {
36243609 log.debug("mark outdated {*} ({s})", .{ decl, decl.name });
36253610 try mod.comp.work_queue.writeItem(.{ .analyze_decl = decl });
3626 if (mod.failed_decls.swapRemove(decl)) |entry| {
3627 entry.value.destroy(mod.gpa);
3611 if (mod.failed_decls.fetchSwapRemove(decl)) |kv| {
3612 kv.value.destroy(mod.gpa);
36283613 }
36293614 if (mod.emit_h) |emit_h| {
3630 if (emit_h.failed_decls.swapRemove(decl)) |entry| {
3631 entry.value.destroy(mod.gpa);
3615 if (emit_h.failed_decls.fetchSwapRemove(decl)) |kv| {
3616 kv.value.destroy(mod.gpa);
36323617 }
36333618 }
36343619 _ = mod.compile_log_decls.swapRemove(decl);
......@@ -3686,17 +3671,24 @@ fn allocateNewDecl(mod: *Module, namespace: *Scope.Namespace, src_node: ast.Node
36863671}
36873672
36883673/// Get error value for error tag `name`.
3689pub fn getErrorValue(mod: *Module, name: []const u8) !std.StringHashMapUnmanaged(ErrorInt).Entry {
3674pub fn getErrorValue(mod: *Module, name: []const u8) !std.StringHashMapUnmanaged(ErrorInt).KV {
36903675 const gop = try mod.global_error_set.getOrPut(mod.gpa, name);
3691 if (gop.found_existing)
3692 return gop.entry.*;
3676 if (gop.found_existing) {
3677 return std.StringHashMapUnmanaged(ErrorInt).KV{
3678 .key = gop.key_ptr.*,
3679 .value = gop.value_ptr.*,
3680 };
3681 }
36933682
3694 errdefer mod.global_error_set.removeAssertDiscard(name);
3683 errdefer assert(mod.global_error_set.remove(name));
36953684 try mod.error_name_list.ensureCapacity(mod.gpa, mod.error_name_list.items.len + 1);
3696 gop.entry.key = try mod.gpa.dupe(u8, name);
3697 gop.entry.value = @intCast(ErrorInt, mod.error_name_list.items.len);
3698 mod.error_name_list.appendAssumeCapacity(gop.entry.key);
3699 return gop.entry.*;
3685 gop.key_ptr.* = try mod.gpa.dupe(u8, name);
3686 gop.value_ptr.* = @intCast(ErrorInt, mod.error_name_list.items.len);
3687 mod.error_name_list.appendAssumeCapacity(gop.key_ptr.*);
3688 return std.StringHashMapUnmanaged(ErrorInt).KV{
3689 .key = gop.key_ptr.*,
3690 .value = gop.value_ptr.*,
3691 };
37003692}
37013693
37023694pub fn analyzeExport(
......@@ -3712,8 +3704,8 @@ pub fn analyzeExport(
37123704 else => return mod.fail(scope, src, "unable to export type '{}'", .{exported_decl.ty}),
37133705 }
37143706
3715 try mod.decl_exports.ensureCapacity(mod.gpa, mod.decl_exports.items().len + 1);
3716 try mod.export_owners.ensureCapacity(mod.gpa, mod.export_owners.items().len + 1);
3707 try mod.decl_exports.ensureCapacity(mod.gpa, mod.decl_exports.count() + 1);
3708 try mod.export_owners.ensureCapacity(mod.gpa, mod.export_owners.count() + 1);
37173709
37183710 const new_export = try mod.gpa.create(Export);
37193711 errdefer mod.gpa.destroy(new_export);
......@@ -3746,20 +3738,20 @@ pub fn analyzeExport(
37463738 // Add to export_owners table.
37473739 const eo_gop = mod.export_owners.getOrPutAssumeCapacity(owner_decl);
37483740 if (!eo_gop.found_existing) {
3749 eo_gop.entry.value = &[0]*Export{};
3741 eo_gop.value_ptr.* = &[0]*Export{};
37503742 }
3751 eo_gop.entry.value = try mod.gpa.realloc(eo_gop.entry.value, eo_gop.entry.value.len + 1);
3752 eo_gop.entry.value[eo_gop.entry.value.len - 1] = new_export;
3753 errdefer eo_gop.entry.value = mod.gpa.shrink(eo_gop.entry.value, eo_gop.entry.value.len - 1);
3743 eo_gop.value_ptr.* = try mod.gpa.realloc(eo_gop.value_ptr.*, eo_gop.value_ptr.len + 1);
3744 eo_gop.value_ptr.*[eo_gop.value_ptr.len - 1] = new_export;
3745 errdefer eo_gop.value_ptr.* = mod.gpa.shrink(eo_gop.value_ptr.*, eo_gop.value_ptr.len - 1);
37543746
37553747 // Add to exported_decl table.
37563748 const de_gop = mod.decl_exports.getOrPutAssumeCapacity(exported_decl);
37573749 if (!de_gop.found_existing) {
3758 de_gop.entry.value = &[0]*Export{};
3750 de_gop.value_ptr.* = &[0]*Export{};
37593751 }
3760 de_gop.entry.value = try mod.gpa.realloc(de_gop.entry.value, de_gop.entry.value.len + 1);
3761 de_gop.entry.value[de_gop.entry.value.len - 1] = new_export;
3762 errdefer de_gop.entry.value = mod.gpa.shrink(de_gop.entry.value, de_gop.entry.value.len - 1);
3752 de_gop.value_ptr.* = try mod.gpa.realloc(de_gop.value_ptr.*, de_gop.value_ptr.len + 1);
3753 de_gop.value_ptr.*[de_gop.value_ptr.len - 1] = new_export;
3754 errdefer de_gop.value_ptr.* = mod.gpa.shrink(de_gop.value_ptr.*, de_gop.value_ptr.len - 1);
37633755}
37643756pub fn constInst(mod: *Module, arena: *Allocator, src: LazySrcLoc, typed_value: TypedValue) !*ir.Inst {
37653757 const const_inst = try arena.create(ir.Inst.Constant);
......@@ -3851,7 +3843,7 @@ pub fn constIntBig(mod: *Module, arena: *Allocator, src: LazySrcLoc, ty: Type, b
38513843
38523844pub fn deleteAnonDecl(mod: *Module, scope: *Scope, decl: *Decl) void {
38533845 const scope_decl = scope.ownerDecl().?;
3854 scope_decl.namespace.anon_decls.swapRemoveAssertDiscard(decl);
3846 assert(scope_decl.namespace.anon_decls.swapRemove(decl));
38553847 decl.destroy(mod);
38563848}
38573849
......@@ -4001,8 +3993,8 @@ pub fn failWithOwnedErrorMsg(mod: *Module, scope: *Scope, err_msg: *ErrorMsg) In
40013993
40023994 {
40033995 errdefer err_msg.destroy(mod.gpa);
4004 try mod.failed_decls.ensureCapacity(mod.gpa, mod.failed_decls.items().len + 1);
4005 try mod.failed_files.ensureCapacity(mod.gpa, mod.failed_files.items().len + 1);
3996 try mod.failed_decls.ensureCapacity(mod.gpa, mod.failed_decls.count() + 1);
3997 try mod.failed_files.ensureCapacity(mod.gpa, mod.failed_files.count() + 1);
40063998 }
40073999 switch (scope.tag) {
40084000 .block => {
......@@ -4420,8 +4412,8 @@ fn lockAndClearFileCompileError(mod: *Module, file: *Scope.File) void {
44204412 .never_loaded, .parse_failure, .astgen_failure => {
44214413 const lock = mod.comp.mutex.acquire();
44224414 defer lock.release();
4423 if (mod.failed_files.swapRemove(file)) |entry| {
4424 if (entry.value) |msg| msg.destroy(mod.gpa); // Delete previous error message.
4415 if (mod.failed_files.fetchSwapRemove(file)) |kv| {
4416 if (kv.value) |msg| msg.destroy(mod.gpa); // Delete previous error message.
44254417 }
44264418 },
44274419 }
......@@ -4649,7 +4641,7 @@ pub fn analyzeStructFields(mod: *Module, struct_obj: *Struct) InnerError!void {
46494641
46504642 const gop = struct_obj.fields.getOrPutAssumeCapacity(field_name);
46514643 assert(!gop.found_existing);
4652 gop.entry.value = .{
4644 gop.value_ptr.* = .{
46534645 .ty = field_ty,
46544646 .abi_align = Value.initTag(.abi_align_default),
46554647 .default_val = Value.initTag(.unreachable_value),
......@@ -4663,7 +4655,7 @@ pub fn analyzeStructFields(mod: *Module, struct_obj: *Struct) InnerError!void {
46634655 // TODO: if we need to report an error here, use a source location
46644656 // that points to this alignment expression rather than the struct.
46654657 // But only resolve the source location if we need to emit a compile error.
4666 gop.entry.value.abi_align = (try sema.resolveInstConst(&block, src, align_ref)).val;
4658 gop.value_ptr.abi_align = (try sema.resolveInstConst(&block, src, align_ref)).val;
46674659 }
46684660 if (has_default) {
46694661 const default_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
......@@ -4671,7 +4663,7 @@ pub fn analyzeStructFields(mod: *Module, struct_obj: *Struct) InnerError!void {
46714663 // TODO: if we need to report an error here, use a source location
46724664 // that points to this default value expression rather than the struct.
46734665 // But only resolve the source location if we need to emit a compile error.
4674 gop.entry.value.default_val = (try sema.resolveInstConst(&block, src, default_ref)).val;
4666 gop.value_ptr.default_val = (try sema.resolveInstConst(&block, src, default_ref)).val;
46754667 }
46764668 }
46774669}
......@@ -4816,7 +4808,7 @@ pub fn analyzeUnionFields(mod: *Module, union_obj: *Union) InnerError!void {
48164808
48174809 const gop = union_obj.fields.getOrPutAssumeCapacity(field_name);
48184810 assert(!gop.found_existing);
4819 gop.entry.value = .{
4811 gop.value_ptr.* = .{
48204812 .ty = field_ty,
48214813 .abi_align = Value.initTag(.abi_align_default),
48224814 };
......@@ -4825,7 +4817,7 @@ pub fn analyzeUnionFields(mod: *Module, union_obj: *Union) InnerError!void {
48254817 // TODO: if we need to report an error here, use a source location
48264818 // that points to this alignment expression rather than the struct.
48274819 // But only resolve the source location if we need to emit a compile error.
4828 gop.entry.value.abi_align = (try sema.resolveInstConst(&block, src, align_ref)).val;
4820 gop.value_ptr.abi_align = (try sema.resolveInstConst(&block, src, align_ref)).val;
48294821 }
48304822 }
48314823
......@@ -4841,9 +4833,7 @@ pub fn processOutdatedAndDeletedDecls(mod: *Module) !void {
48414833 // deleted Decl pointers in the work queue.
48424834 var outdated_decls = std.AutoArrayHashMap(*Decl, void).init(mod.gpa);
48434835 defer outdated_decls.deinit();
4844 for (mod.import_table.items()) |import_table_entry| {
4845 const file = import_table_entry.value;
4846
4836 for (mod.import_table.values()) |file| {
48474837 try outdated_decls.ensureUnusedCapacity(file.outdated_decls.items.len);
48484838 for (file.outdated_decls.items) |decl| {
48494839 outdated_decls.putAssumeCapacity(decl, {});
......@@ -4872,8 +4862,8 @@ pub fn processOutdatedAndDeletedDecls(mod: *Module) !void {
48724862 }
48734863 // Finally we can queue up re-analysis tasks after we have processed
48744864 // the deleted decls.
4875 for (outdated_decls.items()) |entry| {
4876 try mod.markOutdatedDecl(entry.key);
4865 for (outdated_decls.keys()) |key| {
4866 try mod.markOutdatedDecl(key);
48774867 }
48784868}
48794869
......@@ -4886,9 +4876,10 @@ pub fn processExports(mod: *Module) !void {
48864876 var symbol_exports: std.StringArrayHashMapUnmanaged(*Export) = .{};
48874877 defer symbol_exports.deinit(gpa);
48884878
4889 for (mod.decl_exports.items()) |entry| {
4890 const exported_decl = entry.key;
4891 const exports = entry.value;
4879 var it = mod.decl_exports.iterator();
4880 while (it.next()) |entry| {
4881 const exported_decl = entry.key_ptr.*;
4882 const exports = entry.value_ptr.*;
48924883 for (exports) |new_export| {
48934884 const gop = try symbol_exports.getOrPut(gpa, new_export.options.name);
48944885 if (gop.found_existing) {
......@@ -4899,13 +4890,13 @@ pub fn processExports(mod: *Module) !void {
48994890 new_export.options.name,
49004891 });
49014892 errdefer msg.destroy(gpa);
4902 const other_export = gop.entry.value;
4893 const other_export = gop.value_ptr.*;
49034894 const other_src_loc = other_export.getSrcLoc();
49044895 try mod.errNoteNonLazy(other_src_loc, msg, "other symbol here", .{});
49054896 mod.failed_exports.putAssumeCapacityNoClobber(new_export, msg);
49064897 new_export.status = .failed;
49074898 } else {
4908 gop.entry.value = new_export;
4899 gop.value_ptr.* = new_export;
49094900 }
49104901 }
49114902 mod.comp.bin_file.updateDeclExports(mod, exported_decl, exports) catch |err| switch (err) {
src/Package.zig+3-3
......@@ -100,9 +100,9 @@ pub fn destroy(pkg: *Package, gpa: *Allocator) void {
100100 }
101101
102102 {
103 var it = pkg.table.iterator();
104 while (it.next()) |kv| {
105 gpa.free(kv.key);
103 var it = pkg.table.keyIterator();
104 while (it.next()) |key| {
105 gpa.free(key.*);
106106 }
107107 }
108108
src/Sema.zig+23-24
......@@ -1350,7 +1350,7 @@ fn zirValidateStructInitPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Ind
13501350 };
13511351
13521352 // Maps field index to field_ptr index of where it was already initialized.
1353 const found_fields = try gpa.alloc(Zir.Inst.Index, struct_obj.fields.entries.items.len);
1353 const found_fields = try gpa.alloc(Zir.Inst.Index, struct_obj.fields.count());
13541354 defer gpa.free(found_fields);
13551355 mem.set(Zir.Inst.Index, found_fields, 0);
13561356
......@@ -1382,7 +1382,7 @@ fn zirValidateStructInitPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Ind
13821382 for (found_fields) |field_ptr, i| {
13831383 if (field_ptr != 0) continue;
13841384
1385 const field_name = struct_obj.fields.entries.items[i].key;
1385 const field_name = struct_obj.fields.keys()[i];
13861386 const template = "missing struct field: {s}";
13871387 const args = .{field_name};
13881388 if (root_msg) |msg| {
......@@ -1687,7 +1687,7 @@ fn zirCompileLog(
16871687
16881688 const gop = try sema.mod.compile_log_decls.getOrPut(sema.gpa, sema.owner_decl);
16891689 if (!gop.found_existing) {
1690 gop.entry.value = src_node;
1690 gop.value_ptr.* = src_node;
16911691 }
16921692 return sema.mod.constInst(sema.arena, src, .{
16931693 .ty = Type.initTag(.void),
......@@ -1954,7 +1954,7 @@ fn zirExport(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!
19541954 const section_index = struct_obj.fields.getIndex("section").?;
19551955 const export_name = try fields[name_index].toAllocatedBytes(sema.arena);
19561956 const linkage = fields[linkage_index].toEnum(
1957 struct_obj.fields.items()[linkage_index].value.ty,
1957 struct_obj.fields.values()[linkage_index].ty,
19581958 std.builtin.GlobalLinkage,
19591959 );
19601960
......@@ -2426,12 +2426,12 @@ fn zirErrorValue(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerEr
24262426 const src = inst_data.src();
24272427
24282428 // Create an anonymous error set type with only this error value, and return the value.
2429 const entry = try sema.mod.getErrorValue(inst_data.get(sema.code));
2430 const result_type = try Type.Tag.error_set_single.create(sema.arena, entry.key);
2429 const kv = try sema.mod.getErrorValue(inst_data.get(sema.code));
2430 const result_type = try Type.Tag.error_set_single.create(sema.arena, kv.key);
24312431 return sema.mod.constInst(sema.arena, src, .{
24322432 .ty = result_type,
24332433 .val = try Value.Tag.@"error".create(sema.arena, .{
2434 .name = entry.key,
2434 .name = kv.key,
24352435 }),
24362436 });
24372437}
......@@ -2558,10 +2558,10 @@ fn zirMergeErrorSets(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) Inn
25582558 }
25592559
25602560 const new_names = try sema.arena.alloc([]const u8, set.count());
2561 var it = set.iterator();
2561 var it = set.keyIterator();
25622562 var i: usize = 0;
2563 while (it.next()) |entry| : (i += 1) {
2564 new_names[i] = entry.key;
2563 while (it.next()) |key| : (i += 1) {
2564 new_names[i] = key.*;
25652565 }
25662566
25672567 const new_error_set = try sema.arena.create(Module.ErrorSet);
......@@ -2636,7 +2636,7 @@ fn zirEnumToInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerErr
26362636 .enum_full => {
26372637 const enum_full = enum_tag.ty.castTag(.enum_full).?.data;
26382638 if (enum_full.values.count() != 0) {
2639 const val = enum_full.values.entries.items[field_index].key;
2639 const val = enum_full.values.keys()[field_index];
26402640 return mod.constInst(arena, src, .{
26412641 .ty = int_tag_ty,
26422642 .val = val,
......@@ -4360,7 +4360,7 @@ fn validateSwitchItemBool(
43604360 }
43614361}
43624362
4363const ValueSrcMap = std.HashMap(Value, Module.SwitchProngSrc, Value.hash, Value.eql, std.hash_map.DefaultMaxLoadPercentage);
4363const ValueSrcMap = std.HashMap(Value, Module.SwitchProngSrc, Value.HashContext, std.hash_map.default_max_load_percentage);
43644364
43654365fn validateSwitchItemSparse(
43664366 sema: *Sema,
......@@ -4371,8 +4371,8 @@ fn validateSwitchItemSparse(
43714371 switch_prong_src: Module.SwitchProngSrc,
43724372) InnerError!void {
43734373 const item_val = (try sema.resolveSwitchItemVal(block, item_ref, src_node_offset, switch_prong_src, .none)).val;
4374 const entry = (try seen_values.fetchPut(item_val, switch_prong_src)) orelse return;
4375 return sema.validateSwitchDupe(block, entry.value, switch_prong_src, src_node_offset);
4374 const kv = (try seen_values.fetchPut(item_val, switch_prong_src)) orelse return;
4375 return sema.validateSwitchDupe(block, kv.value, switch_prong_src, src_node_offset);
43764376}
43774377
43784378fn validateSwitchNoRange(
......@@ -5470,12 +5470,12 @@ fn zirStructInit(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref:
54705470
54715471 // Maps field index to field_type index of where it was already initialized.
54725472 // For making sure all fields are accounted for and no fields are duplicated.
5473 const found_fields = try gpa.alloc(Zir.Inst.Index, struct_obj.fields.entries.items.len);
5473 const found_fields = try gpa.alloc(Zir.Inst.Index, struct_obj.fields.count());
54745474 defer gpa.free(found_fields);
54755475 mem.set(Zir.Inst.Index, found_fields, 0);
54765476
54775477 // The init values to use for the struct instance.
5478 const field_inits = try gpa.alloc(*ir.Inst, struct_obj.fields.entries.items.len);
5478 const field_inits = try gpa.alloc(*ir.Inst, struct_obj.fields.count());
54795479 defer gpa.free(field_inits);
54805480
54815481 var field_i: u32 = 0;
......@@ -5513,9 +5513,9 @@ fn zirStructInit(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref:
55135513 if (field_type_inst != 0) continue;
55145514
55155515 // Check if the field has a default init.
5516 const field = struct_obj.fields.entries.items[i].value;
5516 const field = struct_obj.fields.values()[i];
55175517 if (field.default_val.tag() == .unreachable_value) {
5518 const field_name = struct_obj.fields.entries.items[i].key;
5518 const field_name = struct_obj.fields.keys()[i];
55195519 const template = "missing struct field: {s}";
55205520 const args = .{field_name};
55215521 if (root_msg) |msg| {
......@@ -6402,7 +6402,7 @@ fn analyzeStructFieldPtr(
64026402
64036403 const field_index = struct_obj.fields.getIndex(field_name) orelse
64046404 return sema.failWithBadFieldAccess(block, struct_obj, field_name_src, field_name);
6405 const field = struct_obj.fields.entries.items[field_index].value;
6405 const field = struct_obj.fields.values()[field_index];
64066406 const ptr_field_ty = try mod.simplePtrType(arena, field.ty, true, .One);
64076407
64086408 if (try sema.resolveDefinedValue(block, src, struct_ptr)) |struct_ptr_val| {
......@@ -6438,7 +6438,7 @@ fn analyzeUnionFieldPtr(
64386438 const field_index = union_obj.fields.getIndex(field_name) orelse
64396439 return sema.failWithBadUnionFieldAccess(block, union_obj, field_name_src, field_name);
64406440
6441 const field = union_obj.fields.entries.items[field_index].value;
6441 const field = union_obj.fields.values()[field_index];
64426442 const ptr_field_ty = try mod.simplePtrType(arena, field.ty, true, .One);
64436443
64446444 if (try sema.resolveDefinedValue(block, src, union_ptr)) |union_ptr_val| {
......@@ -7476,9 +7476,8 @@ fn typeHasOnePossibleValue(
74767476 .@"struct" => {
74777477 const resolved_ty = try sema.resolveTypeFields(block, src, ty);
74787478 const s = resolved_ty.castTag(.@"struct").?.data;
7479 for (s.fields.entries.items) |entry| {
7480 const field_ty = entry.value.ty;
7481 if ((try sema.typeHasOnePossibleValue(block, src, field_ty)) == null) {
7479 for (s.fields.values()) |value| {
7480 if ((try sema.typeHasOnePossibleValue(block, src, value.ty)) == null) {
74827481 return null;
74837482 }
74847483 }
......@@ -7488,7 +7487,7 @@ fn typeHasOnePossibleValue(
74887487 const resolved_ty = try sema.resolveTypeFields(block, src, ty);
74897488 const enum_full = resolved_ty.castTag(.enum_full).?.data;
74907489 if (enum_full.fields.count() == 1) {
7491 return enum_full.values.entries.items[0].key;
7490 return enum_full.values.keys()[0];
74927491 } else {
74937492 return null;
74947493 }
src/air.zig+4-3
......@@ -696,10 +696,11 @@ const DumpTzir = struct {
696696
697697 std.debug.print("Module.Function(name={s}):\n", .{dtz.module_fn.owner_decl.name});
698698
699 for (dtz.const_table.items()) |entry| {
700 const constant = entry.key.castTag(.constant).?;
699 var it = dtz.const_table.iterator();
700 while (it.next()) |entry| {
701 const constant = entry.key_ptr.*.castTag(.constant).?;
701702 try writer.print(" @{d}: {} = {};\n", .{
702 entry.value, constant.base.ty, constant.val,
703 entry.value_ptr.*, constant.base.ty, constant.val,
703704 });
704705 }
705706
src/codegen.zig+35-26
......@@ -794,7 +794,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
794794
795795 fn ensureProcessDeathCapacity(self: *Self, additional_count: usize) !void {
796796 const table = &self.branch_stack.items[self.branch_stack.items.len - 1].inst_table;
797 try table.ensureCapacity(self.gpa, table.items().len + additional_count);
797 try table.ensureCapacity(self.gpa, table.count() + additional_count);
798798 }
799799
800800 /// Adds a Type to the .debug_info at the current position. The bytes will be populated later,
......@@ -808,12 +808,12 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
808808
809809 const gop = try dbg_out.dbg_info_type_relocs.getOrPut(self.gpa, ty);
810810 if (!gop.found_existing) {
811 gop.entry.value = .{
811 gop.value_ptr.* = .{
812812 .off = undefined,
813813 .relocs = .{},
814814 };
815815 }
816 try gop.entry.value.relocs.append(self.gpa, @intCast(u32, index));
816 try gop.value_ptr.relocs.append(self.gpa, @intCast(u32, index));
817817 },
818818 .none => {},
819819 }
......@@ -2877,58 +2877,67 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
28772877 // assert that parent_branch.free_registers equals the saved_then_branch.free_registers
28782878 // rather than assigning it.
28792879 const parent_branch = &self.branch_stack.items[self.branch_stack.items.len - 2];
2880 try parent_branch.inst_table.ensureCapacity(self.gpa, parent_branch.inst_table.items().len +
2881 else_branch.inst_table.items().len);
2882 for (else_branch.inst_table.items()) |else_entry| {
2883 const canon_mcv = if (saved_then_branch.inst_table.swapRemove(else_entry.key)) |then_entry| blk: {
2880 try parent_branch.inst_table.ensureCapacity(self.gpa, parent_branch.inst_table.count() +
2881 else_branch.inst_table.count());
2882
2883 const else_slice = else_branch.inst_table.entries.slice();
2884 const else_keys = else_slice.items(.key);
2885 const else_values = else_slice.items(.value);
2886 for (else_keys) |else_key, else_idx| {
2887 const else_value = else_values[else_idx];
2888 const canon_mcv = if (saved_then_branch.inst_table.fetchSwapRemove(else_key)) |then_entry| blk: {
28842889 // The instruction's MCValue is overridden in both branches.
2885 parent_branch.inst_table.putAssumeCapacity(else_entry.key, then_entry.value);
2886 if (else_entry.value == .dead) {
2890 parent_branch.inst_table.putAssumeCapacity(else_key, then_entry.value);
2891 if (else_value == .dead) {
28872892 assert(then_entry.value == .dead);
28882893 continue;
28892894 }
28902895 break :blk then_entry.value;
28912896 } else blk: {
2892 if (else_entry.value == .dead)
2897 if (else_value == .dead)
28932898 continue;
28942899 // The instruction is only overridden in the else branch.
28952900 var i: usize = self.branch_stack.items.len - 2;
28962901 while (true) {
28972902 i -= 1; // If this overflows, the question is: why wasn't the instruction marked dead?
2898 if (self.branch_stack.items[i].inst_table.get(else_entry.key)) |mcv| {
2903 if (self.branch_stack.items[i].inst_table.get(else_key)) |mcv| {
28992904 assert(mcv != .dead);
29002905 break :blk mcv;
29012906 }
29022907 }
29032908 };
2904 log.debug("consolidating else_entry {*} {}=>{}", .{ else_entry.key, else_entry.value, canon_mcv });
2909 log.debug("consolidating else_entry {*} {}=>{}", .{ else_key, else_value, canon_mcv });
29052910 // TODO make sure the destination stack offset / register does not already have something
29062911 // going on there.
2907 try self.setRegOrMem(inst.base.src, else_entry.key.ty, canon_mcv, else_entry.value);
2912 try self.setRegOrMem(inst.base.src, else_key.ty, canon_mcv, else_value);
29082913 // TODO track the new register / stack allocation
29092914 }
2910 try parent_branch.inst_table.ensureCapacity(self.gpa, parent_branch.inst_table.items().len +
2911 saved_then_branch.inst_table.items().len);
2912 for (saved_then_branch.inst_table.items()) |then_entry| {
2915 try parent_branch.inst_table.ensureCapacity(self.gpa, parent_branch.inst_table.count() +
2916 saved_then_branch.inst_table.count());
2917 const then_slice = saved_then_branch.inst_table.entries.slice();
2918 const then_keys = then_slice.items(.key);
2919 const then_values = then_slice.items(.value);
2920 for (then_keys) |then_key, then_idx| {
2921 const then_value = then_values[then_idx];
29132922 // We already deleted the items from this table that matched the else_branch.
29142923 // So these are all instructions that are only overridden in the then branch.
2915 parent_branch.inst_table.putAssumeCapacity(then_entry.key, then_entry.value);
2916 if (then_entry.value == .dead)
2924 parent_branch.inst_table.putAssumeCapacity(then_key, then_value);
2925 if (then_value == .dead)
29172926 continue;
29182927 const parent_mcv = blk: {
29192928 var i: usize = self.branch_stack.items.len - 2;
29202929 while (true) {
29212930 i -= 1;
2922 if (self.branch_stack.items[i].inst_table.get(then_entry.key)) |mcv| {
2931 if (self.branch_stack.items[i].inst_table.get(then_key)) |mcv| {
29232932 assert(mcv != .dead);
29242933 break :blk mcv;
29252934 }
29262935 }
29272936 };
2928 log.debug("consolidating then_entry {*} {}=>{}", .{ then_entry.key, parent_mcv, then_entry.value });
2937 log.debug("consolidating then_entry {*} {}=>{}", .{ then_key, parent_mcv, then_value });
29292938 // TODO make sure the destination stack offset / register does not already have something
29302939 // going on there.
2931 try self.setRegOrMem(inst.base.src, then_entry.key.ty, parent_mcv, then_entry.value);
2940 try self.setRegOrMem(inst.base.src, then_key.ty, parent_mcv, then_value);
29322941 // TODO track the new register / stack allocation
29332942 }
29342943
......@@ -3028,7 +3037,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
30283037 // block results.
30293038 .mcv = MCValue{ .none = {} },
30303039 });
3031 const block_data = &self.blocks.getEntry(inst).?.value;
3040 const block_data = self.blocks.getPtr(inst).?;
30323041 defer block_data.relocs.deinit(self.gpa);
30333042
30343043 try self.genBody(inst.body);
......@@ -3109,7 +3118,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
31093118 }
31103119
31113120 fn br(self: *Self, src: LazySrcLoc, block: *ir.Inst.Block, operand: *ir.Inst) !MCValue {
3112 const block_data = &self.blocks.getEntry(block).?.value;
3121 const block_data = self.blocks.getPtr(block).?;
31133122
31143123 if (operand.ty.hasCodeGenBits()) {
31153124 const operand_mcv = try self.resolveInst(operand);
......@@ -3124,7 +3133,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
31243133 }
31253134
31263135 fn brVoid(self: *Self, src: LazySrcLoc, block: *ir.Inst.Block) !MCValue {
3127 const block_data = &self.blocks.getEntry(block).?.value;
3136 const block_data = self.blocks.getPtr(block).?;
31283137
31293138 // Emit a jump with a relocation. It will be patched up after the block ends.
31303139 try block_data.relocs.ensureCapacity(self.gpa, block_data.relocs.items.len + 1);
......@@ -4118,9 +4127,9 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
41184127 const branch = &self.branch_stack.items[0];
41194128 const gop = try branch.inst_table.getOrPut(self.gpa, inst);
41204129 if (!gop.found_existing) {
4121 gop.entry.value = try self.genTypedValue(inst.src, .{ .ty = inst.ty, .val = const_inst.val });
4130 gop.value_ptr.* = try self.genTypedValue(inst.src, .{ .ty = inst.ty, .val = const_inst.val });
41224131 }
4123 return gop.entry.value;
4132 return gop.value_ptr.*;
41244133 }
41254134
41264135 return self.getResolvedInstValue(inst);
src/codegen/c.zig+10-7
......@@ -39,7 +39,7 @@ const BlockData = struct {
3939};
4040
4141pub const CValueMap = std.AutoHashMap(*Inst, CValue);
42pub const TypedefMap = std.HashMap(Type, struct { name: []const u8, rendered: []u8 }, Type.hash, Type.eql, std.hash_map.default_max_load_percentage);
42pub const TypedefMap = std.HashMap(Type, struct { name: []const u8, rendered: []u8 }, Type.HashContext, std.hash_map.default_max_load_percentage);
4343
4444fn formatTypeAsCIdentifier(
4545 data: Type,
......@@ -309,7 +309,7 @@ pub const DeclGen = struct {
309309 .enum_full, .enum_nonexhaustive => {
310310 const enum_full = t.cast(Type.Payload.EnumFull).?.data;
311311 if (enum_full.values.count() != 0) {
312 const tag_val = enum_full.values.entries.items[field_index].key;
312 const tag_val = enum_full.values.keys()[field_index];
313313 return dg.renderValue(writer, enum_full.tag_ty, tag_val);
314314 } else {
315315 return writer.print("{d}", .{field_index});
......@@ -493,10 +493,13 @@ pub const DeclGen = struct {
493493 defer buffer.deinit();
494494
495495 try buffer.appendSlice("typedef struct {\n");
496 for (struct_obj.fields.entries.items) |entry| {
497 try buffer.append(' ');
498 try dg.renderType(buffer.writer(), entry.value.ty);
499 try buffer.writer().print(" {s};\n", .{fmtIdent(entry.key)});
496 {
497 var it = struct_obj.fields.iterator();
498 while (it.next()) |entry| {
499 try buffer.append(' ');
500 try dg.renderType(buffer.writer(), entry.value_ptr.ty);
501 try buffer.writer().print(" {s};\n", .{fmtIdent(entry.key_ptr.*)});
502 }
500503 }
501504 try buffer.appendSlice("} ");
502505
......@@ -1186,7 +1189,7 @@ fn genStructFieldPtr(o: *Object, inst: *Inst.StructFieldPtr) !CValue {
11861189 const writer = o.writer();
11871190 const struct_ptr = try o.resolveInst(inst.struct_ptr);
11881191 const struct_obj = inst.struct_ptr.ty.elemType().castTag(.@"struct").?.data;
1189 const field_name = struct_obj.fields.entries.items[inst.field_index].key;
1192 const field_name = struct_obj.fields.keys()[inst.field_index];
11901193
11911194 const local = try o.allocLocal(inst.base.ty, .Const);
11921195 switch (struct_ptr) {
src/codegen/llvm.zig+1-1
......@@ -789,7 +789,7 @@ pub const FuncGen = struct {
789789 .break_vals = &break_vals,
790790 });
791791 defer {
792 self.blocks.removeAssertDiscard(inst);
792 assert(self.blocks.remove(inst));
793793 break_bbs.deinit(self.gpa());
794794 break_vals.deinit(self.gpa());
795795 }
src/codegen/spirv.zig+7-6
......@@ -2,6 +2,7 @@ const std = @import("std");
22const Allocator = std.mem.Allocator;
33const Target = std.Target;
44const log = std.log.scoped(.codegen);
5const assert = std.debug.assert;
56
67const spec = @import("spirv/spec.zig");
78const Opcode = spec.Opcode;
......@@ -17,7 +18,7 @@ const Inst = ir.Inst;
1718pub const Word = u32;
1819pub const ResultId = u32;
1920
20pub const TypeMap = std.HashMap(Type, ResultId, Type.hash, Type.eql, std.hash_map.default_max_load_percentage);
21pub const TypeMap = std.HashMap(Type, u32, Type.HashContext, std.hash_map.default_max_load_percentage);
2122pub const InstMap = std.AutoHashMap(*Inst, ResultId);
2223
2324const IncomingBlock = struct {
......@@ -141,16 +142,16 @@ pub const SPIRVModule = struct {
141142 const path = decl.namespace.file_scope.sub_file_path;
142143 const result = try self.file_names.getOrPut(path);
143144 if (!result.found_existing) {
144 result.entry.value = self.allocResultId();
145 try writeInstructionWithString(&self.binary.debug_strings, .OpString, &[_]Word{result.entry.value}, path);
145 result.value_ptr.* = self.allocResultId();
146 try writeInstructionWithString(&self.binary.debug_strings, .OpString, &[_]Word{result.value_ptr.*}, path);
146147 try writeInstruction(&self.binary.debug_strings, .OpSource, &[_]Word{
147148 @enumToInt(spec.SourceLanguage.Unknown), // TODO: Register Zig source language.
148149 0, // TODO: Zig version as u32?
149 result.entry.value,
150 result.value_ptr.*,
150151 });
151152 }
152153
153 return result.entry.value;
154 return result.value_ptr.*;
154155 }
155156};
156157
......@@ -847,7 +848,7 @@ pub const DeclGen = struct {
847848 .incoming_blocks = &incoming_blocks,
848849 });
849850 defer {
850 self.blocks.removeAssertDiscard(inst);
851 assert(self.blocks.remove(inst));
851852 incoming_blocks.deinit(self.spv.gpa);
852853 }
853854
src/codegen/wasm.zig+3-3
......@@ -625,10 +625,10 @@ pub const Context = struct {
625625 const struct_data: *Module.Struct = ty.castTag(.@"struct").?.data;
626626 const fields_len = @intCast(u32, struct_data.fields.count());
627627 try self.locals.ensureCapacity(self.gpa, self.locals.items.len + fields_len);
628 for (struct_data.fields.items()) |entry| {
628 for (struct_data.fields.values()) |*value| {
629629 const val_type = try self.genValtype(
630630 .{ .node_offset = struct_data.node_offset },
631 entry.value.ty,
631 value.ty,
632632 );
633633 self.locals.appendAssumeCapacity(val_type);
634634 self.local_index += 1;
......@@ -1018,7 +1018,7 @@ pub const Context = struct {
10181018 .enum_full, .enum_nonexhaustive => {
10191019 const enum_full = ty.cast(Type.Payload.EnumFull).?.data;
10201020 if (enum_full.values.count() != 0) {
1021 const tag_val = enum_full.values.entries.items[field_index.data].key;
1021 const tag_val = enum_full.values.keys()[field_index.data];
10221022 try self.emitConstant(src, tag_val, enum_full.tag_ty);
10231023 } else {
10241024 try writer.writeByte(wasm.opcode(.i32_const));
src/libc_installation.zig+2-2
......@@ -252,7 +252,7 @@ pub const LibCInstallation = struct {
252252 // Detect infinite loops.
253253 const inf_loop_env_key = "ZIG_IS_DETECTING_LIBC_PATHS";
254254 if (env_map.get(inf_loop_env_key) != null) return error.ZigIsTheCCompiler;
255 try env_map.set(inf_loop_env_key, "1");
255 try env_map.put(inf_loop_env_key, "1");
256256
257257 const exec_res = std.ChildProcess.exec(.{
258258 .allocator = allocator,
......@@ -564,7 +564,7 @@ fn ccPrintFileName(args: CCPrintFileNameOptions) ![:0]u8 {
564564 // Detect infinite loops.
565565 const inf_loop_env_key = "ZIG_IS_DETECTING_LIBC_PATHS";
566566 if (env_map.get(inf_loop_env_key) != null) return error.ZigIsTheCCompiler;
567 try env_map.set(inf_loop_env_key, "1");
567 try env_map.put(inf_loop_env_key, "1");
568568
569569 const exec_res = std.ChildProcess.exec(.{
570570 .allocator = allocator,
src/link.zig+8-8
......@@ -162,7 +162,7 @@ pub const File = struct {
162162 };
163163
164164 /// For DWARF .debug_info.
165 pub const DbgInfoTypeRelocsTable = std.HashMapUnmanaged(Type, DbgInfoTypeReloc, Type.hash, Type.eql, std.hash_map.DefaultMaxLoadPercentage);
165 pub const DbgInfoTypeRelocsTable = std.HashMapUnmanaged(Type, DbgInfoTypeReloc, Type.HashContext, std.hash_map.default_max_load_percentage);
166166
167167 /// For DWARF .debug_info.
168168 pub const DbgInfoTypeReloc = struct {
......@@ -406,8 +406,8 @@ pub const File = struct {
406406 const full_out_path = try emit.directory.join(comp.gpa, &[_][]const u8{emit.sub_path});
407407 defer comp.gpa.free(full_out_path);
408408 assert(comp.c_object_table.count() == 1);
409 const the_entry = comp.c_object_table.items()[0];
410 const cached_pp_file_path = the_entry.key.status.success.object_path;
409 const the_key = comp.c_object_table.keys()[0];
410 const cached_pp_file_path = the_key.status.success.object_path;
411411 try fs.cwd().copyFile(cached_pp_file_path, fs.cwd(), full_out_path, .{});
412412 return;
413413 }
......@@ -545,8 +545,8 @@ pub const File = struct {
545545 base.releaseLock();
546546
547547 try man.addListOfFiles(base.options.objects);
548 for (comp.c_object_table.items()) |entry| {
549 _ = try man.addFile(entry.key.status.success.object_path, null);
548 for (comp.c_object_table.keys()) |key| {
549 _ = try man.addFile(key.status.success.object_path, null);
550550 }
551551 try man.addOptionalFile(module_obj_path);
552552 try man.addOptionalFile(compiler_rt_path);
......@@ -580,12 +580,12 @@ pub const File = struct {
580580 var object_files = std.ArrayList([*:0]const u8).init(base.allocator);
581581 defer object_files.deinit();
582582
583 try object_files.ensureCapacity(base.options.objects.len + comp.c_object_table.items().len + 2);
583 try object_files.ensureCapacity(base.options.objects.len + comp.c_object_table.count() + 2);
584584 for (base.options.objects) |obj_path| {
585585 object_files.appendAssumeCapacity(try arena.dupeZ(u8, obj_path));
586586 }
587 for (comp.c_object_table.items()) |entry| {
588 object_files.appendAssumeCapacity(try arena.dupeZ(u8, entry.key.status.success.object_path));
587 for (comp.c_object_table.keys()) |key| {
588 object_files.appendAssumeCapacity(try arena.dupeZ(u8, key.status.success.object_path));
589589 }
590590 if (module_obj_path) |p| {
591591 object_files.appendAssumeCapacity(try arena.dupeZ(u8, p));
src/link/C.zig+27-26
......@@ -70,8 +70,8 @@ pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Optio
7070}
7171
7272pub fn deinit(self: *C) void {
73 for (self.decl_table.items()) |entry| {
74 self.freeDecl(entry.key);
73 for (self.decl_table.keys()) |key| {
74 deinitDecl(self.base.allocator, key);
7575 }
7676 self.decl_table.deinit(self.base.allocator);
7777}
......@@ -80,13 +80,17 @@ pub fn allocateDeclIndexes(self: *C, decl: *Module.Decl) !void {}
8080
8181pub fn freeDecl(self: *C, decl: *Module.Decl) void {
8282 _ = self.decl_table.swapRemove(decl);
83 decl.link.c.code.deinit(self.base.allocator);
84 decl.fn_link.c.fwd_decl.deinit(self.base.allocator);
85 var it = decl.fn_link.c.typedefs.iterator();
86 while (it.next()) |some| {
87 self.base.allocator.free(some.value.rendered);
83 deinitDecl(self.base.allocator, decl);
84}
85
86fn deinitDecl(gpa: *Allocator, decl: *Module.Decl) void {
87 decl.link.c.code.deinit(gpa);
88 decl.fn_link.c.fwd_decl.deinit(gpa);
89 var it = decl.fn_link.c.typedefs.valueIterator();
90 while (it.next()) |value| {
91 gpa.free(value.rendered);
8892 }
89 decl.fn_link.c.typedefs.deinit(self.base.allocator);
93 decl.fn_link.c.typedefs.deinit(gpa);
9094}
9195
9296pub fn updateDecl(self: *C, module: *Module, decl: *Module.Decl) !void {
......@@ -101,9 +105,9 @@ pub fn updateDecl(self: *C, module: *Module, decl: *Module.Decl) !void {
101105 const code = &decl.link.c.code;
102106 fwd_decl.shrinkRetainingCapacity(0);
103107 {
104 var it = typedefs.iterator();
105 while (it.next()) |entry| {
106 module.gpa.free(entry.value.rendered);
108 var it = typedefs.valueIterator();
109 while (it.next()) |value| {
110 module.gpa.free(value.rendered);
107111 }
108112 }
109113 typedefs.clearRetainingCapacity();
......@@ -128,9 +132,9 @@ pub fn updateDecl(self: *C, module: *Module, decl: *Module.Decl) !void {
128132 object.blocks.deinit(module.gpa);
129133 object.code.deinit();
130134 object.dg.fwd_decl.deinit();
131 var it = object.dg.typedefs.iterator();
132 while (it.next()) |some| {
133 module.gpa.free(some.value.rendered);
135 var it = object.dg.typedefs.valueIterator();
136 while (it.next()) |value| {
137 module.gpa.free(value.rendered);
134138 }
135139 object.dg.typedefs.deinit();
136140 }
......@@ -194,31 +198,30 @@ pub fn flushModule(self: *C, comp: *Compilation) !void {
194198 if (module.global_error_set.size == 0) break :render_errors;
195199 var it = module.global_error_set.iterator();
196200 while (it.next()) |entry| {
197 try err_typedef_writer.print("#define zig_error_{s} {d}\n", .{ entry.key, entry.value });
201 try err_typedef_writer.print("#define zig_error_{s} {d}\n", .{ entry.key_ptr.*, entry.value_ptr.* });
198202 }
199203 try err_typedef_writer.writeByte('\n');
200204 }
201205
202206 var fn_count: usize = 0;
203 var typedefs = std.HashMap(Type, []const u8, Type.hash, Type.eql, std.hash_map.default_max_load_percentage).init(comp.gpa);
207 var typedefs = std.HashMap(Type, []const u8, Type.HashContext, std.hash_map.default_max_load_percentage).init(comp.gpa);
204208 defer typedefs.deinit();
205209
206210 // Typedefs, forward decls and non-functions first.
207211 // TODO: performance investigation: would keeping a list of Decls that we should
208212 // generate, rather than querying here, be faster?
209 for (self.decl_table.items()) |kv| {
210 const decl = kv.key;
213 for (self.decl_table.keys()) |decl| {
211214 if (!decl.has_tv) continue;
212215 const buf = buf: {
213216 if (decl.val.castTag(.function)) |_| {
214217 var it = decl.fn_link.c.typedefs.iterator();
215218 while (it.next()) |new| {
216 if (typedefs.get(new.key)) |previous| {
217 try err_typedef_writer.print("typedef {s} {s};\n", .{ previous, new.value.name });
219 if (typedefs.get(new.key_ptr.*)) |previous| {
220 try err_typedef_writer.print("typedef {s} {s};\n", .{ previous, new.value_ptr.name });
218221 } else {
219222 try typedefs.ensureCapacity(typedefs.capacity() + 1);
220 try err_typedef_writer.writeAll(new.value.rendered);
221 typedefs.putAssumeCapacityNoClobber(new.key, new.value.name);
223 try err_typedef_writer.writeAll(new.value_ptr.rendered);
224 typedefs.putAssumeCapacityNoClobber(new.key_ptr.*, new.value_ptr.name);
222225 }
223226 }
224227 fn_count += 1;
......@@ -242,8 +245,7 @@ pub fn flushModule(self: *C, comp: *Compilation) !void {
242245
243246 // Now the function bodies.
244247 try all_buffers.ensureCapacity(all_buffers.items.len + fn_count);
245 for (self.decl_table.items()) |kv| {
246 const decl = kv.key;
248 for (self.decl_table.keys()) |decl| {
247249 if (!decl.has_tv) continue;
248250 if (decl.val.castTag(.function)) |_| {
249251 const buf = decl.link.c.code.items;
......@@ -278,8 +280,7 @@ pub fn flushEmitH(module: *Module) !void {
278280 .iov_len = zig_h.len,
279281 });
280282
281 for (emit_h.decl_table.items()) |kv| {
282 const decl = kv.key;
283 for (emit_h.decl_table.keys()) |decl| {
283284 const decl_emit_h = decl.getEmitH(module);
284285 const buf = decl_emit_h.fwd_decl.items;
285286 all_buffers.appendAssumeCapacity(.{
src/link/Coff.zig+9-9
......@@ -735,7 +735,7 @@ pub fn updateDeclExports(self: *Coff, module: *Module, decl: *Module.Decl, expor
735735 for (exports) |exp| {
736736 if (exp.options.section) |section_name| {
737737 if (!mem.eql(u8, section_name, ".text")) {
738 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1);
738 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.count() + 1);
739739 module.failed_exports.putAssumeCapacityNoClobber(
740740 exp,
741741 try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(), "Unimplemented: ExportOptions.section", .{}),
......@@ -746,7 +746,7 @@ pub fn updateDeclExports(self: *Coff, module: *Module, decl: *Module.Decl, expor
746746 if (mem.eql(u8, exp.options.name, "_start")) {
747747 self.entry_addr = decl.link.coff.getVAddr(self.*) - default_image_base;
748748 } else {
749 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1);
749 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.count() + 1);
750750 module.failed_exports.putAssumeCapacityNoClobber(
751751 exp,
752752 try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(), "Unimplemented: Exports other than '_start'", .{}),
......@@ -861,8 +861,8 @@ fn linkWithLLD(self: *Coff, comp: *Compilation) !void {
861861 self.base.releaseLock();
862862
863863 try man.addListOfFiles(self.base.options.objects);
864 for (comp.c_object_table.items()) |entry| {
865 _ = try man.addFile(entry.key.status.success.object_path, null);
864 for (comp.c_object_table.keys()) |key| {
865 _ = try man.addFile(key.status.success.object_path, null);
866866 }
867867 try man.addOptionalFile(module_obj_path);
868868 man.hash.addOptional(self.base.options.stack_size_override);
......@@ -928,7 +928,7 @@ fn linkWithLLD(self: *Coff, comp: *Compilation) !void {
928928 break :blk self.base.options.objects[0];
929929
930930 if (comp.c_object_table.count() != 0)
931 break :blk comp.c_object_table.items()[0].key.status.success.object_path;
931 break :blk comp.c_object_table.keys()[0].status.success.object_path;
932932
933933 if (module_obj_path) |p|
934934 break :blk p;
......@@ -1026,8 +1026,8 @@ fn linkWithLLD(self: *Coff, comp: *Compilation) !void {
10261026
10271027 try argv.appendSlice(self.base.options.objects);
10281028
1029 for (comp.c_object_table.items()) |entry| {
1030 try argv.append(entry.key.status.success.object_path);
1029 for (comp.c_object_table.keys()) |key| {
1030 try argv.append(key.status.success.object_path);
10311031 }
10321032
10331033 if (module_obj_path) |p| {
......@@ -1221,8 +1221,8 @@ fn linkWithLLD(self: *Coff, comp: *Compilation) !void {
12211221 try argv.append(comp.compiler_rt_static_lib.?.full_object_path);
12221222 }
12231223
1224 for (self.base.options.system_libs.items()) |entry| {
1225 const lib_basename = try allocPrint(arena, "{s}.lib", .{entry.key});
1224 for (self.base.options.system_libs.keys()) |key| {
1225 const lib_basename = try allocPrint(arena, "{s}.lib", .{key});
12261226 if (comp.crt_files.get(lib_basename)) |crt_file| {
12271227 try argv.append(crt_file.full_object_path);
12281228 } else {
src/link/Elf.zig+33-31
......@@ -1318,8 +1318,8 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void {
13181318 try man.addOptionalFile(self.base.options.linker_script);
13191319 try man.addOptionalFile(self.base.options.version_script);
13201320 try man.addListOfFiles(self.base.options.objects);
1321 for (comp.c_object_table.items()) |entry| {
1322 _ = try man.addFile(entry.key.status.success.object_path, null);
1321 for (comp.c_object_table.keys()) |key| {
1322 _ = try man.addFile(key.status.success.object_path, null);
13231323 }
13241324 try man.addOptionalFile(module_obj_path);
13251325 try man.addOptionalFile(compiler_rt_path);
......@@ -1394,7 +1394,7 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void {
13941394 break :blk self.base.options.objects[0];
13951395
13961396 if (comp.c_object_table.count() != 0)
1397 break :blk comp.c_object_table.items()[0].key.status.success.object_path;
1397 break :blk comp.c_object_table.keys()[0].status.success.object_path;
13981398
13991399 if (module_obj_path) |p|
14001400 break :blk p;
......@@ -1518,8 +1518,7 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void {
15181518 var test_path = std.ArrayList(u8).init(self.base.allocator);
15191519 defer test_path.deinit();
15201520 for (self.base.options.lib_dirs) |lib_dir_path| {
1521 for (self.base.options.system_libs.items()) |entry| {
1522 const link_lib = entry.key;
1521 for (self.base.options.system_libs.keys()) |link_lib| {
15231522 test_path.shrinkRetainingCapacity(0);
15241523 const sep = fs.path.sep_str;
15251524 try test_path.writer().print("{s}" ++ sep ++ "lib{s}.so", .{ lib_dir_path, link_lib });
......@@ -1568,8 +1567,8 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void {
15681567 // Positional arguments to the linker such as object files.
15691568 try argv.appendSlice(self.base.options.objects);
15701569
1571 for (comp.c_object_table.items()) |entry| {
1572 try argv.append(entry.key.status.success.object_path);
1570 for (comp.c_object_table.keys()) |key| {
1571 try argv.append(key.status.success.object_path);
15731572 }
15741573
15751574 if (module_obj_path) |p| {
......@@ -1598,10 +1597,9 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void {
15981597
15991598 // Shared libraries.
16001599 if (is_exe_or_dyn_lib) {
1601 const system_libs = self.base.options.system_libs.items();
1600 const system_libs = self.base.options.system_libs.keys();
16021601 try argv.ensureCapacity(argv.items.len + system_libs.len);
1603 for (system_libs) |entry| {
1604 const link_lib = entry.key;
1602 for (system_libs) |link_lib| {
16051603 // By this time, we depend on these libs being dynamically linked libraries and not static libraries
16061604 // (the check for that needs to be earlier), but they could be full paths to .so files, in which
16071605 // case we want to avoid prepending "-l".
......@@ -2168,9 +2166,9 @@ pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void {
21682166
21692167 var dbg_info_type_relocs: File.DbgInfoTypeRelocsTable = .{};
21702168 defer {
2171 var it = dbg_info_type_relocs.iterator();
2172 while (it.next()) |entry| {
2173 entry.value.relocs.deinit(self.base.allocator);
2169 var it = dbg_info_type_relocs.valueIterator();
2170 while (it.next()) |value| {
2171 value.relocs.deinit(self.base.allocator);
21742172 }
21752173 dbg_info_type_relocs.deinit(self.base.allocator);
21762174 }
......@@ -2235,12 +2233,12 @@ pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void {
22352233 if (fn_ret_has_bits) {
22362234 const gop = try dbg_info_type_relocs.getOrPut(self.base.allocator, fn_ret_type);
22372235 if (!gop.found_existing) {
2238 gop.entry.value = .{
2236 gop.value_ptr.* = .{
22392237 .off = undefined,
22402238 .relocs = .{},
22412239 };
22422240 }
2243 try gop.entry.value.relocs.append(self.base.allocator, @intCast(u32, dbg_info_buffer.items.len));
2241 try gop.value_ptr.relocs.append(self.base.allocator, @intCast(u32, dbg_info_buffer.items.len));
22442242 dbg_info_buffer.items.len += 4; // DW.AT_type, DW.FORM_ref4
22452243 }
22462244 dbg_info_buffer.appendSliceAssumeCapacity(decl_name_with_null); // DW.AT_name, DW.FORM_string
......@@ -2448,24 +2446,28 @@ pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void {
24482446 // Now we emit the .debug_info types of the Decl. These will count towards the size of
24492447 // the buffer, so we have to do it before computing the offset, and we can't perform the actual
24502448 // relocations yet.
2451 var it = dbg_info_type_relocs.iterator();
2452 while (it.next()) |entry| {
2453 entry.value.off = @intCast(u32, dbg_info_buffer.items.len);
2454 try self.addDbgInfoType(entry.key, &dbg_info_buffer);
2449 {
2450 var it = dbg_info_type_relocs.iterator();
2451 while (it.next()) |entry| {
2452 entry.value_ptr.off = @intCast(u32, dbg_info_buffer.items.len);
2453 try self.addDbgInfoType(entry.key_ptr.*, &dbg_info_buffer);
2454 }
24552455 }
24562456
24572457 try self.updateDeclDebugInfoAllocation(text_block, @intCast(u32, dbg_info_buffer.items.len));
24582458
2459 // Now that we have the offset assigned we can finally perform type relocations.
2460 it = dbg_info_type_relocs.iterator();
2461 while (it.next()) |entry| {
2462 for (entry.value.relocs.items) |off| {
2463 mem.writeInt(
2464 u32,
2465 dbg_info_buffer.items[off..][0..4],
2466 text_block.dbg_info_off + entry.value.off,
2467 target_endian,
2468 );
2459 {
2460 // Now that we have the offset assigned we can finally perform type relocations.
2461 var it = dbg_info_type_relocs.valueIterator();
2462 while (it.next()) |value| {
2463 for (value.relocs.items) |off| {
2464 mem.writeInt(
2465 u32,
2466 dbg_info_buffer.items[off..][0..4],
2467 text_block.dbg_info_off + value.off,
2468 target_endian,
2469 );
2470 }
24692471 }
24702472 }
24712473
......@@ -2636,7 +2638,7 @@ pub fn updateDeclExports(
26362638 for (exports) |exp| {
26372639 if (exp.options.section) |section_name| {
26382640 if (!mem.eql(u8, section_name, ".text")) {
2639 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1);
2641 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.count() + 1);
26402642 module.failed_exports.putAssumeCapacityNoClobber(
26412643 exp,
26422644 try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(), "Unimplemented: ExportOptions.section", .{}),
......@@ -2654,7 +2656,7 @@ pub fn updateDeclExports(
26542656 },
26552657 .Weak => elf.STB_WEAK,
26562658 .LinkOnce => {
2657 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1);
2659 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.count() + 1);
26582660 module.failed_exports.putAssumeCapacityNoClobber(
26592661 exp,
26602662 try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(), "Unimplemented: GlobalLinkage.LinkOnce", .{}),
src/link/MachO.zig+68-60
......@@ -567,8 +567,8 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void {
567567 try man.addOptionalFile(self.base.options.linker_script);
568568 try man.addOptionalFile(self.base.options.version_script);
569569 try man.addListOfFiles(self.base.options.objects);
570 for (comp.c_object_table.items()) |entry| {
571 _ = try man.addFile(entry.key.status.success.object_path, null);
570 for (comp.c_object_table.keys()) |key| {
571 _ = try man.addFile(key.status.success.object_path, null);
572572 }
573573 try man.addOptionalFile(module_obj_path);
574574 // We can skip hashing libc and libc++ components that we are in charge of building from Zig
......@@ -632,7 +632,7 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void {
632632 break :blk self.base.options.objects[0];
633633
634634 if (comp.c_object_table.count() != 0)
635 break :blk comp.c_object_table.items()[0].key.status.success.object_path;
635 break :blk comp.c_object_table.keys()[0].status.success.object_path;
636636
637637 if (module_obj_path) |p|
638638 break :blk p;
......@@ -682,8 +682,8 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void {
682682
683683 try positionals.appendSlice(self.base.options.objects);
684684
685 for (comp.c_object_table.items()) |entry| {
686 try positionals.append(entry.key.status.success.object_path);
685 for (comp.c_object_table.keys()) |key| {
686 try positionals.append(key.status.success.object_path);
687687 }
688688
689689 if (module_obj_path) |p| {
......@@ -702,9 +702,8 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void {
702702 var libs = std.ArrayList([]const u8).init(arena);
703703 var search_lib_names = std.ArrayList([]const u8).init(arena);
704704
705 const system_libs = self.base.options.system_libs.items();
706 for (system_libs) |entry| {
707 const link_lib = entry.key;
705 const system_libs = self.base.options.system_libs.keys();
706 for (system_libs) |link_lib| {
708707 // By this time, we depend on these libs being dynamically linked libraries and not static libraries
709708 // (the check for that needs to be earlier), but they could be full paths to .dylib files, in which
710709 // case we want to avoid prepending "-l".
......@@ -804,8 +803,8 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void {
804803
805804 var rpaths = std.ArrayList([]const u8).init(arena);
806805 try rpaths.ensureCapacity(rpath_table.count());
807 for (rpath_table.items()) |entry| {
808 rpaths.appendAssumeCapacity(entry.key);
806 for (rpath_table.keys()) |*key| {
807 rpaths.appendAssumeCapacity(key.*);
809808 }
810809
811810 if (self.base.options.verbose_link) {
......@@ -973,8 +972,8 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void {
973972 // Positional arguments to the linker such as object files.
974973 try argv.appendSlice(self.base.options.objects);
975974
976 for (comp.c_object_table.items()) |entry| {
977 try argv.append(entry.key.status.success.object_path);
975 for (comp.c_object_table.keys()) |key| {
976 try argv.append(key.status.success.object_path);
978977 }
979978 if (module_obj_path) |p| {
980979 try argv.append(p);
......@@ -986,10 +985,9 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void {
986985 }
987986
988987 // Shared libraries.
989 const system_libs = self.base.options.system_libs.items();
988 const system_libs = self.base.options.system_libs.keys();
990989 try argv.ensureCapacity(argv.items.len + system_libs.len);
991 for (system_libs) |entry| {
992 const link_lib = entry.key;
990 for (system_libs) |link_lib| {
993991 // By this time, we depend on these libs being dynamically linked libraries and not static libraries
994992 // (the check for that needs to be earlier), but they could be full paths to .dylib files, in which
995993 // case we want to avoid prepending "-l".
......@@ -1153,12 +1151,12 @@ pub fn deinit(self: *MachO) void {
11531151 if (self.d_sym) |*ds| {
11541152 ds.deinit(self.base.allocator);
11551153 }
1156 for (self.lazy_imports.items()) |*entry| {
1157 self.base.allocator.free(entry.key);
1154 for (self.lazy_imports.keys()) |*key| {
1155 self.base.allocator.free(key.*);
11581156 }
11591157 self.lazy_imports.deinit(self.base.allocator);
1160 for (self.nonlazy_imports.items()) |*entry| {
1161 self.base.allocator.free(entry.key);
1158 for (self.nonlazy_imports.keys()) |*key| {
1159 self.base.allocator.free(key.*);
11621160 }
11631161 self.nonlazy_imports.deinit(self.base.allocator);
11641162 self.pie_fixups.deinit(self.base.allocator);
......@@ -1167,9 +1165,9 @@ pub fn deinit(self: *MachO) void {
11671165 self.offset_table.deinit(self.base.allocator);
11681166 self.offset_table_free_list.deinit(self.base.allocator);
11691167 {
1170 var it = self.string_table_directory.iterator();
1171 while (it.next()) |entry| {
1172 self.base.allocator.free(entry.key);
1168 var it = self.string_table_directory.keyIterator();
1169 while (it.next()) |key| {
1170 self.base.allocator.free(key.*);
11731171 }
11741172 }
11751173 self.string_table_directory.deinit(self.base.allocator);
......@@ -1318,9 +1316,9 @@ pub fn updateDecl(self: *MachO, module: *Module, decl: *Module.Decl) !void {
13181316 if (debug_buffers) |*dbg| {
13191317 dbg.dbg_line_buffer.deinit();
13201318 dbg.dbg_info_buffer.deinit();
1321 var it = dbg.dbg_info_type_relocs.iterator();
1322 while (it.next()) |entry| {
1323 entry.value.relocs.deinit(self.base.allocator);
1319 var it = dbg.dbg_info_type_relocs.valueIterator();
1320 while (it.next()) |value| {
1321 value.relocs.deinit(self.base.allocator);
13241322 }
13251323 dbg.dbg_info_type_relocs.deinit(self.base.allocator);
13261324 }
......@@ -1543,7 +1541,7 @@ pub fn updateDeclExports(
15431541
15441542 if (exp.options.section) |section_name| {
15451543 if (!mem.eql(u8, section_name, "__text")) {
1546 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1);
1544 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.count() + 1);
15471545 module.failed_exports.putAssumeCapacityNoClobber(
15481546 exp,
15491547 try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(), "Unimplemented: ExportOptions.section", .{}),
......@@ -1578,7 +1576,7 @@ pub fn updateDeclExports(
15781576 n_desc |= macho.N_WEAK_DEF;
15791577 },
15801578 .LinkOnce => {
1581 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1);
1579 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.count() + 1);
15821580 module.failed_exports.putAssumeCapacityNoClobber(
15831581 exp,
15841582 try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(), "Unimplemented: GlobalLinkage.LinkOnce", .{}),
......@@ -2259,7 +2257,7 @@ pub fn populateMissingMetadata(self: *MachO) !void {
22592257 self.load_commands_dirty = true;
22602258 }
22612259 if (!self.nonlazy_imports.contains("dyld_stub_binder")) {
2262 const index = @intCast(u32, self.nonlazy_imports.items().len);
2260 const index = @intCast(u32, self.nonlazy_imports.count());
22632261 const name = try self.base.allocator.dupe(u8, "dyld_stub_binder");
22642262 const offset = try self.makeString("dyld_stub_binder");
22652263 try self.nonlazy_imports.putNoClobber(self.base.allocator, name, .{
......@@ -2440,7 +2438,7 @@ fn updateString(self: *MachO, old_str_off: u32, new_name: []const u8) !u32 {
24402438}
24412439
24422440pub fn addExternSymbol(self: *MachO, name: []const u8) !u32 {
2443 const index = @intCast(u32, self.lazy_imports.items().len);
2441 const index = @intCast(u32, self.lazy_imports.count());
24442442 const offset = try self.makeString(name);
24452443 const sym_name = try self.base.allocator.dupe(u8, name);
24462444 const dylib_ordinal = 1; // TODO this is now hardcoded, since we only support libSystem.
......@@ -2627,7 +2625,7 @@ fn writeOffsetTableEntry(self: *MachO, index: usize) !void {
26272625 break :blk self.locals.items[got_entry.symbol];
26282626 },
26292627 .Extern => {
2630 break :blk self.nonlazy_imports.items()[got_entry.symbol].value.symbol;
2628 break :blk self.nonlazy_imports.values()[got_entry.symbol].symbol;
26312629 },
26322630 }
26332631 };
......@@ -2910,7 +2908,7 @@ fn relocateSymbolTable(self: *MachO) !void {
29102908 const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
29112909 const nlocals = self.locals.items.len;
29122910 const nglobals = self.globals.items.len;
2913 const nundefs = self.lazy_imports.items().len + self.nonlazy_imports.items().len;
2911 const nundefs = self.lazy_imports.count() + self.nonlazy_imports.count();
29142912 const nsyms = nlocals + nglobals + nundefs;
29152913
29162914 if (symtab.nsyms < nsyms) {
......@@ -2957,15 +2955,15 @@ fn writeAllGlobalAndUndefSymbols(self: *MachO) !void {
29572955 const nlocals = self.locals.items.len;
29582956 const nglobals = self.globals.items.len;
29592957
2960 const nundefs = self.lazy_imports.items().len + self.nonlazy_imports.items().len;
2958 const nundefs = self.lazy_imports.count() + self.nonlazy_imports.count();
29612959 var undefs = std.ArrayList(macho.nlist_64).init(self.base.allocator);
29622960 defer undefs.deinit();
29632961 try undefs.ensureCapacity(nundefs);
2964 for (self.lazy_imports.items()) |entry| {
2965 undefs.appendAssumeCapacity(entry.value.symbol);
2962 for (self.lazy_imports.values()) |*value| {
2963 undefs.appendAssumeCapacity(value.symbol);
29662964 }
2967 for (self.nonlazy_imports.items()) |entry| {
2968 undefs.appendAssumeCapacity(entry.value.symbol);
2965 for (self.nonlazy_imports.values()) |*value| {
2966 undefs.appendAssumeCapacity(value.symbol);
29692967 }
29702968
29712969 const locals_off = symtab.symoff;
......@@ -3005,10 +3003,10 @@ fn writeIndirectSymbolTable(self: *MachO) !void {
30053003 const la_symbol_ptr = &data_segment.sections.items[self.la_symbol_ptr_section_index.?];
30063004 const dysymtab = &self.load_commands.items[self.dysymtab_cmd_index.?].Dysymtab;
30073005
3008 const lazy = self.lazy_imports.items();
3006 const lazy_count = self.lazy_imports.count();
30093007 const got_entries = self.offset_table.items;
30103008 const allocated_size = self.allocatedSizeLinkedit(dysymtab.indirectsymoff);
3011 const nindirectsyms = @intCast(u32, lazy.len * 2 + got_entries.len);
3009 const nindirectsyms = @intCast(u32, lazy_count * 2 + got_entries.len);
30123010 const needed_size = @intCast(u32, nindirectsyms * @sizeOf(u32));
30133011
30143012 if (needed_size > allocated_size) {
......@@ -3027,12 +3025,15 @@ fn writeIndirectSymbolTable(self: *MachO) !void {
30273025 var writer = stream.writer();
30283026
30293027 stubs.reserved1 = 0;
3030 for (lazy) |_, i| {
3031 const symtab_idx = @intCast(u32, dysymtab.iundefsym + i);
3032 try writer.writeIntLittle(u32, symtab_idx);
3028 {
3029 var i: usize = 0;
3030 while (i < lazy_count) : (i += 1) {
3031 const symtab_idx = @intCast(u32, dysymtab.iundefsym + i);
3032 try writer.writeIntLittle(u32, symtab_idx);
3033 }
30333034 }
30343035
3035 const base_id = @intCast(u32, lazy.len);
3036 const base_id = @intCast(u32, lazy_count);
30363037 got.reserved1 = base_id;
30373038 for (got_entries) |entry| {
30383039 switch (entry.kind) {
......@@ -3047,9 +3048,12 @@ fn writeIndirectSymbolTable(self: *MachO) !void {
30473048 }
30483049
30493050 la_symbol_ptr.reserved1 = got.reserved1 + @intCast(u32, got_entries.len);
3050 for (lazy) |_, i| {
3051 const symtab_idx = @intCast(u32, dysymtab.iundefsym + i);
3052 try writer.writeIntLittle(u32, symtab_idx);
3051 {
3052 var i: usize = 0;
3053 while (i < lazy_count) : (i += 1) {
3054 const symtab_idx = @intCast(u32, dysymtab.iundefsym + i);
3055 try writer.writeIntLittle(u32, symtab_idx);
3056 }
30533057 }
30543058
30553059 try self.base.file.?.pwriteAll(buf, dysymtab.indirectsymoff);
......@@ -3183,15 +3187,15 @@ fn writeRebaseInfoTable(self: *MachO) !void {
31833187 }
31843188
31853189 if (self.la_symbol_ptr_section_index) |idx| {
3186 try pointers.ensureCapacity(pointers.items.len + self.lazy_imports.items().len);
3190 try pointers.ensureCapacity(pointers.items.len + self.lazy_imports.count());
31873191 const seg = self.load_commands.items[self.data_segment_cmd_index.?].Segment;
31883192 const sect = seg.sections.items[idx];
31893193 const base_offset = sect.addr - seg.inner.vmaddr;
31903194 const segment_id = self.data_segment_cmd_index.?;
31913195
3192 for (self.lazy_imports.items()) |entry| {
3196 for (self.lazy_imports.values()) |*value| {
31933197 pointers.appendAssumeCapacity(.{
3194 .offset = base_offset + entry.value.index * @sizeOf(u64),
3198 .offset = base_offset + value.index * @sizeOf(u64),
31953199 .segment_id = segment_id,
31963200 });
31973201 }
......@@ -3241,12 +3245,13 @@ fn writeBindingInfoTable(self: *MachO) !void {
32413245
32423246 for (self.offset_table.items) |entry| {
32433247 if (entry.kind == .Local) continue;
3244 const import = self.nonlazy_imports.items()[entry.symbol];
3248 const import_key = self.nonlazy_imports.keys()[entry.symbol];
3249 const import_ordinal = self.nonlazy_imports.values()[entry.symbol].dylib_ordinal;
32453250 try pointers.append(.{
32463251 .offset = base_offset + entry.index * @sizeOf(u64),
32473252 .segment_id = segment_id,
3248 .dylib_ordinal = import.value.dylib_ordinal,
3249 .name = import.key,
3253 .dylib_ordinal = import_ordinal,
3254 .name = import_key,
32503255 });
32513256 }
32523257 }
......@@ -3286,18 +3291,21 @@ fn writeLazyBindingInfoTable(self: *MachO) !void {
32863291 defer pointers.deinit();
32873292
32883293 if (self.la_symbol_ptr_section_index) |idx| {
3289 try pointers.ensureCapacity(self.lazy_imports.items().len);
3294 try pointers.ensureCapacity(self.lazy_imports.count());
32903295 const seg = self.load_commands.items[self.data_segment_cmd_index.?].Segment;
32913296 const sect = seg.sections.items[idx];
32923297 const base_offset = sect.addr - seg.inner.vmaddr;
32933298 const segment_id = @intCast(u16, self.data_segment_cmd_index.?);
32943299
3295 for (self.lazy_imports.items()) |entry| {
3300 const slice = self.lazy_imports.entries.slice();
3301 const keys = slice.items(.key);
3302 const values = slice.items(.value);
3303 for (keys) |*key, i| {
32963304 pointers.appendAssumeCapacity(.{
3297 .offset = base_offset + entry.value.index * @sizeOf(u64),
3305 .offset = base_offset + values[i].index * @sizeOf(u64),
32983306 .segment_id = segment_id,
3299 .dylib_ordinal = entry.value.dylib_ordinal,
3300 .name = entry.key,
3307 .dylib_ordinal = values[i].dylib_ordinal,
3308 .name = key.*,
33013309 });
33023310 }
33033311 }
......@@ -3329,7 +3337,7 @@ fn writeLazyBindingInfoTable(self: *MachO) !void {
33293337}
33303338
33313339fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void {
3332 if (self.lazy_imports.items().len == 0) return;
3340 if (self.lazy_imports.count() == 0) return;
33333341
33343342 var stream = std.io.fixedBufferStream(buffer);
33353343 var reader = stream.reader();
......@@ -3375,7 +3383,7 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void {
33753383 else => {},
33763384 }
33773385 }
3378 assert(self.lazy_imports.items().len <= offsets.items.len);
3386 assert(self.lazy_imports.count() <= offsets.items.len);
33793387
33803388 const stub_size: u4 = switch (self.base.options.target.cpu.arch) {
33813389 .x86_64 => 10,
......@@ -3388,9 +3396,9 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void {
33883396 else => unreachable,
33893397 };
33903398 var buf: [@sizeOf(u32)]u8 = undefined;
3391 for (self.lazy_imports.items()) |_, i| {
3399 for (offsets.items[0..self.lazy_imports.count()]) |offset, i| {
33923400 const placeholder_off = self.stub_helper_stubs_start_off.? + i * stub_size + off;
3393 mem.writeIntLittle(u32, &buf, offsets.items[i]);
3401 mem.writeIntLittle(u32, &buf, offset);
33943402 try self.base.file.?.pwriteAll(&buf, placeholder_off);
33953403 }
33963404}
src/link/MachO/Archive.zig+7-5
......@@ -92,9 +92,11 @@ pub fn init(allocator: *Allocator) Archive {
9292}
9393
9494pub fn deinit(self: *Archive) void {
95 for (self.toc.items()) |*entry| {
96 self.allocator.free(entry.key);
97 entry.value.deinit(self.allocator);
95 for (self.toc.keys()) |*key| {
96 self.allocator.free(key.*);
97 }
98 for (self.toc.values()) |*value| {
99 value.deinit(self.allocator);
98100 }
99101 self.toc.deinit(self.allocator);
100102
......@@ -187,10 +189,10 @@ fn parseTableOfContents(self: *Archive, reader: anytype) !void {
187189 defer if (res.found_existing) self.allocator.free(owned_name);
188190
189191 if (!res.found_existing) {
190 res.entry.value = .{};
192 res.value_ptr.* = .{};
191193 }
192194
193 try res.entry.value.append(self.allocator, object_offset);
195 try res.value_ptr.append(self.allocator, object_offset);
194196 }
195197}
196198
src/link/MachO/DebugSymbols.zig+22-18
......@@ -997,12 +997,12 @@ pub fn initDeclDebugBuffers(
997997 if (fn_ret_has_bits) {
998998 const gop = try dbg_info_type_relocs.getOrPut(allocator, fn_ret_type);
999999 if (!gop.found_existing) {
1000 gop.entry.value = .{
1000 gop.value_ptr.* = .{
10011001 .off = undefined,
10021002 .relocs = .{},
10031003 };
10041004 }
1005 try gop.entry.value.relocs.append(allocator, @intCast(u32, dbg_info_buffer.items.len));
1005 try gop.value_ptr.relocs.append(allocator, @intCast(u32, dbg_info_buffer.items.len));
10061006 dbg_info_buffer.items.len += 4; // DW.AT_type, DW.FORM_ref4
10071007 }
10081008 dbg_info_buffer.appendSliceAssumeCapacity(decl_name_with_null); // DW.AT_name, DW.FORM_string
......@@ -1158,26 +1158,30 @@ pub fn commitDeclDebugInfo(
11581158 if (dbg_info_buffer.items.len == 0)
11591159 return;
11601160
1161 // Now we emit the .debug_info types of the Decl. These will count towards the size of
1162 // the buffer, so we have to do it before computing the offset, and we can't perform the actual
1163 // relocations yet.
1164 var it = dbg_info_type_relocs.iterator();
1165 while (it.next()) |entry| {
1166 entry.value.off = @intCast(u32, dbg_info_buffer.items.len);
1167 try self.addDbgInfoType(entry.key, dbg_info_buffer, target);
1161 {
1162 // Now we emit the .debug_info types of the Decl. These will count towards the size of
1163 // the buffer, so we have to do it before computing the offset, and we can't perform the actual
1164 // relocations yet.
1165 var it = dbg_info_type_relocs.iterator();
1166 while (it.next()) |entry| {
1167 entry.value_ptr.off = @intCast(u32, dbg_info_buffer.items.len);
1168 try self.addDbgInfoType(entry.key_ptr.*, dbg_info_buffer, target);
1169 }
11681170 }
11691171
11701172 try self.updateDeclDebugInfoAllocation(allocator, text_block, @intCast(u32, dbg_info_buffer.items.len));
11711173
1172 // Now that we have the offset assigned we can finally perform type relocations.
1173 it = dbg_info_type_relocs.iterator();
1174 while (it.next()) |entry| {
1175 for (entry.value.relocs.items) |off| {
1176 mem.writeIntLittle(
1177 u32,
1178 dbg_info_buffer.items[off..][0..4],
1179 text_block.dbg_info_off + entry.value.off,
1180 );
1174 {
1175 // Now that we have the offset assigned we can finally perform type relocations.
1176 var it = dbg_info_type_relocs.valueIterator();
1177 while (it.next()) |value| {
1178 for (value.relocs.items) |off| {
1179 mem.writeIntLittle(
1180 u32,
1181 dbg_info_buffer.items[off..][0..4],
1182 text_block.dbg_info_off + value.off,
1183 );
1184 }
11811185 }
11821186 }
11831187
src/link/MachO/Dylib.zig+3-3
......@@ -50,9 +50,9 @@ pub fn deinit(self: *Dylib) void {
5050 }
5151 self.load_commands.deinit(self.allocator);
5252
53 for (self.symbols.items()) |entry| {
54 entry.value.deinit(self.allocator);
55 self.allocator.destroy(entry.value);
53 for (self.symbols.values()) |value| {
54 value.deinit(self.allocator);
55 self.allocator.destroy(value);
5656 }
5757 self.symbols.deinit(self.allocator);
5858
src/link/MachO/Zld.zig+20-23
......@@ -168,9 +168,9 @@ pub fn deinit(self: *Zld) void {
168168 self.strtab.deinit(self.allocator);
169169
170170 {
171 var it = self.strtab_dir.iterator();
172 while (it.next()) |entry| {
173 self.allocator.free(entry.key);
171 var it = self.strtab_dir.keyIterator();
172 while (it.next()) |key| {
173 self.allocator.free(key.*);
174174 }
175175 }
176176 self.strtab_dir.deinit(self.allocator);
......@@ -954,9 +954,8 @@ fn sortSections(self: *Zld) !void {
954954 }
955955 }
956956
957 var it = self.mappings.iterator();
958 while (it.next()) |entry| {
959 const mapping = &entry.value;
957 var it = self.mappings.valueIterator();
958 while (it.next()) |mapping| {
960959 if (self.text_segment_cmd_index.? == mapping.target_seg_id) {
961960 const new_index = text_index_mapping.get(mapping.target_sect_id) orelse unreachable;
962961 mapping.target_sect_id = new_index;
......@@ -1400,16 +1399,16 @@ fn resolveSymbolsInObject(self: *Zld, object: *Object) !void {
14001399 if (sym.cast(Symbol.Regular)) |reg| {
14011400 if (reg.linkage == .translation_unit) continue; // Symbol local to TU.
14021401
1403 if (self.unresolved.swapRemove(sym.name)) |entry| {
1402 if (self.unresolved.fetchSwapRemove(sym.name)) |kv| {
14041403 // Create link to the global.
1405 entry.value.alias = sym;
1404 kv.value.alias = sym;
14061405 }
1407 const entry = self.globals.getEntry(sym.name) orelse {
1406 const sym_ptr = self.globals.getPtr(sym.name) orelse {
14081407 // Put new global symbol into the symbol table.
14091408 try self.globals.putNoClobber(self.allocator, sym.name, sym);
14101409 continue;
14111410 };
1412 const g_sym = entry.value;
1411 const g_sym = sym_ptr.*;
14131412 const g_reg = g_sym.cast(Symbol.Regular) orelse unreachable;
14141413
14151414 switch (g_reg.linkage) {
......@@ -1432,7 +1431,7 @@ fn resolveSymbolsInObject(self: *Zld, object: *Object) !void {
14321431 }
14331432
14341433 g_sym.alias = sym;
1435 entry.value = sym;
1434 sym_ptr.* = sym;
14361435 } else if (sym.cast(Symbol.Unresolved)) |und| {
14371436 if (self.globals.get(sym.name)) |g_sym| {
14381437 sym.alias = g_sym;
......@@ -1458,8 +1457,7 @@ fn resolveSymbols(self: *Zld) !void {
14581457 while (true) {
14591458 if (next_sym == self.unresolved.count()) break;
14601459
1461 const entry = self.unresolved.items()[next_sym];
1462 const sym = entry.value;
1460 const sym = self.unresolved.values()[next_sym];
14631461
14641462 var reset: bool = false;
14651463 for (self.archives.items) |archive| {
......@@ -1492,8 +1490,8 @@ fn resolveSymbols(self: *Zld) !void {
14921490 defer unresolved.deinit();
14931491
14941492 try unresolved.ensureCapacity(self.unresolved.count());
1495 for (self.unresolved.items()) |entry| {
1496 unresolved.appendAssumeCapacity(entry.value);
1493 for (self.unresolved.values()) |value| {
1494 unresolved.appendAssumeCapacity(value);
14971495 }
14981496 self.unresolved.clearAndFree(self.allocator);
14991497
......@@ -2780,8 +2778,7 @@ fn writeSymbolTable(self: *Zld) !void {
27802778 var undefs = std.ArrayList(macho.nlist_64).init(self.allocator);
27812779 defer undefs.deinit();
27822780
2783 for (self.imports.items()) |entry| {
2784 const sym = entry.value;
2781 for (self.imports.values()) |sym| {
27852782 const ordinal = ordinal: {
27862783 const dylib = sym.cast(Symbol.Proxy).?.dylib orelse break :ordinal 1; // TODO handle libSystem
27872784 break :ordinal dylib.ordinal.?;
......@@ -3071,9 +3068,9 @@ pub fn parseName(name: *const [16]u8) []const u8 {
30713068
30723069fn printSymbols(self: *Zld) void {
30733070 log.debug("globals", .{});
3074 for (self.globals.items()) |entry| {
3075 const sym = entry.value.cast(Symbol.Regular) orelse unreachable;
3076 log.debug(" | {s} @ {*}", .{ sym.base.name, entry.value });
3071 for (self.globals.values()) |value| {
3072 const sym = value.cast(Symbol.Regular) orelse unreachable;
3073 log.debug(" | {s} @ {*}", .{ sym.base.name, value });
30773074 log.debug(" => alias of {*}", .{sym.base.alias});
30783075 log.debug(" => linkage {s}", .{sym.linkage});
30793076 log.debug(" => defined in {s}", .{sym.file.name.?});
......@@ -3091,9 +3088,9 @@ fn printSymbols(self: *Zld) void {
30913088 }
30923089 }
30933090 log.debug("proxies", .{});
3094 for (self.imports.items()) |entry| {
3095 const sym = entry.value.cast(Symbol.Proxy) orelse unreachable;
3096 log.debug(" | {s} @ {*}", .{ sym.base.name, entry.value });
3091 for (self.imports.values()) |value| {
3092 const sym = value.cast(Symbol.Proxy) orelse unreachable;
3093 log.debug(" | {s} @ {*}", .{ sym.base.name, value });
30973094 log.debug(" => alias of {*}", .{sym.base.alias});
30983095 log.debug(" => defined in libSystem.B.dylib", .{});
30993096 }
src/link/SpirV.zig+3-5
......@@ -114,7 +114,7 @@ pub fn updateDeclExports(
114114) !void {}
115115
116116pub fn freeDecl(self: *SpirV, decl: *Module.Decl) void {
117 self.decl_table.removeAssertDiscard(decl);
117 assert(self.decl_table.swapRemove(decl));
118118}
119119
120120pub fn flush(self: *SpirV, comp: *Compilation) !void {
......@@ -141,8 +141,7 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {
141141 // declarations which don't generate a result?
142142 // TODO: fn_link is used here, but thats probably not the right field. It will work anyway though.
143143 {
144 for (self.decl_table.items()) |entry| {
145 const decl = entry.key;
144 for (self.decl_table.keys()) |decl| {
146145 if (!decl.has_tv) continue;
147146
148147 decl.fn_link.spirv.id = spv.allocResultId();
......@@ -154,8 +153,7 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {
154153 var decl_gen = codegen.DeclGen.init(&spv);
155154 defer decl_gen.deinit();
156155
157 for (self.decl_table.items()) |entry| {
158 const decl = entry.key;
156 for (self.decl_table.keys()) |decl| {
159157 if (!decl.has_tv) continue;
160158
161159 if (try decl_gen.gen(decl)) |msg| {
src/link/Wasm.zig+7-7
......@@ -422,8 +422,8 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void {
422422 const header_offset = try reserveVecSectionHeader(file);
423423 const writer = file.writer();
424424 var count: u32 = 0;
425 for (module.decl_exports.entries.items) |entry| {
426 for (entry.value) |exprt| {
425 for (module.decl_exports.values()) |exports| {
426 for (exports) |exprt| {
427427 // Export name length + name
428428 try leb.writeULEB128(writer, @intCast(u32, exprt.options.name.len));
429429 try writer.writeAll(exprt.options.name);
......@@ -590,8 +590,8 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void {
590590 self.base.releaseLock();
591591
592592 try man.addListOfFiles(self.base.options.objects);
593 for (comp.c_object_table.items()) |entry| {
594 _ = try man.addFile(entry.key.status.success.object_path, null);
593 for (comp.c_object_table.keys()) |key| {
594 _ = try man.addFile(key.status.success.object_path, null);
595595 }
596596 try man.addOptionalFile(module_obj_path);
597597 try man.addOptionalFile(compiler_rt_path);
......@@ -638,7 +638,7 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void {
638638 break :blk self.base.options.objects[0];
639639
640640 if (comp.c_object_table.count() != 0)
641 break :blk comp.c_object_table.items()[0].key.status.success.object_path;
641 break :blk comp.c_object_table.keys()[0].status.success.object_path;
642642
643643 if (module_obj_path) |p|
644644 break :blk p;
......@@ -712,8 +712,8 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void {
712712 // Positional arguments to the linker such as object files.
713713 try argv.appendSlice(self.base.options.objects);
714714
715 for (comp.c_object_table.items()) |entry| {
716 try argv.append(entry.key.status.success.object_path);
715 for (comp.c_object_table.keys()) |key| {
716 try argv.append(key.status.success.object_path);
717717 }
718718 if (module_obj_path) |p| {
719719 try argv.append(p);
src/liveness.zig+28-27
......@@ -2,6 +2,7 @@ const std = @import("std");
22const ir = @import("air.zig");
33const trace = @import("tracy.zig").trace;
44const log = std.log.scoped(.liveness);
5const assert = std.debug.assert;
56
67/// Perform Liveness Analysis over the `Body`. Each `Inst` will have its `deaths` field populated.
78pub fn analyze(
......@@ -86,9 +87,9 @@ fn analyzeInst(
8687
8788 // Reset the table back to its state from before the branch.
8889 {
89 var it = then_table.iterator();
90 while (it.next()) |entry| {
91 table.removeAssertDiscard(entry.key);
90 var it = then_table.keyIterator();
91 while (it.next()) |key| {
92 assert(table.remove(key.*));
9293 }
9394 }
9495
......@@ -102,9 +103,9 @@ fn analyzeInst(
102103 defer else_entry_deaths.deinit();
103104
104105 {
105 var it = else_table.iterator();
106 while (it.next()) |entry| {
107 const else_death = entry.key;
106 var it = else_table.keyIterator();
107 while (it.next()) |key| {
108 const else_death = key.*;
108109 if (!then_table.contains(else_death)) {
109110 try then_entry_deaths.append(else_death);
110111 }
......@@ -113,9 +114,9 @@ fn analyzeInst(
113114 // This loop is the same, except it's for the then branch, and it additionally
114115 // has to put its items back into the table to undo the reset.
115116 {
116 var it = then_table.iterator();
117 while (it.next()) |entry| {
118 const then_death = entry.key;
117 var it = then_table.keyIterator();
118 while (it.next()) |key| {
119 const then_death = key.*;
119120 if (!else_table.contains(then_death)) {
120121 try else_entry_deaths.append(then_death);
121122 }
......@@ -125,13 +126,13 @@ fn analyzeInst(
125126 // Now we have to correctly populate new_set.
126127 if (new_set) |ns| {
127128 try ns.ensureCapacity(@intCast(u32, ns.count() + then_table.count() + else_table.count()));
128 var it = then_table.iterator();
129 while (it.next()) |entry| {
130 _ = ns.putAssumeCapacity(entry.key, {});
129 var it = then_table.keyIterator();
130 while (it.next()) |key| {
131 _ = ns.putAssumeCapacity(key.*, {});
131132 }
132 it = else_table.iterator();
133 while (it.next()) |entry| {
134 _ = ns.putAssumeCapacity(entry.key, {});
133 it = else_table.keyIterator();
134 while (it.next()) |key| {
135 _ = ns.putAssumeCapacity(key.*, {});
135136 }
136137 }
137138 inst.then_death_count = std.math.cast(@TypeOf(inst.then_death_count), then_entry_deaths.items.len) catch return error.OutOfMemory;
......@@ -159,18 +160,18 @@ fn analyzeInst(
159160 try analyzeWithTable(arena, table, &case_tables[i], case.body);
160161
161162 // Reset the table back to its state from before the case.
162 var it = case_tables[i].iterator();
163 while (it.next()) |entry| {
164 table.removeAssertDiscard(entry.key);
163 var it = case_tables[i].keyIterator();
164 while (it.next()) |key| {
165 assert(table.remove(key.*));
165166 }
166167 }
167168 { // else
168169 try analyzeWithTable(arena, table, &case_tables[case_tables.len - 1], inst.else_body);
169170
170171 // Reset the table back to its state from before the case.
171 var it = case_tables[case_tables.len - 1].iterator();
172 while (it.next()) |entry| {
173 table.removeAssertDiscard(entry.key);
172 var it = case_tables[case_tables.len - 1].keyIterator();
173 while (it.next()) |key| {
174 assert(table.remove(key.*));
174175 }
175176 }
176177
......@@ -184,9 +185,9 @@ fn analyzeInst(
184185 var total_deaths: u32 = 0;
185186 for (case_tables) |*ct, i| {
186187 total_deaths += ct.count();
187 var it = ct.iterator();
188 while (it.next()) |entry| {
189 const case_death = entry.key;
188 var it = ct.keyIterator();
189 while (it.next()) |key| {
190 const case_death = key.*;
190191 for (case_tables) |*ct_inner, j| {
191192 if (i == j) continue;
192193 if (!ct_inner.contains(case_death)) {
......@@ -203,9 +204,9 @@ fn analyzeInst(
203204 if (new_set) |ns| {
204205 try ns.ensureCapacity(@intCast(u32, ns.count() + total_deaths));
205206 for (case_tables) |*ct| {
206 var it = ct.iterator();
207 while (it.next()) |entry| {
208 _ = ns.putAssumeCapacity(entry.key, {});
207 var it = ct.keyIterator();
208 while (it.next()) |key| {
209 _ = ns.putAssumeCapacity(key.*, {});
209210 }
210211 }
211212 }
src/main.zig+6-6
......@@ -180,7 +180,7 @@ pub fn mainArgs(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !v
180180 "in order to determine where libc is installed. However the system C " ++
181181 "compiler is `zig cc`, so no libc installation was found.", .{});
182182 }
183 try env_map.set(inf_loop_env_key, "1");
183 try env_map.put(inf_loop_env_key, "1");
184184
185185 // Some programs such as CMake will strip the `cc` and subsequent args from the
186186 // CC environment variable. We detect and support this scenario here because of
......@@ -2310,9 +2310,9 @@ fn updateModule(gpa: *Allocator, comp: *Compilation, hook: AfterUpdateHook) !voi
23102310
23112311fn freePkgTree(gpa: *Allocator, pkg: *Package, free_parent: bool) void {
23122312 {
2313 var it = pkg.table.iterator();
2314 while (it.next()) |kv| {
2315 freePkgTree(gpa, kv.value, true);
2313 var it = pkg.table.valueIterator();
2314 while (it.next()) |value| {
2315 freePkgTree(gpa, value.*, true);
23162316 }
23172317 }
23182318 if (free_parent) {
......@@ -3895,7 +3895,7 @@ pub fn cmdChangelist(
38953895 var it = inst_map.iterator();
38963896 while (it.next()) |entry| {
38973897 try stdout.print(" %{d} => %{d}\n", .{
3898 entry.key, entry.value,
3898 entry.key_ptr.*, entry.value_ptr.*,
38993899 });
39003900 }
39013901 }
......@@ -3904,7 +3904,7 @@ pub fn cmdChangelist(
39043904 var it = extra_map.iterator();
39053905 while (it.next()) |entry| {
39063906 try stdout.print(" {d} => {d}\n", .{
3907 entry.key, entry.value,
3907 entry.key_ptr.*, entry.value_ptr.*,
39083908 });
39093909 }
39103910 }
src/musl.zig+4-3
......@@ -135,9 +135,10 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {
135135
136136 const s = path.sep_str;
137137
138 for (source_table.items()) |entry| {
139 const src_file = entry.key;
140 const ext = entry.value;
138 var it = source_table.iterator();
139 while (it.next()) |entry| {
140 const src_file = entry.key_ptr.*;
141 const ext = entry.value_ptr.*;
141142
142143 const dirname = path.dirname(src_file).?;
143144 const basename = path.basename(src_file);
src/translate_c.zig+5-5
......@@ -453,7 +453,7 @@ fn declVisitorNamesOnly(c: *Context, decl: *const clang.Decl) Error!void {
453453 // Don't put this one in `decl_table` so it's processed later.
454454 return;
455455 }
456 result.entry.value = name;
456 result.value_ptr.* = name;
457457 // Put this typedef in the decl_table to avoid redefinitions.
458458 try c.decl_table.putNoClobber(c.gpa, @ptrToInt(typedef_decl.getCanonicalDecl()), name);
459459 }
......@@ -5765,14 +5765,14 @@ fn getFnProto(c: *Context, ref: Node) ?*ast.Payload.Func {
57655765
57665766fn addMacros(c: *Context) !void {
57675767 var it = c.global_scope.macro_table.iterator();
5768 while (it.next()) |kv| {
5769 if (getFnProto(c, kv.value)) |proto_node| {
5768 while (it.next()) |entry| {
5769 if (getFnProto(c, entry.value_ptr.*)) |proto_node| {
57705770 // If a macro aliases a global variable which is a function pointer, we conclude that
57715771 // the macro is intended to represent a function that assumes the function pointer
57725772 // variable is non-null and calls it.
5773 try addTopLevelDecl(c, kv.key, try transCreateNodeMacroFn(c, kv.key, kv.value, proto_node));
5773 try addTopLevelDecl(c, entry.key_ptr.*, try transCreateNodeMacroFn(c, entry.key_ptr.*, entry.value_ptr.*, proto_node));
57745774 } else {
5775 try addTopLevelDecl(c, kv.key, kv.value);
5775 try addTopLevelDecl(c, entry.key_ptr.*, entry.value_ptr.*);
57765776 }
57775777 }
57785778}
src/type.zig+29-24
......@@ -596,6 +596,15 @@ pub const Type = extern union {
596596 return hasher.final();
597597 }
598598
599 pub const HashContext = struct {
600 pub fn hash(self: @This(), t: Type) u64 {
601 return t.hash();
602 }
603 pub fn eql(self: @This(), a: Type, b: Type) bool {
604 return a.eql(b);
605 }
606 };
607
599608 pub fn copy(self: Type, allocator: *Allocator) error{OutOfMemory}!Type {
600609 if (self.tag_if_small_enough < Tag.no_payload_count) {
601610 return Type{ .tag_if_small_enough = self.tag_if_small_enough };
......@@ -1147,8 +1156,8 @@ pub const Type = extern union {
11471156 .@"struct" => {
11481157 // TODO introduce lazy value mechanism
11491158 const struct_obj = self.castTag(.@"struct").?.data;
1150 for (struct_obj.fields.entries.items) |entry| {
1151 if (entry.value.ty.hasCodeGenBits())
1159 for (struct_obj.fields.values()) |value| {
1160 if (value.ty.hasCodeGenBits())
11521161 return true;
11531162 } else {
11541163 return false;
......@@ -1169,8 +1178,8 @@ pub const Type = extern union {
11691178 },
11701179 .@"union" => {
11711180 const union_obj = self.castTag(.@"union").?.data;
1172 for (union_obj.fields.entries.items) |entry| {
1173 if (entry.value.ty.hasCodeGenBits())
1181 for (union_obj.fields.values()) |value| {
1182 if (value.ty.hasCodeGenBits())
11741183 return true;
11751184 } else {
11761185 return false;
......@@ -1181,8 +1190,8 @@ pub const Type = extern union {
11811190 if (union_obj.tag_ty.hasCodeGenBits()) {
11821191 return true;
11831192 }
1184 for (union_obj.fields.entries.items) |entry| {
1185 if (entry.value.ty.hasCodeGenBits())
1193 for (union_obj.fields.values()) |value| {
1194 if (value.ty.hasCodeGenBits())
11861195 return true;
11871196 } else {
11881197 return false;
......@@ -1380,10 +1389,9 @@ pub const Type = extern union {
13801389 // like we have in stage1.
13811390 const struct_obj = self.castTag(.@"struct").?.data;
13821391 var biggest: u32 = 0;
1383 for (struct_obj.fields.entries.items) |entry| {
1384 const field_ty = entry.value.ty;
1385 if (!field_ty.hasCodeGenBits()) continue;
1386 const field_align = field_ty.abiAlignment(target);
1392 for (struct_obj.fields.values()) |field| {
1393 if (!field.ty.hasCodeGenBits()) continue;
1394 const field_align = field.ty.abiAlignment(target);
13871395 if (field_align > biggest) {
13881396 return field_align;
13891397 }
......@@ -1399,10 +1407,9 @@ pub const Type = extern union {
13991407 .union_tagged => {
14001408 const union_obj = self.castTag(.union_tagged).?.data;
14011409 var biggest: u32 = union_obj.tag_ty.abiAlignment(target);
1402 for (union_obj.fields.entries.items) |entry| {
1403 const field_ty = entry.value.ty;
1404 if (!field_ty.hasCodeGenBits()) continue;
1405 const field_align = field_ty.abiAlignment(target);
1410 for (union_obj.fields.values()) |field| {
1411 if (!field.ty.hasCodeGenBits()) continue;
1412 const field_align = field.ty.abiAlignment(target);
14061413 if (field_align > biggest) {
14071414 biggest = field_align;
14081415 }
......@@ -1413,10 +1420,9 @@ pub const Type = extern union {
14131420 .@"union" => {
14141421 const union_obj = self.castTag(.@"union").?.data;
14151422 var biggest: u32 = 0;
1416 for (union_obj.fields.entries.items) |entry| {
1417 const field_ty = entry.value.ty;
1418 if (!field_ty.hasCodeGenBits()) continue;
1419 const field_align = field_ty.abiAlignment(target);
1423 for (union_obj.fields.values()) |field| {
1424 if (!field.ty.hasCodeGenBits()) continue;
1425 const field_align = field.ty.abiAlignment(target);
14201426 if (field_align > biggest) {
14211427 biggest = field_align;
14221428 }
......@@ -2415,9 +2421,8 @@ pub const Type = extern union {
24152421 .@"struct" => {
24162422 const s = ty.castTag(.@"struct").?.data;
24172423 assert(s.haveFieldTypes());
2418 for (s.fields.entries.items) |entry| {
2419 const field_ty = entry.value.ty;
2420 if (field_ty.onePossibleValue() == null) {
2424 for (s.fields.values()) |field| {
2425 if (field.ty.onePossibleValue() == null) {
24212426 return null;
24222427 }
24232428 }
......@@ -2426,7 +2431,7 @@ pub const Type = extern union {
24262431 .enum_full => {
24272432 const enum_full = ty.castTag(.enum_full).?.data;
24282433 if (enum_full.fields.count() == 1) {
2429 return enum_full.values.entries.items[0].key;
2434 return enum_full.values.keys()[0];
24302435 } else {
24312436 return null;
24322437 }
......@@ -2583,11 +2588,11 @@ pub const Type = extern union {
25832588 switch (ty.tag()) {
25842589 .enum_full, .enum_nonexhaustive => {
25852590 const enum_full = ty.cast(Payload.EnumFull).?.data;
2586 return enum_full.fields.entries.items[field_index].key;
2591 return enum_full.fields.keys()[field_index];
25872592 },
25882593 .enum_simple => {
25892594 const enum_simple = ty.castTag(.enum_simple).?.data;
2590 return enum_simple.fields.entries.items[field_index].key;
2595 return enum_simple.fields.keys()[field_index];
25912596 },
25922597 .atomic_ordering,
25932598 .atomic_rmw_op,
src/value.zig+17
......@@ -1256,6 +1256,23 @@ pub const Value = extern union {
12561256 return hasher.final();
12571257 }
12581258
1259 pub const ArrayHashContext = struct {
1260 pub fn hash(self: @This(), v: Value) u32 {
1261 return v.hash_u32();
1262 }
1263 pub fn eql(self: @This(), a: Value, b: Value) bool {
1264 return a.eql(b);
1265 }
1266 };
1267 pub const HashContext = struct {
1268 pub fn hash(self: @This(), v: Value) u64 {
1269 return v.hash();
1270 }
1271 pub fn eql(self: @This(), a: Value, b: Value) bool {
1272 return a.eql(b);
1273 }
1274 };
1275
12591276 /// Asserts the value is a pointer and dereferences it.
12601277 /// Returns error.AnalysisFail if the pointer points to a Decl that failed semantic analysis.
12611278 pub fn pointerDeref(self: Value, allocator: *Allocator) error{ AnalysisFail, OutOfMemory }!Value {
test/behavior/union.zig+2-2
......@@ -107,11 +107,11 @@ test "union with specified enum tag" {
107107 comptime try doTest();
108108}
109109
110fn doTest() !void {
110fn doTest() error{TestUnexpectedResult}!void {
111111 try expect((try bar(Payload{ .A = 1234 })) == -10);
112112}
113113
114fn bar(value: Payload) !i32 {
114fn bar(value: Payload) error{TestUnexpectedResult}!i32 {
115115 try expect(@as(Letter, value) == Letter.A);
116116 return switch (value) {
117117 Payload.A => |x| return x - 1244,
tools/process_headers.zig+12-12
......@@ -377,14 +377,14 @@ pub fn main() !void {
377377 const gop = try hash_to_contents.getOrPut(hash);
378378 if (gop.found_existing) {
379379 max_bytes_saved += raw_bytes.len;
380 gop.entry.value.hit_count += 1;
380 gop.value_ptr.hit_count += 1;
381381 std.debug.warn("duplicate: {s} {s} ({:2})\n", .{
382382 libc_target.name,
383383 rel_path,
384384 std.fmt.fmtIntSizeDec(raw_bytes.len),
385385 });
386386 } else {
387 gop.entry.value = Contents{
387 gop.value_ptr.* = Contents{
388388 .bytes = trimmed,
389389 .hit_count = 1,
390390 .hash = hash,
......@@ -392,10 +392,10 @@ pub fn main() !void {
392392 };
393393 }
394394 const path_gop = try path_table.getOrPut(rel_path);
395 const target_to_hash = if (path_gop.found_existing) path_gop.entry.value else blk: {
395 const target_to_hash = if (path_gop.found_existing) path_gop.value_ptr.* else blk: {
396396 const ptr = try allocator.create(TargetToHash);
397397 ptr.* = TargetToHash.init(allocator);
398 path_gop.entry.value = ptr;
398 path_gop.value_ptr.* = ptr;
399399 break :blk ptr;
400400 };
401401 try target_to_hash.putNoClobber(dest_target, hash);
......@@ -423,9 +423,9 @@ pub fn main() !void {
423423 while (path_it.next()) |path_kv| {
424424 var contents_list = std.ArrayList(*Contents).init(allocator);
425425 {
426 var hash_it = path_kv.value.iterator();
426 var hash_it = path_kv.value.*.iterator();
427427 while (hash_it.next()) |hash_kv| {
428 const contents = &hash_to_contents.getEntry(hash_kv.value).?.value;
428 const contents = hash_to_contents.get(hash_kv.value.*).?;
429429 try contents_list.append(contents);
430430 }
431431 }
......@@ -433,7 +433,7 @@ pub fn main() !void {
433433 const best_contents = contents_list.popOrNull().?;
434434 if (best_contents.hit_count > 1) {
435435 // worth it to make it generic
436 const full_path = try std.fs.path.join(allocator, &[_][]const u8{ out_dir, generic_name, path_kv.key });
436 const full_path = try std.fs.path.join(allocator, &[_][]const u8{ out_dir, generic_name, path_kv.key.* });
437437 try std.fs.cwd().makePath(std.fs.path.dirname(full_path).?);
438438 try std.fs.cwd().writeFile(full_path, best_contents.bytes);
439439 best_contents.is_generic = true;
......@@ -443,17 +443,17 @@ pub fn main() !void {
443443 missed_opportunity_bytes += this_missed_bytes;
444444 std.debug.warn("Missed opportunity ({:2}): {s}\n", .{
445445 std.fmt.fmtIntSizeDec(this_missed_bytes),
446 path_kv.key,
446 path_kv.key.*,
447447 });
448448 } else break;
449449 }
450450 }
451 var hash_it = path_kv.value.iterator();
451 var hash_it = path_kv.value.*.iterator();
452452 while (hash_it.next()) |hash_kv| {
453 const contents = &hash_to_contents.getEntry(hash_kv.value).?.value;
453 const contents = hash_to_contents.get(hash_kv.value.*).?;
454454 if (contents.is_generic) continue;
455455
456 const dest_target = hash_kv.key;
456 const dest_target = hash_kv.key.*;
457457 const arch_name = switch (dest_target.arch) {
458458 .specific => |a| @tagName(a),
459459 else => @tagName(dest_target.arch),
......@@ -463,7 +463,7 @@ pub fn main() !void {
463463 @tagName(dest_target.os),
464464 @tagName(dest_target.abi),
465465 });
466 const full_path = try std.fs.path.join(allocator, &[_][]const u8{ out_dir, out_subpath, path_kv.key });
466 const full_path = try std.fs.path.join(allocator, &[_][]const u8{ out_dir, out_subpath, path_kv.key.* });
467467 try std.fs.cwd().makePath(std.fs.path.dirname(full_path).?);
468468 try std.fs.cwd().writeFile(full_path, contents.bytes);
469469 }
tools/update_clang_options.zig+3-3
......@@ -413,12 +413,12 @@ pub fn main() anyerror!void {
413413 var it = root_map.iterator();
414414 it_map: while (it.next()) |kv| {
415415 if (kv.key.len == 0) continue;
416 if (kv.key[0] == '!') continue;
417 if (kv.value != .Object) continue;
416 if (kv.key.*[0] == '!') continue;
417 if (kv.value.* != .Object) continue;
418418 if (!kv.value.Object.contains("NumArgs")) continue;
419419 if (!kv.value.Object.contains("Name")) continue;
420420 for (blacklisted_options) |blacklisted_key| {
421 if (std.mem.eql(u8, blacklisted_key, kv.key)) continue :it_map;
421 if (std.mem.eql(u8, blacklisted_key, kv.key.*)) continue :it_map;
422422 }
423423 if (kv.value.Object.get("Name").?.String.len == 0) continue;
424424 try all_objects.append(&kv.value.Object);
tools/update_cpu_features.zig+17-17
......@@ -903,8 +903,8 @@ fn processOneTarget(job: Job) anyerror!void {
903903 var it = root_map.iterator();
904904 root_it: while (it.next()) |kv| {
905905 if (kv.key.len == 0) continue;
906 if (kv.key[0] == '!') continue;
907 if (kv.value != .Object) continue;
906 if (kv.key.*[0] == '!') continue;
907 if (kv.value.* != .Object) continue;
908908 if (hasSuperclass(&kv.value.Object, "SubtargetFeature")) {
909909 const llvm_name = kv.value.Object.get("Name").?.String;
910910 if (llvm_name.len == 0) continue;
......@@ -917,7 +917,7 @@ fn processOneTarget(job: Job) anyerror!void {
917917 const implies = kv.value.Object.get("Implies").?.Array;
918918 for (implies.items) |imply| {
919919 const other_key = imply.Object.get("def").?.String;
920 const other_obj = &root_map.getEntry(other_key).?.value.Object;
920 const other_obj = &root_map.getPtr(other_key).?.Object;
921921 const other_llvm_name = other_obj.get("Name").?.String;
922922 const other_zig_name = (try llvmNameToZigNameOmit(
923923 arena,
......@@ -969,7 +969,7 @@ fn processOneTarget(job: Job) anyerror!void {
969969 const features = kv.value.Object.get("Features").?.Array;
970970 for (features.items) |feature| {
971971 const feature_key = feature.Object.get("def").?.String;
972 const feature_obj = &root_map.getEntry(feature_key).?.value.Object;
972 const feature_obj = &root_map.getPtr(feature_key).?.Object;
973973 const feature_llvm_name = feature_obj.get("Name").?.String;
974974 if (feature_llvm_name.len == 0) continue;
975975 const feature_zig_name = (try llvmNameToZigNameOmit(
......@@ -982,7 +982,7 @@ fn processOneTarget(job: Job) anyerror!void {
982982 const tune_features = kv.value.Object.get("TuneFeatures").?.Array;
983983 for (tune_features.items) |feature| {
984984 const feature_key = feature.Object.get("def").?.String;
985 const feature_obj = &root_map.getEntry(feature_key).?.value.Object;
985 const feature_obj = &root_map.getPtr(feature_key).?.Object;
986986 const feature_llvm_name = feature_obj.get("Name").?.String;
987987 if (feature_llvm_name.len == 0) continue;
988988 const feature_zig_name = (try llvmNameToZigNameOmit(
......@@ -1109,9 +1109,9 @@ fn processOneTarget(job: Job) anyerror!void {
11091109 try pruneFeatures(arena, features_table, &deps_set);
11101110 var dependencies = std.ArrayList([]const u8).init(arena);
11111111 {
1112 var it = deps_set.iterator();
1113 while (it.next()) |entry| {
1114 try dependencies.append(entry.key);
1112 var it = deps_set.keyIterator();
1113 while (it.next()) |key| {
1114 try dependencies.append(key.*);
11151115 }
11161116 }
11171117 std.sort.sort([]const u8, dependencies.items, {}, asciiLessThan);
......@@ -1154,9 +1154,9 @@ fn processOneTarget(job: Job) anyerror!void {
11541154 try pruneFeatures(arena, features_table, &deps_set);
11551155 var cpu_features = std.ArrayList([]const u8).init(arena);
11561156 {
1157 var it = deps_set.iterator();
1158 while (it.next()) |entry| {
1159 try cpu_features.append(entry.key);
1157 var it = deps_set.keyIterator();
1158 while (it.next()) |key| {
1159 try cpu_features.append(key.*);
11601160 }
11611161 }
11621162 std.sort.sort([]const u8, cpu_features.items, {}, asciiLessThan);
......@@ -1278,16 +1278,16 @@ fn pruneFeatures(
12781278 // Then, iterate over the deletion set and delete all that stuff from `deps_set`.
12791279 var deletion_set = std.StringHashMap(void).init(arena);
12801280 {
1281 var it = deps_set.iterator();
1282 while (it.next()) |entry| {
1283 const feature = features_table.get(entry.key).?;
1281 var it = deps_set.keyIterator();
1282 while (it.next()) |key| {
1283 const feature = features_table.get(key.*).?;
12841284 try walkFeatures(features_table, &deletion_set, feature);
12851285 }
12861286 }
12871287 {
1288 var it = deletion_set.iterator();
1289 while (it.next()) |entry| {
1290 _ = deps_set.remove(entry.key);
1288 var it = deletion_set.keyIterator();
1289 while (it.next()) |key| {
1290 _ = deps_set.remove(key.*);
12911291 }
12921292 }
12931293}
tools/update_glibc.zig+22-22
......@@ -148,12 +148,12 @@ pub fn main() !void {
148148 for (abi_lists) |*abi_list| {
149149 const target_funcs_gop = try target_functions.getOrPut(@ptrToInt(abi_list));
150150 if (!target_funcs_gop.found_existing) {
151 target_funcs_gop.entry.value = FunctionSet{
151 target_funcs_gop.value_ptr.* = FunctionSet{
152152 .list = std.ArrayList(VersionedFn).init(allocator),
153153 .fn_vers_list = FnVersionList.init(allocator),
154154 };
155155 }
156 const fn_set = &target_funcs_gop.entry.value.list;
156 const fn_set = &target_funcs_gop.value_ptr.list;
157157
158158 for (lib_names) |lib_name, lib_name_index| {
159159 const lib_prefix = if (std.mem.eql(u8, lib_name, "ld")) "" else "lib";
......@@ -203,11 +203,11 @@ pub fn main() !void {
203203 try global_ver_set.put(ver, undefined);
204204 const gop = try global_fn_set.getOrPut(name);
205205 if (gop.found_existing) {
206 if (!std.mem.eql(u8, gop.entry.value.lib, "c")) {
207 gop.entry.value.lib = lib_name;
206 if (!std.mem.eql(u8, gop.value_ptr.lib, "c")) {
207 gop.value_ptr.lib = lib_name;
208208 }
209209 } else {
210 gop.entry.value = Function{
210 gop.value_ptr.* = Function{
211211 .name = name,
212212 .lib = lib_name,
213213 .index = undefined,
......@@ -223,15 +223,15 @@ pub fn main() !void {
223223
224224 const global_fn_list = blk: {
225225 var list = std.ArrayList([]const u8).init(allocator);
226 var it = global_fn_set.iterator();
227 while (it.next()) |entry| try list.append(entry.key);
226 var it = global_fn_set.keyIterator();
227 while (it.next()) |key| try list.append(key.*);
228228 std.sort.sort([]const u8, list.items, {}, strCmpLessThan);
229229 break :blk list.items;
230230 };
231231 const global_ver_list = blk: {
232232 var list = std.ArrayList([]const u8).init(allocator);
233 var it = global_ver_set.iterator();
234 while (it.next()) |entry| try list.append(entry.key);
233 var it = global_ver_set.keyIterator();
234 while (it.next()) |key| try list.append(key.*);
235235 std.sort.sort([]const u8, list.items, {}, versionLessThan);
236236 break :blk list.items;
237237 };
......@@ -254,9 +254,9 @@ pub fn main() !void {
254254 var buffered = std.io.bufferedWriter(fns_txt_file.writer());
255255 const fns_txt = buffered.writer();
256256 for (global_fn_list) |name, i| {
257 const entry = global_fn_set.getEntry(name).?;
258 entry.value.index = i;
259 try fns_txt.print("{s} {s}\n", .{ name, entry.value.lib });
257 const value = global_fn_set.getPtr(name).?;
258 value.index = i;
259 try fns_txt.print("{s} {s}\n", .{ name, value.lib });
260260 }
261261 try buffered.flush();
262262 }
......@@ -264,16 +264,16 @@ pub fn main() !void {
264264 // Now the mapping of version and function to integer index is complete.
265265 // Here we create a mapping of function name to list of versions.
266266 for (abi_lists) |*abi_list, abi_index| {
267 const entry = target_functions.getEntry(@ptrToInt(abi_list)).?;
268 const fn_vers_list = &entry.value.fn_vers_list;
269 for (entry.value.list.items) |*ver_fn| {
267 const value = target_functions.getPtr(@ptrToInt(abi_list)).?;
268 const fn_vers_list = &value.fn_vers_list;
269 for (value.list.items) |*ver_fn| {
270270 const gop = try fn_vers_list.getOrPut(ver_fn.name);
271271 if (!gop.found_existing) {
272 gop.entry.value = std.ArrayList(usize).init(allocator);
272 gop.value_ptr.* = std.ArrayList(usize).init(allocator);
273273 }
274 const ver_index = global_ver_set.getEntry(ver_fn.ver).?.value;
275 if (std.mem.indexOfScalar(usize, gop.entry.value.items, ver_index) == null) {
276 try gop.entry.value.append(ver_index);
274 const ver_index = global_ver_set.get(ver_fn.ver).?;
275 if (std.mem.indexOfScalar(usize, gop.value_ptr.items, ver_index) == null) {
276 try gop.value_ptr.append(ver_index);
277277 }
278278 }
279279 }
......@@ -287,7 +287,7 @@ pub fn main() !void {
287287
288288 // first iterate over the abi lists
289289 for (abi_lists) |*abi_list, abi_index| {
290 const fn_vers_list = &target_functions.getEntry(@ptrToInt(abi_list)).?.value.fn_vers_list;
290 const fn_vers_list = &target_functions.getPtr(@ptrToInt(abi_list)).?.fn_vers_list;
291291 for (abi_list.targets) |target, it_i| {
292292 if (it_i != 0) try abilist_txt.writeByte(' ');
293293 try abilist_txt.print("{s}-linux-{s}", .{ @tagName(target.arch), @tagName(target.abi) });
......@@ -295,11 +295,11 @@ pub fn main() !void {
295295 try abilist_txt.writeByte('\n');
296296 // next, each line implicitly corresponds to a function
297297 for (global_fn_list) |name| {
298 const entry = fn_vers_list.getEntry(name) orelse {
298 const value = fn_vers_list.getPtr(name) orelse {
299299 try abilist_txt.writeByte('\n');
300300 continue;
301301 };
302 for (entry.value.items) |ver_index, it_i| {
302 for (value.items) |ver_index, it_i| {
303303 if (it_i != 0) try abilist_txt.writeByte(' ');
304304 try abilist_txt.print("{d}", .{ver_index});
305305 }