1 /* 2 * Copyright 2008, Haiku, Inc. 3 * Distributed under the terms of the MIT License. 4 * 5 * Authors: 6 * François Revol <revol@free.fr> 7 */ 8 #ifndef CACHED_BLOCK_H 9 #define CACHED_BLOCK_H 10 11 #include <SupportDefs.h> 12 #include <sys/stat.h> 13 #include <stdlib.h> 14 #include <unistd.h> 15 16 #include "Volume.h" 17 18 namespace FATFS { 19 20 class CachedBlock { 21 public: 22 CachedBlock(Volume &volume); 23 CachedBlock(Volume &volume, off_t block); 24 ~CachedBlock(); 25 26 uint8 *SetTo(off_t block); 27 28 void Unset(); 29 30 uint8 *Block() const { return fBlock; } 31 off_t BlockNumber() const { return fBlockNumber; } 32 uint32 BlockSize() const { return fVolume.BlockSize(); } 33 uint32 BlockShift() const { return fVolume.BlockShift(); } 34 35 private: 36 Volume &fVolume; 37 off_t fBlockNumber; 38 uint8 *fBlock; 39 }; 40 41 42 inline void 43 CachedBlock::Unset() 44 { 45 fBlockNumber = -1; 46 } 47 48 49 inline uint8 * 50 CachedBlock::SetTo(off_t block) 51 { 52 if (block == fBlockNumber) 53 return fBlock; 54 if (fBlock == NULL) { 55 fBlock = (uint8 *)malloc(BlockSize()); 56 if (fBlock == NULL) 57 return NULL; 58 } 59 60 fBlockNumber = block; 61 if (read_pos(fVolume.Device(), block << BlockShift(), fBlock, BlockSize()) < (ssize_t)BlockSize()) 62 return NULL; 63 64 return fBlock; 65 } 66 67 68 } // namespace FATFS 69 70 71 #endif /* CACHED_BLOCK_H */ 72