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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
//! Memory-mapped file I/O for high-performance reading of binary PLY/PCD files
//!
//! This module provides OS-gated memory-mapped file support for fast reading of
//! large binary point cloud and mesh files. Falls back to standard buffered I/O
//! on unsupported platforms or when the feature is disabled.
#[cfg(feature = "io-mmap")]
use memmap2::Mmap;
use std::fs::File;
use std::path::Path;
use threecrate_core::{Result, Error};
/// Memory-mapped file reader for binary data
pub struct MmapReader {
#[cfg(feature = "io-mmap")]
mmap: Option<Mmap>,
#[cfg(feature = "io-mmap")]
position: usize,
// Fallback for when mmap is not available
#[cfg(not(feature = "io-mmap"))]
_phantom: std::marker::PhantomData<()>,
}
impl MmapReader {
/// Create a new memory-mapped reader for the given file
///
/// This will attempt to use memory mapping if available and supported,
/// otherwise returns None to indicate fallback should be used.
pub fn new<P: AsRef<Path>>(path: P) -> Result<Option<Self>> {
#[cfg(feature = "io-mmap")]
{
// Check if we're on a supported platform
if !Self::is_supported() {
return Ok(None);
}
let file = File::open(path)?;
let metadata = file.metadata()?;
// Only use mmap for files larger than a threshold (e.g., 64KB)
// For small files, regular I/O is often faster due to mmap overhead
const MIN_MMAP_SIZE: u64 = 64 * 1024; // 64KB
if metadata.len() < MIN_MMAP_SIZE {
return Ok(None);
}
// Create memory mapping
let mmap = unsafe {
match Mmap::map(&file) {
Ok(mmap) => mmap,
Err(_) => return Ok(None), // Fall back to regular I/O
}
};
Ok(Some(Self {
mmap: Some(mmap),
position: 0,
}))
}
#[cfg(not(feature = "io-mmap"))]
{
let _ = path; // Suppress unused variable warning
Ok(None)
}
}
/// Check if memory mapping is supported on this platform
pub fn is_supported() -> bool {
#[cfg(feature = "io-mmap")]
{
// Memory mapping is generally supported on Unix-like systems and Windows
cfg!(any(unix, windows))
}
#[cfg(not(feature = "io-mmap"))]
{
false
}
}
/// Get the total size of the mapped file
pub fn len(&self) -> usize {
#[cfg(feature = "io-mmap")]
{
self.mmap.as_ref().map(|m| m.len()).unwrap_or(0)
}
#[cfg(not(feature = "io-mmap"))]
{
0
}
}
/// Get the current position in the file
pub fn position(&self) -> usize {
#[cfg(feature = "io-mmap")]
{
self.position
}
#[cfg(not(feature = "io-mmap"))]
{
0
}
}
/// Seek to a specific position in the file
pub fn seek(&mut self, pos: usize) -> Result<()> {
#[cfg(feature = "io-mmap")]
{
if pos > self.len() {
return Err(Error::InvalidData("Seek position beyond file end".to_string()));
}
self.position = pos;
Ok(())
}
#[cfg(not(feature = "io-mmap"))]
{
let _ = pos;
Err(Error::Unsupported("Memory mapping not available".to_string()))
}
}
/// Read a slice of bytes from the current position
pub fn read_slice(&mut self, len: usize) -> Result<&[u8]> {
#[cfg(feature = "io-mmap")]
{
let mmap = self.mmap.as_ref().ok_or_else(||
Error::InvalidData("No memory mapping available".to_string()))?;
if self.position + len > mmap.len() {
return Err(Error::InvalidData("Read beyond file end".to_string()));
}
let slice = &mmap[self.position..self.position + len];
self.position += len;
Ok(slice)
}
#[cfg(not(feature = "io-mmap"))]
{
let _ = len;
Err(Error::Unsupported("Memory mapping not available".to_string()))
}
}
/// Read a single byte from the current position
pub fn read_u8(&mut self) -> Result<u8> {
let slice = self.read_slice(1)?;
Ok(slice[0])
}
/// Read a little-endian u16 from the current position
pub fn read_u16_le(&mut self) -> Result<u16> {
let slice = self.read_slice(2)?;
Ok(u16::from_le_bytes([slice[0], slice[1]]))
}
/// Read a little-endian u32 from the current position
pub fn read_u32_le(&mut self) -> Result<u32> {
let slice = self.read_slice(4)?;
Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
}
/// Read a little-endian f32 from the current position
pub fn read_f32_le(&mut self) -> Result<f32> {
let slice = self.read_slice(4)?;
Ok(f32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
}
/// Read a little-endian f64 from the current position
pub fn read_f64_le(&mut self) -> Result<f64> {
let slice = self.read_slice(8)?;
Ok(f64::from_le_bytes([
slice[0], slice[1], slice[2], slice[3],
slice[4], slice[5], slice[6], slice[7]
]))
}
/// Read a big-endian u16 from the current position
pub fn read_u16_be(&mut self) -> Result<u16> {
let slice = self.read_slice(2)?;
Ok(u16::from_be_bytes([slice[0], slice[1]]))
}
/// Read a big-endian u32 from the current position
pub fn read_u32_be(&mut self) -> Result<u32> {
let slice = self.read_slice(4)?;
Ok(u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
}
/// Read a big-endian f32 from the current position
pub fn read_f32_be(&mut self) -> Result<f32> {
let slice = self.read_slice(4)?;
Ok(f32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
}
/// Read a big-endian f64 from the current position
pub fn read_f64_be(&mut self) -> Result<f64> {
let slice = self.read_slice(8)?;
Ok(f64::from_be_bytes([
slice[0], slice[1], slice[2], slice[3],
slice[4], slice[5], slice[6], slice[7]
]))
}
/// Skip ahead by the specified number of bytes
pub fn skip(&mut self, bytes: usize) -> Result<()> {
#[cfg(feature = "io-mmap")]
{
let new_pos = self.position + bytes;
if new_pos > self.len() {
return Err(Error::InvalidData("Skip beyond file end".to_string()));
}
self.position = new_pos;
Ok(())
}
#[cfg(not(feature = "io-mmap"))]
{
let _ = bytes;
Err(Error::Unsupported("Memory mapping not available".to_string()))
}
}
/// Check if we've reached the end of the file
pub fn is_at_end(&self) -> bool {
#[cfg(feature = "io-mmap")]
{
self.position >= self.len()
}
#[cfg(not(feature = "io-mmap"))]
{
true
}
}
/// Get the remaining bytes in the file
pub fn remaining(&self) -> usize {
#[cfg(feature = "io-mmap")]
{
self.len().saturating_sub(self.position)
}
#[cfg(not(feature = "io-mmap"))]
{
0
}
}
}
/// Utility function to check if a file should use memory mapping
/// based on size and platform support
pub fn should_use_mmap<P: AsRef<Path>>(path: P) -> bool {
if !MmapReader::is_supported() {
return false;
}
// Check file size
if let Ok(metadata) = std::fs::metadata(path) {
const MIN_MMAP_SIZE: u64 = 64 * 1024; // 64KB
metadata.len() >= MIN_MMAP_SIZE
} else {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use tempfile::NamedTempFile;
#[test]
fn test_mmap_availability() {
// This test just checks that the API doesn't panic
let supported = MmapReader::is_supported();
println!("Memory mapping supported: {}", supported);
}
#[cfg(feature = "io-mmap")]
#[test]
fn test_mmap_basic_operations() -> Result<()> {
// Create a temporary file with test data
let mut temp_file = NamedTempFile::new().unwrap();
let test_data = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
// Write enough data to trigger mmap (> 64KB)
for _ in 0..10000 {
temp_file.write_all(&test_data)?;
}
temp_file.flush()?;
// Test memory mapping
if let Some(mut reader) = MmapReader::new(temp_file.path())? {
assert_eq!(reader.position(), 0);
assert!(reader.len() > 64 * 1024);
// Test reading
let byte = reader.read_u8()?;
assert_eq!(byte, 0x01);
assert_eq!(reader.position(), 1);
// Test seeking
reader.seek(4)?;
assert_eq!(reader.position(), 4);
let byte = reader.read_u8()?;
assert_eq!(byte, 0x05);
// Test reading multi-byte values
reader.seek(0)?;
let u32_val = reader.read_u32_le()?;
assert_eq!(u32_val, 0x04030201); // little-endian
reader.seek(0)?;
let u32_val = reader.read_u32_be()?;
assert_eq!(u32_val, 0x01020304); // big-endian
}
Ok(())
}
#[test]
fn test_should_use_mmap() {
// Create a small temporary file
let temp_file = NamedTempFile::new().unwrap();
// Small file should not use mmap
let should_mmap = should_use_mmap(temp_file.path());
// This might be false due to size or platform support
println!("Should use mmap for small file: {}", should_mmap);
}
}