forked from mist-devel/mist-firmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rafile.c
81 lines (72 loc) · 2.05 KB
/
rafile.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "rafile.h"
int RARead(RAFile *file,unsigned char *pBuffer, unsigned long bytes)
{
int result=1;
// Since we can only read from the SD card on 512-byte aligned boundaries,
// we need to copy in multiple pieces.
unsigned long blockoffset=file->ptr&511; // Offset within the current 512 block at which the previous read finished
// Bytes blockoffset to 512 will be drained first, before reading new data.
if(blockoffset) // If blockoffset is zero we'll just use aligned reads and don't need to drain the buffer.
{
int i;
int l=bytes;
if(l>512)
l=512;
for(i=blockoffset;i<l;++i)
{
*pBuffer++=file->buffer[i];
}
file->ptr+=l-blockoffset;
bytes-=l-blockoffset;
}
// We've now read any bytes left over from a previous read. If any data remains to be read we can read it
// in 512-byte aligned chunks, until the last block.
while(bytes>511)
{
result&=FileRead(&file->file,pBuffer); // Read direct to pBuffer
FileNextSector(&file->file);
bytes-=512;
file->ptr+=512;
pBuffer+=512;
}
if(bytes) // Do we have any bytes left to read?
{
int i;
result&=FileRead(&file->file,file->buffer); // Read to temporary buffer, allowing us to preserve any leftover for the next read.
FileNextSector(&file->file);
for(i=0;i<bytes;++i)
{
*pBuffer++=file->buffer[i];
}
file->ptr+=bytes;
}
return(result);
}
int RASeek(RAFile *file,unsigned long offset,unsigned long origin)
{
int result=1;
unsigned long blockoffset;
unsigned long blockaddress;
if(origin==SEEK_CUR)
offset+=file->ptr;
blockoffset=offset&511;
blockaddress=offset-blockoffset; // 512-byte-aligned...
result&=FileSeek(&file->file,blockaddress,SEEK_SET);
if(result && blockoffset) // If we're seeking into the middle of a block, we need to buffer it...
{
result&=FileRead(&file->file,file->buffer);
FileNextSector(&file->file);
}
file->ptr=offset;
return(result);
}
int RAOpen(RAFile *file,const char *filename)
{
int result=1;
if(!file)
return(0);
result=FileOpen(&file->file,filename);
file->size=file->file.size;
file->ptr=0;
return(result);
}