Skip to content

Commit fcbf604

Browse files
committed
Added some error handling in the RawDatasetImporter: Check that the dimension does not exceed the file size.
1 parent 5b2c0ba commit fcbf604

File tree

1 file changed

+47
-5
lines changed

1 file changed

+47
-5
lines changed

Assets/Scripts/Importing/RawDatasetImporter.cs

Lines changed: 47 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,21 +35,37 @@ public RawDatasetImporter(string filePath, int dimX, int dimY, int dimZ, DataCon
3535

3636
public override VolumeDataset Import()
3737
{
38-
VolumeDataset dataset = new VolumeDataset();
38+
// Check that the file exists
39+
if(!File.Exists(filePath))
40+
{
41+
Debug.LogError("The file does not exist.");
42+
return null;
43+
}
44+
45+
FileStream fs = new FileStream(filePath, FileMode.Open);
46+
BinaryReader reader = new BinaryReader(fs);
47+
48+
// Check that the dimension does not exceed the file size
49+
long expectedFileSize = (long)(dimX * dimY * dimZ) * GetSampleFormatSize(contentFormat) + skipBytes;
50+
if (fs.Length < expectedFileSize)
51+
{
52+
Debug.LogError($"The dimension({dimX}, {dimY}, {dimZ}) exceeds the file size. Expected file size is {expectedFileSize} bytes, while the actual file size is {fs.Length} bytes");
53+
return null;
54+
}
3955

56+
VolumeDataset dataset = new VolumeDataset();
4057
dataset.dimX = dimX;
4158
dataset.dimY = dimY;
4259
dataset.dimZ = dimZ;
4360

44-
FileStream fs = new FileStream(filePath, FileMode.Open);
45-
BinaryReader reader = new BinaryReader(fs);
46-
61+
// Skip header (if any)
4762
if (skipBytes > 0)
4863
reader.ReadBytes(skipBytes);
4964

5065
int uDimension = dimX * dimY * dimZ;
5166
dataset.data = new int[uDimension];
5267

68+
// Read the data/sample values
5369
int val = 0;
5470
for (int i = 0; i < uDimension; i++)
5571
{
@@ -80,5 +96,31 @@ public override VolumeDataset Import()
8096

8197
return dataset;
8298
}
99+
100+
private int GetSampleFormatSize(DataContentFormat format)
101+
{
102+
switch (format)
103+
{
104+
case DataContentFormat.Int8:
105+
return 1;
106+
break;
107+
case DataContentFormat.Uint8:
108+
return 1;
109+
break;
110+
case DataContentFormat.Int16:
111+
return 2;
112+
break;
113+
case DataContentFormat.Uint16:
114+
return 2;
115+
break;
116+
case DataContentFormat.Int32:
117+
return 4;
118+
break;
119+
case DataContentFormat.Uint32:
120+
return 4;
121+
break;
122+
}
123+
throw new NotImplementedException();
124+
}
83125
}
84-
}
126+
}

0 commit comments

Comments
 (0)