38 lines
1.5 KiB
C++
38 lines
1.5 KiB
C++
#pragma once
|
|
#include <cstdint>
|
|
#include <vector>
|
|
#include <utility>
|
|
|
|
namespace PortCube {
|
|
// Legacy game allocation uses an exclusive upper bound. DB range collision
|
|
// checks are inclusive, so even touching ranges are rejected for handoff.
|
|
struct ItemIDRange { uint32_t minimum=0, maximum=0, usable=0; };
|
|
struct ItemIDPlan {
|
|
std::vector<uint32_t> ids;
|
|
uint32_t next=0;
|
|
bool spare=false;
|
|
};
|
|
inline bool ValidItemIDRange(const ItemIDRange& r) {
|
|
return r.minimum && r.minimum<=r.usable && r.usable<r.maximum;
|
|
}
|
|
inline bool PlanItemIDs(const ItemIDRange& active,uint32_t next,
|
|
const ItemIDRange& spare,unsigned count,ItemIDPlan& out) {
|
|
// No partial output, wraparound, allocation of the sentinel maximum, or
|
|
// speculative switch when all IDs already fit in the active range.
|
|
if(!count||count>100||!ValidItemIDRange(active)||
|
|
next<active.usable||next>active.maximum)return false;
|
|
const uint64_t available=uint64_t(active.maximum)-next;
|
|
const bool switchRange=count>available;
|
|
if(switchRange && (!ValidItemIDRange(spare)||
|
|
!(active.maximum<spare.minimum||spare.maximum<active.minimum)||
|
|
uint64_t(count)-available>uint64_t(spare.maximum)-spare.usable))return false;
|
|
ItemIDPlan plan;plan.ids.reserve(count);
|
|
uint32_t cursor=next;
|
|
for(unsigned i=0;i<count;++i) {
|
|
if(!plan.spare&&cursor==active.maximum){plan.spare=true;cursor=spare.usable;}
|
|
plan.ids.push_back(cursor++);
|
|
}
|
|
plan.next=cursor;out=std::move(plan);return true;
|
|
}
|
|
}
|