Use a std::unordered_map for looking up sections by name (#1357)

This commit is contained in:
Sylvie
2024-03-13 19:45:52 -04:00
committed by GitHub
parent 8ec0d01fc4
commit eb99fc8681
3 changed files with 13 additions and 14 deletions

View File

@@ -5,6 +5,8 @@
#include <deque>
#include <stdint.h>
#include <string>
#include <unordered_map>
#include <vector>
#include "linkdefs.hpp"
@@ -49,6 +51,7 @@ struct SectionSpec {
};
extern std::deque<Section> sectionList;
extern std::unordered_map<std::string, size_t> sectionMap; // Indexes into `sectionList`
extern Section *currentSection;
Section *sect_FindSectionByName(char const *name);

View File

@@ -83,10 +83,8 @@ static uint32_t getSectIDIfAny(Section *sect) {
if (!sect)
return (uint32_t)-1;
for (auto it = sectionList.begin(); it != sectionList.end(); it++) {
if (&*it == sect)
return it - sectionList.begin();
}
if (auto search = sectionMap.find(sect->name); search != sectionMap.end())
return (uint32_t)(sectionMap.size() - search->second - 1);
fatalerror("Unknown section '%s'\n", sect->name.c_str());
}
@@ -373,8 +371,8 @@ void out_WriteObject() {
for (Symbol const *sym : objectSymbols)
writesymbol(*sym, f);
for (Section &sect : sectionList)
writesection(sect, f);
for (auto it = sectionList.rbegin(); it != sectionList.rend(); it++)
writesection(*it, f);
putlong(assertions.size(), f);

View File

@@ -11,7 +11,6 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include "error.hpp"
@@ -41,6 +40,7 @@ struct SectionStackEntry {
std::stack<UnionStackEntry> currentUnionStack;
std::deque<SectionStackEntry> sectionStack;
std::deque<Section> sectionList;
std::unordered_map<std::string, size_t> sectionMap; // Indexes into `sectionList`
uint32_t curOffset; // Offset into the current section (see sect_GetSymbolOffset)
Section *currentSection = nullptr;
static Section *currentLoadSection = nullptr;
@@ -110,11 +110,8 @@ attr_(warn_unused_result) static bool reserveSpace(uint32_t delta_size) {
}
Section *sect_FindSectionByName(char const *name) {
for (Section &sect : sectionList) {
if (sect.name == name)
return &sect;
}
return nullptr;
auto search = sectionMap.find(name);
return search != sectionMap.end() ? &sectionList[search->second] : nullptr;
}
#define mask(align) ((1U << (align)) - 1)
@@ -300,8 +297,9 @@ static Section *createSection(
uint16_t alignOffset,
SectionModifier mod
) {
// Add the new section to the list (order doesn't matter)
Section &sect = sectionList.emplace_front();
// Add the new section to the list
Section &sect = sectionList.emplace_back();
sectionMap.emplace(name, sectionMap.size());
sect.name = name;
sect.type = type;