Sector structure
ASector is a fixed-size buffer that stores file data. The size is defined by FULL_SECTOR_SIZE and the structure is explicitly packed to prevent padding:
SectorNode structure
Each file owns aSectorNode that contains a vector of sector pointers:
- Vector storage: Uses
std::vector<Sector*>to store pointers to sectors - Thread safety: A shared mutex allows multiple readers or a single writer
- Automatic cleanup: The destructor frees all sectors when the file is deleted
- Move semantics: Supports efficient transfer of ownership
SectorManager class
TheSectorManager coordinates all sector allocation and I/O operations. Each MemFs instance owns one SectorManager that manages the private heap.
Initialization
When you create aSectorManager, it creates a dedicated Windows heap:
Sector alignment
TheAlignSize() method aligns byte sizes to sector boundaries:
Allocation and resizing
When you resize a file, theReAllocate() method adjusts the number of sectors:
- Acquire write lock on the SectorNode’s mutex
- Calculate required sectors based on the new size
- Grow the vector if more sectors are needed:
- Resize the vector to the new count
- Allocate each new sector from the heap
- Shrink the vector if fewer sectors are needed:
- Free excess sectors back to the heap
- Resize the vector to the new count
- Update allocation counter to track total memory usage
Read and write operations
TheReadWrite() template method handles both reading and writing:
- Acquire shared lock for thread-safe access
- Calculate sector range based on offset and size
- Handle first sector (may have offset within the sector)
- Process middle sectors (full sector copies)
- Handle last sector (may be partial)
IsReading determines whether to copy from sectors to buffer (read) or from buffer to sectors (write).
See sectors.cpp:118-160 for the implementation.
Vector advantages
Using vectors of sector pointers provides several benefits:Efficient resizing
Vectors handle memory reallocation efficiently when growing or shrinking. Only the pointer array needs to be resized, not the actual sector data.Reduced fragmentation
Fixed-size sectors reduce heap fragmentation compared to variable-size allocations. The private heap can optimize for this pattern.Better cache locality
The vector of pointers is contiguous in memory, improving cache performance when accessing sector metadata.Predictable performance
Sector allocation time is constant regardless of file size, unlike heap allocations that may need to search for suitable blocks.Memory tracking
TheSectorManager tracks total allocated sectors using an atomic counter:
InterlockedExchangeAdd()when allocating sectorsInterlockedExchangeSubtract()when freeing sectors
GetAllocatedSectors() to monitor memory consumption.
See sectors.h:54 and sectors.cpp:114-116 for the tracking mechanism.