c-内存映射查找表(LUT)



我正在编写一个闪存驱动程序,我有一个根据地址检索内存扇区的函数,还有一个根据扇区查找扇区大小的函数。

如何使用查找表而不是if条件?

我目前的实现:

hal_status_t flashGetSector(uint32_t address, uint32_t* sectorResult) {
hal_status_t status = HAL_STATUS_SUCCESS;
/*BANK1 start*/
if((address < 0x08003FFF) && (address >= 0x08000000)) {
*sectorResult = FLASH_SECTOR_0;
return status;
}
if((address < 0x08007FFF) && (address >= 0x08004000)) {
*sectorResult = FLASH_SECTOR_1;
return status;
}
/*more sectors...*/
if((address < 0x081FFFFF) && (address >= 0x081E0000)) {
*sectorResult = FLASH_SECTOR_23;
return status;
}
return HAL_STATUS_ILLEGAL;
}
hal_status_t flashGetSectorSize(uint32_t sector, uint32_t* sectorSize) {
if((sector == FLASH_SECTOR_0) || (sector == FLASH_SECTOR_1) || (sector == FLASH_SECTOR_2) ||  (sector == FLASH_SECTOR_3)
|| (sector == FLASH_SECTOR_12) || (sector == FLASH_SECTOR_13) || (sector == FLASH_SECTOR_14) || (sector == FLASH_SECTOR_15)) {
*sectorSize = 16 * 1024;
return HAL_STATUS_SUCCESS;
}
if((sector == FLASH_SECTOR_4) || (sector == FLASH_SECTOR_16)) {
*sectorSize = 64 * 1024;
return HAL_STATUS_SUCCESS;
}
if ((sector >= FLASH_SECTOR_5 && sector <= FLASH_SECTOR_11) || (sector >= FLASH_SECTOR_17 && sector <= FLASH_SECTOR_23) ) {
*sectorSize = 128 * 1024;
return HAL_STATUS_SUCCESS;
}
return HAL_STATUS_ILLEGAL;
}

你可以做一些事情:

typedef uint32_t sector_t;
typedef uint32_t address_t;
#define ARRAY_SIZE(x)  sizeof(x)/sizeof(*x)
static const sector_t _idx_to_sector[] = {
FLASH_SECTOR_0,
FLASH_SECTOR_1,
FLASH_SECTOR_2,
...
};
size_t sector_to_idx(sector_t sector) {
for (size_t i = 0; i < ARRAY_SIZE(_idx_to_sector); ++i) {
if (_idx_to_sector[i] == sector) {
return i;
}
}
return -1;
}
#define SMALL_SECTOR_SIZE   (16 * 1024)
#define MEDIUM_SECTOR_SIZE  (64 * 1024)
static const address_t _sector_sizes[] = {
[0] = SMALL_SECTOR_SIZE,
[1] = SMALL_SECTOR_SIZE,
...
[4] = MEDIUM_SECTOR_SIZE,
[5] = SMALL_SECTOR_SIZE,
[6] = MEDIUM_SECTOR_SIZE,
...
};
hal_status_t flashGetSectorSize(sector_t sector, address_t *sectorSize) {
const size_t idx = sector_to_idx(sector);
if (idx == (size_t)-1) return FAILURE;
*sectorSize = _sector_sizes[idx];
return SUCCESS;
}
hal_status_t flashGetSector(address_t address, sector_t *seectorResult) {
const address_t startaddress = 0x08000000;
if (address < startaddress) return FAILURE;
address -= startaddress; // 0...0x1FFFFF
for (size_t i = 0; i < ARRAY_SIZE(_idx_to_sector); ++i) {
const address_t sectorsize = _sector_sizes[i];
// check for each in range - move to the next
if (address < sectorsize) {
*seectorResult = _idx_to_sector[i];
return SUCCESS;
}
address -= sectorsize;
}
return FAILURE;
}

多个数组可能很难管理——你可以考虑做一个结构,把你所有的";扇区描述";在一个地方。

相关内容

  • 没有找到相关文章

最新更新