| author | |
| committer | |
| log | fc9430f56798a53f9393a697f4ccd6bf9981b970 |
| tree | 69a1a3b359e970349f9466f85a370918d78b7217 |
| parent | 87dae0ce98fde1957a9290c22866b3101ce419d8 |
- hash/eql functions moved into a Context object
- *Context functions pass an explicit context
- *Adapted functions pass specialized keys and contexts
- new getPtr() function returns a pointer to value
- remove functions renamed to fetchRemove
- new remove functions return bool
- removeAssertDiscard deleted, use assert(remove(...)) instead
- Keys and values are stored in separate arrays
- Entry is now {*K, *V}, the new KV is {K, V}
- BufSet/BufMap functions renamed to match other set/map types
- fixed iterating-while-modifying bug in src/link/C.zig49 files changed, 3210 insertions(+), 1528 deletions(-)
doc/docgen.zig+3-3| ... | ... | @@ -404,9 +404,9 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { |
| 404 | 404 | .n = header_stack_size, |
| 405 | 405 | }, |
| 406 | 406 | }); |
| 407 | if (try urls.fetchPut(urlized, tag_token)) |entry| { | |
| 407 | if (try urls.fetchPut(urlized, tag_token)) |kv| { | |
| 408 | 408 | 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 {}; | |
| 410 | 410 | return error.ParseError; |
| 411 | 411 | } |
| 412 | 412 | if (last_action == Action.Open) { |
| ... | ... | @@ -1023,7 +1023,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any |
| 1023 | 1023 | defer root_node.end(); |
| 1024 | 1024 | |
| 1025 | 1025 | 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"); | |
| 1027 | 1027 | |
| 1028 | 1028 | const builtin_code = try getBuiltinCode(allocator, &env_map, zig_exe); |
| 1029 | 1029 |
lib/std/array_hash_map.zig+1286-500| ... | ... | @@ -17,23 +17,36 @@ const Allocator = mem.Allocator; |
| 17 | 17 | const builtin = std.builtin; |
| 18 | 18 | const hash_map = @This(); |
| 19 | 19 | |
| 20 | /// An ArrayHashMap with default hash and equal functions. | |
| 21 | /// See AutoContext for a description of the hash and equal implementations. | |
| 20 | 22 | pub 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)); | |
| 22 | 24 | } |
| 23 | 25 | |
| 26 | /// An ArrayHashMapUnmanaged with default hash and equal functions. | |
| 27 | /// See AutoContext for a description of the hash and equal implementations. | |
| 24 | 28 | pub 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)); | |
| 26 | 30 | } |
| 27 | 31 | |
| 28 | 32 | /// Builtin hashmap for strings as keys. |
| 29 | 33 | pub fn StringArrayHashMap(comptime V: type) type { |
| 30 | return ArrayHashMap([]const u8, V, hashString, eqlString, true); | |
| 34 | return ArrayHashMap([]const u8, V, StringContext, true); | |
| 31 | 35 | } |
| 32 | 36 | |
| 33 | 37 | pub fn StringArrayHashMapUnmanaged(comptime V: type) type { |
| 34 | return ArrayHashMapUnmanaged([]const u8, V, hashString, eqlString, true); | |
| 38 | return ArrayHashMapUnmanaged([]const u8, V, StringContext, true); | |
| 35 | 39 | } |
| 36 | 40 | |
| 41 | pub 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 | ||
| 37 | 50 | pub fn eqlString(a: []const u8, b: []const u8) bool { |
| 38 | 51 | return mem.eql(u8, a, b); |
| 39 | 52 | } |
| ... | ... | @@ -54,83 +67,112 @@ pub fn hashString(s: []const u8) u32 { |
| 54 | 67 | /// but only has to call `eql` for hash collisions. |
| 55 | 68 | /// If typical operations (except iteration over entries) need to be faster, prefer |
| 56 | 69 | /// 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 | |
| 57 | 77 | pub fn ArrayHashMap( |
| 58 | 78 | comptime K: type, |
| 59 | 79 | comptime V: type, |
| 60 | comptime hash: fn (key: K) u32, | |
| 61 | comptime eql: fn (a: K, b: K) bool, | |
| 80 | comptime Context: type, | |
| 62 | 81 | comptime store_hash: bool, |
| 63 | 82 | ) type { |
| 83 | comptime std.hash_map.verifyContext(Context, K, K, u32); | |
| 64 | 84 | return struct { |
| 65 | 85 | unmanaged: Unmanaged, |
| 66 | 86 | 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); | |
| 67 | 91 | |
| 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. | |
| 69 | 97 | pub const Entry = Unmanaged.Entry; |
| 70 | pub const Hash = Unmanaged.Hash; | |
| 71 | pub const GetOrPutResult = Unmanaged.GetOrPutResult; | |
| 72 | 98 | |
| 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; | |
| 78 | 101 | |
| 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; | |
| 85 | 106 | |
| 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; | |
| 91 | 121 | |
| 92 | 122 | const Self = @This(); |
| 93 | const Index = Unmanaged.Index; | |
| 94 | 123 | |
| 124 | /// Create an ArrayHashMap instance which will use a specified allocator. | |
| 95 | 125 | 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 { | |
| 96 | 131 | return .{ |
| 97 | 132 | .unmanaged = .{}, |
| 98 | 133 | .allocator = allocator, |
| 134 | .ctx = ctx, | |
| 99 | 135 | }; |
| 100 | 136 | } |
| 101 | 137 | |
| 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. | |
| 112 | 141 | pub fn deinit(self: *Self) void { |
| 113 | 142 | self.unmanaged.deinit(self.allocator); |
| 114 | 143 | self.* = undefined; |
| 115 | 144 | } |
| 116 | 145 | |
| 146 | /// Clears the map but retains the backing allocation for future use. | |
| 117 | 147 | pub fn clearRetainingCapacity(self: *Self) void { |
| 118 | 148 | return self.unmanaged.clearRetainingCapacity(); |
| 119 | 149 | } |
| 120 | 150 | |
| 151 | /// Clears the map and releases the backing allocation | |
| 121 | 152 | pub fn clearAndFree(self: *Self) void { |
| 122 | 153 | return self.unmanaged.clearAndFree(self.allocator); |
| 123 | 154 | } |
| 124 | 155 | |
| 156 | /// Returns the number of KV pairs stored in this map. | |
| 125 | 157 | pub fn count(self: Self) usize { |
| 126 | 158 | return self.unmanaged.count(); |
| 127 | 159 | } |
| 128 | 160 | |
| 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. | |
| 129 | 174 | pub fn iterator(self: *const Self) Iterator { |
| 130 | return Iterator{ | |
| 131 | .hm = self, | |
| 132 | .index = 0, | |
| 133 | }; | |
| 175 | return self.unmanaged.iterator(); | |
| 134 | 176 | } |
| 135 | 177 | |
| 136 | 178 | /// If key exists this function cannot fail. |
| ... | ... | @@ -140,7 +182,10 @@ pub fn ArrayHashMap( |
| 140 | 182 | /// the `Entry` pointer points to it. Caller should then initialize |
| 141 | 183 | /// the value (but not the key). |
| 142 | 184 | 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); | |
| 144 | 189 | } |
| 145 | 190 | |
| 146 | 191 | /// If there is an existing item with `key`, then the result |
| ... | ... | @@ -151,11 +196,13 @@ pub fn ArrayHashMap( |
| 151 | 196 | /// If a new entry needs to be stored, this function asserts there |
| 152 | 197 | /// is enough capacity to store it. |
| 153 | 198 | pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult { |
| 154 | return self.unmanaged.getOrPutAssumeCapacity(key); | |
| 199 | return self.unmanaged.getOrPutAssumeCapacityContext(key, self.ctx); | |
| 155 | 200 | } |
| 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); | |
| 159 | 206 | } |
| 160 | 207 | |
| 161 | 208 | /// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`. |
| ... | ... | @@ -164,14 +211,14 @@ pub fn ArrayHashMap( |
| 164 | 211 | /// Increases capacity, guaranteeing that insertions up until the |
| 165 | 212 | /// `expected_count` will not cause an allocation, and therefore cannot fail. |
| 166 | 213 | 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); | |
| 168 | 215 | } |
| 169 | 216 | |
| 170 | 217 | /// Increases capacity, guaranteeing that insertions up until |
| 171 | 218 | /// `additional_count` **more** items will not cause an allocation, and |
| 172 | 219 | /// therefore cannot fail. |
| 173 | 220 | 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); | |
| 175 | 222 | } |
| 176 | 223 | |
| 177 | 224 | /// Returns the number of total elements which may be present before it is |
| ... | ... | @@ -183,119 +230,187 @@ pub fn ArrayHashMap( |
| 183 | 230 | /// Clobbers any existing data. To detect if a put would clobber |
| 184 | 231 | /// existing data, see `getOrPut`. |
| 185 | 232 | 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); | |
| 187 | 234 | } |
| 188 | 235 | |
| 189 | 236 | /// Inserts a key-value pair into the hash map, asserting that no previous |
| 190 | 237 | /// entry with the same key is already present |
| 191 | 238 | 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); | |
| 193 | 240 | } |
| 194 | 241 | |
| 195 | 242 | /// Asserts there is enough capacity to store the new key-value pair. |
| 196 | 243 | /// Clobbers any existing data. To detect if a put would clobber |
| 197 | 244 | /// existing data, see `getOrPutAssumeCapacity`. |
| 198 | 245 | 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); | |
| 200 | 247 | } |
| 201 | 248 | |
| 202 | 249 | /// Asserts there is enough capacity to store the new key-value pair. |
| 203 | 250 | /// Asserts that it does not clobber any existing data. |
| 204 | 251 | /// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`. |
| 205 | 252 | 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); | |
| 207 | 254 | } |
| 208 | 255 | |
| 209 | 256 | /// 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); | |
| 212 | 259 | } |
| 213 | 260 | |
| 214 | 261 | /// Inserts a new `Entry` into the hash map, returning the previous one, if any. |
| 215 | 262 | /// 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); | |
| 218 | 265 | } |
| 219 | 266 | |
| 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); | |
| 222 | 273 | } |
| 223 | 274 | |
| 275 | /// Finds the index in the `entries` array where a key is stored | |
| 224 | 276 | 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); | |
| 226 | 281 | } |
| 227 | 282 | |
| 283 | /// Find the value associated with a key | |
| 228 | 284 | 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); | |
| 230 | 289 | } |
| 231 | 290 | |
| 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 | |
| 232 | 300 | 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); | |
| 234 | 305 | } |
| 235 | 306 | |
| 236 | 307 | /// If there is an `Entry` with a matching key, it is deleted from |
| 237 | 308 | /// the hash map, and then returned from this function. The entry is |
| 238 | 309 | /// removed from the underlying array by swapping it with the last |
| 239 | 310 | /// 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); | |
| 242 | 316 | } |
| 243 | 317 | |
| 244 | 318 | /// If there is an `Entry` with a matching key, it is deleted from |
| 245 | 319 | /// the hash map, and then returned from this function. The entry is |
| 246 | 320 | /// removed from the underlying array by shifting all elements forward |
| 247 | 321 | /// 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); | |
| 250 | 327 | } |
| 251 | 328 | |
| 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); | |
| 255 | 338 | } |
| 256 | 339 | |
| 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); | |
| 261 | 349 | } |
| 262 | 350 | |
| 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); | |
| 267 | 356 | } |
| 268 | 357 | |
| 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); | |
| 271 | 364 | } |
| 272 | 365 | |
| 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. | |
| 273 | 368 | 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); | |
| 276 | 391 | } |
| 277 | 392 | |
| 278 | 393 | /// Rebuilds the key indexes. If the underlying entries has been modified directly, users |
| 279 | 394 | /// can call `reIndex` to update the indexes to account for these new entries. |
| 280 | 395 | pub fn reIndex(self: *Self) !void { |
| 281 | return self.unmanaged.reIndex(self.allocator); | |
| 396 | return self.unmanaged.reIndexContext(self.allocator, self.ctx); | |
| 282 | 397 | } |
| 283 | 398 | |
| 284 | 399 | /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated |
| 285 | 400 | /// index entries. Keeps capacity the same. |
| 286 | 401 | 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); | |
| 288 | 403 | } |
| 289 | 404 | |
| 290 | 405 | /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated |
| 291 | 406 | /// index entries. Reduces allocated capacity. |
| 292 | 407 | 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); | |
| 294 | 409 | } |
| 295 | 410 | |
| 296 | 411 | /// 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); | |
| 299 | 414 | } |
| 300 | 415 | }; |
| 301 | 416 | } |
| ... | ... | @@ -317,16 +432,23 @@ pub fn ArrayHashMap( |
| 317 | 432 | /// functions. It does not store each item's hash in the table. Setting `store_hash` |
| 318 | 433 | /// to `true` incurs slightly more memory cost by storing each key's hash in the table |
| 319 | 434 | /// 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 | |
| 320 | 442 | pub fn ArrayHashMapUnmanaged( |
| 321 | 443 | comptime K: type, |
| 322 | 444 | comptime V: type, |
| 323 | comptime hash: fn (key: K) u32, | |
| 324 | comptime eql: fn (a: K, b: K) bool, | |
| 445 | comptime Context: type, | |
| 325 | 446 | comptime store_hash: bool, |
| 326 | 447 | ) type { |
| 448 | comptime std.hash_map.verifyContext(Context, K, K, u32); | |
| 327 | 449 | return struct { |
| 328 | 450 | /// It is permitted to access this field directly. |
| 329 | entries: std.ArrayListUnmanaged(Entry) = .{}, | |
| 451 | entries: DataList = .{}, | |
| 330 | 452 | |
| 331 | 453 | /// When entries length is less than `linear_scan_max`, this remains `null`. |
| 332 | 454 | /// Once entries length grows big enough, this field is allocated. There is |
| ... | ... | @@ -334,26 +456,54 @@ pub fn ArrayHashMapUnmanaged( |
| 334 | 456 | /// by how many total indexes there are. |
| 335 | 457 | index_header: ?*IndexHeader = null, |
| 336 | 458 | |
| 337 | /// Modifying the key is illegal behavior. | |
| 459 | /// Modifying the key is allowed only if it does not change the hash. | |
| 338 | 460 | /// Modifying the value is allowed. |
| 339 | 461 | /// Entry pointers become invalid whenever this ArrayHashMap is modified, |
| 340 | 462 | /// unless `ensureCapacity` was previously used. |
| 341 | 463 | 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 { | |
| 343 | 476 | hash: Hash, |
| 344 | 477 | key: K, |
| 345 | 478 | value: V, |
| 346 | 479 | }; |
| 347 | 480 | |
| 481 | /// The MultiArrayList type backing this map | |
| 482 | pub const DataList = std.MultiArrayList(Data); | |
| 483 | ||
| 484 | /// The stored hash type, either u32 or void. | |
| 348 | 485 | pub const Hash = if (store_hash) u32 else void; |
| 349 | 486 | |
| 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. | |
| 350 | 494 | pub const GetOrPutResult = struct { |
| 351 | entry: *Entry, | |
| 495 | key_ptr: *K, | |
| 496 | value_ptr: *V, | |
| 352 | 497 | found_existing: bool, |
| 353 | 498 | index: usize, |
| 354 | 499 | }; |
| 355 | 500 | |
| 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; | |
| 357 | 507 | |
| 358 | 508 | const Self = @This(); |
| 359 | 509 | |
| ... | ... | @@ -362,25 +512,26 @@ pub fn ArrayHashMapUnmanaged( |
| 362 | 512 | const RemovalType = enum { |
| 363 | 513 | swap, |
| 364 | 514 | ordered, |
| 365 | index_only, | |
| 366 | 515 | }; |
| 367 | 516 | |
| 517 | /// Convert from an unmanaged map to a managed map. After calling this, | |
| 518 | /// the promoted map should no longer be used. | |
| 368 | 519 | 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 { | |
| 369 | 525 | return .{ |
| 370 | 526 | .unmanaged = self, |
| 371 | 527 | .allocator = allocator, |
| 528 | .ctx = ctx, | |
| 372 | 529 | }; |
| 373 | 530 | } |
| 374 | 531 | |
| 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. | |
| 384 | 535 | pub fn deinit(self: *Self, allocator: *Allocator) void { |
| 385 | 536 | self.entries.deinit(allocator); |
| 386 | 537 | if (self.index_header) |header| { |
| ... | ... | @@ -389,19 +540,19 @@ pub fn ArrayHashMapUnmanaged( |
| 389 | 540 | self.* = undefined; |
| 390 | 541 | } |
| 391 | 542 | |
| 543 | /// Clears the map but retains the backing allocation for future use. | |
| 392 | 544 | pub fn clearRetainingCapacity(self: *Self) void { |
| 393 | self.entries.items.len = 0; | |
| 545 | self.entries.len = 0; | |
| 394 | 546 | if (self.index_header) |header| { |
| 395 | header.max_distance_from_start_index = 0; | |
| 396 | 547 | switch (header.capacityIndexType()) { |
| 397 | 548 | .u8 => mem.set(Index(u8), header.indexes(u8), Index(u8).empty), |
| 398 | 549 | .u16 => mem.set(Index(u16), header.indexes(u16), Index(u16).empty), |
| 399 | 550 | .u32 => mem.set(Index(u32), header.indexes(u32), Index(u32).empty), |
| 400 | .usize => mem.set(Index(usize), header.indexes(usize), Index(usize).empty), | |
| 401 | 551 | } |
| 402 | 552 | } |
| 403 | 553 | } |
| 404 | 554 | |
| 555 | /// Clears the map and releases the backing allocation | |
| 405 | 556 | pub fn clearAndFree(self: *Self, allocator: *Allocator) void { |
| 406 | 557 | self.entries.shrinkAndFree(allocator, 0); |
| 407 | 558 | if (self.index_header) |header| { |
| ... | ... | @@ -410,9 +561,54 @@ pub fn ArrayHashMapUnmanaged( |
| 410 | 561 | } |
| 411 | 562 | } |
| 412 | 563 | |
| 564 | /// Returns the number of KV pairs stored in this map. | |
| 413 | 565 | 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 | }; | |
| 415 | 589 | } |
| 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 | }; | |
| 416 | 612 | |
| 417 | 613 | /// If key exists this function cannot fail. |
| 418 | 614 | /// If there is an existing item with `key`, then the result |
| ... | ... | @@ -421,16 +617,36 @@ pub fn ArrayHashMapUnmanaged( |
| 421 | 617 | /// the `Entry` pointer points to it. Caller should then initialize |
| 422 | 618 | /// the value (but not the key). |
| 423 | 619 | 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| { | |
| 425 | 638 | // "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(); | |
| 427 | 641 | 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], | |
| 429 | 645 | .found_existing = true, |
| 430 | 646 | .index = index, |
| 431 | 647 | }; |
| 432 | 648 | }; |
| 433 | return self.getOrPutAssumeCapacity(key); | |
| 649 | return self.getOrPutAssumeCapacityAdapted(key, key_ctx); | |
| 434 | 650 | } |
| 435 | 651 | |
| 436 | 652 | /// If there is an existing item with `key`, then the result |
| ... | ... | @@ -441,45 +657,75 @@ pub fn ArrayHashMapUnmanaged( |
| 441 | 657 | /// If a new entry needs to be stored, this function asserts there |
| 442 | 658 | /// is enough capacity to store it. |
| 443 | 659 | 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 { | |
| 444 | 679 | const header = self.index_header orelse { |
| 445 | 680 | // 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.*)) { | |
| 449 | 687 | 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], | |
| 451 | 691 | .found_existing = true, |
| 452 | 692 | .index = i, |
| 453 | 693 | }; |
| 454 | 694 | } |
| 455 | 695 | } |
| 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 | ||
| 462 | 701 | 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], | |
| 464 | 705 | .found_existing = false, |
| 465 | .index = self.entries.items.len - 1, | |
| 706 | .index = index, | |
| 466 | 707 | }; |
| 467 | 708 | }; |
| 468 | 709 | |
| 469 | 710 | 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), | |
| 474 | 714 | } |
| 475 | 715 | } |
| 476 | 716 | |
| 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; | |
| 483 | 729 | } |
| 484 | 730 | |
| 485 | 731 | /// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`. |
| ... | ... | @@ -488,30 +734,30 @@ pub fn ArrayHashMapUnmanaged( |
| 488 | 734 | /// Increases capacity, guaranteeing that insertions up until the |
| 489 | 735 | /// `expected_count` will not cause an allocation, and therefore cannot fail. |
| 490 | 736 | 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 | } | |
| 493 | 746 | |
| 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; | |
| 497 | 747 | 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; | |
| 506 | 751 | } |
| 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; | |
| 514 | 752 | } |
| 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; | |
| 515 | 761 | } |
| 516 | 762 | |
| 517 | 763 | /// Increases capacity, guaranteeing that insertions up until |
| ... | ... | @@ -522,7 +768,17 @@ pub fn ArrayHashMapUnmanaged( |
| 522 | 768 | allocator: *Allocator, |
| 523 | 769 | additional_capacity: usize, |
| 524 | 770 | ) !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); | |
| 526 | 782 | } |
| 527 | 783 | |
| 528 | 784 | /// Returns the number of total elements which may be present before it is |
| ... | ... | @@ -530,141 +786,321 @@ pub fn ArrayHashMapUnmanaged( |
| 530 | 786 | pub fn capacity(self: Self) usize { |
| 531 | 787 | const entry_cap = self.entries.capacity; |
| 532 | 788 | 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(); | |
| 534 | 790 | return math.min(entry_cap, indexes_cap); |
| 535 | 791 | } |
| 536 | 792 | |
| 537 | 793 | /// Clobbers any existing data. To detect if a put would clobber |
| 538 | 794 | /// existing data, see `getOrPut`. |
| 539 | 795 | 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; | |
| 542 | 803 | } |
| 543 | 804 | |
| 544 | 805 | /// Inserts a key-value pair into the hash map, asserting that no previous |
| 545 | 806 | /// entry with the same key is already present |
| 546 | 807 | 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); | |
| 548 | 814 | assert(!result.found_existing); |
| 549 | result.entry.value = value; | |
| 815 | result.value_ptr.* = value; | |
| 550 | 816 | } |
| 551 | 817 | |
| 552 | 818 | /// Asserts there is enough capacity to store the new key-value pair. |
| 553 | 819 | /// Clobbers any existing data. To detect if a put would clobber |
| 554 | 820 | /// existing data, see `getOrPutAssumeCapacity`. |
| 555 | 821 | 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; | |
| 558 | 829 | } |
| 559 | 830 | |
| 560 | 831 | /// Asserts there is enough capacity to store the new key-value pair. |
| 561 | 832 | /// Asserts that it does not clobber any existing data. |
| 562 | 833 | /// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`. |
| 563 | 834 | 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); | |
| 565 | 841 | assert(!result.found_existing); |
| 566 | result.entry.value = value; | |
| 842 | result.value_ptr.* = value; | |
| 567 | 843 | } |
| 568 | 844 | |
| 569 | 845 | /// 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; | |
| 573 | 854 | if (gop.found_existing) { |
| 574 | result = gop.entry.*; | |
| 855 | result = KV{ | |
| 856 | .key = gop.key_ptr.*, | |
| 857 | .value = gop.value_ptr.*, | |
| 858 | }; | |
| 575 | 859 | } |
| 576 | gop.entry.value = value; | |
| 860 | gop.value_ptr.* = value; | |
| 577 | 861 | return result; |
| 578 | 862 | } |
| 579 | 863 | |
| 580 | 864 | /// Inserts a new `Entry` into the hash map, returning the previous one, if any. |
| 581 | 865 | /// 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; | |
| 585 | 874 | if (gop.found_existing) { |
| 586 | result = gop.entry.*; | |
| 875 | result = KV{ | |
| 876 | .key = gop.key_ptr.*, | |
| 877 | .value = gop.value_ptr.*, | |
| 878 | }; | |
| 587 | 879 | } |
| 588 | gop.entry.value = value; | |
| 880 | gop.value_ptr.* = value; | |
| 589 | 881 | return result; |
| 590 | 882 | } |
| 591 | 883 | |
| 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 | }; | |
| 595 | 901 | } |
| 596 | 902 | |
| 903 | /// Finds the index in the `entries` array where a key is stored | |
| 597 | 904 | 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 { | |
| 598 | 913 | const header = self.index_header orelse { |
| 599 | 914 | // 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.*)) { | |
| 603 | 921 | return i; |
| 604 | 922 | } |
| 605 | 923 | } |
| 606 | 924 | return null; |
| 607 | 925 | }; |
| 608 | 926 | 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), | |
| 613 | 930 | } |
| 614 | 931 | } |
| 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 | } | |
| 615 | 937 | |
| 938 | /// Find the value associated with a key | |
| 616 | 939 | 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]; | |
| 618 | 965 | } |
| 619 | 966 | |
| 967 | /// Check whether a key is stored in the map | |
| 620 | 968 | 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; | |
| 622 | 978 | } |
| 623 | 979 | |
| 624 | 980 | /// If there is an `Entry` with a matching key, it is deleted from |
| 625 | 981 | /// the hash map, and then returned from this function. The entry is |
| 626 | 982 | /// removed from the underlying array by swapping it with the last |
| 627 | 983 | /// 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); | |
| 630 | 999 | } |
| 631 | 1000 | |
| 632 | 1001 | /// If there is an `Entry` with a matching key, it is deleted from |
| 633 | 1002 | /// the hash map, and then returned from this function. The entry is |
| 634 | 1003 | /// removed from the underlying array by shifting all elements forward |
| 635 | 1004 | /// 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); | |
| 638 | 1020 | } |
| 639 | 1021 | |
| 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); | |
| 643 | 1041 | } |
| 644 | 1042 | |
| 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); | |
| 649 | 1062 | } |
| 650 | 1063 | |
| 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); | |
| 655 | 1074 | } |
| 656 | 1075 | |
| 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); | |
| 659 | 1087 | } |
| 660 | 1088 | |
| 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. | |
| 661 | 1091 | 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 { | |
| 662 | 1097 | 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); | |
| 664 | 1100 | |
| 665 | 1101 | 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); | |
| 668 | 1104 | other.index_header = new_header; |
| 669 | 1105 | } |
| 670 | 1106 | return other; |
| ... | ... | @@ -673,135 +1109,197 @@ pub fn ArrayHashMapUnmanaged( |
| 673 | 1109 | /// Rebuilds the key indexes. If the underlying entries has been modified directly, users |
| 674 | 1110 | /// can call `reIndex` to update the indexes to account for these new entries. |
| 675 | 1111 | 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 { | |
| 676 | 1117 | if (self.entries.capacity <= linear_scan_max) return; |
| 677 | 1118 | // We're going to rebuild the index header and replace the existing one (if any). The |
| 678 | 1119 | // 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); | |
| 685 | 1124 | self.index_header = new_header; |
| 686 | 1125 | } |
| 687 | 1126 | |
| 688 | 1127 | /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated |
| 689 | 1128 | /// index entries. Keeps capacity the same. |
| 690 | 1129 | 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 { | |
| 691 | 1135 | // Remove index entries from the new length onwards. |
| 692 | 1136 | // Explicitly choose to ONLY remove index entries and not the underlying array list |
| 693 | 1137 | // 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 | } | |
| 697 | 1143 | self.entries.shrinkRetainingCapacity(new_len); |
| 698 | 1144 | } |
| 699 | 1145 | |
| 700 | 1146 | /// Shrinks the underlying `Entry` array to `new_len` elements and discards any associated |
| 701 | 1147 | /// index entries. Reduces allocated capacity. |
| 702 | 1148 | 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 { | |
| 703 | 1154 | // Remove index entries from the new length onwards. |
| 704 | 1155 | // Explicitly choose to ONLY remove index entries and not the underlying array list |
| 705 | 1156 | // 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 | } | |
| 709 | 1162 | self.entries.shrinkAndFree(allocator, new_len); |
| 710 | 1163 | } |
| 711 | 1164 | |
| 712 | 1165 | /// 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); | |
| 718 | 1170 | } |
| 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 | }; | |
| 723 | 1180 | } |
| 724 | 1181 | |
| 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 { | |
| 726 | 1185 | 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; | |
| 730 | 1186 | // 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 | }; | |
| 733 | 1198 | 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), | |
| 737 | 1201 | } |
| 1202 | return removed_entry; | |
| 738 | 1203 | } |
| 739 | 1204 | } |
| 740 | 1205 | return null; |
| 741 | 1206 | }; |
| 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 | }; | |
| 748 | 1212 | } |
| 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 { | |
| 751 | 1214 | 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 | } | |
| 766 | 1224 | |
| 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), | |
| 784 | 1238 | } |
| 785 | }, | |
| 786 | .index_only => removed_entry = null, | |
| 1239 | return true; | |
| 1240 | } | |
| 787 | 1241 | } |
| 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 | } | |
| 788 | 1256 | |
| 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), | |
| 801 | 1263 | } |
| 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 | }, | |
| 803 | 1302 | } |
| 804 | return null; | |
| 805 | 1303 | } |
| 806 | 1304 | |
| 807 | 1305 | fn updateEntryIndex( |
| ... | ... | @@ -809,116 +1307,188 @@ pub fn ArrayHashMapUnmanaged( |
| 809 | 1307 | header: *IndexHeader, |
| 810 | 1308 | old_entry_index: usize, |
| 811 | 1309 | new_entry_index: usize, |
| 1310 | ctx: ByIndexContext, | |
| 812 | 1311 | comptime I: type, |
| 813 | 1312 | indexes: []Index(I), |
| 814 | 1313 | ) 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(); | |
| 823 | 1348 | return; |
| 824 | 1349 | } |
| 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 | } | |
| 825 | 1383 | } |
| 826 | 1384 | unreachable; |
| 827 | 1385 | } |
| 828 | 1386 | |
| 829 | 1387 | /// 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); | |
| 831 | 1393 | 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; | |
| 838 | 1403 | distance_from_start_index += 1; |
| 839 | 1404 | }) { |
| 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), | |
| 853 | 1416 | }; |
| 1417 | ||
| 1418 | // update the hash if applicable | |
| 1419 | if (store_hash) hashes_array.ptr[new_index] = h; | |
| 1420 | ||
| 854 | 1421 | return .{ |
| 855 | 1422 | .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, | |
| 858 | 1427 | }; |
| 859 | 1428 | } |
| 860 | 1429 | |
| 861 | 1430 | // This pointer survives the following append because we call |
| 862 | 1431 | // 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])) { | |
| 866 | 1434 | return .{ |
| 867 | 1435 | .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, | |
| 870 | 1440 | }; |
| 871 | 1441 | } |
| 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) { | |
| 873 | 1448 | // In this case, we did not find the item. We will put a new entry. |
| 874 | 1449 | // 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 | |
| 876 | 1451 | // 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, | |
| 880 | 1457 | }; |
| 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; | |
| 891 | 1460 | |
| 892 | 1461 | // Find somewhere to put the index we replaced by shifting |
| 893 | 1462 | // following indexes backwards. |
| 894 | roll_over += 1; | |
| 1463 | index +%= 1; | |
| 895 | 1464 | distance_from_start_index += 1; |
| 896 | while (roll_over < header.indexes_len) : ({ | |
| 897 | roll_over += 1; | |
| 1465 | while (index != end_index) : ({ | |
| 1466 | index +%= 1; | |
| 898 | 1467 | distance_from_start_index += 1; |
| 899 | 1468 | }) { |
| 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, | |
| 907 | 1475 | }; |
| 908 | 1476 | return .{ |
| 909 | 1477 | .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, | |
| 912 | 1482 | }; |
| 913 | 1483 | } |
| 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, | |
| 919 | 1489 | }; |
| 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; | |
| 922 | 1492 | } |
| 923 | 1493 | } |
| 924 | 1494 | unreachable; |
| ... | ... | @@ -927,61 +1497,69 @@ pub fn ArrayHashMapUnmanaged( |
| 927 | 1497 | unreachable; |
| 928 | 1498 | } |
| 929 | 1499 | |
| 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) | |
| 939 | 1518 | return null; |
| 940 | 1519 | |
| 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; | |
| 945 | 1523 | } |
| 946 | return null; | |
| 1524 | unreachable; | |
| 947 | 1525 | } |
| 948 | 1526 | |
| 949 | fn insertAllEntriesIntoNewHeader(self: *Self, header: *IndexHeader) void { | |
| 1527 | fn insertAllEntriesIntoNewHeader(self: *Self, ctx: ByIndexContext, header: *IndexHeader) void { | |
| 950 | 1528 | 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), | |
| 955 | 1532 | } |
| 956 | 1533 | } |
| 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); | |
| 959 | 1537 | 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; | |
| 968 | 1548 | distance_from_start_index += 1; |
| 969 | 1549 | }) { |
| 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]; | |
| 972 | 1552 | 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, | |
| 977 | 1556 | }; |
| 978 | 1557 | continue :entry_loop; |
| 979 | 1558 | } |
| 980 | 1559 | 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, | |
| 985 | 1563 | }; |
| 986 | 1564 | distance_from_start_index = next_index.distance_from_start_index; |
| 987 | 1565 | entry_index = next_index.entry_index; |
| ... | ... | @@ -990,98 +1568,255 @@ pub fn ArrayHashMapUnmanaged( |
| 990 | 1568 | unreachable; |
| 991 | 1569 | } |
| 992 | 1570 | } |
| 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 | } | |
| 993 | 1651 | }; |
| 994 | 1652 | } |
| 995 | 1653 | |
| 996 | const CapacityIndexType = enum { u8, u16, u32, usize }; | |
| 1654 | const CapacityIndexType = enum { u8, u16, u32 }; | |
| 997 | 1655 | |
| 998 | fn capacityIndexType(indexes_len: usize) CapacityIndexType { | |
| 999 | if (indexes_len < math.maxInt(u8)) | |
| 1656 | fn capacityIndexType(bit_index: u8) CapacityIndexType { | |
| 1657 | if (bit_index <= 8) | |
| 1000 | 1658 | return .u8; |
| 1001 | if (indexes_len < math.maxInt(u16)) | |
| 1659 | if (bit_index <= 16) | |
| 1002 | 1660 | return .u16; |
| 1003 | if (indexes_len < math.maxInt(u32)) | |
| 1004 | return .u32; | |
| 1005 | return .usize; | |
| 1661 | assert(bit_index <= 32); | |
| 1662 | return .u32; | |
| 1006 | 1663 | } |
| 1007 | 1664 | |
| 1008 | fn capacityIndexSize(indexes_len: usize) usize { | |
| 1009 | switch (capacityIndexType(indexes_len)) { | |
| 1665 | fn capacityIndexSize(bit_index: u8) usize { | |
| 1666 | switch (capacityIndexType(bit_index)) { | |
| 1010 | 1667 | .u8 => return @sizeOf(Index(u8)), |
| 1011 | 1668 | .u16 => return @sizeOf(Index(u16)), |
| 1012 | 1669 | .u32 => return @sizeOf(Index(u32)), |
| 1013 | .usize => return @sizeOf(Index(usize)), | |
| 1014 | 1670 | } |
| 1015 | 1671 | } |
| 1016 | 1672 | |
| 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. | |
| 1679 | fn 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. | |
| 1017 | 1688 | fn Index(comptime I: type) type { |
| 1018 | 1689 | 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. | |
| 1019 | 1694 | 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. | |
| 1020 | 1699 | distance_from_start_index: I, |
| 1021 | 1700 | |
| 1022 | const Self = @This(); | |
| 1701 | /// The special entry_index value marking an empty slot. | |
| 1702 | const empty_sentinel = ~@as(I, 0); | |
| 1023 | 1703 | |
| 1704 | /// A constant empty index | |
| 1024 | 1705 | const empty = Self{ |
| 1025 | .entry_index = math.maxInt(I), | |
| 1706 | .entry_index = empty_sentinel, | |
| 1026 | 1707 | .distance_from_start_index = undefined, |
| 1027 | 1708 | }; |
| 1028 | 1709 | |
| 1710 | /// Checks if a slot is empty | |
| 1029 | 1711 | fn isEmpty(idx: Self) bool { |
| 1030 | return idx.entry_index == math.maxInt(I); | |
| 1712 | return idx.entry_index == empty_sentinel; | |
| 1031 | 1713 | } |
| 1032 | 1714 | |
| 1715 | /// Sets a slot to empty | |
| 1033 | 1716 | 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; | |
| 1035 | 1719 | } |
| 1036 | 1720 | }; |
| 1037 | 1721 | } |
| 1038 | 1722 | |
| 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. | |
| 1726 | const max_representable_index_len = @bitSizeOf(usize) - 4; | |
| 1727 | const max_bit_index = math.min(32, max_representable_index_len); | |
| 1728 | const min_bit_index = 5; | |
| 1729 | const max_capacity = (1 << max_bit_index) - 1; | |
| 1730 | const 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. | |
| 1041 | 1748 | const 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)), | |
| 1044 | 1753 | |
| 1754 | /// Map from an incrementing index to an index slot in the attached arrays. | |
| 1045 | 1755 | fn constrainIndex(header: IndexHeader, i: usize) usize { |
| 1046 | 1756 | // This is an optimization for modulo of power of two integers; |
| 1047 | 1757 | // 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()); | |
| 1049 | 1759 | } |
| 1050 | 1760 | |
| 1761 | /// Returns the attached array of indexes. I must match the type | |
| 1762 | /// returned by capacityIndexType. | |
| 1051 | 1763 | 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()]; | |
| 1054 | 1766 | } |
| 1055 | 1767 | |
| 1768 | /// Returns the type used for the index arrays. | |
| 1056 | 1769 | fn capacityIndexType(header: IndexHeader) CapacityIndexType { |
| 1057 | return hash_map.capacityIndexType(header.indexes_len); | |
| 1770 | return hash_map.capacityIndexType(header.bit_index); | |
| 1058 | 1771 | } |
| 1059 | 1772 | |
| 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; | |
| 1064 | 1790 | } |
| 1065 | 1791 | |
| 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); | |
| 1068 | 1797 | const nbytes = @sizeOf(IndexHeader) + index_size * len; |
| 1069 | 1798 | const bytes = try allocator.allocAdvanced(u8, @alignOf(IndexHeader), nbytes, .exact); |
| 1070 | 1799 | @memset(bytes.ptr + @sizeOf(IndexHeader), 0xff, bytes.len - @sizeOf(IndexHeader)); |
| 1071 | 1800 | const result = @ptrCast(*IndexHeader, bytes.ptr); |
| 1072 | 1801 | result.* = .{ |
| 1073 | .max_distance_from_start_index = 0, | |
| 1074 | .indexes_len = len, | |
| 1802 | .bit_index = new_bit_index, | |
| 1075 | 1803 | }; |
| 1076 | 1804 | return result; |
| 1077 | 1805 | } |
| 1078 | 1806 | |
| 1807 | /// Releases the memory for a header and its associated arrays. | |
| 1079 | 1808 | 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]; | |
| 1083 | 1812 | allocator.free(slice); |
| 1084 | 1813 | } |
| 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 | } | |
| 1085 | 1820 | }; |
| 1086 | 1821 | |
| 1087 | 1822 | test "basic hash map usage" { |
| ... | ... | @@ -1099,31 +1834,32 @@ test "basic hash map usage" { |
| 1099 | 1834 | |
| 1100 | 1835 | const gop1 = try map.getOrPut(5); |
| 1101 | 1836 | try testing.expect(gop1.found_existing == true); |
| 1102 | try testing.expect(gop1.entry.value == 55); | |
| 1837 | try testing.expect(gop1.value_ptr.* == 55); | |
| 1103 | 1838 | 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); | |
| 1106 | 1841 | |
| 1107 | 1842 | const gop2 = try map.getOrPut(99); |
| 1108 | 1843 | try testing.expect(gop2.found_existing == false); |
| 1109 | 1844 | 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); | |
| 1112 | 1847 | |
| 1113 | 1848 | const gop3 = try map.getOrPutValue(5, 5); |
| 1114 | try testing.expect(gop3.value == 77); | |
| 1849 | try testing.expect(gop3.value_ptr.* == 77); | |
| 1115 | 1850 | |
| 1116 | 1851 | const gop4 = try map.getOrPutValue(100, 41); |
| 1117 | try testing.expect(gop4.value == 41); | |
| 1852 | try testing.expect(gop4.value_ptr.* == 41); | |
| 1118 | 1853 | |
| 1119 | 1854 | 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); | |
| 1121 | 1856 | try testing.expect(map.get(2).? == 22); |
| 1122 | 1857 | |
| 1123 | const rmv1 = map.swapRemove(2); | |
| 1858 | const rmv1 = map.fetchSwapRemove(2); | |
| 1124 | 1859 | try testing.expect(rmv1.?.key == 2); |
| 1125 | 1860 | 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); | |
| 1127 | 1863 | try testing.expect(map.getEntry(2) == null); |
| 1128 | 1864 | try testing.expect(map.get(2) == null); |
| 1129 | 1865 | |
| ... | ... | @@ -1131,22 +1867,23 @@ test "basic hash map usage" { |
| 1131 | 1867 | try testing.expect(map.getIndex(100).? == 1); |
| 1132 | 1868 | const gop5 = try map.getOrPut(5); |
| 1133 | 1869 | try testing.expect(gop5.found_existing == true); |
| 1134 | try testing.expect(gop5.entry.value == 77); | |
| 1870 | try testing.expect(gop5.value_ptr.* == 77); | |
| 1135 | 1871 | try testing.expect(gop5.index == 4); |
| 1136 | 1872 | |
| 1137 | 1873 | // 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); | |
| 1139 | 1875 | try testing.expect(rmv2.?.key == 100); |
| 1140 | 1876 | 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); | |
| 1142 | 1879 | try testing.expect(map.getEntry(100) == null); |
| 1143 | 1880 | try testing.expect(map.get(100) == null); |
| 1144 | 1881 | const gop6 = try map.getOrPut(5); |
| 1145 | 1882 | try testing.expect(gop6.found_existing == true); |
| 1146 | try testing.expect(gop6.entry.value == 77); | |
| 1883 | try testing.expect(gop6.value_ptr.* == 77); | |
| 1147 | 1884 | try testing.expect(gop6.index == 3); |
| 1148 | 1885 | |
| 1149 | map.removeAssertDiscard(3); | |
| 1886 | try testing.expect(map.swapRemove(3)); | |
| 1150 | 1887 | } |
| 1151 | 1888 | |
| 1152 | 1889 | test "iterator hash map" { |
| ... | ... | @@ -1154,7 +1891,7 @@ test "iterator hash map" { |
| 1154 | 1891 | defer reset_map.deinit(); |
| 1155 | 1892 | |
| 1156 | 1893 | // test ensureCapacity with a 0 parameter |
| 1157 | try reset_map.ensureCapacity(0); | |
| 1894 | try reset_map.ensureTotalCapacity(0); | |
| 1158 | 1895 | |
| 1159 | 1896 | try reset_map.putNoClobber(0, 11); |
| 1160 | 1897 | try reset_map.putNoClobber(1, 22); |
| ... | ... | @@ -1178,7 +1915,7 @@ test "iterator hash map" { |
| 1178 | 1915 | |
| 1179 | 1916 | var count: usize = 0; |
| 1180 | 1917 | while (it.next()) |entry| : (count += 1) { |
| 1181 | buffer[@intCast(usize, entry.key)] = entry.value; | |
| 1918 | buffer[@intCast(usize, entry.key_ptr.*)] = entry.value_ptr.*; | |
| 1182 | 1919 | } |
| 1183 | 1920 | try testing.expect(count == 3); |
| 1184 | 1921 | try testing.expect(it.next() == null); |
| ... | ... | @@ -1190,7 +1927,7 @@ test "iterator hash map" { |
| 1190 | 1927 | it.reset(); |
| 1191 | 1928 | count = 0; |
| 1192 | 1929 | while (it.next()) |entry| { |
| 1193 | buffer[@intCast(usize, entry.key)] = entry.value; | |
| 1930 | buffer[@intCast(usize, entry.key_ptr.*)] = entry.value_ptr.*; | |
| 1194 | 1931 | count += 1; |
| 1195 | 1932 | if (count >= 2) break; |
| 1196 | 1933 | } |
| ... | ... | @@ -1201,15 +1938,15 @@ test "iterator hash map" { |
| 1201 | 1938 | |
| 1202 | 1939 | it.reset(); |
| 1203 | 1940 | 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.*); | |
| 1206 | 1943 | } |
| 1207 | 1944 | |
| 1208 | 1945 | test "ensure capacity" { |
| 1209 | 1946 | var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); |
| 1210 | 1947 | defer map.deinit(); |
| 1211 | 1948 | |
| 1212 | try map.ensureCapacity(20); | |
| 1949 | try map.ensureTotalCapacity(20); | |
| 1213 | 1950 | const initial_capacity = map.capacity(); |
| 1214 | 1951 | try testing.expect(initial_capacity >= 20); |
| 1215 | 1952 | var i: i32 = 0; |
| ... | ... | @@ -1220,6 +1957,59 @@ test "ensure capacity" { |
| 1220 | 1957 | try testing.expect(initial_capacity == map.capacity()); |
| 1221 | 1958 | } |
| 1222 | 1959 | |
| 1960 | test "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 | ||
| 1223 | 2013 | test "clone" { |
| 1224 | 2014 | var original = AutoArrayHashMap(i32, i32).init(std.testing.allocator); |
| 1225 | 2015 | defer original.deinit(); |
| ... | ... | @@ -1235,7 +2025,14 @@ test "clone" { |
| 1235 | 2025 | |
| 1236 | 2026 | i = 0; |
| 1237 | 2027 | while (i < 10) : (i += 1) { |
| 2028 | try testing.expect(original.get(i).? == i * 10); | |
| 1238 | 2029 | 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); | |
| 1239 | 2036 | } |
| 1240 | 2037 | } |
| 1241 | 2038 | |
| ... | ... | @@ -1261,7 +2058,7 @@ test "shrink" { |
| 1261 | 2058 | const gop = try map.getOrPut(i); |
| 1262 | 2059 | if (i < 17) { |
| 1263 | 2060 | 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); | |
| 1265 | 2062 | } else try testing.expect(gop.found_existing == false); |
| 1266 | 2063 | } |
| 1267 | 2064 | |
| ... | ... | @@ -1274,7 +2071,7 @@ test "shrink" { |
| 1274 | 2071 | const gop = try map.getOrPut(i); |
| 1275 | 2072 | if (i < 15) { |
| 1276 | 2073 | 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); | |
| 1278 | 2075 | } else try testing.expect(gop.found_existing == false); |
| 1279 | 2076 | } |
| 1280 | 2077 | } |
| ... | ... | @@ -1298,7 +2095,7 @@ test "pop" { |
| 1298 | 2095 | } |
| 1299 | 2096 | |
| 1300 | 2097 | test "reIndex" { |
| 1301 | var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); | |
| 2098 | var map = ArrayHashMap(i32, i32, AutoContext(i32), true).init(std.testing.allocator); | |
| 1302 | 2099 | defer map.deinit(); |
| 1303 | 2100 | |
| 1304 | 2101 | // Populate via the API. |
| ... | ... | @@ -1312,13 +2109,13 @@ test "reIndex" { |
| 1312 | 2109 | |
| 1313 | 2110 | // Now write to the underlying array list directly. |
| 1314 | 2111 | const num_unindexed_entries = 20; |
| 1315 | const hash = getAutoHashFn(i32); | |
| 2112 | const hash = getAutoHashFn(i32, void); | |
| 1316 | 2113 | var al = &map.unmanaged.entries; |
| 1317 | 2114 | while (i < num_indexed_entries + num_unindexed_entries) : (i += 1) { |
| 1318 | 2115 | try al.append(std.testing.allocator, .{ |
| 1319 | 2116 | .key = i, |
| 1320 | 2117 | .value = i * 10, |
| 1321 | .hash = {}, | |
| 2118 | .hash = hash({}, i), | |
| 1322 | 2119 | }); |
| 1323 | 2120 | } |
| 1324 | 2121 | |
| ... | ... | @@ -1328,36 +2125,7 @@ test "reIndex" { |
| 1328 | 2125 | while (i < num_indexed_entries + num_unindexed_entries) : (i += 1) { |
| 1329 | 2126 | const gop = try map.getOrPut(i); |
| 1330 | 2127 | 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 | ||
| 1336 | test "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); | |
| 1361 | 2129 | try testing.expect(gop.index == i); |
| 1362 | 2130 | } |
| 1363 | 2131 | } |
| ... | ... | @@ -1365,34 +2133,52 @@ test "fromOwnedArrayList" { |
| 1365 | 2133 | test "auto store_hash" { |
| 1366 | 2134 | const HasCheapEql = AutoArrayHashMap(i32, i32); |
| 1367 | 2135 | 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); | |
| 1370 | 2138 | |
| 1371 | 2139 | const HasCheapEqlUn = AutoArrayHashMapUnmanaged(i32, i32); |
| 1372 | 2140 | 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 | ||
| 2145 | test "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)); | |
| 1375 | 2154 | } |
| 1376 | 2155 | |
| 1377 | pub fn getHashPtrAddrFn(comptime K: type) (fn (K) u32) { | |
| 2156 | pub fn getHashPtrAddrFn(comptime K: type, comptime Context: type) (fn (Context, K) u32) { | |
| 1378 | 2157 | 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)); | |
| 1381 | 2160 | } |
| 1382 | 2161 | }.hash; |
| 1383 | 2162 | } |
| 1384 | 2163 | |
| 1385 | pub fn getTrivialEqlFn(comptime K: type) (fn (K, K) bool) { | |
| 2164 | pub fn getTrivialEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K) bool) { | |
| 1386 | 2165 | return struct { |
| 1387 | fn eql(a: K, b: K) bool { | |
| 2166 | fn eql(ctx: Context, a: K, b: K) bool { | |
| 1388 | 2167 | return a == b; |
| 1389 | 2168 | } |
| 1390 | 2169 | }.eql; |
| 1391 | 2170 | } |
| 1392 | 2171 | |
| 1393 | pub fn getAutoHashFn(comptime K: type) (fn (K) u32) { | |
| 2172 | pub 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 | ||
| 2179 | pub fn getAutoHashFn(comptime K: type, comptime Context: type) (fn (Context, K) u32) { | |
| 1394 | 2180 | return struct { |
| 1395 | fn hash(key: K) u32 { | |
| 2181 | fn hash(ctx: Context, key: K) u32 { | |
| 1396 | 2182 | if (comptime trait.hasUniqueRepresentation(K)) { |
| 1397 | 2183 | return @truncate(u32, Wyhash.hash(0, std.mem.asBytes(&key))); |
| 1398 | 2184 | } else { |
| ... | ... | @@ -1404,9 +2190,9 @@ pub fn getAutoHashFn(comptime K: type) (fn (K) u32) { |
| 1404 | 2190 | }.hash; |
| 1405 | 2191 | } |
| 1406 | 2192 | |
| 1407 | pub fn getAutoEqlFn(comptime K: type) (fn (K, K) bool) { | |
| 2193 | pub fn getAutoEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K) bool) { | |
| 1408 | 2194 | return struct { |
| 1409 | fn eql(a: K, b: K) bool { | |
| 2195 | fn eql(ctx: Context, a: K, b: K) bool { | |
| 1410 | 2196 | return meta.eql(a, b); |
| 1411 | 2197 | } |
| 1412 | 2198 | }.eql; |
| ... | ... | @@ -1430,9 +2216,9 @@ pub fn autoEqlIsCheap(comptime K: type) bool { |
| 1430 | 2216 | }; |
| 1431 | 2217 | } |
| 1432 | 2218 | |
| 1433 | pub fn getAutoHashStratFn(comptime K: type, comptime strategy: std.hash.Strategy) (fn (K) u32) { | |
| 2219 | pub fn getAutoHashStratFn(comptime K: type, comptime Context: type, comptime strategy: std.hash.Strategy) (fn (Context, K) u32) { | |
| 1434 | 2220 | return struct { |
| 1435 | fn hash(key: K) u32 { | |
| 2221 | fn hash(ctx: Context, key: K) u32 { | |
| 1436 | 2222 | var hasher = Wyhash.init(0); |
| 1437 | 2223 | std.hash.autoHashStrat(&hasher, key, strategy); |
| 1438 | 2224 | return @truncate(u32, hasher.final()); |
lib/std/buf_map.zig+42-25| ... | ... | @@ -16,65 +16,82 @@ pub const BufMap = struct { |
| 16 | 16 | |
| 17 | 17 | const BufMapHashMap = StringHashMap([]const u8); |
| 18 | 18 | |
| 19 | /// Create a BufMap backed by a specific allocator. | |
| 20 | /// That allocator will be used for both backing allocations | |
| 21 | /// and string deduplication. | |
| 19 | 22 | pub fn init(allocator: *Allocator) BufMap { |
| 20 | 23 | var self = BufMap{ .hash_map = BufMapHashMap.init(allocator) }; |
| 21 | 24 | return self; |
| 22 | 25 | } |
| 23 | 26 | |
| 27 | /// Free the backing storage of the map, as well as all | |
| 28 | /// of the stored keys and values. | |
| 24 | 29 | pub fn deinit(self: *BufMap) void { |
| 25 | 30 | 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.*); | |
| 30 | 34 | } |
| 31 | 35 | |
| 32 | 36 | self.hash_map.deinit(); |
| 33 | 37 | } |
| 34 | 38 | |
| 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 | |
| 36 | 40 | /// 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 { | |
| 39 | 43 | const get_or_put = try self.hash_map.getOrPut(key); |
| 40 | 44 | 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; | |
| 44 | 48 | } |
| 45 | get_or_put.entry.value = value; | |
| 49 | get_or_put.value_ptr.* = value; | |
| 46 | 50 | } |
| 47 | 51 | |
| 48 | 52 | /// `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 { | |
| 50 | 54 | const value_copy = try self.copy(value); |
| 51 | 55 | errdefer self.free(value_copy); |
| 52 | 56 | const get_or_put = try self.hash_map.getOrPut(key); |
| 53 | 57 | if (get_or_put.found_existing) { |
| 54 | self.free(get_or_put.entry.value); | |
| 58 | self.free(get_or_put.value_ptr.*); | |
| 55 | 59 | } else { |
| 56 | get_or_put.entry.key = self.copy(key) catch |err| { | |
| 60 | get_or_put.key_ptr.* = self.copy(key) catch |err| { | |
| 57 | 61 | _ = self.hash_map.remove(key); |
| 58 | 62 | return err; |
| 59 | 63 | }; |
| 60 | 64 | } |
| 61 | get_or_put.entry.value = value_copy; | |
| 65 | get_or_put.value_ptr.* = value_copy; | |
| 62 | 66 | } |
| 63 | 67 | |
| 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. | |
| 64 | 77 | pub fn get(self: BufMap, key: []const u8) ?[]const u8 { |
| 65 | 78 | return self.hash_map.get(key); |
| 66 | 79 | } |
| 67 | 80 | |
| 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); | |
| 72 | 87 | } |
| 73 | 88 | |
| 89 | /// Returns the number of KV pairs stored in the map. | |
| 74 | 90 | pub fn count(self: BufMap) usize { |
| 75 | 91 | return self.hash_map.count(); |
| 76 | 92 | } |
| 77 | 93 | |
| 94 | /// Returns an iterator over entries in the map. | |
| 78 | 95 | pub fn iterator(self: *const BufMap) BufMapHashMap.Iterator { |
| 79 | 96 | return self.hash_map.iterator(); |
| 80 | 97 | } |
| ... | ... | @@ -93,21 +110,21 @@ test "BufMap" { |
| 93 | 110 | var bufmap = BufMap.init(allocator); |
| 94 | 111 | defer bufmap.deinit(); |
| 95 | 112 | |
| 96 | try bufmap.set("x", "1"); | |
| 113 | try bufmap.put("x", "1"); | |
| 97 | 114 | try testing.expect(mem.eql(u8, bufmap.get("x").?, "1")); |
| 98 | 115 | try testing.expect(1 == bufmap.count()); |
| 99 | 116 | |
| 100 | try bufmap.set("x", "2"); | |
| 117 | try bufmap.put("x", "2"); | |
| 101 | 118 | try testing.expect(mem.eql(u8, bufmap.get("x").?, "2")); |
| 102 | 119 | try testing.expect(1 == bufmap.count()); |
| 103 | 120 | |
| 104 | try bufmap.set("x", "3"); | |
| 121 | try bufmap.put("x", "3"); | |
| 105 | 122 | try testing.expect(mem.eql(u8, bufmap.get("x").?, "3")); |
| 106 | 123 | try testing.expect(1 == bufmap.count()); |
| 107 | 124 | |
| 108 | bufmap.delete("x"); | |
| 125 | bufmap.remove("x"); | |
| 109 | 126 | try testing.expect(0 == bufmap.count()); |
| 110 | 127 | |
| 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")); | |
| 113 | 130 | } |
lib/std/buf_set.zig+39-20| ... | ... | @@ -9,50 +9,69 @@ const mem = @import("mem.zig"); |
| 9 | 9 | const Allocator = mem.Allocator; |
| 10 | 10 | const testing = std.testing; |
| 11 | 11 | |
| 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. | |
| 12 | 15 | pub const BufSet = struct { |
| 13 | 16 | hash_map: BufSetHashMap, |
| 14 | 17 | |
| 15 | 18 | const BufSetHashMap = StringHashMap(void); |
| 19 | pub const Iterator = BufSetHashMap.KeyIterator; | |
| 16 | 20 | |
| 21 | /// Create a BufSet using an allocator. The allocator will | |
| 22 | /// be used internally for both backing allocations and | |
| 23 | /// string duplication. | |
| 17 | 24 | pub fn init(a: *Allocator) BufSet { |
| 18 | 25 | var self = BufSet{ .hash_map = BufSetHashMap.init(a) }; |
| 19 | 26 | return self; |
| 20 | 27 | } |
| 21 | 28 | |
| 29 | /// Free a BufSet along with all stored keys. | |
| 22 | 30 | 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.*); | |
| 26 | 34 | } |
| 27 | 35 | self.hash_map.deinit(); |
| 28 | 36 | self.* = undefined; |
| 29 | 37 | } |
| 30 | 38 | |
| 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 | }; | |
| 36 | 49 | } |
| 37 | 50 | } |
| 38 | 51 | |
| 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); | |
| 41 | 55 | } |
| 42 | 56 | |
| 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); | |
| 46 | 61 | } |
| 47 | 62 | |
| 63 | /// Returns the number of items stored in the set | |
| 48 | 64 | pub fn count(self: *const BufSet) usize { |
| 49 | 65 | return self.hash_map.count(); |
| 50 | 66 | } |
| 51 | 67 | |
| 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(); | |
| 54 | 72 | } |
| 55 | 73 | |
| 74 | /// Get the allocator used by this set | |
| 56 | 75 | pub fn allocator(self: *const BufSet) *Allocator { |
| 57 | 76 | return self.hash_map.allocator; |
| 58 | 77 | } |
| ... | ... | @@ -72,12 +91,12 @@ test "BufSet" { |
| 72 | 91 | var bufset = BufSet.init(std.testing.allocator); |
| 73 | 92 | defer bufset.deinit(); |
| 74 | 93 | |
| 75 | try bufset.put("x"); | |
| 94 | try bufset.insert("x"); | |
| 76 | 95 | try testing.expect(bufset.count() == 1); |
| 77 | bufset.delete("x"); | |
| 96 | bufset.remove("x"); | |
| 78 | 97 | try testing.expect(bufset.count() == 0); |
| 79 | 98 | |
| 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"); | |
| 83 | 102 | } |
lib/std/build.zig+21-21| ... | ... | @@ -504,10 +504,10 @@ pub const Builder = struct { |
| 504 | 504 | } |
| 505 | 505 | self.available_options_list.append(available_option) catch unreachable; |
| 506 | 506 | |
| 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; | |
| 509 | 509 | switch (type_id) { |
| 510 | .Bool => switch (entry.value.value) { | |
| 510 | .Bool => switch (option_ptr.value) { | |
| 511 | 511 | .Flag => return true, |
| 512 | 512 | .Scalar => |s| { |
| 513 | 513 | if (mem.eql(u8, s, "true")) { |
| ... | ... | @@ -526,7 +526,7 @@ pub const Builder = struct { |
| 526 | 526 | return null; |
| 527 | 527 | }, |
| 528 | 528 | }, |
| 529 | .Int => switch (entry.value.value) { | |
| 529 | .Int => switch (option_ptr.value) { | |
| 530 | 530 | .Flag => { |
| 531 | 531 | warn("Expected -D{s} to be an integer, but received a boolean.\n\n", .{name}); |
| 532 | 532 | self.markInvalidUserInput(); |
| ... | ... | @@ -553,7 +553,7 @@ pub const Builder = struct { |
| 553 | 553 | return null; |
| 554 | 554 | }, |
| 555 | 555 | }, |
| 556 | .Float => switch (entry.value.value) { | |
| 556 | .Float => switch (option_ptr.value) { | |
| 557 | 557 | .Flag => { |
| 558 | 558 | warn("Expected -D{s} to be a float, but received a boolean.\n\n", .{name}); |
| 559 | 559 | self.markInvalidUserInput(); |
| ... | ... | @@ -573,7 +573,7 @@ pub const Builder = struct { |
| 573 | 573 | return null; |
| 574 | 574 | }, |
| 575 | 575 | }, |
| 576 | .Enum => switch (entry.value.value) { | |
| 576 | .Enum => switch (option_ptr.value) { | |
| 577 | 577 | .Flag => { |
| 578 | 578 | warn("Expected -D{s} to be a string, but received a boolean.\n\n", .{name}); |
| 579 | 579 | self.markInvalidUserInput(); |
| ... | ... | @@ -594,7 +594,7 @@ pub const Builder = struct { |
| 594 | 594 | return null; |
| 595 | 595 | }, |
| 596 | 596 | }, |
| 597 | .String => switch (entry.value.value) { | |
| 597 | .String => switch (option_ptr.value) { | |
| 598 | 598 | .Flag => { |
| 599 | 599 | warn("Expected -D{s} to be a string, but received a boolean.\n\n", .{name}); |
| 600 | 600 | self.markInvalidUserInput(); |
| ... | ... | @@ -607,7 +607,7 @@ pub const Builder = struct { |
| 607 | 607 | }, |
| 608 | 608 | .Scalar => |s| return s, |
| 609 | 609 | }, |
| 610 | .List => switch (entry.value.value) { | |
| 610 | .List => switch (option_ptr.value) { | |
| 611 | 611 | .Flag => { |
| 612 | 612 | warn("Expected -D{s} to be a list, but received a boolean.\n\n", .{name}); |
| 613 | 613 | self.markInvalidUserInput(); |
| ... | ... | @@ -769,7 +769,7 @@ pub const Builder = struct { |
| 769 | 769 | const value = self.dupe(value_raw); |
| 770 | 770 | const gop = try self.user_input_options.getOrPut(name); |
| 771 | 771 | if (!gop.found_existing) { |
| 772 | gop.entry.value = UserInputOption{ | |
| 772 | gop.value_ptr.* = UserInputOption{ | |
| 773 | 773 | .name = name, |
| 774 | 774 | .value = UserValue{ .Scalar = value }, |
| 775 | 775 | .used = false, |
| ... | ... | @@ -778,7 +778,7 @@ pub const Builder = struct { |
| 778 | 778 | } |
| 779 | 779 | |
| 780 | 780 | // option already exists |
| 781 | switch (gop.entry.value.value) { | |
| 781 | switch (gop.value_ptr.value) { | |
| 782 | 782 | UserValue.Scalar => |s| { |
| 783 | 783 | // turn it into a list |
| 784 | 784 | var list = ArrayList([]const u8).init(self.allocator); |
| ... | ... | @@ -811,7 +811,7 @@ pub const Builder = struct { |
| 811 | 811 | const name = self.dupe(name_raw); |
| 812 | 812 | const gop = try self.user_input_options.getOrPut(name); |
| 813 | 813 | if (!gop.found_existing) { |
| 814 | gop.entry.value = UserInputOption{ | |
| 814 | gop.value_ptr.* = UserInputOption{ | |
| 815 | 815 | .name = name, |
| 816 | 816 | .value = UserValue{ .Flag = {} }, |
| 817 | 817 | .used = false, |
| ... | ... | @@ -820,7 +820,7 @@ pub const Builder = struct { |
| 820 | 820 | } |
| 821 | 821 | |
| 822 | 822 | // option already exists |
| 823 | switch (gop.entry.value.value) { | |
| 823 | switch (gop.value_ptr.value) { | |
| 824 | 824 | UserValue.Scalar => |s| { |
| 825 | 825 | warn("Flag '-D{s}' conflicts with option '-D{s}={s}'.\n", .{ name, name, s }); |
| 826 | 826 | return true; |
| ... | ... | @@ -866,10 +866,9 @@ pub const Builder = struct { |
| 866 | 866 | pub fn validateUserInputDidItFail(self: *Builder) bool { |
| 867 | 867 | // make sure all args are used |
| 868 | 868 | 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.*}); | |
| 873 | 872 | self.markInvalidUserInput(); |
| 874 | 873 | } |
| 875 | 874 | } |
| ... | ... | @@ -1653,7 +1652,8 @@ pub const LibExeObjStep = struct { |
| 1653 | 1652 | |
| 1654 | 1653 | pub fn linkFramework(self: *LibExeObjStep, framework_name: []const u8) void { |
| 1655 | 1654 | 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; | |
| 1657 | 1657 | } |
| 1658 | 1658 | |
| 1659 | 1659 | /// Returns whether the library, executable, or object depends on a particular system library. |
| ... | ... | @@ -2155,8 +2155,8 @@ pub const LibExeObjStep = struct { |
| 2155 | 2155 | // Inherit dependencies on darwin frameworks |
| 2156 | 2156 | if (self.target.isDarwin() and !other.isDynamicLibrary()) { |
| 2157 | 2157 | 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; | |
| 2160 | 2160 | } |
| 2161 | 2161 | } |
| 2162 | 2162 | } |
| ... | ... | @@ -2591,9 +2591,9 @@ pub const LibExeObjStep = struct { |
| 2591 | 2591 | } |
| 2592 | 2592 | |
| 2593 | 2593 | var it = self.frameworks.iterator(); |
| 2594 | while (it.next()) |entry| { | |
| 2594 | while (it.next()) |framework| { | |
| 2595 | 2595 | zig_args.append("-framework") catch unreachable; |
| 2596 | zig_args.append(entry.key) catch unreachable; | |
| 2596 | zig_args.append(framework.*) catch unreachable; | |
| 2597 | 2597 | } |
| 2598 | 2598 | } |
| 2599 | 2599 |
lib/std/build/run.zig+4-6| ... | ... | @@ -117,9 +117,9 @@ pub const RunStep = struct { |
| 117 | 117 | |
| 118 | 118 | if (prev_path) |pp| { |
| 119 | 119 | 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; | |
| 121 | 121 | } 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; | |
| 123 | 123 | } |
| 124 | 124 | } |
| 125 | 125 | |
| ... | ... | @@ -134,10 +134,8 @@ pub const RunStep = struct { |
| 134 | 134 | |
| 135 | 135 | pub fn setEnvironmentVariable(self: *RunStep, key: []const u8, value: []const u8) void { |
| 136 | 136 | 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; | |
| 141 | 139 | } |
| 142 | 140 | |
| 143 | 141 | 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) |
| 955 | 955 | while (it.next()) |pair| { |
| 956 | 956 | // +1 for '=' |
| 957 | 957 | // +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; | |
| 959 | 959 | } |
| 960 | 960 | break :x max_chars_needed; |
| 961 | 961 | }; |
| ... | ... | @@ -965,10 +965,10 @@ pub fn createWindowsEnvBlock(allocator: *mem.Allocator, env_map: *const BufMap) |
| 965 | 965 | var it = env_map.iterator(); |
| 966 | 966 | var i: usize = 0; |
| 967 | 967 | while (it.next()) |pair| { |
| 968 | i += try unicode.utf8ToUtf16Le(result[i..], pair.key); | |
| 968 | i += try unicode.utf8ToUtf16Le(result[i..], pair.key_ptr.*); | |
| 969 | 969 | result[i] = '='; |
| 970 | 970 | i += 1; |
| 971 | i += try unicode.utf8ToUtf16Le(result[i..], pair.value); | |
| 971 | i += try unicode.utf8ToUtf16Le(result[i..], pair.value_ptr.*); | |
| 972 | 972 | result[i] = 0; |
| 973 | 973 | i += 1; |
| 974 | 974 | } |
| ... | ... | @@ -990,10 +990,10 @@ pub fn createNullDelimitedEnvMap(arena: *mem.Allocator, env_map: *const std.BufM |
| 990 | 990 | var it = env_map.iterator(); |
| 991 | 991 | var i: usize = 0; |
| 992 | 992 | 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.*); | |
| 997 | 997 | envp_buf[i] = env_buf.ptr; |
| 998 | 998 | } |
| 999 | 999 | assert(i == envp_count); |
| ... | ... | @@ -1007,11 +1007,11 @@ test "createNullDelimitedEnvMap" { |
| 1007 | 1007 | var envmap = BufMap.init(allocator); |
| 1008 | 1008 | defer envmap.deinit(); |
| 1009 | 1009 | |
| 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"); | |
| 1015 | 1015 | |
| 1016 | 1016 | var arena = std.heap.ArenaAllocator.init(allocator); |
| 1017 | 1017 | defer arena.deinit(); |
lib/std/fs/watch.zig+58-56| ... | ... | @@ -165,11 +165,13 @@ pub fn Watch(comptime V: type) type { |
| 165 | 165 | .macos, .freebsd, .netbsd, .dragonfly, .openbsd => { |
| 166 | 166 | var it = self.os_data.file_table.iterator(); |
| 167 | 167 | 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; | |
| 169 | 171 | // @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); | |
| 173 | 175 | } |
| 174 | 176 | }, |
| 175 | 177 | .linux => { |
| ... | ... | @@ -177,9 +179,9 @@ pub fn Watch(comptime V: type) type { |
| 177 | 179 | { |
| 178 | 180 | // Remove all directory watches linuxEventPutter will take care of |
| 179 | 181 | // 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.*); | |
| 183 | 185 | // Errno can only be EBADF, EINVAL if either the inotify fs or the wd are invalid |
| 184 | 186 | std.debug.assert(rc == 0); |
| 185 | 187 | } |
| ... | ... | @@ -202,13 +204,13 @@ pub fn Watch(comptime V: type) type { |
| 202 | 204 | await dir_entry.value.putter_frame; |
| 203 | 205 | } |
| 204 | 206 | |
| 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(); | |
| 207 | 209 | while (file_it.next()) |file_entry| { |
| 208 | self.allocator.free(file_entry.key); | |
| 210 | self.allocator.free(file_entry.*); | |
| 209 | 211 | } |
| 210 | 212 | dir_entry.value.file_table.deinit(self.allocator); |
| 211 | self.allocator.destroy(dir_entry.value); | |
| 213 | self.allocator.destroy(dir_entry.value_ptr.*); | |
| 212 | 214 | } |
| 213 | 215 | self.os_data.dir_table.deinit(self.allocator); |
| 214 | 216 | }, |
| ... | ... | @@ -236,18 +238,18 @@ pub fn Watch(comptime V: type) type { |
| 236 | 238 | defer held.release(); |
| 237 | 239 | |
| 238 | 240 | 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)); | |
| 240 | 242 | 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; | |
| 243 | 245 | return prev_value; |
| 244 | 246 | } |
| 245 | 247 | |
| 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.* = .{ | |
| 251 | 253 | .putter_frame = undefined, |
| 252 | 254 | .value = value, |
| 253 | 255 | }; |
| ... | ... | @@ -255,7 +257,7 @@ pub fn Watch(comptime V: type) type { |
| 255 | 257 | // @TODO Can I close this fd and get an error from bsdWaitKev? |
| 256 | 258 | const flags = if (comptime std.Target.current.isDarwin()) os.O_SYMLINK | os.O_EVTONLY else 0; |
| 257 | 259 | 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.*); | |
| 259 | 261 | return null; |
| 260 | 262 | } |
| 261 | 263 | |
| ... | ... | @@ -345,24 +347,24 @@ pub fn Watch(comptime V: type) type { |
| 345 | 347 | defer held.release(); |
| 346 | 348 | |
| 347 | 349 | 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)); | |
| 349 | 351 | if (!gop.found_existing) { |
| 350 | gop.entry.value = OsData.Dir{ | |
| 352 | gop.value_ptr.* = OsData.Dir{ | |
| 351 | 353 | .dirname = try self.allocator.dupe(u8, dirname), |
| 352 | 354 | .file_table = OsData.FileTable.init(self.allocator), |
| 353 | 355 | }; |
| 354 | 356 | } |
| 355 | 357 | |
| 356 | const dir = &gop.entry.value; | |
| 358 | const dir = gop.value_ptr; | |
| 357 | 359 | 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)); | |
| 359 | 361 | 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; | |
| 362 | 364 | return prev_value; |
| 363 | 365 | } 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; | |
| 366 | 368 | return null; |
| 367 | 369 | } |
| 368 | 370 | } |
| ... | ... | @@ -383,19 +385,19 @@ pub fn Watch(comptime V: type) type { |
| 383 | 385 | defer held.release(); |
| 384 | 386 | |
| 385 | 387 | 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)); | |
| 387 | 389 | if (gop.found_existing) { |
| 388 | const dir = gop.entry.value; | |
| 390 | const dir = gop.value_ptr.*; | |
| 389 | 391 | |
| 390 | 392 | 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)); | |
| 392 | 394 | 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; | |
| 395 | 397 | return prev_value; |
| 396 | 398 | } 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); | |
| 399 | 401 | return null; |
| 400 | 402 | } |
| 401 | 403 | } else { |
| ... | ... | @@ -411,17 +413,17 @@ pub fn Watch(comptime V: type) type { |
| 411 | 413 | const dir = try self.allocator.create(OsData.Dir); |
| 412 | 414 | errdefer self.allocator.destroy(dir); |
| 413 | 415 | |
| 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.*); | |
| 416 | 418 | |
| 417 | 419 | dir.* = OsData.Dir{ |
| 418 | 420 | .file_table = OsData.FileTable.init(self.allocator), |
| 419 | 421 | .putter_frame = undefined, |
| 420 | 422 | .dir_handle = dir_handle, |
| 421 | 423 | }; |
| 422 | gop.entry.value = dir; | |
| 424 | gop.value_ptr.* = dir; | |
| 423 | 425 | 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.*); | |
| 425 | 427 | return null; |
| 426 | 428 | } |
| 427 | 429 | } |
| ... | ... | @@ -501,9 +503,9 @@ pub fn Watch(comptime V: type) type { |
| 501 | 503 | if (dir.file_table.getEntry(basename)) |entry| { |
| 502 | 504 | self.channel.put(Event{ |
| 503 | 505 | .id = id, |
| 504 | .data = entry.value, | |
| 506 | .data = entry.value_ptr.*, | |
| 505 | 507 | .dirname = dirname, |
| 506 | .basename = entry.key, | |
| 508 | .basename = entry.key_ptr.*, | |
| 507 | 509 | }); |
| 508 | 510 | } |
| 509 | 511 | } |
| ... | ... | @@ -525,7 +527,7 @@ pub fn Watch(comptime V: type) type { |
| 525 | 527 | defer held.release(); |
| 526 | 528 | |
| 527 | 529 | 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| { | |
| 529 | 531 | self.allocator.free(file_entry.key); |
| 530 | 532 | return file_entry.value; |
| 531 | 533 | } |
| ... | ... | @@ -539,7 +541,7 @@ pub fn Watch(comptime V: type) type { |
| 539 | 541 | defer held.release(); |
| 540 | 542 | |
| 541 | 543 | 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| { | |
| 543 | 545 | self.allocator.free(file_entry.key); |
| 544 | 546 | return file_entry.value; |
| 545 | 547 | } |
| ... | ... | @@ -552,14 +554,14 @@ pub fn Watch(comptime V: type) type { |
| 552 | 554 | const held = self.os_data.table_lock.acquire(); |
| 553 | 555 | defer held.release(); |
| 554 | 556 | |
| 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; | |
| 557 | 559 | // @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.*); | |
| 561 | 563 | |
| 562 | self.os_data.file_table.removeAssertDiscard(realpath); | |
| 564 | assert(self.os_data.file_table.remove(realpath)); | |
| 563 | 565 | }, |
| 564 | 566 | else => @compileError("Unsupported OS"), |
| 565 | 567 | } |
| ... | ... | @@ -594,19 +596,19 @@ pub fn Watch(comptime V: type) type { |
| 594 | 596 | if (dir.file_table.getEntry(basename)) |file_value| { |
| 595 | 597 | self.channel.put(Event{ |
| 596 | 598 | .id = .CloseWrite, |
| 597 | .data = file_value.value, | |
| 599 | .data = file_value.value_ptr.*, | |
| 598 | 600 | .dirname = dir.dirname, |
| 599 | .basename = file_value.key, | |
| 601 | .basename = file_value.key_ptr.*, | |
| 600 | 602 | }); |
| 601 | 603 | } |
| 602 | 604 | } else if (ev.mask & os.linux.IN_IGNORED == os.linux.IN_IGNORED) { |
| 603 | 605 | // Directory watch was removed |
| 604 | 606 | const held = self.os_data.table_lock.acquire(); |
| 605 | 607 | 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(); | |
| 608 | 610 | while (file_it.next()) |file_entry| { |
| 609 | self.allocator.free(file_entry.key); | |
| 611 | self.allocator.free(file_entry.*); | |
| 610 | 612 | } |
| 611 | 613 | self.allocator.free(wd_entry.value.dirname); |
| 612 | 614 | wd_entry.value.file_table.deinit(self.allocator); |
| ... | ... | @@ -620,9 +622,9 @@ pub fn Watch(comptime V: type) type { |
| 620 | 622 | if (dir.file_table.getEntry(basename)) |file_value| { |
| 621 | 623 | self.channel.put(Event{ |
| 622 | 624 | .id = .Delete, |
| 623 | .data = file_value.value, | |
| 625 | .data = file_value.value_ptr.*, | |
| 624 | 626 | .dirname = dir.dirname, |
| 625 | .basename = file_value.key, | |
| 627 | .basename = file_value.key_ptr.*, | |
| 626 | 628 | }); |
| 627 | 629 | } |
| 628 | 630 | } |
lib/std/hash_map.zig+872-225| ... | ... | @@ -15,7 +15,7 @@ const trait = meta.trait; |
| 15 | 15 | const Allocator = mem.Allocator; |
| 16 | 16 | const Wyhash = std.hash.Wyhash; |
| 17 | 17 | |
| 18 | pub fn getAutoHashFn(comptime K: type) (fn (K) u64) { | |
| 18 | pub fn getAutoHashFn(comptime K: type, comptime Context: type) (fn (Context, K) u64) { | |
| 19 | 19 | comptime { |
| 20 | 20 | assert(@hasDecl(std, "StringHashMap")); // detect when the following message needs updated |
| 21 | 21 | if (K == []const u8) { |
| ... | ... | @@ -28,7 +28,7 @@ pub fn getAutoHashFn(comptime K: type) (fn (K) u64) { |
| 28 | 28 | } |
| 29 | 29 | |
| 30 | 30 | return struct { |
| 31 | fn hash(key: K) u64 { | |
| 31 | fn hash(ctx: Context, key: K) u64 { | |
| 32 | 32 | if (comptime trait.hasUniqueRepresentation(K)) { |
| 33 | 33 | return Wyhash.hash(0, std.mem.asBytes(&key)); |
| 34 | 34 | } else { |
| ... | ... | @@ -40,31 +40,51 @@ pub fn getAutoHashFn(comptime K: type) (fn (K) u64) { |
| 40 | 40 | }.hash; |
| 41 | 41 | } |
| 42 | 42 | |
| 43 | pub fn getAutoEqlFn(comptime K: type) (fn (K, K) bool) { | |
| 43 | pub fn getAutoEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K) bool) { | |
| 44 | 44 | return struct { |
| 45 | fn eql(a: K, b: K) bool { | |
| 45 | fn eql(ctx: Context, a: K, b: K) bool { | |
| 46 | 46 | return meta.eql(a, b); |
| 47 | 47 | } |
| 48 | 48 | }.eql; |
| 49 | 49 | } |
| 50 | 50 | |
| 51 | 51 | pub 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); | |
| 53 | 53 | } |
| 54 | 54 | |
| 55 | 55 | pub 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 | ||
| 59 | pub fn AutoContext(comptime K: type) type { | |
| 60 | return struct { | |
| 61 | pub const hash = getAutoHashFn(K, @This()); | |
| 62 | pub const eql = getAutoEqlFn(K, @This()); | |
| 63 | }; | |
| 57 | 64 | } |
| 58 | 65 | |
| 59 | 66 | /// Builtin hashmap for strings as keys. |
| 67 | /// Key memory is managed by the caller. Keys and values | |
| 68 | /// will not automatically be freed. | |
| 60 | 69 | pub 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); | |
| 62 | 71 | } |
| 63 | 72 | |
| 73 | /// Key memory is managed by the caller. Keys and values | |
| 74 | /// will not automatically be freed. | |
| 64 | 75 | pub 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); | |
| 66 | 77 | } |
| 67 | 78 | |
| 79 | pub 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 | ||
| 68 | 88 | pub fn eqlString(a: []const u8, b: []const u8) bool { |
| 69 | 89 | return mem.eql(u8, a, b); |
| 70 | 90 | } |
| ... | ... | @@ -78,6 +98,222 @@ pub const DefaultMaxLoadPercentage = default_max_load_percentage; |
| 78 | 98 | |
| 79 | 99 | pub const default_max_load_percentage = 80; |
| 80 | 100 | |
| 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. | |
| 109 | pub 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 | ||
| 81 | 317 | /// General purpose hash table. |
| 82 | 318 | /// No order is guaranteed and any modification invalidates live iterators. |
| 83 | 319 | /// It provides fast operations (lookup, insertion, deletion) with quite high |
| ... | ... | @@ -86,83 +322,167 @@ pub const default_max_load_percentage = 80; |
| 86 | 322 | /// field, see `HashMapUnmanaged`. |
| 87 | 323 | /// If iterating over the table entries is a strong usecase and needs to be fast, |
| 88 | 324 | /// 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 | |
| 89 | 332 | pub fn HashMap( |
| 90 | 333 | comptime K: type, |
| 91 | 334 | comptime V: type, |
| 92 | comptime hashFn: fn (key: K) u64, | |
| 93 | comptime eqlFn: fn (a: K, b: K) bool, | |
| 335 | comptime Context: type, | |
| 94 | 336 | comptime max_load_percentage: u64, |
| 95 | 337 | ) type { |
| 338 | comptime verifyContext(Context, K, K, u64); | |
| 96 | 339 | return struct { |
| 97 | 340 | unmanaged: Unmanaged, |
| 98 | 341 | allocator: *Allocator, |
| 342 | ctx: Context, | |
| 99 | 343 | |
| 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 | |
| 101 | 347 | 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 | |
| 102 | 351 | pub const Hash = Unmanaged.Hash; |
| 352 | /// The iterator type returned by iterator() | |
| 103 | 353 | 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 | |
| 104 | 359 | pub const Size = Unmanaged.Size; |
| 360 | /// The type returned from getOrPut and variants | |
| 105 | 361 | pub const GetOrPutResult = Unmanaged.GetOrPutResult; |
| 106 | 362 | |
| 107 | 363 | const Self = @This(); |
| 108 | 364 | |
| 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. | |
| 109 | 368 | 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 { | |
| 110 | 381 | return .{ |
| 111 | 382 | .unmanaged = .{}, |
| 112 | 383 | .allocator = allocator, |
| 384 | .ctx = ctx, | |
| 113 | 385 | }; |
| 114 | 386 | } |
| 115 | 387 | |
| 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. | |
| 116 | 392 | pub fn deinit(self: *Self) void { |
| 117 | 393 | self.unmanaged.deinit(self.allocator); |
| 118 | 394 | self.* = undefined; |
| 119 | 395 | } |
| 120 | 396 | |
| 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. | |
| 121 | 401 | pub fn clearRetainingCapacity(self: *Self) void { |
| 122 | 402 | return self.unmanaged.clearRetainingCapacity(); |
| 123 | 403 | } |
| 124 | 404 | |
| 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. | |
| 125 | 409 | pub fn clearAndFree(self: *Self) void { |
| 126 | 410 | return self.unmanaged.clearAndFree(self.allocator); |
| 127 | 411 | } |
| 128 | 412 | |
| 413 | /// Return the number of items in the map. | |
| 129 | 414 | pub fn count(self: Self) Size { |
| 130 | 415 | return self.unmanaged.count(); |
| 131 | 416 | } |
| 132 | 417 | |
| 418 | /// Create an iterator over the entries in the map. | |
| 419 | /// The iterator is invalidated if the map is modified. | |
| 133 | 420 | pub fn iterator(self: *const Self) Iterator { |
| 134 | 421 | return self.unmanaged.iterator(); |
| 135 | 422 | } |
| 136 | 423 | |
| 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 | ||
| 137 | 436 | /// If key exists this function cannot fail. |
| 138 | 437 | /// 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. | |
| 140 | 439 | /// 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 | |
| 142 | 441 | /// the value (but not the key). |
| 143 | 442 | 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); | |
| 145 | 454 | } |
| 146 | 455 | |
| 147 | 456 | /// 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. | |
| 149 | 458 | /// 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 | |
| 151 | 460 | /// the value (but not the key). |
| 152 | 461 | /// If a new entry needs to be stored, this function asserts there |
| 153 | 462 | /// is enough capacity to store it. |
| 154 | 463 | 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); | |
| 156 | 476 | } |
| 157 | 477 | |
| 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); | |
| 160 | 480 | } |
| 161 | 481 | |
| 162 | 482 | /// Increases capacity, guaranteeing that insertions up until the |
| 163 | 483 | /// `expected_count` will not cause an allocation, and therefore cannot fail. |
| 164 | 484 | 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); | |
| 166 | 486 | } |
| 167 | 487 | |
| 168 | 488 | /// Returns the number of total elements which may be present before it is |
| ... | ... | @@ -174,67 +494,114 @@ pub fn HashMap( |
| 174 | 494 | /// Clobbers any existing data. To detect if a put would clobber |
| 175 | 495 | /// existing data, see `getOrPut`. |
| 176 | 496 | 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); | |
| 178 | 498 | } |
| 179 | 499 | |
| 180 | 500 | /// Inserts a key-value pair into the hash map, asserting that no previous |
| 181 | 501 | /// entry with the same key is already present |
| 182 | 502 | 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); | |
| 184 | 504 | } |
| 185 | 505 | |
| 186 | 506 | /// Asserts there is enough capacity to store the new key-value pair. |
| 187 | 507 | /// Clobbers any existing data. To detect if a put would clobber |
| 188 | 508 | /// existing data, see `getOrPutAssumeCapacity`. |
| 189 | 509 | 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); | |
| 191 | 511 | } |
| 192 | 512 | |
| 193 | 513 | /// Asserts there is enough capacity to store the new key-value pair. |
| 194 | 514 | /// Asserts that it does not clobber any existing data. |
| 195 | 515 | /// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`. |
| 196 | 516 | 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); | |
| 198 | 518 | } |
| 199 | 519 | |
| 200 | 520 | /// 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); | |
| 203 | 523 | } |
| 204 | 524 | |
| 205 | 525 | /// Inserts a new `Entry` into the hash map, returning the previous one, if any. |
| 206 | 526 | /// 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); | |
| 209 | 529 | } |
| 210 | 530 | |
| 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 | |
| 211 | 541 | 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); | |
| 213 | 558 | } |
| 214 | 559 | |
| 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); | |
| 217 | 562 | } |
| 218 | 563 | |
| 564 | /// Check if the map contains a key | |
| 219 | 565 | 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); | |
| 221 | 571 | } |
| 222 | 572 | |
| 223 | 573 | /// If there is an `Entry` with a matching key, it is deleted from |
| 224 | 574 | /// 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); | |
| 227 | 577 | } |
| 228 | 578 | |
| 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); | |
| 233 | 581 | } |
| 234 | 582 | |
| 583 | /// Creates a copy of this map, using the same allocator | |
| 235 | 584 | 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); | |
| 238 | 605 | } |
| 239 | 606 | }; |
| 240 | 607 | } |
| ... | ... | @@ -251,11 +618,12 @@ pub fn HashMap( |
| 251 | 618 | pub fn HashMapUnmanaged( |
| 252 | 619 | comptime K: type, |
| 253 | 620 | comptime V: type, |
| 254 | hashFn: fn (key: K) u64, | |
| 255 | eqlFn: fn (a: K, b: K) bool, | |
| 621 | comptime Context: type, | |
| 256 | 622 | comptime max_load_percentage: u64, |
| 257 | 623 | ) 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); | |
| 259 | 627 | |
| 260 | 628 | return struct { |
| 261 | 629 | const Self = @This(); |
| ... | ... | @@ -284,19 +652,25 @@ pub fn HashMapUnmanaged( |
| 284 | 652 | const minimal_capacity = 8; |
| 285 | 653 | |
| 286 | 654 | // This hashmap is specially designed for sizes that fit in a u32. |
| 287 | const Size = u32; | |
| 655 | pub const Size = u32; | |
| 288 | 656 | |
| 289 | 657 | // u64 hashes guarantee us that the fingerprint bits will never be used |
| 290 | 658 | // to compute the index of a slot, maximizing the use of entropy. |
| 291 | const Hash = u64; | |
| 659 | pub const Hash = u64; | |
| 292 | 660 | |
| 293 | 661 | pub const Entry = struct { |
| 662 | key_ptr: *K, | |
| 663 | value_ptr: *V, | |
| 664 | }; | |
| 665 | ||
| 666 | pub const KV = struct { | |
| 294 | 667 | key: K, |
| 295 | 668 | value: V, |
| 296 | 669 | }; |
| 297 | 670 | |
| 298 | 671 | const Header = packed struct { |
| 299 | entries: [*]Entry, | |
| 672 | values: [*]V, | |
| 673 | keys: [*]K, | |
| 300 | 674 | capacity: Size, |
| 301 | 675 | }; |
| 302 | 676 | |
| ... | ... | @@ -353,11 +727,11 @@ pub fn HashMapUnmanaged( |
| 353 | 727 | assert(@alignOf(Metadata) == 1); |
| 354 | 728 | } |
| 355 | 729 | |
| 356 | const Iterator = struct { | |
| 730 | pub const Iterator = struct { | |
| 357 | 731 | hm: *const Self, |
| 358 | 732 | index: Size = 0, |
| 359 | 733 | |
| 360 | pub fn next(it: *Iterator) ?*Entry { | |
| 734 | pub fn next(it: *Iterator) ?Entry { | |
| 361 | 735 | assert(it.index <= it.hm.capacity()); |
| 362 | 736 | if (it.hm.size == 0) return null; |
| 363 | 737 | |
| ... | ... | @@ -370,9 +744,10 @@ pub fn HashMapUnmanaged( |
| 370 | 744 | it.index += 1; |
| 371 | 745 | }) { |
| 372 | 746 | 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]; | |
| 374 | 749 | it.index += 1; |
| 375 | return entry; | |
| 750 | return Entry{ .key_ptr = key, .value_ptr = value }; | |
| 376 | 751 | } |
| 377 | 752 | } |
| 378 | 753 | |
| ... | ... | @@ -380,17 +755,50 @@ pub fn HashMapUnmanaged( |
| 380 | 755 | } |
| 381 | 756 | }; |
| 382 | 757 | |
| 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 | ||
| 383 | 783 | pub const GetOrPutResult = struct { |
| 384 | entry: *Entry, | |
| 784 | key_ptr: *K, | |
| 785 | value_ptr: *V, | |
| 385 | 786 | found_existing: bool, |
| 386 | 787 | }; |
| 387 | 788 | |
| 388 | pub const Managed = HashMap(K, V, hashFn, eqlFn, max_load_percentage); | |
| 789 | pub const Managed = HashMap(K, V, Context, max_load_percentage); | |
| 389 | 790 | |
| 390 | 791 | 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 { | |
| 391 | 798 | return .{ |
| 392 | 799 | .unmanaged = self, |
| 393 | 800 | .allocator = allocator, |
| 801 | .ctx = ctx, | |
| 394 | 802 | }; |
| 395 | 803 | } |
| 396 | 804 | |
| ... | ... | @@ -403,26 +811,6 @@ pub fn HashMapUnmanaged( |
| 403 | 811 | self.* = undefined; |
| 404 | 812 | } |
| 405 | 813 | |
| 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 | ||
| 426 | 814 | fn capacityForSize(size: Size) Size { |
| 427 | 815 | var new_cap = @truncate(u32, (@as(u64, size) * 100) / max_load_percentage + 1); |
| 428 | 816 | new_cap = math.ceilPowerOfTwo(u32, new_cap) catch unreachable; |
| ... | ... | @@ -430,8 +818,13 @@ pub fn HashMapUnmanaged( |
| 430 | 818 | } |
| 431 | 819 | |
| 432 | 820 | 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 { | |
| 433 | 826 | if (new_size > self.size) |
| 434 | try self.growIfNeeded(allocator, new_size - self.size); | |
| 827 | try self.growIfNeeded(allocator, new_size - self.size, ctx); | |
| 435 | 828 | } |
| 436 | 829 | |
| 437 | 830 | pub fn clearRetainingCapacity(self: *Self) void { |
| ... | ... | @@ -456,8 +849,12 @@ pub fn HashMapUnmanaged( |
| 456 | 849 | return @ptrCast(*Header, @ptrCast([*]Header, self.metadata.?) - 1); |
| 457 | 850 | } |
| 458 | 851 | |
| 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; | |
| 461 | 858 | } |
| 462 | 859 | |
| 463 | 860 | pub fn capacity(self: *const Self) Size { |
| ... | ... | @@ -470,28 +867,75 @@ pub fn HashMapUnmanaged( |
| 470 | 867 | return .{ .hm = self }; |
| 471 | 868 | } |
| 472 | 869 | |
| 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 | ||
| 473 | 902 | /// Insert an entry in the map. Assumes it is not already present. |
| 474 | 903 | 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); | |
| 477 | 911 | |
| 478 | self.putAssumeCapacityNoClobber(key, value); | |
| 912 | self.putAssumeCapacityNoClobberContext(key, value, ctx); | |
| 479 | 913 | } |
| 480 | 914 | |
| 481 | 915 | /// Asserts there is enough capacity to store the new key-value pair. |
| 482 | 916 | /// Clobbers any existing data. To detect if a put would clobber |
| 483 | 917 | /// existing data, see `getOrPutAssumeCapacity`. |
| 484 | 918 | 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; | |
| 487 | 926 | } |
| 488 | 927 | |
| 489 | 928 | /// Insert an entry in the map. Assumes it is not already present, |
| 490 | 929 | /// and that no allocation is needed. |
| 491 | 930 | 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)); | |
| 493 | 937 | |
| 494 | const hash = hashFn(key); | |
| 938 | const hash = ctx.hash(key); | |
| 495 | 939 | const mask = self.capacity() - 1; |
| 496 | 940 | var idx = @truncate(usize, hash & mask); |
| 497 | 941 | |
| ... | ... | @@ -508,40 +952,102 @@ pub fn HashMapUnmanaged( |
| 508 | 952 | |
| 509 | 953 | const fingerprint = Metadata.takeFingerprint(hash); |
| 510 | 954 | metadata[0].fill(fingerprint); |
| 511 | self.entries()[idx] = Entry{ .key = key, .value = value }; | |
| 955 | self.keys()[idx] = key; | |
| 956 | self.values()[idx] = value; | |
| 512 | 957 | |
| 513 | 958 | self.size += 1; |
| 514 | 959 | } |
| 515 | 960 | |
| 516 | 961 | /// 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; | |
| 520 | 970 | if (gop.found_existing) { |
| 521 | result = gop.entry.*; | |
| 971 | result = KV{ | |
| 972 | .key = gop.key_ptr.*, | |
| 973 | .value = gop.value_ptr.*, | |
| 974 | }; | |
| 522 | 975 | } |
| 523 | gop.entry.value = value; | |
| 976 | gop.value_ptr.* = value; | |
| 524 | 977 | return result; |
| 525 | 978 | } |
| 526 | 979 | |
| 527 | 980 | /// Inserts a new `Entry` into the hash map, returning the previous one, if any. |
| 528 | 981 | /// 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; | |
| 532 | 990 | if (gop.found_existing) { |
| 533 | result = gop.entry.*; | |
| 991 | result = KV{ | |
| 992 | .key = gop.key_ptr.*, | |
| 993 | .value = gop.value_ptr.*, | |
| 994 | }; | |
| 534 | 995 | } |
| 535 | gop.entry.value = value; | |
| 996 | gop.value_ptr.* = value; | |
| 536 | 997 | return result; |
| 537 | 998 | } |
| 538 | 999 | |
| 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 | ||
| 540 | 1039 | if (self.size == 0) { |
| 541 | 1040 | return null; |
| 542 | 1041 | } |
| 543 | 1042 | |
| 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 | } | |
| 545 | 1051 | const mask = self.capacity() - 1; |
| 546 | 1052 | const fingerprint = Metadata.takeFingerprint(hash); |
| 547 | 1053 | var idx = @truncate(usize, hash & mask); |
| ... | ... | @@ -549,11 +1055,20 @@ pub fn HashMapUnmanaged( |
| 549 | 1055 | var metadata = self.metadata.? + idx; |
| 550 | 1056 | while (metadata[0].isUsed() or metadata[0].isTombstone()) { |
| 551 | 1057 | 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; | |
| 555 | 1069 | } |
| 556 | 1070 | } |
| 1071 | ||
| 557 | 1072 | idx = (idx + 1) & mask; |
| 558 | 1073 | metadata = self.metadata.? + idx; |
| 559 | 1074 | } |
| ... | ... | @@ -561,46 +1076,122 @@ pub fn HashMapUnmanaged( |
| 561 | 1076 | return null; |
| 562 | 1077 | } |
| 563 | 1078 | |
| 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 | ||
| 564 | 1097 | /// Insert an entry if the associated key is not already present, otherwise update preexisting value. |
| 565 | 1098 | 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; | |
| 568 | 1106 | } |
| 569 | 1107 | |
| 570 | 1108 | /// 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]; | |
| 574 | 1120 | } |
| 1121 | return null; | |
| 1122 | } | |
| 575 | 1123 | |
| 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]; | |
| 591 | 1136 | } |
| 592 | ||
| 593 | 1137 | return null; |
| 594 | 1138 | } |
| 595 | 1139 | |
| 596 | 1140 | 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); | |
| 600 | 1170 | } |
| 601 | 1171 | |
| 602 | 1172 | 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 | } | |
| 604 | 1195 | const mask = self.capacity() - 1; |
| 605 | 1196 | const fingerprint = Metadata.takeFingerprint(hash); |
| 606 | 1197 | var idx = @truncate(usize, hash & mask); |
| ... | ... | @@ -609,9 +1200,21 @@ pub fn HashMapUnmanaged( |
| 609 | 1200 | var metadata = self.metadata.? + idx; |
| 610 | 1201 | while (metadata[0].isUsed() or metadata[0].isTombstone()) { |
| 611 | 1202 | 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 | }; | |
| 615 | 1218 | } |
| 616 | 1219 | } else if (first_tombstone_idx == self.capacity() and metadata[0].isTombstone()) { |
| 617 | 1220 | first_tombstone_idx = idx; |
| ... | ... | @@ -631,79 +1234,67 @@ pub fn HashMapUnmanaged( |
| 631 | 1234 | } |
| 632 | 1235 | |
| 633 | 1236 | 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; | |
| 636 | 1241 | self.size += 1; |
| 637 | 1242 | |
| 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 | }; | |
| 639 | 1248 | } |
| 640 | 1249 | |
| 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 }; | |
| 645 | 1262 | } |
| 646 | 1263 | |
| 647 | 1264 | /// Return true if there is a value associated with key in the map. |
| 648 | 1265 | 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); | |
| 650 | 1269 | } |
| 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; | |
| 679 | 1275 | } |
| 680 | 1276 | |
| 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; | |
| 704 | 1295 | } |
| 705 | 1296 | |
| 706 | unreachable; | |
| 1297 | return false; | |
| 707 | 1298 | } |
| 708 | 1299 | |
| 709 | 1300 | fn initMetadatas(self: *Self) void { |
| ... | ... | @@ -718,14 +1309,19 @@ pub fn HashMapUnmanaged( |
| 718 | 1309 | return @truncate(Size, max_load - self.available); |
| 719 | 1310 | } |
| 720 | 1311 | |
| 721 | fn growIfNeeded(self: *Self, allocator: *Allocator, new_count: Size) !void { | |
| 1312 | fn growIfNeeded(self: *Self, allocator: *Allocator, new_count: Size, ctx: Context) !void { | |
| 722 | 1313 | 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); | |
| 724 | 1315 | } |
| 725 | 1316 | } |
| 726 | 1317 | |
| 727 | 1318 | 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){}; | |
| 729 | 1325 | if (self.size == 0) |
| 730 | 1326 | return other; |
| 731 | 1327 | |
| ... | ... | @@ -736,11 +1332,11 @@ pub fn HashMapUnmanaged( |
| 736 | 1332 | |
| 737 | 1333 | var i: Size = 0; |
| 738 | 1334 | var metadata = self.metadata.?; |
| 739 | var entr = self.entries(); | |
| 1335 | var keys_ptr = self.keys(); | |
| 1336 | var values_ptr = self.values(); | |
| 740 | 1337 | while (i < self.capacity()) : (i += 1) { |
| 741 | 1338 | 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); | |
| 744 | 1340 | if (other.size == self.size) |
| 745 | 1341 | break; |
| 746 | 1342 | } |
| ... | ... | @@ -749,7 +1345,8 @@ pub fn HashMapUnmanaged( |
| 749 | 1345 | return other; |
| 750 | 1346 | } |
| 751 | 1347 | |
| 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); | |
| 753 | 1350 | const new_cap = std.math.max(new_capacity, minimal_capacity); |
| 754 | 1351 | assert(new_cap > self.capacity()); |
| 755 | 1352 | assert(std.math.isPowerOfTwo(new_cap)); |
| ... | ... | @@ -764,11 +1361,11 @@ pub fn HashMapUnmanaged( |
| 764 | 1361 | const old_capacity = self.capacity(); |
| 765 | 1362 | var i: Size = 0; |
| 766 | 1363 | var metadata = self.metadata.?; |
| 767 | var entr = self.entries(); | |
| 1364 | var keys_ptr = self.keys(); | |
| 1365 | var values_ptr = self.values(); | |
| 768 | 1366 | while (i < old_capacity) : (i += 1) { |
| 769 | 1367 | 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); | |
| 772 | 1369 | if (map.size == self.size) |
| 773 | 1370 | break; |
| 774 | 1371 | } |
| ... | ... | @@ -780,26 +1377,64 @@ pub fn HashMapUnmanaged( |
| 780 | 1377 | } |
| 781 | 1378 | |
| 782 | 1379 | 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 | ||
| 783 | 1385 | 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); | |
| 784 | 1390 | |
| 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); | |
| 787 | 1393 | |
| 788 | const total_size = meta_size + entries_size; | |
| 1394 | const total_size = std.mem.alignForward(vals_end, max_align); | |
| 789 | 1395 | |
| 790 | const slice = try allocator.alignedAlloc(u8, @alignOf(Header), total_size); | |
| 1396 | const slice = try allocator.alignedAlloc(u8, max_align, total_size); | |
| 791 | 1397 | const ptr = @ptrToInt(slice.ptr); |
| 792 | 1398 | |
| 793 | 1399 | 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); | |
| 797 | 1400 | |
| 798 | 1401 | 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 | } | |
| 800 | 1408 | hdr.capacity = new_capacity; |
| 801 | 1409 | self.metadata = @intToPtr([*]Metadata, metadata); |
| 802 | 1410 | } |
| 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 | } | |
| 803 | 1438 | }; |
| 804 | 1439 | } |
| 805 | 1440 | |
| ... | ... | @@ -822,14 +1457,14 @@ test "std.hash_map basic usage" { |
| 822 | 1457 | var sum: u32 = 0; |
| 823 | 1458 | var it = map.iterator(); |
| 824 | 1459 | while (it.next()) |kv| { |
| 825 | sum += kv.key; | |
| 1460 | sum += kv.key_ptr.*; | |
| 826 | 1461 | } |
| 827 | try expect(sum == total); | |
| 1462 | try expectEqual(total, sum); | |
| 828 | 1463 | |
| 829 | 1464 | i = 0; |
| 830 | 1465 | sum = 0; |
| 831 | 1466 | while (i < count) : (i += 1) { |
| 832 | try expectEqual(map.get(i).?, i); | |
| 1467 | try expectEqual(i, map.get(i).?); | |
| 833 | 1468 | sum += map.get(i).?; |
| 834 | 1469 | } |
| 835 | 1470 | try expectEqual(total, sum); |
| ... | ... | @@ -903,7 +1538,7 @@ test "std.hash_map grow" { |
| 903 | 1538 | i = 0; |
| 904 | 1539 | var it = map.iterator(); |
| 905 | 1540 | while (it.next()) |kv| { |
| 906 | try expectEqual(kv.key, kv.value); | |
| 1541 | try expectEqual(kv.key_ptr.*, kv.value_ptr.*); | |
| 907 | 1542 | i += 1; |
| 908 | 1543 | } |
| 909 | 1544 | try expectEqual(i, growTo); |
| ... | ... | @@ -931,9 +1566,9 @@ test "std.hash_map clone" { |
| 931 | 1566 | defer b.deinit(); |
| 932 | 1567 | |
| 933 | 1568 | 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); | |
| 937 | 1572 | } |
| 938 | 1573 | |
| 939 | 1574 | test "std.hash_map ensureCapacity with existing elements" { |
| ... | ... | @@ -975,8 +1610,8 @@ test "std.hash_map remove" { |
| 975 | 1610 | try expectEqual(map.count(), 10); |
| 976 | 1611 | var it = map.iterator(); |
| 977 | 1612 | 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); | |
| 980 | 1615 | } |
| 981 | 1616 | |
| 982 | 1617 | i = 0; |
| ... | ... | @@ -1146,7 +1781,7 @@ test "std.hash_map putAssumeCapacity" { |
| 1146 | 1781 | i = 0; |
| 1147 | 1782 | var sum = i; |
| 1148 | 1783 | while (i < 20) : (i += 1) { |
| 1149 | sum += map.get(i).?; | |
| 1784 | sum += map.getPtr(i).?.*; | |
| 1150 | 1785 | } |
| 1151 | 1786 | try expectEqual(sum, 190); |
| 1152 | 1787 | |
| ... | ... | @@ -1201,33 +1836,34 @@ test "std.hash_map basic hash map usage" { |
| 1201 | 1836 | |
| 1202 | 1837 | const gop1 = try map.getOrPut(5); |
| 1203 | 1838 | 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); | |
| 1207 | 1842 | |
| 1208 | 1843 | const gop2 = try map.getOrPut(99); |
| 1209 | 1844 | 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); | |
| 1212 | 1847 | |
| 1213 | 1848 | const gop3 = try map.getOrPutValue(5, 5); |
| 1214 | try testing.expect(gop3.value == 77); | |
| 1849 | try testing.expect(gop3.value_ptr.* == 77); | |
| 1215 | 1850 | |
| 1216 | 1851 | const gop4 = try map.getOrPutValue(100, 41); |
| 1217 | try testing.expect(gop4.value == 41); | |
| 1852 | try testing.expect(gop4.value_ptr.* == 41); | |
| 1218 | 1853 | |
| 1219 | 1854 | 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); | |
| 1221 | 1856 | try testing.expect(map.get(2).? == 22); |
| 1222 | 1857 | |
| 1223 | const rmv1 = map.remove(2); | |
| 1858 | const rmv1 = map.fetchRemove(2); | |
| 1224 | 1859 | try testing.expect(rmv1.?.key == 2); |
| 1225 | 1860 | 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); | |
| 1227 | 1863 | try testing.expect(map.getEntry(2) == null); |
| 1228 | 1864 | try testing.expect(map.get(2) == null); |
| 1229 | 1865 | |
| 1230 | map.removeAssertDiscard(3); | |
| 1866 | try testing.expect(map.remove(3) == true); | |
| 1231 | 1867 | } |
| 1232 | 1868 | |
| 1233 | 1869 | test "std.hash_map clone" { |
| ... | ... | @@ -1247,3 +1883,14 @@ test "std.hash_map clone" { |
| 1247 | 1883 | try testing.expect(copy.get(i).? == i * 10); |
| 1248 | 1884 | } |
| 1249 | 1885 | } |
| 1886 | ||
| 1887 | test "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 { |
| 346 | 346 | break; |
| 347 | 347 | } |
| 348 | 348 | } |
| 349 | var it = self.large_allocations.iterator(); | |
| 349 | var it = self.large_allocations.valueIterator(); | |
| 350 | 350 | while (it.next()) |large_alloc| { |
| 351 | 351 | 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(), | |
| 353 | 353 | }); |
| 354 | 354 | leaks = true; |
| 355 | 355 | } |
| ... | ... | @@ -444,7 +444,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type { |
| 444 | 444 | } |
| 445 | 445 | }; |
| 446 | 446 | |
| 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) { | |
| 448 | 448 | var addresses: [stack_n]usize = [1]usize{0} ** stack_n; |
| 449 | 449 | var free_stack_trace = StackTrace{ |
| 450 | 450 | .instruction_addresses = &addresses, |
| ... | ... | @@ -452,9 +452,9 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type { |
| 452 | 452 | }; |
| 453 | 453 | std.debug.captureStackTrace(ret_addr, &free_stack_trace); |
| 454 | 454 | 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, | |
| 456 | 456 | old_mem.len, |
| 457 | entry.value.getStackTrace(), | |
| 457 | entry.value_ptr.getStackTrace(), | |
| 458 | 458 | free_stack_trace, |
| 459 | 459 | }); |
| 460 | 460 | } |
| ... | ... | @@ -466,7 +466,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type { |
| 466 | 466 | log.info("large free {d} bytes at {*}", .{ old_mem.len, old_mem.ptr }); |
| 467 | 467 | } |
| 468 | 468 | |
| 469 | self.large_allocations.removeAssertDiscard(@ptrToInt(old_mem.ptr)); | |
| 469 | assert(self.large_allocations.remove(@ptrToInt(old_mem.ptr))); | |
| 470 | 470 | return 0; |
| 471 | 471 | } |
| 472 | 472 | |
| ... | ... | @@ -475,8 +475,8 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type { |
| 475 | 475 | old_mem.len, old_mem.ptr, new_size, |
| 476 | 476 | }); |
| 477 | 477 | } |
| 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); | |
| 480 | 480 | return result_len; |
| 481 | 481 | } |
| 482 | 482 | |
| ... | ... | @@ -645,8 +645,8 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type { |
| 645 | 645 | |
| 646 | 646 | const gop = self.large_allocations.getOrPutAssumeCapacity(@ptrToInt(slice.ptr)); |
| 647 | 647 | 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); | |
| 650 | 650 | |
| 651 | 651 | if (config.verbose_log) { |
| 652 | 652 | 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) { |
| 1303 | 1303 | try child_whitespace.outputIndent(out_stream); |
| 1304 | 1304 | } |
| 1305 | 1305 | |
| 1306 | try stringify(entry.key, options, out_stream); | |
| 1306 | try stringify(entry.key_ptr.*, options, out_stream); | |
| 1307 | 1307 | try out_stream.writeByte(':'); |
| 1308 | 1308 | if (child_options.whitespace) |child_whitespace| { |
| 1309 | 1309 | if (child_whitespace.separator) { |
| 1310 | 1310 | try out_stream.writeByte(' '); |
| 1311 | 1311 | } |
| 1312 | 1312 | } |
| 1313 | try stringify(entry.value, child_options, out_stream); | |
| 1313 | try stringify(entry.value_ptr.*, child_options, out_stream); | |
| 1314 | 1314 | } |
| 1315 | 1315 | if (field_output) { |
| 1316 | 1316 | if (options.whitespace) |whitespace| { |
lib/std/math.zig+47-4| ... | ... | @@ -380,12 +380,41 @@ test "math.min" { |
| 380 | 380 | } |
| 381 | 381 | } |
| 382 | 382 | |
| 383 | /// Finds the min of three numbers | |
| 384 | pub fn min3(x: anytype, y: anytype, z: anytype) @TypeOf(x, y, z) { | |
| 385 | return min(x, min(y, z)); | |
| 386 | } | |
| 387 | ||
| 388 | test "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 | ||
| 383 | 397 | pub fn max(x: anytype, y: anytype) @TypeOf(x, y) { |
| 384 | 398 | return if (x > y) x else y; |
| 385 | 399 | } |
| 386 | 400 | |
| 387 | 401 | test "math.max" { |
| 388 | 402 | 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 | |
| 407 | pub fn max3(x: anytype, y: anytype, z: anytype) @TypeOf(x, y, z) { | |
| 408 | return max(x, max(y, z)); | |
| 409 | } | |
| 410 | ||
| 411 | test "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); | |
| 389 | 418 | } |
| 390 | 419 | |
| 391 | 420 | pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper) { |
| ... | ... | @@ -581,6 +610,17 @@ pub fn Log2Int(comptime T: type) type { |
| 581 | 610 | return std.meta.Int(.unsigned, count); |
| 582 | 611 | } |
| 583 | 612 | |
| 613 | pub 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 | ||
| 584 | 624 | pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) type { |
| 585 | 625 | assert(from <= to); |
| 586 | 626 | if (from == 0 and to == 0) { |
| ... | ... | @@ -1046,15 +1086,18 @@ fn testCeilPowerOfTwo() !void { |
| 1046 | 1086 | } |
| 1047 | 1087 | |
| 1048 | 1088 | pub 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)); | |
| 1049 | 1091 | assert(x != 0); |
| 1050 | 1092 | return @intCast(Log2Int(T), @typeInfo(T).Int.bits - 1 - @clz(T, x)); |
| 1051 | 1093 | } |
| 1052 | 1094 | |
| 1053 | pub fn log2_int_ceil(comptime T: type, x: T) Log2Int(T) { | |
| 1095 | pub 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)); | |
| 1054 | 1098 | 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); | |
| 1058 | 1101 | return log2_val + 1; |
| 1059 | 1102 | } |
| 1060 | 1103 |
lib/std/multi_array_list.zig+137-23| ... | ... | @@ -10,6 +10,15 @@ const mem = std.mem; |
| 10 | 10 | const Allocator = mem.Allocator; |
| 11 | 11 | const testing = std.testing; |
| 12 | 12 | |
| 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. | |
| 13 | 22 | pub fn MultiArrayList(comptime S: type) type { |
| 14 | 23 | return struct { |
| 15 | 24 | bytes: [*]align(@alignOf(S)) u8 = undefined, |
| ... | ... | @@ -20,6 +29,10 @@ pub fn MultiArrayList(comptime S: type) type { |
| 20 | 29 | |
| 21 | 30 | pub const Field = meta.FieldEnum(S); |
| 22 | 31 | |
| 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. | |
| 23 | 36 | pub const Slice = struct { |
| 24 | 37 | /// This array is indexed by the field index which can be obtained |
| 25 | 38 | /// by using @enumToInt() on the Field enum |
| ... | ... | @@ -29,11 +42,12 @@ pub fn MultiArrayList(comptime S: type) type { |
| 29 | 42 | |
| 30 | 43 | pub fn items(self: Slice, comptime field: Field) []FieldType(field) { |
| 31 | 44 | const F = FieldType(field); |
| 32 | if (self.len == 0) { | |
| 45 | if (self.capacity == 0) { | |
| 33 | 46 | return &[_]F{}; |
| 34 | 47 | } |
| 35 | 48 | 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)); | |
| 37 | 51 | return casted_ptr[0..self.len]; |
| 38 | 52 | } |
| 39 | 53 | |
| ... | ... | @@ -74,12 +88,12 @@ pub fn MultiArrayList(comptime S: type) type { |
| 74 | 88 | data[i] = .{ |
| 75 | 89 | .size = @sizeOf(field_info.field_type), |
| 76 | 90 | .size_index = i, |
| 77 | .alignment = field_info.alignment, | |
| 91 | .alignment = if (@sizeOf(field_info.field_type) == 0) 1 else field_info.alignment, | |
| 78 | 92 | }; |
| 79 | 93 | } |
| 80 | 94 | const Sort = struct { |
| 81 | 95 | fn lessThan(trash: *i32, lhs: Data, rhs: Data) bool { |
| 82 | return lhs.alignment >= rhs.alignment; | |
| 96 | return lhs.alignment > rhs.alignment; | |
| 83 | 97 | } |
| 84 | 98 | }; |
| 85 | 99 | var trash: i32 = undefined; // workaround for stage1 compiler bug |
| ... | ... | @@ -109,6 +123,9 @@ pub fn MultiArrayList(comptime S: type) type { |
| 109 | 123 | return result; |
| 110 | 124 | } |
| 111 | 125 | |
| 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. | |
| 112 | 129 | pub fn slice(self: Self) Slice { |
| 113 | 130 | var result: Slice = .{ |
| 114 | 131 | .ptrs = undefined, |
| ... | ... | @@ -123,6 +140,9 @@ pub fn MultiArrayList(comptime S: type) type { |
| 123 | 140 | return result; |
| 124 | 141 | } |
| 125 | 142 | |
| 143 | /// Get the slice of values for a specified field. | |
| 144 | /// If you need multiple fields, consider calling slice() | |
| 145 | /// instead. | |
| 126 | 146 | pub fn items(self: Self, comptime field: Field) []FieldType(field) { |
| 127 | 147 | return self.slice().items(field); |
| 128 | 148 | } |
| ... | ... | @@ -159,6 +179,72 @@ pub fn MultiArrayList(comptime S: type) type { |
| 159 | 179 | self.set(self.len - 1, elem); |
| 160 | 180 | } |
| 161 | 181 | |
| 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 | ||
| 162 | 248 | /// Adjust the list's length to `new_len`. |
| 163 | 249 | /// Does not initialize added items, if any. |
| 164 | 250 | pub fn resize(self: *Self, gpa: *Allocator, new_len: usize) !void { |
| ... | ... | @@ -186,13 +272,15 @@ pub fn MultiArrayList(comptime S: type) type { |
| 186 | 272 | ) catch { |
| 187 | 273 | const self_slice = self.slice(); |
| 188 | 274 | 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 | } | |
| 196 | 284 | } |
| 197 | 285 | self.len = new_len; |
| 198 | 286 | return; |
| ... | ... | @@ -206,12 +294,14 @@ pub fn MultiArrayList(comptime S: type) type { |
| 206 | 294 | const self_slice = self.slice(); |
| 207 | 295 | const other_slice = other.slice(); |
| 208 | 296 | 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 | } | |
| 215 | 305 | } |
| 216 | 306 | gpa.free(self.allocatedBytes()); |
| 217 | 307 | self.* = other; |
| ... | ... | @@ -273,17 +363,41 @@ pub fn MultiArrayList(comptime S: type) type { |
| 273 | 363 | const self_slice = self.slice(); |
| 274 | 364 | const other_slice = other.slice(); |
| 275 | 365 | 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 | } | |
| 282 | 374 | } |
| 283 | 375 | gpa.free(self.allocatedBytes()); |
| 284 | 376 | self.* = other; |
| 285 | 377 | } |
| 286 | 378 | |
| 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 | ||
| 287 | 401 | fn capacityInBytes(capacity: usize) usize { |
| 288 | 402 | const sizes_vector: std.meta.Vector(sizes.bytes.len, usize) = sizes.bytes; |
| 289 | 403 | const capacity_vector = @splat(sizes.bytes.len, capacity); |
lib/std/process.zig+4-4| ... | ... | @@ -85,7 +85,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap { |
| 85 | 85 | |
| 86 | 86 | i += 1; // skip over null byte |
| 87 | 87 | |
| 88 | try result.setMove(key, value); | |
| 88 | try result.putMove(key, value); | |
| 89 | 89 | } |
| 90 | 90 | return result; |
| 91 | 91 | } else if (builtin.os.tag == .wasi) { |
| ... | ... | @@ -112,7 +112,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap { |
| 112 | 112 | var parts = mem.split(pair, "="); |
| 113 | 113 | const key = parts.next().?; |
| 114 | 114 | const value = parts.next().?; |
| 115 | try result.set(key, value); | |
| 115 | try result.put(key, value); | |
| 116 | 116 | } |
| 117 | 117 | return result; |
| 118 | 118 | } else if (builtin.link_libc) { |
| ... | ... | @@ -126,7 +126,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap { |
| 126 | 126 | while (line[end_i] != 0) : (end_i += 1) {} |
| 127 | 127 | const value = line[line_i + 1 .. end_i]; |
| 128 | 128 | |
| 129 | try result.set(key, value); | |
| 129 | try result.put(key, value); | |
| 130 | 130 | } |
| 131 | 131 | return result; |
| 132 | 132 | } else { |
| ... | ... | @@ -139,7 +139,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap { |
| 139 | 139 | while (line[end_i] != 0) : (end_i += 1) {} |
| 140 | 140 | const value = line[line_i + 1 .. end_i]; |
| 141 | 141 | |
| 142 | try result.set(key, value); | |
| 142 | try result.put(key, value); | |
| 143 | 143 | } |
| 144 | 144 | return result; |
| 145 | 145 | } |
src/AstGen.zig+9-11| ... | ... | @@ -144,9 +144,7 @@ pub fn generate(gpa: *Allocator, tree: ast.Tree) InnerError!Zir { |
| 144 | 144 | astgen.extra.items[imports_index] = astgen.addExtraAssumeCapacity(Zir.Inst.Imports{ |
| 145 | 145 | .imports_len = @intCast(u32, astgen.imports.count()), |
| 146 | 146 | }); |
| 147 | for (astgen.imports.items()) |entry| { | |
| 148 | astgen.extra.appendAssumeCapacity(entry.key); | |
| 149 | } | |
| 147 | astgen.extra.appendSliceAssumeCapacity(astgen.imports.keys()); | |
| 150 | 148 | } |
| 151 | 149 | |
| 152 | 150 | return Zir{ |
| ... | ... | @@ -7932,13 +7930,13 @@ fn identAsString(astgen: *AstGen, ident_token: ast.TokenIndex) !u32 { |
| 7932 | 7930 | const gop = try astgen.string_table.getOrPut(gpa, key); |
| 7933 | 7931 | if (gop.found_existing) { |
| 7934 | 7932 | string_bytes.shrinkRetainingCapacity(str_index); |
| 7935 | return gop.entry.value; | |
| 7933 | return gop.value_ptr.*; | |
| 7936 | 7934 | } else { |
| 7937 | 7935 | // We have to dupe the key into the arena, otherwise the memory |
| 7938 | 7936 | // becomes invalidated when string_bytes gets data appended. |
| 7939 | 7937 | // 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; | |
| 7942 | 7940 | try string_bytes.append(gpa, 0); |
| 7943 | 7941 | return str_index; |
| 7944 | 7942 | } |
| ... | ... | @@ -7957,15 +7955,15 @@ fn strLitAsString(astgen: *AstGen, str_lit_token: ast.TokenIndex) !IndexSlice { |
| 7957 | 7955 | if (gop.found_existing) { |
| 7958 | 7956 | string_bytes.shrinkRetainingCapacity(str_index); |
| 7959 | 7957 | return IndexSlice{ |
| 7960 | .index = gop.entry.value, | |
| 7958 | .index = gop.value_ptr.*, | |
| 7961 | 7959 | .len = @intCast(u32, key.len), |
| 7962 | 7960 | }; |
| 7963 | 7961 | } else { |
| 7964 | 7962 | // We have to dupe the key into the arena, otherwise the memory |
| 7965 | 7963 | // becomes invalidated when string_bytes gets data appended. |
| 7966 | 7964 | // 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; | |
| 7969 | 7967 | // Still need a null byte because we are using the same table |
| 7970 | 7968 | // to lookup null terminated strings, so if we get a match, it has to |
| 7971 | 7969 | // be null terminated for that to work. |
| ... | ... | @@ -9122,10 +9120,10 @@ fn declareNewName( |
| 9122 | 9120 | return astgen.failNodeNotes(node, "redeclaration of '{s}'", .{ |
| 9123 | 9121 | name, |
| 9124 | 9122 | }, &[_]u32{ |
| 9125 | try astgen.errNoteNode(gop.entry.value, "other declaration here", .{}), | |
| 9123 | try astgen.errNoteNode(gop.value_ptr.*, "other declaration here", .{}), | |
| 9126 | 9124 | }); |
| 9127 | 9125 | } |
| 9128 | gop.entry.value = node; | |
| 9126 | gop.value_ptr.* = node; | |
| 9129 | 9127 | break; |
| 9130 | 9128 | }, |
| 9131 | 9129 | .top => break, |
src/Cache.zig+4-4| ... | ... | @@ -90,10 +90,10 @@ pub const HashHelper = struct { |
| 90 | 90 | } |
| 91 | 91 | |
| 92 | 92 | 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); | |
| 97 | 97 | } |
| 98 | 98 | } |
| 99 | 99 |
src/Compilation.zig+107-89| ... | ... | @@ -729,18 +729,21 @@ fn addPackageTableToCacheHash( |
| 729 | 729 | ) (error{OutOfMemory} || std.os.GetCwdError)!void { |
| 730 | 730 | const allocator = &arena.allocator; |
| 731 | 731 | |
| 732 | const packages = try allocator.alloc(Package.Table.Entry, pkg_table.count()); | |
| 732 | const packages = try allocator.alloc(Package.Table.KV, pkg_table.count()); | |
| 733 | 733 | { |
| 734 | 734 | // Copy over the hashmap entries to our slice |
| 735 | 735 | var table_it = pkg_table.iterator(); |
| 736 | 736 | var idx: usize = 0; |
| 737 | 737 | 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 | }; | |
| 739 | 742 | } |
| 740 | 743 | } |
| 741 | 744 | // 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 { | |
| 744 | 747 | return std.mem.lessThan(u8, lhs.key, rhs.key); |
| 745 | 748 | } |
| 746 | 749 | }.lessThan); |
| ... | ... | @@ -1525,8 +1528,8 @@ pub fn destroy(self: *Compilation) void { |
| 1525 | 1528 | { |
| 1526 | 1529 | var it = self.crt_files.iterator(); |
| 1527 | 1530 | 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); | |
| 1530 | 1533 | } |
| 1531 | 1534 | self.crt_files.deinit(gpa); |
| 1532 | 1535 | } |
| ... | ... | @@ -1554,14 +1557,14 @@ pub fn destroy(self: *Compilation) void { |
| 1554 | 1557 | glibc_file.deinit(gpa); |
| 1555 | 1558 | } |
| 1556 | 1559 | |
| 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); | |
| 1559 | 1562 | } |
| 1560 | 1563 | self.c_object_table.deinit(gpa); |
| 1561 | 1564 | self.c_object_cache_digest_set.deinit(gpa); |
| 1562 | 1565 | |
| 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); | |
| 1565 | 1568 | } |
| 1566 | 1569 | self.failed_c_objects.deinit(gpa); |
| 1567 | 1570 | |
| ... | ... | @@ -1578,8 +1581,8 @@ pub fn destroy(self: *Compilation) void { |
| 1578 | 1581 | } |
| 1579 | 1582 | |
| 1580 | 1583 | pub 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); | |
| 1583 | 1586 | } |
| 1584 | 1587 | comp.misc_failures.deinit(comp.gpa); |
| 1585 | 1588 | comp.misc_failures = .{}; |
| ... | ... | @@ -1599,9 +1602,10 @@ pub fn update(self: *Compilation) !void { |
| 1599 | 1602 | |
| 1600 | 1603 | // For compiling C objects, we rely on the cache hash system to avoid duplicating work. |
| 1601 | 1604 | // 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); | |
| 1605 | 1609 | } |
| 1606 | 1610 | |
| 1607 | 1611 | const use_stage1 = build_options.omit_stage2 or |
| ... | ... | @@ -1620,8 +1624,8 @@ pub fn update(self: *Compilation) !void { |
| 1620 | 1624 | // it changed, and, if so, re-compute ZIR and then queue the job |
| 1621 | 1625 | // to update it. |
| 1622 | 1626 | 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); | |
| 1625 | 1629 | } |
| 1626 | 1630 | |
| 1627 | 1631 | try self.work_queue.writeItem(.{ .analyze_pkg = std_pkg }); |
| ... | ... | @@ -1635,12 +1639,12 @@ pub fn update(self: *Compilation) !void { |
| 1635 | 1639 | // Process the deletion set. We use a while loop here because the |
| 1636 | 1640 | // deletion set may grow as we call `clearDecl` within this loop, |
| 1637 | 1641 | // 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]; | |
| 1640 | 1644 | assert(decl.deletion_flag); |
| 1641 | 1645 | assert(decl.dependants.count() == 0); |
| 1642 | 1646 | 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); | |
| 1644 | 1648 | } else false; |
| 1645 | 1649 | |
| 1646 | 1650 | try module.clearDecl(decl, null); |
| ... | ... | @@ -1677,8 +1681,7 @@ pub fn update(self: *Compilation) !void { |
| 1677 | 1681 | // to reference the ZIR. |
| 1678 | 1682 | if (self.totalErrorCount() == 0 and !self.keep_source_files_loaded) { |
| 1679 | 1683 | 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| { | |
| 1682 | 1685 | file.unloadTree(self.gpa); |
| 1683 | 1686 | file.unloadSource(self.gpa); |
| 1684 | 1687 | } |
| ... | ... | @@ -1702,18 +1705,21 @@ pub fn totalErrorCount(self: *Compilation) usize { |
| 1702 | 1705 | var total: usize = self.failed_c_objects.count() + self.misc_failures.count(); |
| 1703 | 1706 | |
| 1704 | 1707 | if (self.bin_file.options.module) |module| { |
| 1705 | total += module.failed_exports.items().len; | |
| 1708 | total += module.failed_exports.count(); | |
| 1706 | 1709 | |
| 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 | } | |
| 1717 | 1723 | } |
| 1718 | 1724 | } |
| 1719 | 1725 | |
| ... | ... | @@ -1721,14 +1727,14 @@ pub fn totalErrorCount(self: *Compilation) usize { |
| 1721 | 1727 | // When a parse error is introduced, we keep all the semantic analysis for |
| 1722 | 1728 | // the previous parse success, including compile errors, but we cannot |
| 1723 | 1729 | // 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()) { | |
| 1726 | 1732 | total += 1; |
| 1727 | 1733 | } |
| 1728 | 1734 | } |
| 1729 | 1735 | 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()) { | |
| 1732 | 1738 | total += 1; |
| 1733 | 1739 | } |
| 1734 | 1740 | } |
| ... | ... | @@ -1743,7 +1749,7 @@ pub fn totalErrorCount(self: *Compilation) usize { |
| 1743 | 1749 | // Compile log errors only count if there are no other errors. |
| 1744 | 1750 | if (total == 0) { |
| 1745 | 1751 | 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); | |
| 1747 | 1753 | } |
| 1748 | 1754 | } |
| 1749 | 1755 | |
| ... | ... | @@ -1757,57 +1763,67 @@ pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors { |
| 1757 | 1763 | var errors = std.ArrayList(AllErrors.Message).init(self.gpa); |
| 1758 | 1764 | defer errors.deinit(); |
| 1759 | 1765 | |
| 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 | } | |
| 1777 | 1786 | } |
| 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); | |
| 1780 | 1789 | } |
| 1781 | 1790 | 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 | } | |
| 1791 | 1803 | } |
| 1792 | 1804 | } |
| 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 | } | |
| 1798 | 1813 | } |
| 1799 | 1814 | } |
| 1800 | 1815 | 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| { | |
| 1802 | 1818 | // Skip errors for Decls within files that had a parse failure. |
| 1803 | 1819 | // 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.*.*); | |
| 1806 | 1822 | } |
| 1807 | 1823 | } |
| 1808 | 1824 | } |
| 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.*); | |
| 1811 | 1827 | } |
| 1812 | 1828 | } |
| 1813 | 1829 | |
| ... | ... | @@ -1820,20 +1836,21 @@ pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors { |
| 1820 | 1836 | } |
| 1821 | 1837 | |
| 1822 | 1838 | 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(); | |
| 1825 | 1842 | // 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]); | |
| 1827 | 1844 | const err_msg = Module.ErrorMsg{ |
| 1828 | 1845 | .src_loc = src_loc, |
| 1829 | 1846 | .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), | |
| 1831 | 1848 | }; |
| 1832 | 1849 | defer self.gpa.free(err_msg.notes); |
| 1833 | 1850 | |
| 1834 | for (compile_log_items[1..]) |entry, i| { | |
| 1851 | for (keys[1..]) |key, i| { | |
| 1835 | 1852 | err_msg.notes[i] = .{ |
| 1836 | .src_loc = entry.key.nodeOffsetSrcLoc(entry.value), | |
| 1853 | .src_loc = key.nodeOffsetSrcLoc(values[i+1]), | |
| 1837 | 1854 | .msg = "also here", |
| 1838 | 1855 | }; |
| 1839 | 1856 | } |
| ... | ... | @@ -1898,6 +1915,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor |
| 1898 | 1915 | } |
| 1899 | 1916 | |
| 1900 | 1917 | while (self.c_object_work_queue.readItem()) |c_object| { |
| 1918 | assert(@ptrToInt(c_object) != 0xaaaa_aaaa_aaaa_aaaa); | |
| 1901 | 1919 | self.work_queue_wait_group.start(); |
| 1902 | 1920 | try self.thread_pool.spawn(workerUpdateCObject, .{ |
| 1903 | 1921 | self, c_object, &c_obj_prog_node, &self.work_queue_wait_group, |
| ... | ... | @@ -1964,7 +1982,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor |
| 1964 | 1982 | continue; |
| 1965 | 1983 | }, |
| 1966 | 1984 | 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); | |
| 1968 | 1986 | module.failed_decls.putAssumeCapacityNoClobber(decl, try Module.ErrorMsg.create( |
| 1969 | 1987 | module.gpa, |
| 1970 | 1988 | decl.srcLoc(), |
| ... | ... | @@ -2036,7 +2054,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor |
| 2036 | 2054 | @panic("sadly stage2 is omitted from this build to save memory on the CI server"); |
| 2037 | 2055 | const module = self.bin_file.options.module.?; |
| 2038 | 2056 | 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); | |
| 2040 | 2058 | module.failed_decls.putAssumeCapacityNoClobber(decl, try Module.ErrorMsg.create( |
| 2041 | 2059 | module.gpa, |
| 2042 | 2060 | decl.srcLoc(), |
| ... | ... | @@ -2101,7 +2119,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor |
| 2101 | 2119 | }; |
| 2102 | 2120 | }, |
| 2103 | 2121 | .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]; | |
| 2105 | 2123 | mingw.buildImportLib(self, link_lib) catch |err| { |
| 2106 | 2124 | // TODO Surface more error details. |
| 2107 | 2125 | try self.setMiscFailure( |
| ... | ... | @@ -3023,7 +3041,7 @@ fn failCObjWithOwnedErrorMsg( |
| 3023 | 3041 | defer lock.release(); |
| 3024 | 3042 | { |
| 3025 | 3043 | 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); | |
| 3027 | 3045 | } |
| 3028 | 3046 | comp.failed_c_objects.putAssumeCapacityNoClobber(c_object, err_msg); |
| 3029 | 3047 | } |
| ... | ... | @@ -3953,8 +3971,8 @@ fn updateStage1Module(comp: *Compilation, main_progress_node: *std.Progress.Node |
| 3953 | 3971 | // We need to save the inferred link libs to the cache, otherwise if we get a cache hit |
| 3954 | 3972 | // next time we will be missing these libs. |
| 3955 | 3973 | 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}); | |
| 3958 | 3976 | } |
| 3959 | 3977 | try directory.handle.writeFile(libs_txt_basename, libs_txt.items); |
| 3960 | 3978 | } |
| ... | ... | @@ -4017,7 +4035,7 @@ fn createStage1Pkg( |
| 4017 | 4035 | var children = std.ArrayList(*stage1.Pkg).init(arena); |
| 4018 | 4036 | var it = pkg.table.iterator(); |
| 4019 | 4037 | 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)); | |
| 4021 | 4039 | } |
| 4022 | 4040 | break :blk children.items; |
| 4023 | 4041 | }; |
src/Module.zig+113-122| ... | ... | @@ -268,15 +268,7 @@ pub const Decl = struct { |
| 268 | 268 | /// typed_value may need to be regenerated. |
| 269 | 269 | dependencies: DepsTable = .{}, |
| 270 | 270 | |
| 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); | |
| 280 | 272 | |
| 281 | 273 | pub fn clearName(decl: *Decl, gpa: *Allocator) void { |
| 282 | 274 | gpa.free(mem.spanZ(decl.name)); |
| ... | ... | @@ -287,7 +279,7 @@ pub const Decl = struct { |
| 287 | 279 | const gpa = module.gpa; |
| 288 | 280 | log.debug("destroy {*} ({s})", .{ decl, decl.name }); |
| 289 | 281 | if (decl.deletion_flag) { |
| 290 | module.deletion_set.swapRemoveAssertDiscard(decl); | |
| 282 | assert(module.deletion_set.swapRemove(decl)); | |
| 291 | 283 | } |
| 292 | 284 | if (decl.has_tv) { |
| 293 | 285 | if (decl.getInnerNamespace()) |namespace| { |
| ... | ... | @@ -550,11 +542,11 @@ pub const Decl = struct { |
| 550 | 542 | } |
| 551 | 543 | |
| 552 | 544 | fn removeDependant(decl: *Decl, other: *Decl) void { |
| 553 | decl.dependants.removeAssertDiscard(other); | |
| 545 | assert(decl.dependants.swapRemove(other)); | |
| 554 | 546 | } |
| 555 | 547 | |
| 556 | 548 | fn removeDependency(decl: *Decl, other: *Decl) void { |
| 557 | decl.dependencies.removeAssertDiscard(other); | |
| 549 | assert(decl.dependencies.swapRemove(other)); | |
| 558 | 550 | } |
| 559 | 551 | }; |
| 560 | 552 | |
| ... | ... | @@ -683,7 +675,7 @@ pub const EnumFull = struct { |
| 683 | 675 | /// Offset from `owner_decl`, points to the enum decl AST node. |
| 684 | 676 | node_offset: i32, |
| 685 | 677 | |
| 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); | |
| 687 | 679 | |
| 688 | 680 | pub fn srcLoc(self: EnumFull) SrcLoc { |
| 689 | 681 | return .{ |
| ... | ... | @@ -895,13 +887,13 @@ pub const Scope = struct { |
| 895 | 887 | var anon_decls = ns.anon_decls; |
| 896 | 888 | ns.anon_decls = .{}; |
| 897 | 889 | |
| 898 | for (decls.items()) |entry| { | |
| 899 | entry.value.destroy(mod); | |
| 890 | for (decls.values()) |value| { | |
| 891 | value.destroy(mod); | |
| 900 | 892 | } |
| 901 | 893 | decls.deinit(gpa); |
| 902 | 894 | |
| 903 | for (anon_decls.items()) |entry| { | |
| 904 | entry.key.destroy(mod); | |
| 895 | for (anon_decls.keys()) |key| { | |
| 896 | key.destroy(mod); | |
| 905 | 897 | } |
| 906 | 898 | anon_decls.deinit(gpa); |
| 907 | 899 | } |
| ... | ... | @@ -924,15 +916,13 @@ pub const Scope = struct { |
| 924 | 916 | // TODO rework this code to not panic on OOM. |
| 925 | 917 | // (might want to coordinate with the clearDecl function) |
| 926 | 918 | |
| 927 | for (decls.items()) |entry| { | |
| 928 | const child_decl = entry.value; | |
| 919 | for (decls.values()) |child_decl| { | |
| 929 | 920 | mod.clearDecl(child_decl, outdated_decls) catch @panic("out of memory"); |
| 930 | 921 | child_decl.destroy(mod); |
| 931 | 922 | } |
| 932 | 923 | decls.deinit(gpa); |
| 933 | 924 | |
| 934 | for (anon_decls.items()) |entry| { | |
| 935 | const child_decl = entry.key; | |
| 925 | for (anon_decls.keys()) |child_decl| { | |
| 936 | 926 | mod.clearDecl(child_decl, outdated_decls) catch @panic("out of memory"); |
| 937 | 927 | child_decl.destroy(mod); |
| 938 | 928 | } |
| ... | ... | @@ -2120,9 +2110,11 @@ pub const InnerError = error{ OutOfMemory, AnalysisFail }; |
| 2120 | 2110 | pub fn deinit(mod: *Module) void { |
| 2121 | 2111 | const gpa = mod.gpa; |
| 2122 | 2112 | |
| 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); | |
| 2126 | 2118 | } |
| 2127 | 2119 | mod.import_table.deinit(gpa); |
| 2128 | 2120 | |
| ... | ... | @@ -2130,16 +2122,16 @@ pub fn deinit(mod: *Module) void { |
| 2130 | 2122 | |
| 2131 | 2123 | // The callsite of `Compilation.create` owns the `root_pkg`, however |
| 2132 | 2124 | // 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); | |
| 2136 | 2128 | } |
| 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); | |
| 2140 | 2132 | } |
| 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); | |
| 2143 | 2135 | } |
| 2144 | 2136 | |
| 2145 | 2137 | mod.compile_log_text.deinit(gpa); |
| ... | ... | @@ -2148,46 +2140,45 @@ pub fn deinit(mod: *Module) void { |
| 2148 | 2140 | mod.local_zir_cache.handle.close(); |
| 2149 | 2141 | mod.global_zir_cache.handle.close(); |
| 2150 | 2142 | |
| 2151 | for (mod.failed_decls.items()) |entry| { | |
| 2152 | entry.value.destroy(gpa); | |
| 2143 | for (mod.failed_decls.values()) |value| { | |
| 2144 | value.destroy(gpa); | |
| 2153 | 2145 | } |
| 2154 | 2146 | mod.failed_decls.deinit(gpa); |
| 2155 | 2147 | |
| 2156 | 2148 | 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); | |
| 2159 | 2151 | } |
| 2160 | 2152 | emit_h.failed_decls.deinit(gpa); |
| 2161 | 2153 | emit_h.decl_table.deinit(gpa); |
| 2162 | 2154 | gpa.destroy(emit_h); |
| 2163 | 2155 | } |
| 2164 | 2156 | |
| 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); | |
| 2167 | 2159 | } |
| 2168 | 2160 | mod.failed_files.deinit(gpa); |
| 2169 | 2161 | |
| 2170 | for (mod.failed_exports.items()) |entry| { | |
| 2171 | entry.value.destroy(gpa); | |
| 2162 | for (mod.failed_exports.values()) |value| { | |
| 2163 | value.destroy(gpa); | |
| 2172 | 2164 | } |
| 2173 | 2165 | mod.failed_exports.deinit(gpa); |
| 2174 | 2166 | |
| 2175 | 2167 | mod.compile_log_decls.deinit(gpa); |
| 2176 | 2168 | |
| 2177 | for (mod.decl_exports.items()) |entry| { | |
| 2178 | const export_list = entry.value; | |
| 2169 | for (mod.decl_exports.values()) |export_list| { | |
| 2179 | 2170 | gpa.free(export_list); |
| 2180 | 2171 | } |
| 2181 | 2172 | mod.decl_exports.deinit(gpa); |
| 2182 | 2173 | |
| 2183 | for (mod.export_owners.items()) |entry| { | |
| 2184 | freeExportList(gpa, entry.value); | |
| 2174 | for (mod.export_owners.values()) |value| { | |
| 2175 | freeExportList(gpa, value); | |
| 2185 | 2176 | } |
| 2186 | 2177 | mod.export_owners.deinit(gpa); |
| 2187 | 2178 | |
| 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.*); | |
| 2191 | 2182 | } |
| 2192 | 2183 | mod.global_error_set.deinit(gpa); |
| 2193 | 2184 | |
| ... | ... | @@ -2670,12 +2661,10 @@ fn updateZirRefs(gpa: *Allocator, file: *Scope.File, old_zir: Zir) !void { |
| 2670 | 2661 | } |
| 2671 | 2662 | |
| 2672 | 2663 | if (decl.getInnerNamespace()) |namespace| { |
| 2673 | for (namespace.decls.items()) |entry| { | |
| 2674 | const sub_decl = entry.value; | |
| 2664 | for (namespace.decls.values()) |sub_decl| { | |
| 2675 | 2665 | try decl_stack.append(gpa, sub_decl); |
| 2676 | 2666 | } |
| 2677 | for (namespace.anon_decls.items()) |entry| { | |
| 2678 | const sub_decl = entry.key; | |
| 2667 | for (namespace.anon_decls.keys()) |sub_decl| { | |
| 2679 | 2668 | try decl_stack.append(gpa, sub_decl); |
| 2680 | 2669 | } |
| 2681 | 2670 | } |
| ... | ... | @@ -2769,8 +2758,7 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl: *Decl) InnerError!void { |
| 2769 | 2758 | // prior to re-analysis. |
| 2770 | 2759 | mod.deleteDeclExports(decl); |
| 2771 | 2760 | // 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| { | |
| 2774 | 2762 | dep.removeDependant(decl); |
| 2775 | 2763 | if (dep.dependants.count() == 0 and !dep.deletion_flag) { |
| 2776 | 2764 | log.debug("insert {*} ({s}) dependant {*} ({s}) into deletion set", .{ |
| ... | ... | @@ -2817,8 +2805,7 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl: *Decl) InnerError!void { |
| 2817 | 2805 | // We may need to chase the dependants and re-analyze them. |
| 2818 | 2806 | // However, if the decl is a function, and the type is the same, we do not need to. |
| 2819 | 2807 | 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| { | |
| 2822 | 2809 | switch (dep.analysis) { |
| 2823 | 2810 | .unreferenced => unreachable, |
| 2824 | 2811 | .in_progress => continue, // already doing analysis, ok |
| ... | ... | @@ -3128,7 +3115,7 @@ pub fn declareDeclDependency(mod: *Module, depender: *Decl, dependee: *Decl) !vo |
| 3128 | 3115 | |
| 3129 | 3116 | if (dependee.deletion_flag) { |
| 3130 | 3117 | dependee.deletion_flag = false; |
| 3131 | mod.deletion_set.removeAssertDiscard(dependee); | |
| 3118 | assert(mod.deletion_set.swapRemove(dependee)); | |
| 3132 | 3119 | } |
| 3133 | 3120 | |
| 3134 | 3121 | dependee.dependants.putAssumeCapacity(depender, {}); |
| ... | ... | @@ -3154,7 +3141,7 @@ pub fn importPkg(mod: *Module, cur_pkg: *Package, pkg: *Package) !ImportFileResu |
| 3154 | 3141 | |
| 3155 | 3142 | const gop = try mod.import_table.getOrPut(gpa, resolved_path); |
| 3156 | 3143 | if (gop.found_existing) return ImportFileResult{ |
| 3157 | .file = gop.entry.value, | |
| 3144 | .file = gop.value_ptr.*, | |
| 3158 | 3145 | .is_new = false, |
| 3159 | 3146 | }; |
| 3160 | 3147 | 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 |
| 3165 | 3152 | const new_file = try gpa.create(Scope.File); |
| 3166 | 3153 | errdefer gpa.destroy(new_file); |
| 3167 | 3154 | |
| 3168 | gop.entry.value = new_file; | |
| 3155 | gop.value_ptr.* = new_file; | |
| 3169 | 3156 | new_file.* = .{ |
| 3170 | 3157 | .sub_file_path = sub_file_path, |
| 3171 | 3158 | .source = undefined, |
| ... | ... | @@ -3209,7 +3196,7 @@ pub fn importFile( |
| 3209 | 3196 | |
| 3210 | 3197 | const gop = try mod.import_table.getOrPut(gpa, resolved_path); |
| 3211 | 3198 | if (gop.found_existing) return ImportFileResult{ |
| 3212 | .file = gop.entry.value, | |
| 3199 | .file = gop.value_ptr.*, | |
| 3213 | 3200 | .is_new = false, |
| 3214 | 3201 | }; |
| 3215 | 3202 | keep_resolved_path = true; // It's now owned by import_table. |
| ... | ... | @@ -3231,7 +3218,7 @@ pub fn importFile( |
| 3231 | 3218 | resolved_root_path, resolved_path, sub_file_path, import_string, |
| 3232 | 3219 | }); |
| 3233 | 3220 | |
| 3234 | gop.entry.value = new_file; | |
| 3221 | gop.value_ptr.* = new_file; | |
| 3235 | 3222 | new_file.* = .{ |
| 3236 | 3223 | .sub_file_path = sub_file_path, |
| 3237 | 3224 | .source = undefined, |
| ... | ... | @@ -3366,7 +3353,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) InnerError!vo |
| 3366 | 3353 | log.debug("scan new {*} ({s}) into {*}", .{ new_decl, decl_name, namespace }); |
| 3367 | 3354 | new_decl.src_line = line; |
| 3368 | 3355 | new_decl.name = decl_name; |
| 3369 | gop.entry.value = new_decl; | |
| 3356 | gop.value_ptr.* = new_decl; | |
| 3370 | 3357 | // Exported decls, comptime decls, usingnamespace decls, and |
| 3371 | 3358 | // test decls if in test mode, get analyzed. |
| 3372 | 3359 | 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 |
| 3385 | 3372 | return; |
| 3386 | 3373 | } |
| 3387 | 3374 | gpa.free(decl_name); |
| 3388 | const decl = gop.entry.value; | |
| 3375 | const decl = gop.value_ptr.*; | |
| 3389 | 3376 | log.debug("scan existing {*} ({s}) of {*}", .{ decl, decl.name, namespace }); |
| 3390 | 3377 | // Update the AST node of the decl; even if its contents are unchanged, it may |
| 3391 | 3378 | // have been re-ordered. |
| ... | ... | @@ -3438,10 +3425,9 @@ pub fn clearDecl( |
| 3438 | 3425 | } |
| 3439 | 3426 | |
| 3440 | 3427 | // Remove itself from its dependencies. |
| 3441 | for (decl.dependencies.items()) |entry| { | |
| 3442 | const dep = entry.key; | |
| 3428 | for (decl.dependencies.keys()) |dep| { | |
| 3443 | 3429 | dep.removeDependant(decl); |
| 3444 | if (dep.dependants.items().len == 0 and !dep.deletion_flag) { | |
| 3430 | if (dep.dependants.count() == 0 and !dep.deletion_flag) { | |
| 3445 | 3431 | // We don't recursively perform a deletion here, because during the update, |
| 3446 | 3432 | // another reference to it may turn up. |
| 3447 | 3433 | dep.deletion_flag = true; |
| ... | ... | @@ -3451,8 +3437,7 @@ pub fn clearDecl( |
| 3451 | 3437 | decl.dependencies.clearRetainingCapacity(); |
| 3452 | 3438 | |
| 3453 | 3439 | // 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| { | |
| 3456 | 3441 | dep.removeDependency(decl); |
| 3457 | 3442 | if (outdated_decls) |map| { |
| 3458 | 3443 | map.putAssumeCapacity(dep, {}); |
| ... | ... | @@ -3467,14 +3452,14 @@ pub fn clearDecl( |
| 3467 | 3452 | } |
| 3468 | 3453 | decl.dependants.clearRetainingCapacity(); |
| 3469 | 3454 | |
| 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); | |
| 3472 | 3457 | } |
| 3473 | 3458 | 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); | |
| 3476 | 3461 | } |
| 3477 | emit_h.decl_table.removeAssertDiscard(decl); | |
| 3462 | assert(emit_h.decl_table.swapRemove(decl)); | |
| 3478 | 3463 | } |
| 3479 | 3464 | _ = mod.compile_log_decls.swapRemove(decl); |
| 3480 | 3465 | mod.deleteDeclExports(decl); |
| ... | ... | @@ -3510,7 +3495,7 @@ pub fn clearDecl( |
| 3510 | 3495 | |
| 3511 | 3496 | if (decl.deletion_flag) { |
| 3512 | 3497 | decl.deletion_flag = false; |
| 3513 | mod.deletion_set.swapRemoveAssertDiscard(decl); | |
| 3498 | assert(mod.deletion_set.swapRemove(decl)); | |
| 3514 | 3499 | } |
| 3515 | 3500 | |
| 3516 | 3501 | decl.analysis = .unreferenced; |
| ... | ... | @@ -3519,12 +3504,12 @@ pub fn clearDecl( |
| 3519 | 3504 | /// Delete all the Export objects that are caused by this Decl. Re-analysis of |
| 3520 | 3505 | /// this Decl will cause them to be re-created (or not). |
| 3521 | 3506 | fn 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; | |
| 3523 | 3508 | |
| 3524 | 3509 | 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| { | |
| 3526 | 3511 | // Remove exports with owner_decl matching the regenerating decl. |
| 3527 | const list = decl_exports_kv.value; | |
| 3512 | const list = value_ptr.*; | |
| 3528 | 3513 | var i: usize = 0; |
| 3529 | 3514 | var new_len = list.len; |
| 3530 | 3515 | while (i < new_len) { |
| ... | ... | @@ -3535,9 +3520,9 @@ fn deleteDeclExports(mod: *Module, decl: *Decl) void { |
| 3535 | 3520 | i += 1; |
| 3536 | 3521 | } |
| 3537 | 3522 | } |
| 3538 | decl_exports_kv.value = mod.gpa.shrink(list, new_len); | |
| 3523 | value_ptr.* = mod.gpa.shrink(list, new_len); | |
| 3539 | 3524 | if (new_len == 0) { |
| 3540 | mod.decl_exports.removeAssertDiscard(exp.exported_decl); | |
| 3525 | assert(mod.decl_exports.swapRemove(exp.exported_decl)); | |
| 3541 | 3526 | } |
| 3542 | 3527 | } |
| 3543 | 3528 | if (mod.comp.bin_file.cast(link.File.Elf)) |elf| { |
| ... | ... | @@ -3546,8 +3531,8 @@ fn deleteDeclExports(mod: *Module, decl: *Decl) void { |
| 3546 | 3531 | if (mod.comp.bin_file.cast(link.File.MachO)) |macho| { |
| 3547 | 3532 | macho.deleteExport(exp.link.macho); |
| 3548 | 3533 | } |
| 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); | |
| 3551 | 3536 | } |
| 3552 | 3537 | mod.gpa.free(exp.options.name); |
| 3553 | 3538 | mod.gpa.destroy(exp); |
| ... | ... | @@ -3623,12 +3608,12 @@ pub fn analyzeFnBody(mod: *Module, decl: *Decl, func: *Fn) !void { |
| 3623 | 3608 | fn markOutdatedDecl(mod: *Module, decl: *Decl) !void { |
| 3624 | 3609 | log.debug("mark outdated {*} ({s})", .{ decl, decl.name }); |
| 3625 | 3610 | 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); | |
| 3628 | 3613 | } |
| 3629 | 3614 | 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); | |
| 3632 | 3617 | } |
| 3633 | 3618 | } |
| 3634 | 3619 | _ = mod.compile_log_decls.swapRemove(decl); |
| ... | ... | @@ -3686,17 +3671,24 @@ fn allocateNewDecl(mod: *Module, namespace: *Scope.Namespace, src_node: ast.Node |
| 3686 | 3671 | } |
| 3687 | 3672 | |
| 3688 | 3673 | /// Get error value for error tag `name`. |
| 3689 | pub fn getErrorValue(mod: *Module, name: []const u8) !std.StringHashMapUnmanaged(ErrorInt).Entry { | |
| 3674 | pub fn getErrorValue(mod: *Module, name: []const u8) !std.StringHashMapUnmanaged(ErrorInt).KV { | |
| 3690 | 3675 | 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 | } | |
| 3693 | 3682 | |
| 3694 | errdefer mod.global_error_set.removeAssertDiscard(name); | |
| 3683 | errdefer assert(mod.global_error_set.remove(name)); | |
| 3695 | 3684 | 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 | }; | |
| 3700 | 3692 | } |
| 3701 | 3693 | |
| 3702 | 3694 | pub fn analyzeExport( |
| ... | ... | @@ -3712,8 +3704,8 @@ pub fn analyzeExport( |
| 3712 | 3704 | else => return mod.fail(scope, src, "unable to export type '{}'", .{exported_decl.ty}), |
| 3713 | 3705 | } |
| 3714 | 3706 | |
| 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); | |
| 3717 | 3709 | |
| 3718 | 3710 | const new_export = try mod.gpa.create(Export); |
| 3719 | 3711 | errdefer mod.gpa.destroy(new_export); |
| ... | ... | @@ -3746,20 +3738,20 @@ pub fn analyzeExport( |
| 3746 | 3738 | // Add to export_owners table. |
| 3747 | 3739 | const eo_gop = mod.export_owners.getOrPutAssumeCapacity(owner_decl); |
| 3748 | 3740 | if (!eo_gop.found_existing) { |
| 3749 | eo_gop.entry.value = &[0]*Export{}; | |
| 3741 | eo_gop.value_ptr.* = &[0]*Export{}; | |
| 3750 | 3742 | } |
| 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); | |
| 3754 | 3746 | |
| 3755 | 3747 | // Add to exported_decl table. |
| 3756 | 3748 | const de_gop = mod.decl_exports.getOrPutAssumeCapacity(exported_decl); |
| 3757 | 3749 | if (!de_gop.found_existing) { |
| 3758 | de_gop.entry.value = &[0]*Export{}; | |
| 3750 | de_gop.value_ptr.* = &[0]*Export{}; | |
| 3759 | 3751 | } |
| 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); | |
| 3763 | 3755 | } |
| 3764 | 3756 | pub fn constInst(mod: *Module, arena: *Allocator, src: LazySrcLoc, typed_value: TypedValue) !*ir.Inst { |
| 3765 | 3757 | 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 |
| 3851 | 3843 | |
| 3852 | 3844 | pub fn deleteAnonDecl(mod: *Module, scope: *Scope, decl: *Decl) void { |
| 3853 | 3845 | const scope_decl = scope.ownerDecl().?; |
| 3854 | scope_decl.namespace.anon_decls.swapRemoveAssertDiscard(decl); | |
| 3846 | assert(scope_decl.namespace.anon_decls.swapRemove(decl)); | |
| 3855 | 3847 | decl.destroy(mod); |
| 3856 | 3848 | } |
| 3857 | 3849 | |
| ... | ... | @@ -4001,8 +3993,8 @@ pub fn failWithOwnedErrorMsg(mod: *Module, scope: *Scope, err_msg: *ErrorMsg) In |
| 4001 | 3993 | |
| 4002 | 3994 | { |
| 4003 | 3995 | 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); | |
| 4006 | 3998 | } |
| 4007 | 3999 | switch (scope.tag) { |
| 4008 | 4000 | .block => { |
| ... | ... | @@ -4420,8 +4412,8 @@ fn lockAndClearFileCompileError(mod: *Module, file: *Scope.File) void { |
| 4420 | 4412 | .never_loaded, .parse_failure, .astgen_failure => { |
| 4421 | 4413 | const lock = mod.comp.mutex.acquire(); |
| 4422 | 4414 | 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. | |
| 4425 | 4417 | } |
| 4426 | 4418 | }, |
| 4427 | 4419 | } |
| ... | ... | @@ -4649,7 +4641,7 @@ pub fn analyzeStructFields(mod: *Module, struct_obj: *Struct) InnerError!void { |
| 4649 | 4641 | |
| 4650 | 4642 | const gop = struct_obj.fields.getOrPutAssumeCapacity(field_name); |
| 4651 | 4643 | assert(!gop.found_existing); |
| 4652 | gop.entry.value = .{ | |
| 4644 | gop.value_ptr.* = .{ | |
| 4653 | 4645 | .ty = field_ty, |
| 4654 | 4646 | .abi_align = Value.initTag(.abi_align_default), |
| 4655 | 4647 | .default_val = Value.initTag(.unreachable_value), |
| ... | ... | @@ -4663,7 +4655,7 @@ pub fn analyzeStructFields(mod: *Module, struct_obj: *Struct) InnerError!void { |
| 4663 | 4655 | // TODO: if we need to report an error here, use a source location |
| 4664 | 4656 | // that points to this alignment expression rather than the struct. |
| 4665 | 4657 | // 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; | |
| 4667 | 4659 | } |
| 4668 | 4660 | if (has_default) { |
| 4669 | 4661 | 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 { |
| 4671 | 4663 | // TODO: if we need to report an error here, use a source location |
| 4672 | 4664 | // that points to this default value expression rather than the struct. |
| 4673 | 4665 | // 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; | |
| 4675 | 4667 | } |
| 4676 | 4668 | } |
| 4677 | 4669 | } |
| ... | ... | @@ -4816,7 +4808,7 @@ pub fn analyzeUnionFields(mod: *Module, union_obj: *Union) InnerError!void { |
| 4816 | 4808 | |
| 4817 | 4809 | const gop = union_obj.fields.getOrPutAssumeCapacity(field_name); |
| 4818 | 4810 | assert(!gop.found_existing); |
| 4819 | gop.entry.value = .{ | |
| 4811 | gop.value_ptr.* = .{ | |
| 4820 | 4812 | .ty = field_ty, |
| 4821 | 4813 | .abi_align = Value.initTag(.abi_align_default), |
| 4822 | 4814 | }; |
| ... | ... | @@ -4825,7 +4817,7 @@ pub fn analyzeUnionFields(mod: *Module, union_obj: *Union) InnerError!void { |
| 4825 | 4817 | // TODO: if we need to report an error here, use a source location |
| 4826 | 4818 | // that points to this alignment expression rather than the struct. |
| 4827 | 4819 | // 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; | |
| 4829 | 4821 | } |
| 4830 | 4822 | } |
| 4831 | 4823 | |
| ... | ... | @@ -4841,9 +4833,7 @@ pub fn processOutdatedAndDeletedDecls(mod: *Module) !void { |
| 4841 | 4833 | // deleted Decl pointers in the work queue. |
| 4842 | 4834 | var outdated_decls = std.AutoArrayHashMap(*Decl, void).init(mod.gpa); |
| 4843 | 4835 | 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| { | |
| 4847 | 4837 | try outdated_decls.ensureUnusedCapacity(file.outdated_decls.items.len); |
| 4848 | 4838 | for (file.outdated_decls.items) |decl| { |
| 4849 | 4839 | outdated_decls.putAssumeCapacity(decl, {}); |
| ... | ... | @@ -4872,8 +4862,8 @@ pub fn processOutdatedAndDeletedDecls(mod: *Module) !void { |
| 4872 | 4862 | } |
| 4873 | 4863 | // Finally we can queue up re-analysis tasks after we have processed |
| 4874 | 4864 | // 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); | |
| 4877 | 4867 | } |
| 4878 | 4868 | } |
| 4879 | 4869 | |
| ... | ... | @@ -4886,9 +4876,10 @@ pub fn processExports(mod: *Module) !void { |
| 4886 | 4876 | var symbol_exports: std.StringArrayHashMapUnmanaged(*Export) = .{}; |
| 4887 | 4877 | defer symbol_exports.deinit(gpa); |
| 4888 | 4878 | |
| 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.*; | |
| 4892 | 4883 | for (exports) |new_export| { |
| 4893 | 4884 | const gop = try symbol_exports.getOrPut(gpa, new_export.options.name); |
| 4894 | 4885 | if (gop.found_existing) { |
| ... | ... | @@ -4899,13 +4890,13 @@ pub fn processExports(mod: *Module) !void { |
| 4899 | 4890 | new_export.options.name, |
| 4900 | 4891 | }); |
| 4901 | 4892 | errdefer msg.destroy(gpa); |
| 4902 | const other_export = gop.entry.value; | |
| 4893 | const other_export = gop.value_ptr.*; | |
| 4903 | 4894 | const other_src_loc = other_export.getSrcLoc(); |
| 4904 | 4895 | try mod.errNoteNonLazy(other_src_loc, msg, "other symbol here", .{}); |
| 4905 | 4896 | mod.failed_exports.putAssumeCapacityNoClobber(new_export, msg); |
| 4906 | 4897 | new_export.status = .failed; |
| 4907 | 4898 | } else { |
| 4908 | gop.entry.value = new_export; | |
| 4899 | gop.value_ptr.* = new_export; | |
| 4909 | 4900 | } |
| 4910 | 4901 | } |
| 4911 | 4902 | 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 { |
| 100 | 100 | } |
| 101 | 101 | |
| 102 | 102 | { |
| 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.*); | |
| 106 | 106 | } |
| 107 | 107 | } |
| 108 | 108 |
src/Sema.zig+23-24| ... | ... | @@ -1350,7 +1350,7 @@ fn zirValidateStructInitPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Ind |
| 1350 | 1350 | }; |
| 1351 | 1351 | |
| 1352 | 1352 | // 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()); | |
| 1354 | 1354 | defer gpa.free(found_fields); |
| 1355 | 1355 | mem.set(Zir.Inst.Index, found_fields, 0); |
| 1356 | 1356 | |
| ... | ... | @@ -1382,7 +1382,7 @@ fn zirValidateStructInitPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Ind |
| 1382 | 1382 | for (found_fields) |field_ptr, i| { |
| 1383 | 1383 | if (field_ptr != 0) continue; |
| 1384 | 1384 | |
| 1385 | const field_name = struct_obj.fields.entries.items[i].key; | |
| 1385 | const field_name = struct_obj.fields.keys()[i]; | |
| 1386 | 1386 | const template = "missing struct field: {s}"; |
| 1387 | 1387 | const args = .{field_name}; |
| 1388 | 1388 | if (root_msg) |msg| { |
| ... | ... | @@ -1687,7 +1687,7 @@ fn zirCompileLog( |
| 1687 | 1687 | |
| 1688 | 1688 | const gop = try sema.mod.compile_log_decls.getOrPut(sema.gpa, sema.owner_decl); |
| 1689 | 1689 | if (!gop.found_existing) { |
| 1690 | gop.entry.value = src_node; | |
| 1690 | gop.value_ptr.* = src_node; | |
| 1691 | 1691 | } |
| 1692 | 1692 | return sema.mod.constInst(sema.arena, src, .{ |
| 1693 | 1693 | .ty = Type.initTag(.void), |
| ... | ... | @@ -1954,7 +1954,7 @@ fn zirExport(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError! |
| 1954 | 1954 | const section_index = struct_obj.fields.getIndex("section").?; |
| 1955 | 1955 | const export_name = try fields[name_index].toAllocatedBytes(sema.arena); |
| 1956 | 1956 | const linkage = fields[linkage_index].toEnum( |
| 1957 | struct_obj.fields.items()[linkage_index].value.ty, | |
| 1957 | struct_obj.fields.values()[linkage_index].ty, | |
| 1958 | 1958 | std.builtin.GlobalLinkage, |
| 1959 | 1959 | ); |
| 1960 | 1960 | |
| ... | ... | @@ -2426,12 +2426,12 @@ fn zirErrorValue(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerEr |
| 2426 | 2426 | const src = inst_data.src(); |
| 2427 | 2427 | |
| 2428 | 2428 | // 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); | |
| 2431 | 2431 | return sema.mod.constInst(sema.arena, src, .{ |
| 2432 | 2432 | .ty = result_type, |
| 2433 | 2433 | .val = try Value.Tag.@"error".create(sema.arena, .{ |
| 2434 | .name = entry.key, | |
| 2434 | .name = kv.key, | |
| 2435 | 2435 | }), |
| 2436 | 2436 | }); |
| 2437 | 2437 | } |
| ... | ... | @@ -2558,10 +2558,10 @@ fn zirMergeErrorSets(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) Inn |
| 2558 | 2558 | } |
| 2559 | 2559 | |
| 2560 | 2560 | const new_names = try sema.arena.alloc([]const u8, set.count()); |
| 2561 | var it = set.iterator(); | |
| 2561 | var it = set.keyIterator(); | |
| 2562 | 2562 | 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.*; | |
| 2565 | 2565 | } |
| 2566 | 2566 | |
| 2567 | 2567 | 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 |
| 2636 | 2636 | .enum_full => { |
| 2637 | 2637 | const enum_full = enum_tag.ty.castTag(.enum_full).?.data; |
| 2638 | 2638 | 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]; | |
| 2640 | 2640 | return mod.constInst(arena, src, .{ |
| 2641 | 2641 | .ty = int_tag_ty, |
| 2642 | 2642 | .val = val, |
| ... | ... | @@ -4360,7 +4360,7 @@ fn validateSwitchItemBool( |
| 4360 | 4360 | } |
| 4361 | 4361 | } |
| 4362 | 4362 | |
| 4363 | const ValueSrcMap = std.HashMap(Value, Module.SwitchProngSrc, Value.hash, Value.eql, std.hash_map.DefaultMaxLoadPercentage); | |
| 4363 | const ValueSrcMap = std.HashMap(Value, Module.SwitchProngSrc, Value.HashContext, std.hash_map.default_max_load_percentage); | |
| 4364 | 4364 | |
| 4365 | 4365 | fn validateSwitchItemSparse( |
| 4366 | 4366 | sema: *Sema, |
| ... | ... | @@ -4371,8 +4371,8 @@ fn validateSwitchItemSparse( |
| 4371 | 4371 | switch_prong_src: Module.SwitchProngSrc, |
| 4372 | 4372 | ) InnerError!void { |
| 4373 | 4373 | 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); | |
| 4376 | 4376 | } |
| 4377 | 4377 | |
| 4378 | 4378 | fn validateSwitchNoRange( |
| ... | ... | @@ -5470,12 +5470,12 @@ fn zirStructInit(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: |
| 5470 | 5470 | |
| 5471 | 5471 | // Maps field index to field_type index of where it was already initialized. |
| 5472 | 5472 | // 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()); | |
| 5474 | 5474 | defer gpa.free(found_fields); |
| 5475 | 5475 | mem.set(Zir.Inst.Index, found_fields, 0); |
| 5476 | 5476 | |
| 5477 | 5477 | // 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()); | |
| 5479 | 5479 | defer gpa.free(field_inits); |
| 5480 | 5480 | |
| 5481 | 5481 | var field_i: u32 = 0; |
| ... | ... | @@ -5513,9 +5513,9 @@ fn zirStructInit(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: |
| 5513 | 5513 | if (field_type_inst != 0) continue; |
| 5514 | 5514 | |
| 5515 | 5515 | // 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]; | |
| 5517 | 5517 | 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]; | |
| 5519 | 5519 | const template = "missing struct field: {s}"; |
| 5520 | 5520 | const args = .{field_name}; |
| 5521 | 5521 | if (root_msg) |msg| { |
| ... | ... | @@ -6402,7 +6402,7 @@ fn analyzeStructFieldPtr( |
| 6402 | 6402 | |
| 6403 | 6403 | const field_index = struct_obj.fields.getIndex(field_name) orelse |
| 6404 | 6404 | 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]; | |
| 6406 | 6406 | const ptr_field_ty = try mod.simplePtrType(arena, field.ty, true, .One); |
| 6407 | 6407 | |
| 6408 | 6408 | if (try sema.resolveDefinedValue(block, src, struct_ptr)) |struct_ptr_val| { |
| ... | ... | @@ -6438,7 +6438,7 @@ fn analyzeUnionFieldPtr( |
| 6438 | 6438 | const field_index = union_obj.fields.getIndex(field_name) orelse |
| 6439 | 6439 | return sema.failWithBadUnionFieldAccess(block, union_obj, field_name_src, field_name); |
| 6440 | 6440 | |
| 6441 | const field = union_obj.fields.entries.items[field_index].value; | |
| 6441 | const field = union_obj.fields.values()[field_index]; | |
| 6442 | 6442 | const ptr_field_ty = try mod.simplePtrType(arena, field.ty, true, .One); |
| 6443 | 6443 | |
| 6444 | 6444 | if (try sema.resolveDefinedValue(block, src, union_ptr)) |union_ptr_val| { |
| ... | ... | @@ -7476,9 +7476,8 @@ fn typeHasOnePossibleValue( |
| 7476 | 7476 | .@"struct" => { |
| 7477 | 7477 | const resolved_ty = try sema.resolveTypeFields(block, src, ty); |
| 7478 | 7478 | 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) { | |
| 7482 | 7481 | return null; |
| 7483 | 7482 | } |
| 7484 | 7483 | } |
| ... | ... | @@ -7488,7 +7487,7 @@ fn typeHasOnePossibleValue( |
| 7488 | 7487 | const resolved_ty = try sema.resolveTypeFields(block, src, ty); |
| 7489 | 7488 | const enum_full = resolved_ty.castTag(.enum_full).?.data; |
| 7490 | 7489 | if (enum_full.fields.count() == 1) { |
| 7491 | return enum_full.values.entries.items[0].key; | |
| 7490 | return enum_full.values.keys()[0]; | |
| 7492 | 7491 | } else { |
| 7493 | 7492 | return null; |
| 7494 | 7493 | } |
src/air.zig+4-3| ... | ... | @@ -696,10 +696,11 @@ const DumpTzir = struct { |
| 696 | 696 | |
| 697 | 697 | std.debug.print("Module.Function(name={s}):\n", .{dtz.module_fn.owner_decl.name}); |
| 698 | 698 | |
| 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).?; | |
| 701 | 702 | try writer.print(" @{d}: {} = {};\n", .{ |
| 702 | entry.value, constant.base.ty, constant.val, | |
| 703 | entry.value_ptr.*, constant.base.ty, constant.val, | |
| 703 | 704 | }); |
| 704 | 705 | } |
| 705 | 706 |
src/codegen.zig+35-26| ... | ... | @@ -794,7 +794,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { |
| 794 | 794 | |
| 795 | 795 | fn ensureProcessDeathCapacity(self: *Self, additional_count: usize) !void { |
| 796 | 796 | 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); | |
| 798 | 798 | } |
| 799 | 799 | |
| 800 | 800 | /// 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 { |
| 808 | 808 | |
| 809 | 809 | const gop = try dbg_out.dbg_info_type_relocs.getOrPut(self.gpa, ty); |
| 810 | 810 | if (!gop.found_existing) { |
| 811 | gop.entry.value = .{ | |
| 811 | gop.value_ptr.* = .{ | |
| 812 | 812 | .off = undefined, |
| 813 | 813 | .relocs = .{}, |
| 814 | 814 | }; |
| 815 | 815 | } |
| 816 | try gop.entry.value.relocs.append(self.gpa, @intCast(u32, index)); | |
| 816 | try gop.value_ptr.relocs.append(self.gpa, @intCast(u32, index)); | |
| 817 | 817 | }, |
| 818 | 818 | .none => {}, |
| 819 | 819 | } |
| ... | ... | @@ -2877,58 +2877,67 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { |
| 2877 | 2877 | // assert that parent_branch.free_registers equals the saved_then_branch.free_registers |
| 2878 | 2878 | // rather than assigning it. |
| 2879 | 2879 | 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: { | |
| 2884 | 2889 | // 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) { | |
| 2887 | 2892 | assert(then_entry.value == .dead); |
| 2888 | 2893 | continue; |
| 2889 | 2894 | } |
| 2890 | 2895 | break :blk then_entry.value; |
| 2891 | 2896 | } else blk: { |
| 2892 | if (else_entry.value == .dead) | |
| 2897 | if (else_value == .dead) | |
| 2893 | 2898 | continue; |
| 2894 | 2899 | // The instruction is only overridden in the else branch. |
| 2895 | 2900 | var i: usize = self.branch_stack.items.len - 2; |
| 2896 | 2901 | while (true) { |
| 2897 | 2902 | 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| { | |
| 2899 | 2904 | assert(mcv != .dead); |
| 2900 | 2905 | break :blk mcv; |
| 2901 | 2906 | } |
| 2902 | 2907 | } |
| 2903 | 2908 | }; |
| 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 }); | |
| 2905 | 2910 | // TODO make sure the destination stack offset / register does not already have something |
| 2906 | 2911 | // 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); | |
| 2908 | 2913 | // TODO track the new register / stack allocation |
| 2909 | 2914 | } |
| 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]; | |
| 2913 | 2922 | // We already deleted the items from this table that matched the else_branch. |
| 2914 | 2923 | // 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) | |
| 2917 | 2926 | continue; |
| 2918 | 2927 | const parent_mcv = blk: { |
| 2919 | 2928 | var i: usize = self.branch_stack.items.len - 2; |
| 2920 | 2929 | while (true) { |
| 2921 | 2930 | 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| { | |
| 2923 | 2932 | assert(mcv != .dead); |
| 2924 | 2933 | break :blk mcv; |
| 2925 | 2934 | } |
| 2926 | 2935 | } |
| 2927 | 2936 | }; |
| 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 }); | |
| 2929 | 2938 | // TODO make sure the destination stack offset / register does not already have something |
| 2930 | 2939 | // 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); | |
| 2932 | 2941 | // TODO track the new register / stack allocation |
| 2933 | 2942 | } |
| 2934 | 2943 | |
| ... | ... | @@ -3028,7 +3037,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { |
| 3028 | 3037 | // block results. |
| 3029 | 3038 | .mcv = MCValue{ .none = {} }, |
| 3030 | 3039 | }); |
| 3031 | const block_data = &self.blocks.getEntry(inst).?.value; | |
| 3040 | const block_data = self.blocks.getPtr(inst).?; | |
| 3032 | 3041 | defer block_data.relocs.deinit(self.gpa); |
| 3033 | 3042 | |
| 3034 | 3043 | try self.genBody(inst.body); |
| ... | ... | @@ -3109,7 +3118,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { |
| 3109 | 3118 | } |
| 3110 | 3119 | |
| 3111 | 3120 | 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).?; | |
| 3113 | 3122 | |
| 3114 | 3123 | if (operand.ty.hasCodeGenBits()) { |
| 3115 | 3124 | const operand_mcv = try self.resolveInst(operand); |
| ... | ... | @@ -3124,7 +3133,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { |
| 3124 | 3133 | } |
| 3125 | 3134 | |
| 3126 | 3135 | 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).?; | |
| 3128 | 3137 | |
| 3129 | 3138 | // Emit a jump with a relocation. It will be patched up after the block ends. |
| 3130 | 3139 | 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 { |
| 4118 | 4127 | const branch = &self.branch_stack.items[0]; |
| 4119 | 4128 | const gop = try branch.inst_table.getOrPut(self.gpa, inst); |
| 4120 | 4129 | 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 }); | |
| 4122 | 4131 | } |
| 4123 | return gop.entry.value; | |
| 4132 | return gop.value_ptr.*; | |
| 4124 | 4133 | } |
| 4125 | 4134 | |
| 4126 | 4135 | return self.getResolvedInstValue(inst); |
src/codegen/c.zig+10-7| ... | ... | @@ -39,7 +39,7 @@ const BlockData = struct { |
| 39 | 39 | }; |
| 40 | 40 | |
| 41 | 41 | pub const CValueMap = std.AutoHashMap(*Inst, CValue); |
| 42 | pub const TypedefMap = std.HashMap(Type, struct { name: []const u8, rendered: []u8 }, Type.hash, Type.eql, std.hash_map.default_max_load_percentage); | |
| 42 | pub const TypedefMap = std.HashMap(Type, struct { name: []const u8, rendered: []u8 }, Type.HashContext, std.hash_map.default_max_load_percentage); | |
| 43 | 43 | |
| 44 | 44 | fn formatTypeAsCIdentifier( |
| 45 | 45 | data: Type, |
| ... | ... | @@ -309,7 +309,7 @@ pub const DeclGen = struct { |
| 309 | 309 | .enum_full, .enum_nonexhaustive => { |
| 310 | 310 | const enum_full = t.cast(Type.Payload.EnumFull).?.data; |
| 311 | 311 | 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]; | |
| 313 | 313 | return dg.renderValue(writer, enum_full.tag_ty, tag_val); |
| 314 | 314 | } else { |
| 315 | 315 | return writer.print("{d}", .{field_index}); |
| ... | ... | @@ -493,10 +493,13 @@ pub const DeclGen = struct { |
| 493 | 493 | defer buffer.deinit(); |
| 494 | 494 | |
| 495 | 495 | 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 | } | |
| 500 | 503 | } |
| 501 | 504 | try buffer.appendSlice("} "); |
| 502 | 505 | |
| ... | ... | @@ -1186,7 +1189,7 @@ fn genStructFieldPtr(o: *Object, inst: *Inst.StructFieldPtr) !CValue { |
| 1186 | 1189 | const writer = o.writer(); |
| 1187 | 1190 | const struct_ptr = try o.resolveInst(inst.struct_ptr); |
| 1188 | 1191 | 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]; | |
| 1190 | 1193 | |
| 1191 | 1194 | const local = try o.allocLocal(inst.base.ty, .Const); |
| 1192 | 1195 | switch (struct_ptr) { |
src/codegen/llvm.zig+1-1| ... | ... | @@ -789,7 +789,7 @@ pub const FuncGen = struct { |
| 789 | 789 | .break_vals = &break_vals, |
| 790 | 790 | }); |
| 791 | 791 | defer { |
| 792 | self.blocks.removeAssertDiscard(inst); | |
| 792 | assert(self.blocks.remove(inst)); | |
| 793 | 793 | break_bbs.deinit(self.gpa()); |
| 794 | 794 | break_vals.deinit(self.gpa()); |
| 795 | 795 | } |
src/codegen/spirv.zig+7-6| ... | ... | @@ -2,6 +2,7 @@ const std = @import("std"); |
| 2 | 2 | const Allocator = std.mem.Allocator; |
| 3 | 3 | const Target = std.Target; |
| 4 | 4 | const log = std.log.scoped(.codegen); |
| 5 | const assert = std.debug.assert; | |
| 5 | 6 | |
| 6 | 7 | const spec = @import("spirv/spec.zig"); |
| 7 | 8 | const Opcode = spec.Opcode; |
| ... | ... | @@ -17,7 +18,7 @@ const Inst = ir.Inst; |
| 17 | 18 | pub const Word = u32; |
| 18 | 19 | pub const ResultId = u32; |
| 19 | 20 | |
| 20 | pub const TypeMap = std.HashMap(Type, ResultId, Type.hash, Type.eql, std.hash_map.default_max_load_percentage); | |
| 21 | pub const TypeMap = std.HashMap(Type, u32, Type.HashContext, std.hash_map.default_max_load_percentage); | |
| 21 | 22 | pub const InstMap = std.AutoHashMap(*Inst, ResultId); |
| 22 | 23 | |
| 23 | 24 | const IncomingBlock = struct { |
| ... | ... | @@ -141,16 +142,16 @@ pub const SPIRVModule = struct { |
| 141 | 142 | const path = decl.namespace.file_scope.sub_file_path; |
| 142 | 143 | const result = try self.file_names.getOrPut(path); |
| 143 | 144 | 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); | |
| 146 | 147 | try writeInstruction(&self.binary.debug_strings, .OpSource, &[_]Word{ |
| 147 | 148 | @enumToInt(spec.SourceLanguage.Unknown), // TODO: Register Zig source language. |
| 148 | 149 | 0, // TODO: Zig version as u32? |
| 149 | result.entry.value, | |
| 150 | result.value_ptr.*, | |
| 150 | 151 | }); |
| 151 | 152 | } |
| 152 | 153 | |
| 153 | return result.entry.value; | |
| 154 | return result.value_ptr.*; | |
| 154 | 155 | } |
| 155 | 156 | }; |
| 156 | 157 | |
| ... | ... | @@ -847,7 +848,7 @@ pub const DeclGen = struct { |
| 847 | 848 | .incoming_blocks = &incoming_blocks, |
| 848 | 849 | }); |
| 849 | 850 | defer { |
| 850 | self.blocks.removeAssertDiscard(inst); | |
| 851 | assert(self.blocks.remove(inst)); | |
| 851 | 852 | incoming_blocks.deinit(self.spv.gpa); |
| 852 | 853 | } |
| 853 | 854 |
src/codegen/wasm.zig+3-3| ... | ... | @@ -625,10 +625,10 @@ pub const Context = struct { |
| 625 | 625 | const struct_data: *Module.Struct = ty.castTag(.@"struct").?.data; |
| 626 | 626 | const fields_len = @intCast(u32, struct_data.fields.count()); |
| 627 | 627 | 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| { | |
| 629 | 629 | const val_type = try self.genValtype( |
| 630 | 630 | .{ .node_offset = struct_data.node_offset }, |
| 631 | entry.value.ty, | |
| 631 | value.ty, | |
| 632 | 632 | ); |
| 633 | 633 | self.locals.appendAssumeCapacity(val_type); |
| 634 | 634 | self.local_index += 1; |
| ... | ... | @@ -1018,7 +1018,7 @@ pub const Context = struct { |
| 1018 | 1018 | .enum_full, .enum_nonexhaustive => { |
| 1019 | 1019 | const enum_full = ty.cast(Type.Payload.EnumFull).?.data; |
| 1020 | 1020 | 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]; | |
| 1022 | 1022 | try self.emitConstant(src, tag_val, enum_full.tag_ty); |
| 1023 | 1023 | } else { |
| 1024 | 1024 | try writer.writeByte(wasm.opcode(.i32_const)); |
src/libc_installation.zig+2-2| ... | ... | @@ -252,7 +252,7 @@ pub const LibCInstallation = struct { |
| 252 | 252 | // Detect infinite loops. |
| 253 | 253 | const inf_loop_env_key = "ZIG_IS_DETECTING_LIBC_PATHS"; |
| 254 | 254 | 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"); | |
| 256 | 256 | |
| 257 | 257 | const exec_res = std.ChildProcess.exec(.{ |
| 258 | 258 | .allocator = allocator, |
| ... | ... | @@ -564,7 +564,7 @@ fn ccPrintFileName(args: CCPrintFileNameOptions) ![:0]u8 { |
| 564 | 564 | // Detect infinite loops. |
| 565 | 565 | const inf_loop_env_key = "ZIG_IS_DETECTING_LIBC_PATHS"; |
| 566 | 566 | 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"); | |
| 568 | 568 | |
| 569 | 569 | const exec_res = std.ChildProcess.exec(.{ |
| 570 | 570 | .allocator = allocator, |
src/link.zig+8-8| ... | ... | @@ -162,7 +162,7 @@ pub const File = struct { |
| 162 | 162 | }; |
| 163 | 163 | |
| 164 | 164 | /// 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); | |
| 166 | 166 | |
| 167 | 167 | /// For DWARF .debug_info. |
| 168 | 168 | pub const DbgInfoTypeReloc = struct { |
| ... | ... | @@ -406,8 +406,8 @@ pub const File = struct { |
| 406 | 406 | const full_out_path = try emit.directory.join(comp.gpa, &[_][]const u8{emit.sub_path}); |
| 407 | 407 | defer comp.gpa.free(full_out_path); |
| 408 | 408 | 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; | |
| 411 | 411 | try fs.cwd().copyFile(cached_pp_file_path, fs.cwd(), full_out_path, .{}); |
| 412 | 412 | return; |
| 413 | 413 | } |
| ... | ... | @@ -545,8 +545,8 @@ pub const File = struct { |
| 545 | 545 | base.releaseLock(); |
| 546 | 546 | |
| 547 | 547 | 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); | |
| 550 | 550 | } |
| 551 | 551 | try man.addOptionalFile(module_obj_path); |
| 552 | 552 | try man.addOptionalFile(compiler_rt_path); |
| ... | ... | @@ -580,12 +580,12 @@ pub const File = struct { |
| 580 | 580 | var object_files = std.ArrayList([*:0]const u8).init(base.allocator); |
| 581 | 581 | defer object_files.deinit(); |
| 582 | 582 | |
| 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); | |
| 584 | 584 | for (base.options.objects) |obj_path| { |
| 585 | 585 | object_files.appendAssumeCapacity(try arena.dupeZ(u8, obj_path)); |
| 586 | 586 | } |
| 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)); | |
| 589 | 589 | } |
| 590 | 590 | if (module_obj_path) |p| { |
| 591 | 591 | 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 |
| 70 | 70 | } |
| 71 | 71 | |
| 72 | 72 | pub 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); | |
| 75 | 75 | } |
| 76 | 76 | self.decl_table.deinit(self.base.allocator); |
| 77 | 77 | } |
| ... | ... | @@ -80,13 +80,17 @@ pub fn allocateDeclIndexes(self: *C, decl: *Module.Decl) !void {} |
| 80 | 80 | |
| 81 | 81 | pub fn freeDecl(self: *C, decl: *Module.Decl) void { |
| 82 | 82 | _ = 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 | ||
| 86 | fn 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); | |
| 88 | 92 | } |
| 89 | decl.fn_link.c.typedefs.deinit(self.base.allocator); | |
| 93 | decl.fn_link.c.typedefs.deinit(gpa); | |
| 90 | 94 | } |
| 91 | 95 | |
| 92 | 96 | pub 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 { |
| 101 | 105 | const code = &decl.link.c.code; |
| 102 | 106 | fwd_decl.shrinkRetainingCapacity(0); |
| 103 | 107 | { |
| 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); | |
| 107 | 111 | } |
| 108 | 112 | } |
| 109 | 113 | typedefs.clearRetainingCapacity(); |
| ... | ... | @@ -128,9 +132,9 @@ pub fn updateDecl(self: *C, module: *Module, decl: *Module.Decl) !void { |
| 128 | 132 | object.blocks.deinit(module.gpa); |
| 129 | 133 | object.code.deinit(); |
| 130 | 134 | 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); | |
| 134 | 138 | } |
| 135 | 139 | object.dg.typedefs.deinit(); |
| 136 | 140 | } |
| ... | ... | @@ -194,31 +198,30 @@ pub fn flushModule(self: *C, comp: *Compilation) !void { |
| 194 | 198 | if (module.global_error_set.size == 0) break :render_errors; |
| 195 | 199 | var it = module.global_error_set.iterator(); |
| 196 | 200 | 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.* }); | |
| 198 | 202 | } |
| 199 | 203 | try err_typedef_writer.writeByte('\n'); |
| 200 | 204 | } |
| 201 | 205 | |
| 202 | 206 | 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); | |
| 204 | 208 | defer typedefs.deinit(); |
| 205 | 209 | |
| 206 | 210 | // Typedefs, forward decls and non-functions first. |
| 207 | 211 | // TODO: performance investigation: would keeping a list of Decls that we should |
| 208 | 212 | // 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| { | |
| 211 | 214 | if (!decl.has_tv) continue; |
| 212 | 215 | const buf = buf: { |
| 213 | 216 | if (decl.val.castTag(.function)) |_| { |
| 214 | 217 | var it = decl.fn_link.c.typedefs.iterator(); |
| 215 | 218 | 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 }); | |
| 218 | 221 | } else { |
| 219 | 222 | 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); | |
| 222 | 225 | } |
| 223 | 226 | } |
| 224 | 227 | fn_count += 1; |
| ... | ... | @@ -242,8 +245,7 @@ pub fn flushModule(self: *C, comp: *Compilation) !void { |
| 242 | 245 | |
| 243 | 246 | // Now the function bodies. |
| 244 | 247 | 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| { | |
| 247 | 249 | if (!decl.has_tv) continue; |
| 248 | 250 | if (decl.val.castTag(.function)) |_| { |
| 249 | 251 | const buf = decl.link.c.code.items; |
| ... | ... | @@ -278,8 +280,7 @@ pub fn flushEmitH(module: *Module) !void { |
| 278 | 280 | .iov_len = zig_h.len, |
| 279 | 281 | }); |
| 280 | 282 | |
| 281 | for (emit_h.decl_table.items()) |kv| { | |
| 282 | const decl = kv.key; | |
| 283 | for (emit_h.decl_table.keys()) |decl| { | |
| 283 | 284 | const decl_emit_h = decl.getEmitH(module); |
| 284 | 285 | const buf = decl_emit_h.fwd_decl.items; |
| 285 | 286 | all_buffers.appendAssumeCapacity(.{ |
src/link/Coff.zig+9-9| ... | ... | @@ -735,7 +735,7 @@ pub fn updateDeclExports(self: *Coff, module: *Module, decl: *Module.Decl, expor |
| 735 | 735 | for (exports) |exp| { |
| 736 | 736 | if (exp.options.section) |section_name| { |
| 737 | 737 | 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); | |
| 739 | 739 | module.failed_exports.putAssumeCapacityNoClobber( |
| 740 | 740 | exp, |
| 741 | 741 | 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 |
| 746 | 746 | if (mem.eql(u8, exp.options.name, "_start")) { |
| 747 | 747 | self.entry_addr = decl.link.coff.getVAddr(self.*) - default_image_base; |
| 748 | 748 | } 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); | |
| 750 | 750 | module.failed_exports.putAssumeCapacityNoClobber( |
| 751 | 751 | exp, |
| 752 | 752 | 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 { |
| 861 | 861 | self.base.releaseLock(); |
| 862 | 862 | |
| 863 | 863 | 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); | |
| 866 | 866 | } |
| 867 | 867 | try man.addOptionalFile(module_obj_path); |
| 868 | 868 | man.hash.addOptional(self.base.options.stack_size_override); |
| ... | ... | @@ -928,7 +928,7 @@ fn linkWithLLD(self: *Coff, comp: *Compilation) !void { |
| 928 | 928 | break :blk self.base.options.objects[0]; |
| 929 | 929 | |
| 930 | 930 | 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; | |
| 932 | 932 | |
| 933 | 933 | if (module_obj_path) |p| |
| 934 | 934 | break :blk p; |
| ... | ... | @@ -1026,8 +1026,8 @@ fn linkWithLLD(self: *Coff, comp: *Compilation) !void { |
| 1026 | 1026 | |
| 1027 | 1027 | try argv.appendSlice(self.base.options.objects); |
| 1028 | 1028 | |
| 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); | |
| 1031 | 1031 | } |
| 1032 | 1032 | |
| 1033 | 1033 | if (module_obj_path) |p| { |
| ... | ... | @@ -1221,8 +1221,8 @@ fn linkWithLLD(self: *Coff, comp: *Compilation) !void { |
| 1221 | 1221 | try argv.append(comp.compiler_rt_static_lib.?.full_object_path); |
| 1222 | 1222 | } |
| 1223 | 1223 | |
| 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}); | |
| 1226 | 1226 | if (comp.crt_files.get(lib_basename)) |crt_file| { |
| 1227 | 1227 | try argv.append(crt_file.full_object_path); |
| 1228 | 1228 | } else { |
src/link/Elf.zig+33-31| ... | ... | @@ -1318,8 +1318,8 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void { |
| 1318 | 1318 | try man.addOptionalFile(self.base.options.linker_script); |
| 1319 | 1319 | try man.addOptionalFile(self.base.options.version_script); |
| 1320 | 1320 | 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); | |
| 1323 | 1323 | } |
| 1324 | 1324 | try man.addOptionalFile(module_obj_path); |
| 1325 | 1325 | try man.addOptionalFile(compiler_rt_path); |
| ... | ... | @@ -1394,7 +1394,7 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void { |
| 1394 | 1394 | break :blk self.base.options.objects[0]; |
| 1395 | 1395 | |
| 1396 | 1396 | 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; | |
| 1398 | 1398 | |
| 1399 | 1399 | if (module_obj_path) |p| |
| 1400 | 1400 | break :blk p; |
| ... | ... | @@ -1518,8 +1518,7 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void { |
| 1518 | 1518 | var test_path = std.ArrayList(u8).init(self.base.allocator); |
| 1519 | 1519 | defer test_path.deinit(); |
| 1520 | 1520 | 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| { | |
| 1523 | 1522 | test_path.shrinkRetainingCapacity(0); |
| 1524 | 1523 | const sep = fs.path.sep_str; |
| 1525 | 1524 | 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 { |
| 1568 | 1567 | // Positional arguments to the linker such as object files. |
| 1569 | 1568 | try argv.appendSlice(self.base.options.objects); |
| 1570 | 1569 | |
| 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); | |
| 1573 | 1572 | } |
| 1574 | 1573 | |
| 1575 | 1574 | if (module_obj_path) |p| { |
| ... | ... | @@ -1598,10 +1597,9 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void { |
| 1598 | 1597 | |
| 1599 | 1598 | // Shared libraries. |
| 1600 | 1599 | 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(); | |
| 1602 | 1601 | 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| { | |
| 1605 | 1603 | // By this time, we depend on these libs being dynamically linked libraries and not static libraries |
| 1606 | 1604 | // (the check for that needs to be earlier), but they could be full paths to .so files, in which |
| 1607 | 1605 | // case we want to avoid prepending "-l". |
| ... | ... | @@ -2168,9 +2166,9 @@ pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void { |
| 2168 | 2166 | |
| 2169 | 2167 | var dbg_info_type_relocs: File.DbgInfoTypeRelocsTable = .{}; |
| 2170 | 2168 | 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); | |
| 2174 | 2172 | } |
| 2175 | 2173 | dbg_info_type_relocs.deinit(self.base.allocator); |
| 2176 | 2174 | } |
| ... | ... | @@ -2235,12 +2233,12 @@ pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void { |
| 2235 | 2233 | if (fn_ret_has_bits) { |
| 2236 | 2234 | const gop = try dbg_info_type_relocs.getOrPut(self.base.allocator, fn_ret_type); |
| 2237 | 2235 | if (!gop.found_existing) { |
| 2238 | gop.entry.value = .{ | |
| 2236 | gop.value_ptr.* = .{ | |
| 2239 | 2237 | .off = undefined, |
| 2240 | 2238 | .relocs = .{}, |
| 2241 | 2239 | }; |
| 2242 | 2240 | } |
| 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)); | |
| 2244 | 2242 | dbg_info_buffer.items.len += 4; // DW.AT_type, DW.FORM_ref4 |
| 2245 | 2243 | } |
| 2246 | 2244 | 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 { |
| 2448 | 2446 | // Now we emit the .debug_info types of the Decl. These will count towards the size of |
| 2449 | 2447 | // the buffer, so we have to do it before computing the offset, and we can't perform the actual |
| 2450 | 2448 | // 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 | } | |
| 2455 | 2455 | } |
| 2456 | 2456 | |
| 2457 | 2457 | try self.updateDeclDebugInfoAllocation(text_block, @intCast(u32, dbg_info_buffer.items.len)); |
| 2458 | 2458 | |
| 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 | } | |
| 2469 | 2471 | } |
| 2470 | 2472 | } |
| 2471 | 2473 | |
| ... | ... | @@ -2636,7 +2638,7 @@ pub fn updateDeclExports( |
| 2636 | 2638 | for (exports) |exp| { |
| 2637 | 2639 | if (exp.options.section) |section_name| { |
| 2638 | 2640 | 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); | |
| 2640 | 2642 | module.failed_exports.putAssumeCapacityNoClobber( |
| 2641 | 2643 | exp, |
| 2642 | 2644 | try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(), "Unimplemented: ExportOptions.section", .{}), |
| ... | ... | @@ -2654,7 +2656,7 @@ pub fn updateDeclExports( |
| 2654 | 2656 | }, |
| 2655 | 2657 | .Weak => elf.STB_WEAK, |
| 2656 | 2658 | .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); | |
| 2658 | 2660 | module.failed_exports.putAssumeCapacityNoClobber( |
| 2659 | 2661 | exp, |
| 2660 | 2662 | 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 { |
| 567 | 567 | try man.addOptionalFile(self.base.options.linker_script); |
| 568 | 568 | try man.addOptionalFile(self.base.options.version_script); |
| 569 | 569 | 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); | |
| 572 | 572 | } |
| 573 | 573 | try man.addOptionalFile(module_obj_path); |
| 574 | 574 | // 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 { |
| 632 | 632 | break :blk self.base.options.objects[0]; |
| 633 | 633 | |
| 634 | 634 | 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; | |
| 636 | 636 | |
| 637 | 637 | if (module_obj_path) |p| |
| 638 | 638 | break :blk p; |
| ... | ... | @@ -682,8 +682,8 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void { |
| 682 | 682 | |
| 683 | 683 | try positionals.appendSlice(self.base.options.objects); |
| 684 | 684 | |
| 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); | |
| 687 | 687 | } |
| 688 | 688 | |
| 689 | 689 | if (module_obj_path) |p| { |
| ... | ... | @@ -702,9 +702,8 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void { |
| 702 | 702 | var libs = std.ArrayList([]const u8).init(arena); |
| 703 | 703 | var search_lib_names = std.ArrayList([]const u8).init(arena); |
| 704 | 704 | |
| 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| { | |
| 708 | 707 | // By this time, we depend on these libs being dynamically linked libraries and not static libraries |
| 709 | 708 | // (the check for that needs to be earlier), but they could be full paths to .dylib files, in which |
| 710 | 709 | // case we want to avoid prepending "-l". |
| ... | ... | @@ -804,8 +803,8 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void { |
| 804 | 803 | |
| 805 | 804 | var rpaths = std.ArrayList([]const u8).init(arena); |
| 806 | 805 | 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.*); | |
| 809 | 808 | } |
| 810 | 809 | |
| 811 | 810 | if (self.base.options.verbose_link) { |
| ... | ... | @@ -973,8 +972,8 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void { |
| 973 | 972 | // Positional arguments to the linker such as object files. |
| 974 | 973 | try argv.appendSlice(self.base.options.objects); |
| 975 | 974 | |
| 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); | |
| 978 | 977 | } |
| 979 | 978 | if (module_obj_path) |p| { |
| 980 | 979 | try argv.append(p); |
| ... | ... | @@ -986,10 +985,9 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void { |
| 986 | 985 | } |
| 987 | 986 | |
| 988 | 987 | // Shared libraries. |
| 989 | const system_libs = self.base.options.system_libs.items(); | |
| 988 | const system_libs = self.base.options.system_libs.keys(); | |
| 990 | 989 | 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| { | |
| 993 | 991 | // By this time, we depend on these libs being dynamically linked libraries and not static libraries |
| 994 | 992 | // (the check for that needs to be earlier), but they could be full paths to .dylib files, in which |
| 995 | 993 | // case we want to avoid prepending "-l". |
| ... | ... | @@ -1153,12 +1151,12 @@ pub fn deinit(self: *MachO) void { |
| 1153 | 1151 | if (self.d_sym) |*ds| { |
| 1154 | 1152 | ds.deinit(self.base.allocator); |
| 1155 | 1153 | } |
| 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.*); | |
| 1158 | 1156 | } |
| 1159 | 1157 | 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.*); | |
| 1162 | 1160 | } |
| 1163 | 1161 | self.nonlazy_imports.deinit(self.base.allocator); |
| 1164 | 1162 | self.pie_fixups.deinit(self.base.allocator); |
| ... | ... | @@ -1167,9 +1165,9 @@ pub fn deinit(self: *MachO) void { |
| 1167 | 1165 | self.offset_table.deinit(self.base.allocator); |
| 1168 | 1166 | self.offset_table_free_list.deinit(self.base.allocator); |
| 1169 | 1167 | { |
| 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.*); | |
| 1173 | 1171 | } |
| 1174 | 1172 | } |
| 1175 | 1173 | self.string_table_directory.deinit(self.base.allocator); |
| ... | ... | @@ -1318,9 +1316,9 @@ pub fn updateDecl(self: *MachO, module: *Module, decl: *Module.Decl) !void { |
| 1318 | 1316 | if (debug_buffers) |*dbg| { |
| 1319 | 1317 | dbg.dbg_line_buffer.deinit(); |
| 1320 | 1318 | 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); | |
| 1324 | 1322 | } |
| 1325 | 1323 | dbg.dbg_info_type_relocs.deinit(self.base.allocator); |
| 1326 | 1324 | } |
| ... | ... | @@ -1543,7 +1541,7 @@ pub fn updateDeclExports( |
| 1543 | 1541 | |
| 1544 | 1542 | if (exp.options.section) |section_name| { |
| 1545 | 1543 | 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); | |
| 1547 | 1545 | module.failed_exports.putAssumeCapacityNoClobber( |
| 1548 | 1546 | exp, |
| 1549 | 1547 | try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(), "Unimplemented: ExportOptions.section", .{}), |
| ... | ... | @@ -1578,7 +1576,7 @@ pub fn updateDeclExports( |
| 1578 | 1576 | n_desc |= macho.N_WEAK_DEF; |
| 1579 | 1577 | }, |
| 1580 | 1578 | .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); | |
| 1582 | 1580 | module.failed_exports.putAssumeCapacityNoClobber( |
| 1583 | 1581 | exp, |
| 1584 | 1582 | try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(), "Unimplemented: GlobalLinkage.LinkOnce", .{}), |
| ... | ... | @@ -2259,7 +2257,7 @@ pub fn populateMissingMetadata(self: *MachO) !void { |
| 2259 | 2257 | self.load_commands_dirty = true; |
| 2260 | 2258 | } |
| 2261 | 2259 | 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()); | |
| 2263 | 2261 | const name = try self.base.allocator.dupe(u8, "dyld_stub_binder"); |
| 2264 | 2262 | const offset = try self.makeString("dyld_stub_binder"); |
| 2265 | 2263 | 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 { |
| 2440 | 2438 | } |
| 2441 | 2439 | |
| 2442 | 2440 | pub 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()); | |
| 2444 | 2442 | const offset = try self.makeString(name); |
| 2445 | 2443 | const sym_name = try self.base.allocator.dupe(u8, name); |
| 2446 | 2444 | 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 { |
| 2627 | 2625 | break :blk self.locals.items[got_entry.symbol]; |
| 2628 | 2626 | }, |
| 2629 | 2627 | .Extern => { |
| 2630 | break :blk self.nonlazy_imports.items()[got_entry.symbol].value.symbol; | |
| 2628 | break :blk self.nonlazy_imports.values()[got_entry.symbol].symbol; | |
| 2631 | 2629 | }, |
| 2632 | 2630 | } |
| 2633 | 2631 | }; |
| ... | ... | @@ -2910,7 +2908,7 @@ fn relocateSymbolTable(self: *MachO) !void { |
| 2910 | 2908 | const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab; |
| 2911 | 2909 | const nlocals = self.locals.items.len; |
| 2912 | 2910 | 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(); | |
| 2914 | 2912 | const nsyms = nlocals + nglobals + nundefs; |
| 2915 | 2913 | |
| 2916 | 2914 | if (symtab.nsyms < nsyms) { |
| ... | ... | @@ -2957,15 +2955,15 @@ fn writeAllGlobalAndUndefSymbols(self: *MachO) !void { |
| 2957 | 2955 | const nlocals = self.locals.items.len; |
| 2958 | 2956 | const nglobals = self.globals.items.len; |
| 2959 | 2957 | |
| 2960 | const nundefs = self.lazy_imports.items().len + self.nonlazy_imports.items().len; | |
| 2958 | const nundefs = self.lazy_imports.count() + self.nonlazy_imports.count(); | |
| 2961 | 2959 | var undefs = std.ArrayList(macho.nlist_64).init(self.base.allocator); |
| 2962 | 2960 | defer undefs.deinit(); |
| 2963 | 2961 | 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); | |
| 2966 | 2964 | } |
| 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); | |
| 2969 | 2967 | } |
| 2970 | 2968 | |
| 2971 | 2969 | const locals_off = symtab.symoff; |
| ... | ... | @@ -3005,10 +3003,10 @@ fn writeIndirectSymbolTable(self: *MachO) !void { |
| 3005 | 3003 | const la_symbol_ptr = &data_segment.sections.items[self.la_symbol_ptr_section_index.?]; |
| 3006 | 3004 | const dysymtab = &self.load_commands.items[self.dysymtab_cmd_index.?].Dysymtab; |
| 3007 | 3005 | |
| 3008 | const lazy = self.lazy_imports.items(); | |
| 3006 | const lazy_count = self.lazy_imports.count(); | |
| 3009 | 3007 | const got_entries = self.offset_table.items; |
| 3010 | 3008 | 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); | |
| 3012 | 3010 | const needed_size = @intCast(u32, nindirectsyms * @sizeOf(u32)); |
| 3013 | 3011 | |
| 3014 | 3012 | if (needed_size > allocated_size) { |
| ... | ... | @@ -3027,12 +3025,15 @@ fn writeIndirectSymbolTable(self: *MachO) !void { |
| 3027 | 3025 | var writer = stream.writer(); |
| 3028 | 3026 | |
| 3029 | 3027 | 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 | } | |
| 3033 | 3034 | } |
| 3034 | 3035 | |
| 3035 | const base_id = @intCast(u32, lazy.len); | |
| 3036 | const base_id = @intCast(u32, lazy_count); | |
| 3036 | 3037 | got.reserved1 = base_id; |
| 3037 | 3038 | for (got_entries) |entry| { |
| 3038 | 3039 | switch (entry.kind) { |
| ... | ... | @@ -3047,9 +3048,12 @@ fn writeIndirectSymbolTable(self: *MachO) !void { |
| 3047 | 3048 | } |
| 3048 | 3049 | |
| 3049 | 3050 | 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 | } | |
| 3053 | 3057 | } |
| 3054 | 3058 | |
| 3055 | 3059 | try self.base.file.?.pwriteAll(buf, dysymtab.indirectsymoff); |
| ... | ... | @@ -3183,15 +3187,15 @@ fn writeRebaseInfoTable(self: *MachO) !void { |
| 3183 | 3187 | } |
| 3184 | 3188 | |
| 3185 | 3189 | 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()); | |
| 3187 | 3191 | const seg = self.load_commands.items[self.data_segment_cmd_index.?].Segment; |
| 3188 | 3192 | const sect = seg.sections.items[idx]; |
| 3189 | 3193 | const base_offset = sect.addr - seg.inner.vmaddr; |
| 3190 | 3194 | const segment_id = self.data_segment_cmd_index.?; |
| 3191 | 3195 | |
| 3192 | for (self.lazy_imports.items()) |entry| { | |
| 3196 | for (self.lazy_imports.values()) |*value| { | |
| 3193 | 3197 | pointers.appendAssumeCapacity(.{ |
| 3194 | .offset = base_offset + entry.value.index * @sizeOf(u64), | |
| 3198 | .offset = base_offset + value.index * @sizeOf(u64), | |
| 3195 | 3199 | .segment_id = segment_id, |
| 3196 | 3200 | }); |
| 3197 | 3201 | } |
| ... | ... | @@ -3241,12 +3245,13 @@ fn writeBindingInfoTable(self: *MachO) !void { |
| 3241 | 3245 | |
| 3242 | 3246 | for (self.offset_table.items) |entry| { |
| 3243 | 3247 | 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; | |
| 3245 | 3250 | try pointers.append(.{ |
| 3246 | 3251 | .offset = base_offset + entry.index * @sizeOf(u64), |
| 3247 | 3252 | .segment_id = segment_id, |
| 3248 | .dylib_ordinal = import.value.dylib_ordinal, | |
| 3249 | .name = import.key, | |
| 3253 | .dylib_ordinal = import_ordinal, | |
| 3254 | .name = import_key, | |
| 3250 | 3255 | }); |
| 3251 | 3256 | } |
| 3252 | 3257 | } |
| ... | ... | @@ -3286,18 +3291,21 @@ fn writeLazyBindingInfoTable(self: *MachO) !void { |
| 3286 | 3291 | defer pointers.deinit(); |
| 3287 | 3292 | |
| 3288 | 3293 | 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()); | |
| 3290 | 3295 | const seg = self.load_commands.items[self.data_segment_cmd_index.?].Segment; |
| 3291 | 3296 | const sect = seg.sections.items[idx]; |
| 3292 | 3297 | const base_offset = sect.addr - seg.inner.vmaddr; |
| 3293 | 3298 | const segment_id = @intCast(u16, self.data_segment_cmd_index.?); |
| 3294 | 3299 | |
| 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| { | |
| 3296 | 3304 | pointers.appendAssumeCapacity(.{ |
| 3297 | .offset = base_offset + entry.value.index * @sizeOf(u64), | |
| 3305 | .offset = base_offset + values[i].index * @sizeOf(u64), | |
| 3298 | 3306 | .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.*, | |
| 3301 | 3309 | }); |
| 3302 | 3310 | } |
| 3303 | 3311 | } |
| ... | ... | @@ -3329,7 +3337,7 @@ fn writeLazyBindingInfoTable(self: *MachO) !void { |
| 3329 | 3337 | } |
| 3330 | 3338 | |
| 3331 | 3339 | fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 3332 | if (self.lazy_imports.items().len == 0) return; | |
| 3340 | if (self.lazy_imports.count() == 0) return; | |
| 3333 | 3341 | |
| 3334 | 3342 | var stream = std.io.fixedBufferStream(buffer); |
| 3335 | 3343 | var reader = stream.reader(); |
| ... | ... | @@ -3375,7 +3383,7 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 3375 | 3383 | else => {}, |
| 3376 | 3384 | } |
| 3377 | 3385 | } |
| 3378 | assert(self.lazy_imports.items().len <= offsets.items.len); | |
| 3386 | assert(self.lazy_imports.count() <= offsets.items.len); | |
| 3379 | 3387 | |
| 3380 | 3388 | const stub_size: u4 = switch (self.base.options.target.cpu.arch) { |
| 3381 | 3389 | .x86_64 => 10, |
| ... | ... | @@ -3388,9 +3396,9 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 3388 | 3396 | else => unreachable, |
| 3389 | 3397 | }; |
| 3390 | 3398 | var buf: [@sizeOf(u32)]u8 = undefined; |
| 3391 | for (self.lazy_imports.items()) |_, i| { | |
| 3399 | for (offsets.items[0..self.lazy_imports.count()]) |offset, i| { | |
| 3392 | 3400 | 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); | |
| 3394 | 3402 | try self.base.file.?.pwriteAll(&buf, placeholder_off); |
| 3395 | 3403 | } |
| 3396 | 3404 | } |
src/link/MachO/Archive.zig+7-5| ... | ... | @@ -92,9 +92,11 @@ pub fn init(allocator: *Allocator) Archive { |
| 92 | 92 | } |
| 93 | 93 | |
| 94 | 94 | pub 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); | |
| 98 | 100 | } |
| 99 | 101 | self.toc.deinit(self.allocator); |
| 100 | 102 | |
| ... | ... | @@ -187,10 +189,10 @@ fn parseTableOfContents(self: *Archive, reader: anytype) !void { |
| 187 | 189 | defer if (res.found_existing) self.allocator.free(owned_name); |
| 188 | 190 | |
| 189 | 191 | if (!res.found_existing) { |
| 190 | res.entry.value = .{}; | |
| 192 | res.value_ptr.* = .{}; | |
| 191 | 193 | } |
| 192 | 194 | |
| 193 | try res.entry.value.append(self.allocator, object_offset); | |
| 195 | try res.value_ptr.append(self.allocator, object_offset); | |
| 194 | 196 | } |
| 195 | 197 | } |
| 196 | 198 |
src/link/MachO/DebugSymbols.zig+22-18| ... | ... | @@ -997,12 +997,12 @@ pub fn initDeclDebugBuffers( |
| 997 | 997 | if (fn_ret_has_bits) { |
| 998 | 998 | const gop = try dbg_info_type_relocs.getOrPut(allocator, fn_ret_type); |
| 999 | 999 | if (!gop.found_existing) { |
| 1000 | gop.entry.value = .{ | |
| 1000 | gop.value_ptr.* = .{ | |
| 1001 | 1001 | .off = undefined, |
| 1002 | 1002 | .relocs = .{}, |
| 1003 | 1003 | }; |
| 1004 | 1004 | } |
| 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)); | |
| 1006 | 1006 | dbg_info_buffer.items.len += 4; // DW.AT_type, DW.FORM_ref4 |
| 1007 | 1007 | } |
| 1008 | 1008 | dbg_info_buffer.appendSliceAssumeCapacity(decl_name_with_null); // DW.AT_name, DW.FORM_string |
| ... | ... | @@ -1158,26 +1158,30 @@ pub fn commitDeclDebugInfo( |
| 1158 | 1158 | if (dbg_info_buffer.items.len == 0) |
| 1159 | 1159 | return; |
| 1160 | 1160 | |
| 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 | } | |
| 1168 | 1170 | } |
| 1169 | 1171 | |
| 1170 | 1172 | try self.updateDeclDebugInfoAllocation(allocator, text_block, @intCast(u32, dbg_info_buffer.items.len)); |
| 1171 | 1173 | |
| 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 | } | |
| 1181 | 1185 | } |
| 1182 | 1186 | } |
| 1183 | 1187 |
src/link/MachO/Dylib.zig+3-3| ... | ... | @@ -50,9 +50,9 @@ pub fn deinit(self: *Dylib) void { |
| 50 | 50 | } |
| 51 | 51 | self.load_commands.deinit(self.allocator); |
| 52 | 52 | |
| 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); | |
| 56 | 56 | } |
| 57 | 57 | self.symbols.deinit(self.allocator); |
| 58 | 58 |
src/link/MachO/Zld.zig+20-23| ... | ... | @@ -168,9 +168,9 @@ pub fn deinit(self: *Zld) void { |
| 168 | 168 | self.strtab.deinit(self.allocator); |
| 169 | 169 | |
| 170 | 170 | { |
| 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.*); | |
| 174 | 174 | } |
| 175 | 175 | } |
| 176 | 176 | self.strtab_dir.deinit(self.allocator); |
| ... | ... | @@ -954,9 +954,8 @@ fn sortSections(self: *Zld) !void { |
| 954 | 954 | } |
| 955 | 955 | } |
| 956 | 956 | |
| 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| { | |
| 960 | 959 | if (self.text_segment_cmd_index.? == mapping.target_seg_id) { |
| 961 | 960 | const new_index = text_index_mapping.get(mapping.target_sect_id) orelse unreachable; |
| 962 | 961 | mapping.target_sect_id = new_index; |
| ... | ... | @@ -1400,16 +1399,16 @@ fn resolveSymbolsInObject(self: *Zld, object: *Object) !void { |
| 1400 | 1399 | if (sym.cast(Symbol.Regular)) |reg| { |
| 1401 | 1400 | if (reg.linkage == .translation_unit) continue; // Symbol local to TU. |
| 1402 | 1401 | |
| 1403 | if (self.unresolved.swapRemove(sym.name)) |entry| { | |
| 1402 | if (self.unresolved.fetchSwapRemove(sym.name)) |kv| { | |
| 1404 | 1403 | // Create link to the global. |
| 1405 | entry.value.alias = sym; | |
| 1404 | kv.value.alias = sym; | |
| 1406 | 1405 | } |
| 1407 | const entry = self.globals.getEntry(sym.name) orelse { | |
| 1406 | const sym_ptr = self.globals.getPtr(sym.name) orelse { | |
| 1408 | 1407 | // Put new global symbol into the symbol table. |
| 1409 | 1408 | try self.globals.putNoClobber(self.allocator, sym.name, sym); |
| 1410 | 1409 | continue; |
| 1411 | 1410 | }; |
| 1412 | const g_sym = entry.value; | |
| 1411 | const g_sym = sym_ptr.*; | |
| 1413 | 1412 | const g_reg = g_sym.cast(Symbol.Regular) orelse unreachable; |
| 1414 | 1413 | |
| 1415 | 1414 | switch (g_reg.linkage) { |
| ... | ... | @@ -1432,7 +1431,7 @@ fn resolveSymbolsInObject(self: *Zld, object: *Object) !void { |
| 1432 | 1431 | } |
| 1433 | 1432 | |
| 1434 | 1433 | g_sym.alias = sym; |
| 1435 | entry.value = sym; | |
| 1434 | sym_ptr.* = sym; | |
| 1436 | 1435 | } else if (sym.cast(Symbol.Unresolved)) |und| { |
| 1437 | 1436 | if (self.globals.get(sym.name)) |g_sym| { |
| 1438 | 1437 | sym.alias = g_sym; |
| ... | ... | @@ -1458,8 +1457,7 @@ fn resolveSymbols(self: *Zld) !void { |
| 1458 | 1457 | while (true) { |
| 1459 | 1458 | if (next_sym == self.unresolved.count()) break; |
| 1460 | 1459 | |
| 1461 | const entry = self.unresolved.items()[next_sym]; | |
| 1462 | const sym = entry.value; | |
| 1460 | const sym = self.unresolved.values()[next_sym]; | |
| 1463 | 1461 | |
| 1464 | 1462 | var reset: bool = false; |
| 1465 | 1463 | for (self.archives.items) |archive| { |
| ... | ... | @@ -1492,8 +1490,8 @@ fn resolveSymbols(self: *Zld) !void { |
| 1492 | 1490 | defer unresolved.deinit(); |
| 1493 | 1491 | |
| 1494 | 1492 | 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); | |
| 1497 | 1495 | } |
| 1498 | 1496 | self.unresolved.clearAndFree(self.allocator); |
| 1499 | 1497 | |
| ... | ... | @@ -2780,8 +2778,7 @@ fn writeSymbolTable(self: *Zld) !void { |
| 2780 | 2778 | var undefs = std.ArrayList(macho.nlist_64).init(self.allocator); |
| 2781 | 2779 | defer undefs.deinit(); |
| 2782 | 2780 | |
| 2783 | for (self.imports.items()) |entry| { | |
| 2784 | const sym = entry.value; | |
| 2781 | for (self.imports.values()) |sym| { | |
| 2785 | 2782 | const ordinal = ordinal: { |
| 2786 | 2783 | const dylib = sym.cast(Symbol.Proxy).?.dylib orelse break :ordinal 1; // TODO handle libSystem |
| 2787 | 2784 | break :ordinal dylib.ordinal.?; |
| ... | ... | @@ -3071,9 +3068,9 @@ pub fn parseName(name: *const [16]u8) []const u8 { |
| 3071 | 3068 | |
| 3072 | 3069 | fn printSymbols(self: *Zld) void { |
| 3073 | 3070 | 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 }); | |
| 3077 | 3074 | log.debug(" => alias of {*}", .{sym.base.alias}); |
| 3078 | 3075 | log.debug(" => linkage {s}", .{sym.linkage}); |
| 3079 | 3076 | log.debug(" => defined in {s}", .{sym.file.name.?}); |
| ... | ... | @@ -3091,9 +3088,9 @@ fn printSymbols(self: *Zld) void { |
| 3091 | 3088 | } |
| 3092 | 3089 | } |
| 3093 | 3090 | 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 }); | |
| 3097 | 3094 | log.debug(" => alias of {*}", .{sym.base.alias}); |
| 3098 | 3095 | log.debug(" => defined in libSystem.B.dylib", .{}); |
| 3099 | 3096 | } |
src/link/SpirV.zig+3-5| ... | ... | @@ -114,7 +114,7 @@ pub fn updateDeclExports( |
| 114 | 114 | ) !void {} |
| 115 | 115 | |
| 116 | 116 | pub fn freeDecl(self: *SpirV, decl: *Module.Decl) void { |
| 117 | self.decl_table.removeAssertDiscard(decl); | |
| 117 | assert(self.decl_table.swapRemove(decl)); | |
| 118 | 118 | } |
| 119 | 119 | |
| 120 | 120 | pub fn flush(self: *SpirV, comp: *Compilation) !void { |
| ... | ... | @@ -141,8 +141,7 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void { |
| 141 | 141 | // declarations which don't generate a result? |
| 142 | 142 | // TODO: fn_link is used here, but thats probably not the right field. It will work anyway though. |
| 143 | 143 | { |
| 144 | for (self.decl_table.items()) |entry| { | |
| 145 | const decl = entry.key; | |
| 144 | for (self.decl_table.keys()) |decl| { | |
| 146 | 145 | if (!decl.has_tv) continue; |
| 147 | 146 | |
| 148 | 147 | decl.fn_link.spirv.id = spv.allocResultId(); |
| ... | ... | @@ -154,8 +153,7 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void { |
| 154 | 153 | var decl_gen = codegen.DeclGen.init(&spv); |
| 155 | 154 | defer decl_gen.deinit(); |
| 156 | 155 | |
| 157 | for (self.decl_table.items()) |entry| { | |
| 158 | const decl = entry.key; | |
| 156 | for (self.decl_table.keys()) |decl| { | |
| 159 | 157 | if (!decl.has_tv) continue; |
| 160 | 158 | |
| 161 | 159 | 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 { |
| 422 | 422 | const header_offset = try reserveVecSectionHeader(file); |
| 423 | 423 | const writer = file.writer(); |
| 424 | 424 | 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| { | |
| 427 | 427 | // Export name length + name |
| 428 | 428 | try leb.writeULEB128(writer, @intCast(u32, exprt.options.name.len)); |
| 429 | 429 | try writer.writeAll(exprt.options.name); |
| ... | ... | @@ -590,8 +590,8 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void { |
| 590 | 590 | self.base.releaseLock(); |
| 591 | 591 | |
| 592 | 592 | 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); | |
| 595 | 595 | } |
| 596 | 596 | try man.addOptionalFile(module_obj_path); |
| 597 | 597 | try man.addOptionalFile(compiler_rt_path); |
| ... | ... | @@ -638,7 +638,7 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void { |
| 638 | 638 | break :blk self.base.options.objects[0]; |
| 639 | 639 | |
| 640 | 640 | 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; | |
| 642 | 642 | |
| 643 | 643 | if (module_obj_path) |p| |
| 644 | 644 | break :blk p; |
| ... | ... | @@ -712,8 +712,8 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void { |
| 712 | 712 | // Positional arguments to the linker such as object files. |
| 713 | 713 | try argv.appendSlice(self.base.options.objects); |
| 714 | 714 | |
| 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); | |
| 717 | 717 | } |
| 718 | 718 | if (module_obj_path) |p| { |
| 719 | 719 | try argv.append(p); |
src/liveness.zig+28-27| ... | ... | @@ -2,6 +2,7 @@ const std = @import("std"); |
| 2 | 2 | const ir = @import("air.zig"); |
| 3 | 3 | const trace = @import("tracy.zig").trace; |
| 4 | 4 | const log = std.log.scoped(.liveness); |
| 5 | const assert = std.debug.assert; | |
| 5 | 6 | |
| 6 | 7 | /// Perform Liveness Analysis over the `Body`. Each `Inst` will have its `deaths` field populated. |
| 7 | 8 | pub fn analyze( |
| ... | ... | @@ -86,9 +87,9 @@ fn analyzeInst( |
| 86 | 87 | |
| 87 | 88 | // Reset the table back to its state from before the branch. |
| 88 | 89 | { |
| 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.*)); | |
| 92 | 93 | } |
| 93 | 94 | } |
| 94 | 95 | |
| ... | ... | @@ -102,9 +103,9 @@ fn analyzeInst( |
| 102 | 103 | defer else_entry_deaths.deinit(); |
| 103 | 104 | |
| 104 | 105 | { |
| 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.*; | |
| 108 | 109 | if (!then_table.contains(else_death)) { |
| 109 | 110 | try then_entry_deaths.append(else_death); |
| 110 | 111 | } |
| ... | ... | @@ -113,9 +114,9 @@ fn analyzeInst( |
| 113 | 114 | // This loop is the same, except it's for the then branch, and it additionally |
| 114 | 115 | // has to put its items back into the table to undo the reset. |
| 115 | 116 | { |
| 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.*; | |
| 119 | 120 | if (!else_table.contains(then_death)) { |
| 120 | 121 | try else_entry_deaths.append(then_death); |
| 121 | 122 | } |
| ... | ... | @@ -125,13 +126,13 @@ fn analyzeInst( |
| 125 | 126 | // Now we have to correctly populate new_set. |
| 126 | 127 | if (new_set) |ns| { |
| 127 | 128 | 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.*, {}); | |
| 131 | 132 | } |
| 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.*, {}); | |
| 135 | 136 | } |
| 136 | 137 | } |
| 137 | 138 | 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( |
| 159 | 160 | try analyzeWithTable(arena, table, &case_tables[i], case.body); |
| 160 | 161 | |
| 161 | 162 | // 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.*)); | |
| 165 | 166 | } |
| 166 | 167 | } |
| 167 | 168 | { // else |
| 168 | 169 | try analyzeWithTable(arena, table, &case_tables[case_tables.len - 1], inst.else_body); |
| 169 | 170 | |
| 170 | 171 | // 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.*)); | |
| 174 | 175 | } |
| 175 | 176 | } |
| 176 | 177 | |
| ... | ... | @@ -184,9 +185,9 @@ fn analyzeInst( |
| 184 | 185 | var total_deaths: u32 = 0; |
| 185 | 186 | for (case_tables) |*ct, i| { |
| 186 | 187 | 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.*; | |
| 190 | 191 | for (case_tables) |*ct_inner, j| { |
| 191 | 192 | if (i == j) continue; |
| 192 | 193 | if (!ct_inner.contains(case_death)) { |
| ... | ... | @@ -203,9 +204,9 @@ fn analyzeInst( |
| 203 | 204 | if (new_set) |ns| { |
| 204 | 205 | try ns.ensureCapacity(@intCast(u32, ns.count() + total_deaths)); |
| 205 | 206 | 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.*, {}); | |
| 209 | 210 | } |
| 210 | 211 | } |
| 211 | 212 | } |
src/main.zig+6-6| ... | ... | @@ -180,7 +180,7 @@ pub fn mainArgs(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !v |
| 180 | 180 | "in order to determine where libc is installed. However the system C " ++ |
| 181 | 181 | "compiler is `zig cc`, so no libc installation was found.", .{}); |
| 182 | 182 | } |
| 183 | try env_map.set(inf_loop_env_key, "1"); | |
| 183 | try env_map.put(inf_loop_env_key, "1"); | |
| 184 | 184 | |
| 185 | 185 | // Some programs such as CMake will strip the `cc` and subsequent args from the |
| 186 | 186 | // 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 |
| 2310 | 2310 | |
| 2311 | 2311 | fn freePkgTree(gpa: *Allocator, pkg: *Package, free_parent: bool) void { |
| 2312 | 2312 | { |
| 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); | |
| 2316 | 2316 | } |
| 2317 | 2317 | } |
| 2318 | 2318 | if (free_parent) { |
| ... | ... | @@ -3895,7 +3895,7 @@ pub fn cmdChangelist( |
| 3895 | 3895 | var it = inst_map.iterator(); |
| 3896 | 3896 | while (it.next()) |entry| { |
| 3897 | 3897 | try stdout.print(" %{d} => %{d}\n", .{ |
| 3898 | entry.key, entry.value, | |
| 3898 | entry.key_ptr.*, entry.value_ptr.*, | |
| 3899 | 3899 | }); |
| 3900 | 3900 | } |
| 3901 | 3901 | } |
| ... | ... | @@ -3904,7 +3904,7 @@ pub fn cmdChangelist( |
| 3904 | 3904 | var it = extra_map.iterator(); |
| 3905 | 3905 | while (it.next()) |entry| { |
| 3906 | 3906 | try stdout.print(" {d} => {d}\n", .{ |
| 3907 | entry.key, entry.value, | |
| 3907 | entry.key_ptr.*, entry.value_ptr.*, | |
| 3908 | 3908 | }); |
| 3909 | 3909 | } |
| 3910 | 3910 | } |
src/musl.zig+4-3| ... | ... | @@ -135,9 +135,10 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void { |
| 135 | 135 | |
| 136 | 136 | const s = path.sep_str; |
| 137 | 137 | |
| 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.*; | |
| 141 | 142 | |
| 142 | 143 | const dirname = path.dirname(src_file).?; |
| 143 | 144 | 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 { |
| 453 | 453 | // Don't put this one in `decl_table` so it's processed later. |
| 454 | 454 | return; |
| 455 | 455 | } |
| 456 | result.entry.value = name; | |
| 456 | result.value_ptr.* = name; | |
| 457 | 457 | // Put this typedef in the decl_table to avoid redefinitions. |
| 458 | 458 | try c.decl_table.putNoClobber(c.gpa, @ptrToInt(typedef_decl.getCanonicalDecl()), name); |
| 459 | 459 | } |
| ... | ... | @@ -5765,14 +5765,14 @@ fn getFnProto(c: *Context, ref: Node) ?*ast.Payload.Func { |
| 5765 | 5765 | |
| 5766 | 5766 | fn addMacros(c: *Context) !void { |
| 5767 | 5767 | 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| { | |
| 5770 | 5770 | // If a macro aliases a global variable which is a function pointer, we conclude that |
| 5771 | 5771 | // the macro is intended to represent a function that assumes the function pointer |
| 5772 | 5772 | // 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)); | |
| 5774 | 5774 | } else { |
| 5775 | try addTopLevelDecl(c, kv.key, kv.value); | |
| 5775 | try addTopLevelDecl(c, entry.key_ptr.*, entry.value_ptr.*); | |
| 5776 | 5776 | } |
| 5777 | 5777 | } |
| 5778 | 5778 | } |
src/type.zig+29-24| ... | ... | @@ -596,6 +596,15 @@ pub const Type = extern union { |
| 596 | 596 | return hasher.final(); |
| 597 | 597 | } |
| 598 | 598 | |
| 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 | ||
| 599 | 608 | pub fn copy(self: Type, allocator: *Allocator) error{OutOfMemory}!Type { |
| 600 | 609 | if (self.tag_if_small_enough < Tag.no_payload_count) { |
| 601 | 610 | return Type{ .tag_if_small_enough = self.tag_if_small_enough }; |
| ... | ... | @@ -1147,8 +1156,8 @@ pub const Type = extern union { |
| 1147 | 1156 | .@"struct" => { |
| 1148 | 1157 | // TODO introduce lazy value mechanism |
| 1149 | 1158 | 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()) | |
| 1152 | 1161 | return true; |
| 1153 | 1162 | } else { |
| 1154 | 1163 | return false; |
| ... | ... | @@ -1169,8 +1178,8 @@ pub const Type = extern union { |
| 1169 | 1178 | }, |
| 1170 | 1179 | .@"union" => { |
| 1171 | 1180 | 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()) | |
| 1174 | 1183 | return true; |
| 1175 | 1184 | } else { |
| 1176 | 1185 | return false; |
| ... | ... | @@ -1181,8 +1190,8 @@ pub const Type = extern union { |
| 1181 | 1190 | if (union_obj.tag_ty.hasCodeGenBits()) { |
| 1182 | 1191 | return true; |
| 1183 | 1192 | } |
| 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()) | |
| 1186 | 1195 | return true; |
| 1187 | 1196 | } else { |
| 1188 | 1197 | return false; |
| ... | ... | @@ -1380,10 +1389,9 @@ pub const Type = extern union { |
| 1380 | 1389 | // like we have in stage1. |
| 1381 | 1390 | const struct_obj = self.castTag(.@"struct").?.data; |
| 1382 | 1391 | 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); | |
| 1387 | 1395 | if (field_align > biggest) { |
| 1388 | 1396 | return field_align; |
| 1389 | 1397 | } |
| ... | ... | @@ -1399,10 +1407,9 @@ pub const Type = extern union { |
| 1399 | 1407 | .union_tagged => { |
| 1400 | 1408 | const union_obj = self.castTag(.union_tagged).?.data; |
| 1401 | 1409 | 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); | |
| 1406 | 1413 | if (field_align > biggest) { |
| 1407 | 1414 | biggest = field_align; |
| 1408 | 1415 | } |
| ... | ... | @@ -1413,10 +1420,9 @@ pub const Type = extern union { |
| 1413 | 1420 | .@"union" => { |
| 1414 | 1421 | const union_obj = self.castTag(.@"union").?.data; |
| 1415 | 1422 | 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); | |
| 1420 | 1426 | if (field_align > biggest) { |
| 1421 | 1427 | biggest = field_align; |
| 1422 | 1428 | } |
| ... | ... | @@ -2415,9 +2421,8 @@ pub const Type = extern union { |
| 2415 | 2421 | .@"struct" => { |
| 2416 | 2422 | const s = ty.castTag(.@"struct").?.data; |
| 2417 | 2423 | 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) { | |
| 2421 | 2426 | return null; |
| 2422 | 2427 | } |
| 2423 | 2428 | } |
| ... | ... | @@ -2426,7 +2431,7 @@ pub const Type = extern union { |
| 2426 | 2431 | .enum_full => { |
| 2427 | 2432 | const enum_full = ty.castTag(.enum_full).?.data; |
| 2428 | 2433 | if (enum_full.fields.count() == 1) { |
| 2429 | return enum_full.values.entries.items[0].key; | |
| 2434 | return enum_full.values.keys()[0]; | |
| 2430 | 2435 | } else { |
| 2431 | 2436 | return null; |
| 2432 | 2437 | } |
| ... | ... | @@ -2583,11 +2588,11 @@ pub const Type = extern union { |
| 2583 | 2588 | switch (ty.tag()) { |
| 2584 | 2589 | .enum_full, .enum_nonexhaustive => { |
| 2585 | 2590 | 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]; | |
| 2587 | 2592 | }, |
| 2588 | 2593 | .enum_simple => { |
| 2589 | 2594 | 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]; | |
| 2591 | 2596 | }, |
| 2592 | 2597 | .atomic_ordering, |
| 2593 | 2598 | .atomic_rmw_op, |
src/value.zig+17| ... | ... | @@ -1256,6 +1256,23 @@ pub const Value = extern union { |
| 1256 | 1256 | return hasher.final(); |
| 1257 | 1257 | } |
| 1258 | 1258 | |
| 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 | ||
| 1259 | 1276 | /// Asserts the value is a pointer and dereferences it. |
| 1260 | 1277 | /// Returns error.AnalysisFail if the pointer points to a Decl that failed semantic analysis. |
| 1261 | 1278 | 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" { |
| 107 | 107 | comptime try doTest(); |
| 108 | 108 | } |
| 109 | 109 | |
| 110 | fn doTest() !void { | |
| 110 | fn doTest() error{TestUnexpectedResult}!void { | |
| 111 | 111 | try expect((try bar(Payload{ .A = 1234 })) == -10); |
| 112 | 112 | } |
| 113 | 113 | |
| 114 | fn bar(value: Payload) !i32 { | |
| 114 | fn bar(value: Payload) error{TestUnexpectedResult}!i32 { | |
| 115 | 115 | try expect(@as(Letter, value) == Letter.A); |
| 116 | 116 | return switch (value) { |
| 117 | 117 | Payload.A => |x| return x - 1244, |
tools/process_headers.zig+12-12| ... | ... | @@ -377,14 +377,14 @@ pub fn main() !void { |
| 377 | 377 | const gop = try hash_to_contents.getOrPut(hash); |
| 378 | 378 | if (gop.found_existing) { |
| 379 | 379 | max_bytes_saved += raw_bytes.len; |
| 380 | gop.entry.value.hit_count += 1; | |
| 380 | gop.value_ptr.hit_count += 1; | |
| 381 | 381 | std.debug.warn("duplicate: {s} {s} ({:2})\n", .{ |
| 382 | 382 | libc_target.name, |
| 383 | 383 | rel_path, |
| 384 | 384 | std.fmt.fmtIntSizeDec(raw_bytes.len), |
| 385 | 385 | }); |
| 386 | 386 | } else { |
| 387 | gop.entry.value = Contents{ | |
| 387 | gop.value_ptr.* = Contents{ | |
| 388 | 388 | .bytes = trimmed, |
| 389 | 389 | .hit_count = 1, |
| 390 | 390 | .hash = hash, |
| ... | ... | @@ -392,10 +392,10 @@ pub fn main() !void { |
| 392 | 392 | }; |
| 393 | 393 | } |
| 394 | 394 | 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: { | |
| 396 | 396 | const ptr = try allocator.create(TargetToHash); |
| 397 | 397 | ptr.* = TargetToHash.init(allocator); |
| 398 | path_gop.entry.value = ptr; | |
| 398 | path_gop.value_ptr.* = ptr; | |
| 399 | 399 | break :blk ptr; |
| 400 | 400 | }; |
| 401 | 401 | try target_to_hash.putNoClobber(dest_target, hash); |
| ... | ... | @@ -423,9 +423,9 @@ pub fn main() !void { |
| 423 | 423 | while (path_it.next()) |path_kv| { |
| 424 | 424 | var contents_list = std.ArrayList(*Contents).init(allocator); |
| 425 | 425 | { |
| 426 | var hash_it = path_kv.value.iterator(); | |
| 426 | var hash_it = path_kv.value.*.iterator(); | |
| 427 | 427 | 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.*).?; | |
| 429 | 429 | try contents_list.append(contents); |
| 430 | 430 | } |
| 431 | 431 | } |
| ... | ... | @@ -433,7 +433,7 @@ pub fn main() !void { |
| 433 | 433 | const best_contents = contents_list.popOrNull().?; |
| 434 | 434 | if (best_contents.hit_count > 1) { |
| 435 | 435 | // 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.* }); | |
| 437 | 437 | try std.fs.cwd().makePath(std.fs.path.dirname(full_path).?); |
| 438 | 438 | try std.fs.cwd().writeFile(full_path, best_contents.bytes); |
| 439 | 439 | best_contents.is_generic = true; |
| ... | ... | @@ -443,17 +443,17 @@ pub fn main() !void { |
| 443 | 443 | missed_opportunity_bytes += this_missed_bytes; |
| 444 | 444 | std.debug.warn("Missed opportunity ({:2}): {s}\n", .{ |
| 445 | 445 | std.fmt.fmtIntSizeDec(this_missed_bytes), |
| 446 | path_kv.key, | |
| 446 | path_kv.key.*, | |
| 447 | 447 | }); |
| 448 | 448 | } else break; |
| 449 | 449 | } |
| 450 | 450 | } |
| 451 | var hash_it = path_kv.value.iterator(); | |
| 451 | var hash_it = path_kv.value.*.iterator(); | |
| 452 | 452 | 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.*).?; | |
| 454 | 454 | if (contents.is_generic) continue; |
| 455 | 455 | |
| 456 | const dest_target = hash_kv.key; | |
| 456 | const dest_target = hash_kv.key.*; | |
| 457 | 457 | const arch_name = switch (dest_target.arch) { |
| 458 | 458 | .specific => |a| @tagName(a), |
| 459 | 459 | else => @tagName(dest_target.arch), |
| ... | ... | @@ -463,7 +463,7 @@ pub fn main() !void { |
| 463 | 463 | @tagName(dest_target.os), |
| 464 | 464 | @tagName(dest_target.abi), |
| 465 | 465 | }); |
| 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.* }); | |
| 467 | 467 | try std.fs.cwd().makePath(std.fs.path.dirname(full_path).?); |
| 468 | 468 | try std.fs.cwd().writeFile(full_path, contents.bytes); |
| 469 | 469 | } |
tools/update_clang_options.zig+3-3| ... | ... | @@ -413,12 +413,12 @@ pub fn main() anyerror!void { |
| 413 | 413 | var it = root_map.iterator(); |
| 414 | 414 | it_map: while (it.next()) |kv| { |
| 415 | 415 | 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; | |
| 418 | 418 | if (!kv.value.Object.contains("NumArgs")) continue; |
| 419 | 419 | if (!kv.value.Object.contains("Name")) continue; |
| 420 | 420 | 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; | |
| 422 | 422 | } |
| 423 | 423 | if (kv.value.Object.get("Name").?.String.len == 0) continue; |
| 424 | 424 | try all_objects.append(&kv.value.Object); |
tools/update_cpu_features.zig+17-17| ... | ... | @@ -903,8 +903,8 @@ fn processOneTarget(job: Job) anyerror!void { |
| 903 | 903 | var it = root_map.iterator(); |
| 904 | 904 | root_it: while (it.next()) |kv| { |
| 905 | 905 | 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; | |
| 908 | 908 | if (hasSuperclass(&kv.value.Object, "SubtargetFeature")) { |
| 909 | 909 | const llvm_name = kv.value.Object.get("Name").?.String; |
| 910 | 910 | if (llvm_name.len == 0) continue; |
| ... | ... | @@ -917,7 +917,7 @@ fn processOneTarget(job: Job) anyerror!void { |
| 917 | 917 | const implies = kv.value.Object.get("Implies").?.Array; |
| 918 | 918 | for (implies.items) |imply| { |
| 919 | 919 | 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; | |
| 921 | 921 | const other_llvm_name = other_obj.get("Name").?.String; |
| 922 | 922 | const other_zig_name = (try llvmNameToZigNameOmit( |
| 923 | 923 | arena, |
| ... | ... | @@ -969,7 +969,7 @@ fn processOneTarget(job: Job) anyerror!void { |
| 969 | 969 | const features = kv.value.Object.get("Features").?.Array; |
| 970 | 970 | for (features.items) |feature| { |
| 971 | 971 | 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; | |
| 973 | 973 | const feature_llvm_name = feature_obj.get("Name").?.String; |
| 974 | 974 | if (feature_llvm_name.len == 0) continue; |
| 975 | 975 | const feature_zig_name = (try llvmNameToZigNameOmit( |
| ... | ... | @@ -982,7 +982,7 @@ fn processOneTarget(job: Job) anyerror!void { |
| 982 | 982 | const tune_features = kv.value.Object.get("TuneFeatures").?.Array; |
| 983 | 983 | for (tune_features.items) |feature| { |
| 984 | 984 | 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; | |
| 986 | 986 | const feature_llvm_name = feature_obj.get("Name").?.String; |
| 987 | 987 | if (feature_llvm_name.len == 0) continue; |
| 988 | 988 | const feature_zig_name = (try llvmNameToZigNameOmit( |
| ... | ... | @@ -1109,9 +1109,9 @@ fn processOneTarget(job: Job) anyerror!void { |
| 1109 | 1109 | try pruneFeatures(arena, features_table, &deps_set); |
| 1110 | 1110 | var dependencies = std.ArrayList([]const u8).init(arena); |
| 1111 | 1111 | { |
| 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.*); | |
| 1115 | 1115 | } |
| 1116 | 1116 | } |
| 1117 | 1117 | std.sort.sort([]const u8, dependencies.items, {}, asciiLessThan); |
| ... | ... | @@ -1154,9 +1154,9 @@ fn processOneTarget(job: Job) anyerror!void { |
| 1154 | 1154 | try pruneFeatures(arena, features_table, &deps_set); |
| 1155 | 1155 | var cpu_features = std.ArrayList([]const u8).init(arena); |
| 1156 | 1156 | { |
| 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.*); | |
| 1160 | 1160 | } |
| 1161 | 1161 | } |
| 1162 | 1162 | std.sort.sort([]const u8, cpu_features.items, {}, asciiLessThan); |
| ... | ... | @@ -1278,16 +1278,16 @@ fn pruneFeatures( |
| 1278 | 1278 | // Then, iterate over the deletion set and delete all that stuff from `deps_set`. |
| 1279 | 1279 | var deletion_set = std.StringHashMap(void).init(arena); |
| 1280 | 1280 | { |
| 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.*).?; | |
| 1284 | 1284 | try walkFeatures(features_table, &deletion_set, feature); |
| 1285 | 1285 | } |
| 1286 | 1286 | } |
| 1287 | 1287 | { |
| 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.*); | |
| 1291 | 1291 | } |
| 1292 | 1292 | } |
| 1293 | 1293 | } |
tools/update_glibc.zig+22-22| ... | ... | @@ -148,12 +148,12 @@ pub fn main() !void { |
| 148 | 148 | for (abi_lists) |*abi_list| { |
| 149 | 149 | const target_funcs_gop = try target_functions.getOrPut(@ptrToInt(abi_list)); |
| 150 | 150 | if (!target_funcs_gop.found_existing) { |
| 151 | target_funcs_gop.entry.value = FunctionSet{ | |
| 151 | target_funcs_gop.value_ptr.* = FunctionSet{ | |
| 152 | 152 | .list = std.ArrayList(VersionedFn).init(allocator), |
| 153 | 153 | .fn_vers_list = FnVersionList.init(allocator), |
| 154 | 154 | }; |
| 155 | 155 | } |
| 156 | const fn_set = &target_funcs_gop.entry.value.list; | |
| 156 | const fn_set = &target_funcs_gop.value_ptr.list; | |
| 157 | 157 | |
| 158 | 158 | for (lib_names) |lib_name, lib_name_index| { |
| 159 | 159 | const lib_prefix = if (std.mem.eql(u8, lib_name, "ld")) "" else "lib"; |
| ... | ... | @@ -203,11 +203,11 @@ pub fn main() !void { |
| 203 | 203 | try global_ver_set.put(ver, undefined); |
| 204 | 204 | const gop = try global_fn_set.getOrPut(name); |
| 205 | 205 | 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; | |
| 208 | 208 | } |
| 209 | 209 | } else { |
| 210 | gop.entry.value = Function{ | |
| 210 | gop.value_ptr.* = Function{ | |
| 211 | 211 | .name = name, |
| 212 | 212 | .lib = lib_name, |
| 213 | 213 | .index = undefined, |
| ... | ... | @@ -223,15 +223,15 @@ pub fn main() !void { |
| 223 | 223 | |
| 224 | 224 | const global_fn_list = blk: { |
| 225 | 225 | 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.*); | |
| 228 | 228 | std.sort.sort([]const u8, list.items, {}, strCmpLessThan); |
| 229 | 229 | break :blk list.items; |
| 230 | 230 | }; |
| 231 | 231 | const global_ver_list = blk: { |
| 232 | 232 | 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.*); | |
| 235 | 235 | std.sort.sort([]const u8, list.items, {}, versionLessThan); |
| 236 | 236 | break :blk list.items; |
| 237 | 237 | }; |
| ... | ... | @@ -254,9 +254,9 @@ pub fn main() !void { |
| 254 | 254 | var buffered = std.io.bufferedWriter(fns_txt_file.writer()); |
| 255 | 255 | const fns_txt = buffered.writer(); |
| 256 | 256 | 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 }); | |
| 260 | 260 | } |
| 261 | 261 | try buffered.flush(); |
| 262 | 262 | } |
| ... | ... | @@ -264,16 +264,16 @@ pub fn main() !void { |
| 264 | 264 | // Now the mapping of version and function to integer index is complete. |
| 265 | 265 | // Here we create a mapping of function name to list of versions. |
| 266 | 266 | 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| { | |
| 270 | 270 | const gop = try fn_vers_list.getOrPut(ver_fn.name); |
| 271 | 271 | if (!gop.found_existing) { |
| 272 | gop.entry.value = std.ArrayList(usize).init(allocator); | |
| 272 | gop.value_ptr.* = std.ArrayList(usize).init(allocator); | |
| 273 | 273 | } |
| 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); | |
| 277 | 277 | } |
| 278 | 278 | } |
| 279 | 279 | } |
| ... | ... | @@ -287,7 +287,7 @@ pub fn main() !void { |
| 287 | 287 | |
| 288 | 288 | // first iterate over the abi lists |
| 289 | 289 | 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; | |
| 291 | 291 | for (abi_list.targets) |target, it_i| { |
| 292 | 292 | if (it_i != 0) try abilist_txt.writeByte(' '); |
| 293 | 293 | try abilist_txt.print("{s}-linux-{s}", .{ @tagName(target.arch), @tagName(target.abi) }); |
| ... | ... | @@ -295,11 +295,11 @@ pub fn main() !void { |
| 295 | 295 | try abilist_txt.writeByte('\n'); |
| 296 | 296 | // next, each line implicitly corresponds to a function |
| 297 | 297 | for (global_fn_list) |name| { |
| 298 | const entry = fn_vers_list.getEntry(name) orelse { | |
| 298 | const value = fn_vers_list.getPtr(name) orelse { | |
| 299 | 299 | try abilist_txt.writeByte('\n'); |
| 300 | 300 | continue; |
| 301 | 301 | }; |
| 302 | for (entry.value.items) |ver_index, it_i| { | |
| 302 | for (value.items) |ver_index, it_i| { | |
| 303 | 303 | if (it_i != 0) try abilist_txt.writeByte(' '); |
| 304 | 304 | try abilist_txt.print("{d}", .{ver_index}); |
| 305 | 305 | } |