Trait spectrusty_formats::ReadExactEx
source · pub trait ReadExactEx: Read {
fn read_exact_or_to_end(&mut self, buf: &mut [u8]) -> Result<usize> { ... }
fn read_exact_or_none(&mut self, buf: &mut [u8]) -> Result<bool> { ... }
}
Expand description
A trait that extends Read with methods that ease reading from chunked files.
Provided Methods§
sourcefn read_exact_or_to_end(&mut self, buf: &mut [u8]) -> Result<usize>
fn read_exact_or_to_end(&mut self, buf: &mut [u8]) -> Result<usize>
Reads all bytes to fill buf
or until EOF. If successful, returns the total number of bytes read.
This function behaves like Read::read_to_end but it reads data into the mutable slice
instead of into a Vec and stops reading when the whole buf
has been filled.
Examples found in repository?
src/lib.rs (line 56)
55 56 57 58 59 60 61 62 63 64 65 66
fn read_exact_or_none(&mut self, buf: &mut [u8]) -> io::Result<bool> {
let bytes_read = self.read_exact_or_to_end(buf)?;
if bytes_read == 0 {
Ok(false)
}
else if bytes_read == buf.len() {
Ok(true)
}
else {
Err(io::Error::new(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
}
}
More examples
src/mdr.rs (line 864)
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
fn store_file<S: AsRef<[u8]>, R: Read>(
&mut self,
file_name: S,
is_save: bool,
mut rd: R
) -> io::Result<u8>
{
let file_name = file_name.as_ref();
if let Some((index, _)) = self.iter_with_indices().find(|(_,s)|
!s.is_free() && s.file_name_matches(file_name)) {
return Err(io::Error::new(io::ErrorKind::AlreadyExists,
MdrValidationError { index, description: "file name already exists" }))
}
let mut block_seq = 0;
let mut first_byte = 0u8;
if !rd.read_exact_or_none(slice::from_mut(&mut first_byte))? {
return Ok(0);
}
for sector in self.into_iter() {
if sector.is_free() {
let buf = sector.data_mut();
buf[0] = first_byte;
let len = 1 + rd.read_exact_or_to_end(&mut buf[1..])?;
sector.set_file_name(file_name);
sector.set_file_block_seq(block_seq);
block_seq += 1;
sector.set_file_block_len(len.try_into().unwrap());
sector.set_save_file_flag(is_save);
let is_last = !rd.read_exact_or_none(slice::from_mut(&mut first_byte))?;
sector.set_last_file_block(is_last);
sector.update_block_checksums();
if is_last {
return Ok(block_seq);
}
}
}
Err(io::Error::new(io::ErrorKind::WriteZero, "not enough free sectors to fit the whole file"))
}
fn erase_file<S: AsRef<[u8]>>(&mut self, file_name: S) -> u8 {
let file_name = file_name.as_ref();
let mut block_seq = 0;
for sector in self.into_iter() {
if !sector.is_free() && sector.file_name_matches(file_name) {
sector.erase();
block_seq += 1;
}
}
block_seq
}
fn file_sector_ids_unordered<S: AsRef<[u8]>>(
&self,
file_name: S
) -> FileSectorIdsUnordIter<'_>
{
let file_name = file_name.as_ref();
let mut name = [b' '; 10];
copy_name(&mut name, file_name);
FileSectorIdsUnordIter {
name,
iter: self.iter_with_indices()
}
}
fn file_sectors<S: AsRef<[u8]>>(
&self,
file_name: S
) -> FileSectorIter<'_>
{
let file_name = file_name.as_ref();
let mut name = [b' '; 10];
copy_name(&mut name, file_name);
let counter = self.count_formatted().try_into().unwrap();
FileSectorIter {
counter,
stop: !0,
block_seq: 0,
name,
iter: self.iter_with_indices().cycle()
}
}
fn catalog(&self) -> Result<Option<Catalog>, MdrValidationError> {
let name = if let Some(name) = self.catalog_name()? {
name.to_string()
}
else {
return Ok(None)
};
let mut files: HashMap<[u8;10], CatFile> = HashMap::new();
let mut sectors_free = 0u8;
for (index, sector) in self.iter_with_indices() {
if sector.is_free() {
sectors_free += 1;
}
else {
let meta = files.entry(*sector.file_name()).or_default();
if sector.file_block_seq() == 0 {
meta.copies += 1;
meta.file_type = sector.file_type()
.map_err(|e| MdrValidationError { index, description: e })?
.unwrap();
}
meta.blocks += 1;
meta.size += sector.file_block_len() as u32;
}
}
for meta in files.values_mut() {
if meta.copies == 0 {
return Err(MdrValidationError { index: u8::max_value(), description: "block 0 is missing" })
}
meta.size /= meta.copies as u32;
}
Ok(Some(Catalog {
name, files, sectors_free
}))
}
fn catalog_name(&self) -> Result<Option<Cow<'_, str>>, MdrValidationError> {
let mut header: Option<&[u8]> = None;
let mut seqs: HashSet<u8> = HashSet::new();
for (index, sector) in self.iter_with_indices() {
sector.validate().map_err(|description| MdrValidationError { index, description })?;
if let Some(name) = header {
if name != sector.catalog_name() {
return Err(MdrValidationError { index, description:
"catalog name is inconsistent" })
}
}
else {
header = Some(sector.catalog_name());
}
if !seqs.insert(sector.sector_seq()) {
return Err(MdrValidationError { index, description:
"at least two sectors have the same identification number" })
}
}
Ok(header.map(String::from_utf8_lossy))
}
fn validate_sectors(&self) -> Result<usize, MdrValidationError> {
let mut count = 0usize;
for (index, sector) in self.iter_with_indices() {
sector.validate().map_err(|description| MdrValidationError { index, description })?;
count += 1;
}
Ok(count)
}
fn count_sectors_in_use(&self) -> usize {
self.into_iter().filter(|sec| !sec.is_free()).count()
}
fn from_mdr<R: Read>(mut rd: R, max_sectors: usize) -> io::Result<Self> {
let mut sectors: Vec<Sector> = Vec::with_capacity(max_sectors);
let mut write_protect = false;
'sectors: loop {
let mut sector = Sector::default();
loop {
match rd.read_exact_or_to_end(&mut sector.head) {
Ok(0) => break 'sectors,
Ok(1) => {
write_protect = sector.head[0] != 0;
break 'sectors
}
Ok(HEAD_SIZE) => break,
Ok(..) => return Err(io::Error::new(io::ErrorKind::UnexpectedEof,
"failed to fill whole sector header")),
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
}
}
if sectors.len() == MAX_USABLE_SECTORS {
return Err(io::Error::new(io::ErrorKind::InvalidData,
"only 254 sectors are supported"));
}
rd.read_exact(&mut sector.data)?;
sectors.push(sector);
}
if sectors.is_empty() {
return Err(io::Error::new(io::ErrorKind::InvalidData, "no sectors read"));
}
let max_sectors = max_sectors.max(sectors.len());
Ok(MicroCartridge::new_with_sectors(sectors, write_protect, max_sectors))
}
sourcefn read_exact_or_none(&mut self, buf: &mut [u8]) -> Result<bool>
fn read_exact_or_none(&mut self, buf: &mut [u8]) -> Result<bool>
Reads the exact number of bytes required to fill buf
and returns Ok(true)
or returns
Ok(false)
if exactly zero bytes were read. In this instance, buf
will be left unmodified.
If at least one byte was read, this function behaves exactly like Read::read_exact.
Examples found in repository?
More examples
src/tap/read.rs (line 254)
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
fn next_chunk(&mut self) -> Result<Option<u16>> {
let rd = self.inner.get_mut();
if self.next_pos != rd.seek(SeekFrom::Start(self.next_pos))? {
return Err(Error::new(ErrorKind::UnexpectedEof, "stream unexpectedly ended"));
}
let mut size: [u8; 2] = Default::default();
if !rd.read_exact_or_none(&mut size)? {
self.inner.set_limit(0);
return Ok(None)
}
let size = u16::from_le_bytes(size);
self.chunk_index += 1;
self.checksum = 0;
self.inner.set_limit(size as u64);
self.next_pos += size as u64 + 2;
Ok(Some(size))
}
src/mdr.rs (line 857)
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
fn store_file<S: AsRef<[u8]>, R: Read>(
&mut self,
file_name: S,
is_save: bool,
mut rd: R
) -> io::Result<u8>
{
let file_name = file_name.as_ref();
if let Some((index, _)) = self.iter_with_indices().find(|(_,s)|
!s.is_free() && s.file_name_matches(file_name)) {
return Err(io::Error::new(io::ErrorKind::AlreadyExists,
MdrValidationError { index, description: "file name already exists" }))
}
let mut block_seq = 0;
let mut first_byte = 0u8;
if !rd.read_exact_or_none(slice::from_mut(&mut first_byte))? {
return Ok(0);
}
for sector in self.into_iter() {
if sector.is_free() {
let buf = sector.data_mut();
buf[0] = first_byte;
let len = 1 + rd.read_exact_or_to_end(&mut buf[1..])?;
sector.set_file_name(file_name);
sector.set_file_block_seq(block_seq);
block_seq += 1;
sector.set_file_block_len(len.try_into().unwrap());
sector.set_save_file_flag(is_save);
let is_last = !rd.read_exact_or_none(slice::from_mut(&mut first_byte))?;
sector.set_last_file_block(is_last);
sector.update_block_checksums();
if is_last {
return Ok(block_seq);
}
}
}
Err(io::Error::new(io::ErrorKind::WriteZero, "not enough free sectors to fit the whole file"))
}