Skip to main content

spatialrust_io/pcd/
reader.rs

1use std::io::BufRead;
2
3use spatialrust_core::{
4    DType, PointBuffer, PointBufferSet, PointCloud, PointSchema, SpatialMetadata,
5};
6
7use crate::error::{pcd_format, pcd_parse, IoError};
8use crate::pcd::header::{read_binary_payload, PcdDataKind, PcdHeader};
9use crate::pcd::schema::schema_from_pcd_fields;
10use crate::{PointReader, ReadOptions};
11
12#[cfg(feature = "streaming")]
13use crate::streaming::{
14    read_bounded_ascii_line, records_io, FormatStreamState, MAX_ASCII_RECORD_BYTES,
15};
16#[cfg(feature = "streaming")]
17use spatialrust_records::{
18    BoundedSpatialRecordSource, CancellationToken, MemoryTracker, RecordsResult, SchemaDescriptor,
19    SpatialRecordChunk, StreamOptions,
20};
21
22/// Reads point clouds from PCD files or streams.
23pub struct PcdReader<R: BufRead> {
24    reader: R,
25    header: PcdHeader,
26    metadata: SpatialMetadata,
27    schema: PointSchema,
28    loaded: bool,
29}
30
31impl<R: BufRead> PcdReader<R> {
32    /// Creates a reader and parses the PCD header eagerly.
33    pub fn new(mut reader: R) -> Result<Self, IoError> {
34        let (header, _) = PcdHeader::parse(&mut reader)?;
35        let schema = schema_from_pcd_fields(&header.fields)?;
36        let metadata = metadata_from_header(&header);
37        Ok(Self { reader, header, metadata, schema, loaded: false })
38    }
39
40    /// Returns the parsed PCD header.
41    #[must_use]
42    pub fn header(&self) -> &PcdHeader {
43        &self.header
44    }
45
46    /// Reads the point cloud payload.
47    pub fn read_cloud(&mut self) -> Result<PointCloud, IoError> {
48        if self.loaded {
49            return Err(pcd_format("PCD reader already consumed"));
50        }
51        self.loaded = true;
52        read_pcd_body(&self.header, &mut self.reader, self.schema.clone(), self.metadata.clone())
53    }
54}
55
56impl<R: BufRead> PointReader for PcdReader<R> {
57    fn schema(&self) -> spatialrust_core::SpatialResult<PointSchema> {
58        Ok(self.schema.clone())
59    }
60
61    fn metadata(&self) -> spatialrust_core::SpatialResult<SpatialMetadata> {
62        Ok(self.metadata.clone())
63    }
64
65    fn read(&mut self, _options: &ReadOptions) -> spatialrust_core::SpatialResult<PointCloud> {
66        self.read_cloud().map_err(|error| spatialrust_core::SpatialError::Io(error.to_string()))
67    }
68}
69
70/// Reads a complete PCD file from any buffered reader.
71pub fn read_pcd<R: BufRead>(reader: &mut R) -> Result<PointCloud, IoError> {
72    let (header, _) = PcdHeader::parse(reader)?;
73    let schema = schema_from_pcd_fields(&header.fields)?;
74    let metadata = metadata_from_header(&header);
75    read_pcd_body(&header, reader, schema, metadata)
76}
77
78fn read_pcd_body<R: BufRead>(
79    header: &PcdHeader,
80    reader: &mut R,
81    schema: PointSchema,
82    metadata: SpatialMetadata,
83) -> Result<PointCloud, IoError> {
84    let mut buffers = PointBufferSet::new();
85    for field in schema.fields() {
86        buffers.insert(field.name.clone(), PointBuffer::with_capacity(field.dtype, header.points));
87    }
88
89    match header.data {
90        PcdDataKind::Ascii => read_ascii_payload(reader, header, &schema, &mut buffers)?,
91        PcdDataKind::Binary => {
92            let payload = read_binary_payload(reader, header.point_step() * header.points)?;
93            decode_binary_payload(header, &schema, &payload, &mut buffers)?;
94        }
95        PcdDataKind::BinaryCompressed => {
96            let expected_size = header
97                .point_step()
98                .checked_mul(header.points)
99                .ok_or_else(|| pcd_format("binary_compressed PCD payload size overflow"))?;
100            let payload = read_binary_compressed_payload(reader, expected_size)?;
101            decode_binary_compressed_payload(header, &schema, &payload, &mut buffers)?;
102        }
103    }
104
105    PointCloud::try_from_parts(schema, buffers, metadata).map_err(IoError::from)
106}
107
108fn metadata_from_header(_header: &PcdHeader) -> SpatialMetadata {
109    SpatialMetadata {
110        frame_id: spatialrust_core::FrameId::new("pcd"),
111        timestamp: spatialrust_core::Timestamp::from_nanos(0),
112        sensor_origin: None,
113        unit: "meter".to_owned(),
114    }
115}
116
117fn read_ascii_payload<R: BufRead>(
118    reader: &mut R,
119    header: &PcdHeader,
120    schema: &PointSchema,
121    buffers: &mut PointBufferSet,
122) -> Result<(), IoError> {
123    let mut loaded = 0usize;
124    while loaded < header.points {
125        let mut line = String::new();
126        let read = reader.read_line(&mut line)?;
127        if read == 0 {
128            return Err(pcd_parse(format!(
129                "unexpected EOF after {loaded} of {} ASCII points",
130                header.points
131            )));
132        }
133        let trimmed = line.trim();
134        if trimmed.is_empty() || trimmed.starts_with('#') {
135            continue;
136        }
137
138        let mut tokens = trimmed.split_whitespace();
139        for field in &header.fields {
140            if field.name.eq_ignore_ascii_case("rgb") {
141                let token =
142                    tokens.next().ok_or_else(|| pcd_parse("missing rgb token in ASCII PCD"))?;
143                let packed = parse_packed_rgb(token, field.kind)?;
144                push_to_field(buffers, schema, "r", f64::from(packed.0))?;
145                push_to_field(buffers, schema, "g", f64::from(packed.1))?;
146                push_to_field(buffers, schema, "b", f64::from(packed.2))?;
147                continue;
148            }
149
150            for _ in 0..field.count {
151                let token = tokens.next().ok_or_else(|| {
152                    pcd_parse(format!("missing token for field `{}`", field.name))
153                })?;
154                let value = token
155                    .parse::<f64>()
156                    .map_err(|_| pcd_parse(format!("invalid ASCII value `{token}`")))?;
157                push_to_field(buffers, schema, &field.name, value)?;
158            }
159        }
160        loaded += 1;
161    }
162    Ok(())
163}
164
165fn parse_packed_rgb(
166    token: &str,
167    kind: crate::pcd::schema::PcdType,
168) -> Result<(f32, f32, f32), IoError> {
169    let bits = match kind {
170        crate::pcd::schema::PcdType::F => token
171            .parse::<f32>()
172            .map_err(|_| pcd_parse(format!("invalid rgb value `{token}`")))?
173            .to_bits(),
174        crate::pcd::schema::PcdType::U => {
175            token.parse::<u32>().map_err(|_| pcd_parse(format!("invalid rgb value `{token}`")))?
176        }
177        _ => return Err(pcd_format("unsupported packed rgb TYPE")),
178    };
179    Ok((((bits >> 16) & 0xFF) as f32, ((bits >> 8) & 0xFF) as f32, (bits & 0xFF) as f32))
180}
181
182fn read_binary_compressed_payload<R: BufRead>(
183    reader: &mut R,
184    expected_size: usize,
185) -> Result<Vec<u8>, IoError> {
186    let mut size_buf = [0_u8; 4];
187    reader.read_exact(&mut size_buf)?;
188    let compressed_size = u32::from_le_bytes(size_buf) as usize;
189    reader.read_exact(&mut size_buf)?;
190    let uncompressed_size = u32::from_le_bytes(size_buf) as usize;
191
192    // Validate the file-controlled lengths before allocating either payload.
193    if uncompressed_size != expected_size {
194        return Err(pcd_format(format!(
195            "binary_compressed payload size mismatch: expected {expected_size}, found {uncompressed_size}"
196        )));
197    }
198    // A literal needs at most one control byte per output byte; back-references
199    // encode at least three output bytes in at most three input bytes.
200    if compressed_size > expected_size.saturating_mul(2) {
201        return Err(pcd_format("binary_compressed payload exceeds maximum LZF encoded size"));
202    }
203
204    let compressed = read_binary_payload(reader, compressed_size)?;
205    lzf_decompress(&compressed, uncompressed_size)
206}
207
208fn lzf_decompress(input: &[u8], output_len: usize) -> Result<Vec<u8>, IoError> {
209    let mut output = vec![0_u8; output_len];
210    let mut ip = 0usize;
211    let mut op = 0usize;
212
213    while ip < input.len() {
214        let ctrl = input[ip];
215        ip += 1;
216
217        if ctrl < 32 {
218            let len = ctrl as usize + 1;
219            if ip + len > input.len() || op + len > output.len() {
220                return Err(pcd_format("truncated LZF literal run in binary_compressed PCD"));
221            }
222            output[op..op + len].copy_from_slice(&input[ip..ip + len]);
223            ip += len;
224            op += len;
225            continue;
226        }
227
228        let mut len = (ctrl >> 5) as usize;
229        let mut reference_offset = ((ctrl as usize & 0x1f) << 8) + 1;
230        if len == 7 {
231            if ip >= input.len() {
232                return Err(pcd_format("truncated LZF length in binary_compressed PCD"));
233            }
234            len += input[ip] as usize;
235            ip += 1;
236        }
237        if ip >= input.len() {
238            return Err(pcd_format("truncated LZF back-reference in binary_compressed PCD"));
239        }
240        reference_offset += input[ip] as usize;
241        ip += 1;
242
243        let copy_len = len + 2;
244        if reference_offset > op || op + copy_len > output.len() {
245            return Err(pcd_format("invalid LZF back-reference in binary_compressed PCD"));
246        }
247        let ref_start = op - reference_offset;
248        for offset in 0..copy_len {
249            output[op + offset] = output[ref_start + offset];
250        }
251        op += copy_len;
252    }
253
254    if op != output.len() {
255        return Err(pcd_format(format!(
256            "LZF payload size mismatch: expected {}, decoded {op}",
257            output.len()
258        )));
259    }
260    Ok(output)
261}
262
263fn decode_binary_payload(
264    header: &PcdHeader,
265    schema: &PointSchema,
266    payload: &[u8],
267    buffers: &mut PointBufferSet,
268) -> Result<(), IoError> {
269    let point_step = header.point_step();
270    if payload.len() != point_step * header.points {
271        return Err(pcd_format(format!(
272            "binary payload size mismatch: expected {}, found {}",
273            point_step * header.points,
274            payload.len()
275        )));
276    }
277
278    for point_index in 0..header.points {
279        let start = point_index * point_step;
280        let end = start + point_step;
281        decode_binary_point(&header.fields, &payload[start..end], schema, buffers)?;
282    }
283    Ok(())
284}
285
286fn decode_binary_compressed_payload(
287    header: &PcdHeader,
288    schema: &PointSchema,
289    payload: &[u8],
290    buffers: &mut PointBufferSet,
291) -> Result<(), IoError> {
292    let point_step = header.point_step();
293    if payload.len() != point_step * header.points {
294        return Err(pcd_format(format!(
295            "binary_compressed payload size mismatch: expected {}, found {}",
296            point_step * header.points,
297            payload.len()
298        )));
299    }
300
301    let mut field_base = 0usize;
302    for field in &header.fields {
303        let field_step = field.byte_size();
304        for point_index in 0..header.points {
305            let point_base = field_base + point_index * field_step;
306            if field.name.eq_ignore_ascii_case("rgb") && field.count == 1 && field.size == 4 {
307                let chunk = &payload[point_base..point_base + 4];
308                let bits = u32::from_le_bytes(chunk.try_into().expect("rgb chunk"));
309                push_to_field(buffers, schema, "r", ((bits >> 16) & 0xFF) as f64)?;
310                push_to_field(buffers, schema, "g", ((bits >> 8) & 0xFF) as f64)?;
311                push_to_field(buffers, schema, "b", (bits & 0xFF) as f64)?;
312                continue;
313            }
314
315            for component in 0..field.count {
316                let scalar_start = point_base + component * field.size;
317                let scalar_end = scalar_start + field.size;
318                let value = read_binary_scalar(field, &payload[scalar_start..scalar_end])?;
319                push_to_field(buffers, schema, &field.name, value)?;
320            }
321        }
322        field_base += field_step * header.points;
323    }
324    Ok(())
325}
326
327fn decode_binary_point(
328    fields: &[crate::pcd::schema::PcdFieldSpec],
329    bytes: &[u8],
330    schema: &PointSchema,
331    buffers: &mut PointBufferSet,
332) -> Result<(), IoError> {
333    let mut offset = 0usize;
334    for field in fields {
335        let size = field.byte_size();
336        if offset + size > bytes.len() {
337            return Err(pcd_parse("truncated binary PCD point"));
338        }
339        let field_start = offset;
340        offset += size;
341
342        if field.name.eq_ignore_ascii_case("rgb") && field.count == 1 && field.size == 4 {
343            let chunk = &bytes[field_start..field_start + 4];
344            let bits = u32::from_le_bytes(chunk.try_into().expect("rgb chunk"));
345            push_to_field(buffers, schema, "r", ((bits >> 16) & 0xFF) as f64)?;
346            push_to_field(buffers, schema, "g", ((bits >> 8) & 0xFF) as f64)?;
347            push_to_field(buffers, schema, "b", (bits & 0xFF) as f64)?;
348            continue;
349        }
350
351        for component in 0..field.count {
352            let scalar_start = field_start + component * field.size;
353            let scalar_end = scalar_start + field.size;
354            let value = read_binary_scalar(field, &bytes[scalar_start..scalar_end])?;
355            push_to_field(buffers, schema, &field.name, value)?;
356        }
357    }
358    Ok(())
359}
360
361fn read_binary_scalar(
362    field: &crate::pcd::schema::PcdFieldSpec,
363    chunk: &[u8],
364) -> Result<f64, IoError> {
365    let value = match (field.kind, field.size) {
366        (crate::pcd::schema::PcdType::F, 4) => {
367            f64::from(f32::from_le_bytes(chunk.try_into().expect("f32")))
368        }
369        (crate::pcd::schema::PcdType::F, 8) => f64::from_le_bytes(chunk.try_into().expect("f64")),
370        (crate::pcd::schema::PcdType::I, 4) => {
371            f64::from(i32::from_le_bytes(chunk.try_into().expect("i32")))
372        }
373        (crate::pcd::schema::PcdType::U, 1) => f64::from(chunk[0]),
374        (crate::pcd::schema::PcdType::U, 2) => {
375            f64::from(u16::from_le_bytes(chunk.try_into().expect("u16")))
376        }
377        (crate::pcd::schema::PcdType::U, 4) => {
378            f64::from(u32::from_le_bytes(chunk.try_into().expect("u32")))
379        }
380        _ => return Err(pcd_format(format!("unsupported binary field `{}`", field.name))),
381    };
382    Ok(value)
383}
384
385fn push_to_field(
386    buffers: &mut PointBufferSet,
387    schema: &PointSchema,
388    name: &str,
389    value: f64,
390) -> Result<(), IoError> {
391    let field = schema
392        .fields()
393        .iter()
394        .find(|field| field.name == name)
395        .ok_or_else(|| pcd_format(format!("schema missing mapped field `{name}`")))?;
396
397    let buffer = buffers
398        .get_mut(name)
399        .ok_or_else(|| pcd_format(format!("buffer missing for field `{name}`")))?;
400
401    let integer_bounds = match field.dtype {
402        DType::U8 => Some((0.0, f64::from(u8::MAX))),
403        DType::U16 => Some((0.0, f64::from(u16::MAX))),
404        DType::I32 => Some((f64::from(i32::MIN), f64::from(i32::MAX))),
405        DType::U32 => Some((0.0, f64::from(u32::MAX))),
406        _ => None,
407    };
408    if let Some((min, max)) = integer_bounds {
409        if !value.is_finite() || value.fract() != 0.0 || value < min || value > max {
410            return Err(pcd_parse(format!(
411                "invalid integer value `{value}` for field `{name}` ({:?})",
412                field.dtype
413            )));
414        }
415    }
416
417    match field.dtype {
418        DType::F32 | DType::F16 => buffer.push_f32(value as f32).map_err(IoError::from),
419        DType::F64 => buffer.push_f64(value).map_err(IoError::from),
420        DType::U8 => buffer.push_u8(value as u8).map_err(IoError::from),
421        DType::U16 => buffer.push_u16(value as u16).map_err(IoError::from),
422        DType::I32 => buffer.push_i32(value as i32).map_err(IoError::from),
423        DType::U32 => {
424            let PointBuffer::U32(values) = buffer else {
425                return Err(IoError::Core(spatialrust_core::SpatialError::UnsupportedDType(
426                    field.dtype,
427                )));
428            };
429            values.push(value as u32);
430            Ok(())
431        }
432    }
433}
434
435/// Reads a PCD file from disk.
436pub fn read_pcd_file(path: impl AsRef<std::path::Path>) -> Result<PointCloud, IoError> {
437    let file = std::fs::File::open(path.as_ref())?;
438    let mut reader = std::io::BufReader::new(file);
439    read_pcd(&mut reader)
440}
441
442/// Bounded sequential PCD source for ASCII and interleaved binary payloads.
443///
444/// Field-major `binary_compressed` PCD requires a bounded spool adapter.
445#[cfg(feature = "streaming")]
446pub struct PcdChunkSource<R: BufRead> {
447    reader: R,
448    header: PcdHeader,
449    metadata: SpatialMetadata,
450    state: FormatStreamState,
451    loaded: usize,
452}
453
454#[cfg(feature = "streaming")]
455impl<R: BufRead> PcdChunkSource<R> {
456    /// Parses the header and creates a bounded PCD source.
457    pub fn new(
458        mut reader: R,
459        options: StreamOptions,
460        cancellation: CancellationToken,
461    ) -> Result<Self, IoError> {
462        let (header, _) = PcdHeader::parse(&mut reader)?;
463        if header.data == PcdDataKind::BinaryCompressed {
464            return Err(pcd_format("binary_compressed PCD requires the bounded spool adapter"));
465        }
466        let schema = schema_from_pcd_fields(&header.fields)?;
467        let metadata = metadata_from_header(&header);
468        let state = FormatStreamState::new("pcd", schema, options, cancellation)?;
469        Ok(Self { reader, header, metadata, state, loaded: 0 })
470    }
471
472    /// Returns the parsed header, including the declared total point count.
473    #[must_use]
474    pub fn header(&self) -> &PcdHeader {
475        &self.header
476    }
477}
478
479#[cfg(feature = "streaming")]
480impl PcdChunkSource<std::io::BufReader<std::fs::File>> {
481    /// Opens a local PCD file for bounded chunk reads.
482    pub fn open(
483        path: impl AsRef<std::path::Path>,
484        options: StreamOptions,
485        cancellation: CancellationToken,
486    ) -> Result<Self, IoError> {
487        Self::new(std::io::BufReader::new(std::fs::File::open(path)?), options, cancellation)
488    }
489}
490
491#[cfg(feature = "streaming")]
492impl<R: BufRead> BoundedSpatialRecordSource for PcdChunkSource<R> {
493    fn schema(&self) -> &SchemaDescriptor {
494        &self.state.schema
495    }
496
497    fn options(&self) -> &StreamOptions {
498        &self.state.options
499    }
500
501    fn memory_tracker(&self) -> &MemoryTracker {
502        &self.state.tracker
503    }
504
505    fn cancellation_token(&self) -> CancellationToken {
506        self.state.cancellation.clone()
507    }
508
509    fn max_chunk_bytes(&self) -> u64 {
510        self.state.max_chunk_bytes
511    }
512
513    fn next_chunk(&mut self) -> Option<RecordsResult<SpatialRecordChunk>> {
514        if self.loaded == self.header.points {
515            return None;
516        }
517        let count = (self.header.points - self.loaded).min(self.state.options.chunk_points());
518        let scratch = match self.header.data {
519            PcdDataKind::Ascii => 0,
520            PcdDataKind::Binary => match self
521                .header
522                .point_step()
523                .checked_mul(count)
524                .and_then(|bytes| u64::try_from(bytes).ok())
525            {
526                Some(bytes) => bytes,
527                None => {
528                    return Some(Err(spatialrust_records::RecordsError::InvalidChunk(
529                        "PCD binary chunk size overflow".into(),
530                    )));
531                }
532            },
533            PcdDataKind::BinaryCompressed => unreachable!("rejected by constructor"),
534        };
535        let reservation = match self.state.reserve_points_with_scratch(count, scratch) {
536            Ok(reservation) => reservation,
537            Err(error) => return Some(Err(error)),
538        };
539        let schema = self.state.schema.point_schema().clone();
540        let mut buffers = PointBufferSet::new();
541        for field in schema.fields() {
542            buffers.insert(field.name.clone(), PointBuffer::with_capacity(field.dtype, count));
543        }
544
545        let decoded = match self.header.data {
546            PcdDataKind::Ascii => read_ascii_chunk(
547                &mut self.reader,
548                &self.header,
549                &schema,
550                &mut buffers,
551                count,
552                self.loaded,
553            ),
554            PcdDataKind::Binary => {
555                let mut payload = vec![0_u8; self.header.point_step() * count];
556                std::io::Read::read_exact(&mut self.reader, &mut payload)
557                    .map_err(IoError::from)
558                    .and_then(|()| {
559                        payload.chunks_exact(self.header.point_step()).try_for_each(|point| {
560                            decode_binary_point(&self.header.fields, point, &schema, &mut buffers)
561                        })
562                    })
563            }
564            PcdDataKind::BinaryCompressed => unreachable!("rejected by constructor"),
565        };
566        if let Err(error) = decoded {
567            return Some(Err(records_io(error)));
568        }
569        let cloud = match PointCloud::try_from_parts(schema, buffers, self.metadata.clone()) {
570            Ok(cloud) => cloud,
571            Err(error) => return Some(Err(error.into())),
572        };
573        self.loaded += count;
574        Some(self.state.lease(cloud, reservation))
575    }
576}
577
578#[cfg(feature = "streaming")]
579fn read_ascii_chunk<R: BufRead>(
580    reader: &mut R,
581    header: &PcdHeader,
582    schema: &PointSchema,
583    buffers: &mut PointBufferSet,
584    count: usize,
585    point_offset: usize,
586) -> Result<(), IoError> {
587    let mut loaded = 0;
588    let mut line = [0_u8; MAX_ASCII_RECORD_BYTES];
589    while loaded < count {
590        let Some(line) = read_bounded_ascii_line(reader, &mut line, "PCD")? else {
591            return Err(pcd_parse(format!(
592                "unexpected EOF after {} of {} ASCII points",
593                point_offset + loaded,
594                header.points
595            )));
596        };
597        let trimmed = line.trim();
598        if trimmed.is_empty() || trimmed.starts_with('#') {
599            continue;
600        }
601        let mut tokens = trimmed.split_whitespace();
602        for field in &header.fields {
603            if field.name.eq_ignore_ascii_case("rgb") {
604                let packed = parse_packed_rgb(
605                    tokens.next().ok_or_else(|| pcd_parse("missing rgb token in ASCII PCD"))?,
606                    field.kind,
607                )?;
608                push_to_field(buffers, schema, "r", f64::from(packed.0))?;
609                push_to_field(buffers, schema, "g", f64::from(packed.1))?;
610                push_to_field(buffers, schema, "b", f64::from(packed.2))?;
611            } else {
612                for _ in 0..field.count {
613                    let token = tokens
614                        .next()
615                        .ok_or_else(|| pcd_parse(format!("missing field `{}`", field.name)))?;
616                    let value = token
617                        .parse::<f64>()
618                        .map_err(|_| pcd_parse(format!("invalid ASCII value `{token}`")))?;
619                    push_to_field(buffers, schema, &field.name, value)?;
620                }
621            }
622        }
623        loaded += 1;
624    }
625    Ok(())
626}
627
628#[cfg(test)]
629mod tests {
630    use super::read_pcd;
631    use crate::pcd::writer::{write_pcd, PcdWriteFormat};
632    use spatialrust_core::{HasIntensity, HasPositions3, PointCloudBuilder, StandardSchemas};
633    use std::io::Cursor;
634
635    #[test]
636    fn preserves_f64_and_large_integer_attributes_in_ascii_and_binary() {
637        use crate::pcd::writer::{write_pcd, PcdWriteFormat};
638        use spatialrust_core::PointBuffer;
639        let input = b"VERSION .7\nFIELDS x y z timestamp label id\nSIZE 4 4 4 8 4 4\nTYPE F F F F I U\nCOUNT 1 1 1 1 1 1\nWIDTH 1\nHEIGHT 1\nPOINTS 1\nDATA ascii\n0 0 0 1000000000000.125 -2147483647 4294967295\n";
640        let cloud = super::read_pcd(&mut Cursor::new(input)).unwrap();
641        for format in [PcdWriteFormat::Ascii, PcdWriteFormat::Binary] {
642            let mut bytes = Vec::new();
643            write_pcd(&mut bytes, &cloud, format).unwrap();
644            let decoded = super::read_pcd(&mut Cursor::new(bytes)).unwrap();
645            assert!(
646                matches!(decoded.field("timestamp").unwrap(), PointBuffer::F64(v) if v == &[1000000000000.125])
647            );
648            assert!(
649                matches!(decoded.field("label").unwrap(), PointBuffer::I32(v) if v == &[-2147483647])
650            );
651            assert!(
652                matches!(decoded.field("id").unwrap(), PointBuffer::U32(v) if v == &[u32::MAX])
653            );
654        }
655    }
656
657    #[test]
658    fn compressed_lengths_are_rejected_before_reading_payload() {
659        for (compressed, uncompressed, expected, message) in [
660            (1_u32, u32::MAX, 12_usize, "size mismatch"),
661            (u32::MAX, 12, 12, "maximum LZF"),
662            (1, 0, 0, "maximum LZF"),
663        ] {
664            let mut bytes = compressed.to_le_bytes().to_vec();
665            bytes.extend_from_slice(&uncompressed.to_le_bytes());
666            let mut reader = Cursor::new(bytes);
667            let error = super::read_binary_compressed_payload(&mut reader, expected).unwrap_err();
668            assert!(error.to_string().contains(message), "{error}");
669            assert_eq!(reader.position(), 8);
670        }
671    }
672
673    #[test]
674    fn malformed_lzf_returns_errors_and_overlapping_references_work() {
675        for (encoded, size) in [
676            (&[1_u8, 42][..], 2),
677            (&[32][..], 3),
678            (&[224][..], 9),
679            (&[32, 0][..], 3),
680            (&[0, 42][..], 2),
681        ] {
682            assert!(super::lzf_decompress(encoded, size).is_err());
683        }
684        assert_eq!(super::lzf_decompress(&[0, 42, 32, 0], 4).unwrap(), vec![42; 4]);
685        assert_eq!(super::lzf_decompress(&[], 0).unwrap(), Vec::<u8>::new());
686    }
687
688    #[test]
689    fn compressed_field_major_attributes_preserve_precision_and_order() {
690        use spatialrust_core::PointBuffer;
691        let mut bytes = b"VERSION .7\nFIELDS x y z timestamp label id\nSIZE 4 4 4 8 4 4\nTYPE F F F F I U\nCOUNT 1 1 1 1 1 1\nWIDTH 2\nHEIGHT 1\nPOINTS 2\nDATA binary_compressed\n".to_vec();
692        let mut payload = Vec::new();
693        for value in [1_f32, 2., 3., 4., 5., 6.] {
694            payload.extend_from_slice(&value.to_le_bytes());
695        }
696        for value in [1_000_000_000_000.125_f64, 1_000_000_000_000.25] {
697            payload.extend_from_slice(&value.to_le_bytes());
698        }
699        for value in [i32::MIN + 1, i32::MAX] {
700            payload.extend_from_slice(&value.to_le_bytes());
701        }
702        for value in [u32::MAX, u32::MAX - 1] {
703            payload.extend_from_slice(&value.to_le_bytes());
704        }
705        // Literal-only LZF, split at its maximum literal run length.
706        let mut compressed = Vec::new();
707        for run in payload.chunks(32) {
708            compressed.push((run.len() - 1) as u8);
709            compressed.extend_from_slice(run);
710        }
711        bytes.extend_from_slice(&(compressed.len() as u32).to_le_bytes());
712        bytes.extend_from_slice(&(payload.len() as u32).to_le_bytes());
713        bytes.extend_from_slice(&compressed);
714        let cloud = read_pcd(&mut Cursor::new(bytes)).unwrap();
715        assert_eq!(cloud.positions3().unwrap(), (&[1., 2.][..], &[3., 4.][..], &[5., 6.][..]));
716        assert!(
717            matches!(cloud.field("timestamp").unwrap(), PointBuffer::F64(v) if v == &[1_000_000_000_000.125, 1_000_000_000_000.25])
718        );
719        assert!(
720            matches!(cloud.field("label").unwrap(), PointBuffer::I32(v) if v == &[i32::MIN + 1, i32::MAX])
721        );
722        assert!(
723            matches!(cloud.field("id").unwrap(), PointBuffer::U32(v) if v == &[u32::MAX, u32::MAX - 1])
724        );
725    }
726
727    #[cfg(feature = "streaming")]
728    #[test]
729    fn bounded_chunks_preserve_attributes_at_point_boundaries() {
730        use spatialrust_core::PointBuffer;
731        use spatialrust_records::{
732            BoundedSpatialRecordSource, CancellationToken, MemoryBudget, StreamOptions,
733        };
734        let input = b"VERSION .7\nFIELDS x y z timestamp label id\nSIZE 4 4 4 8 4 4\nTYPE F F F F I U\nCOUNT 1 1 1 1 1 1\nWIDTH 3\nHEIGHT 1\nPOINTS 3\nDATA ascii\n0 0 0 1000000000000.125 -2147483647 4294967295\n1 0 0 1000000000000.25 2147483647 4294967294\n2 0 0 1000000000000.375 -2147483648 4294967293\n";
735        let original = read_pcd(&mut Cursor::new(input)).unwrap();
736        for format in [PcdWriteFormat::Ascii, PcdWriteFormat::Binary] {
737            let mut bytes = Vec::new();
738            write_pcd(&mut bytes, &original, format).unwrap();
739            let options = StreamOptions::new(1, MemoryBudget::new(56).unwrap()).unwrap();
740            let mut source = super::PcdChunkSource::new(
741                Cursor::new(bytes),
742                options,
743                CancellationToken::default(),
744            )
745            .unwrap();
746            for index in 0..3 {
747                let chunk = source.next_chunk().unwrap().unwrap();
748                assert_eq!(chunk.identity().point_offset, index as u64);
749                let cloud = chunk.record().cloud();
750                assert_eq!(cloud.len(), 1);
751                for name in ["timestamp", "label", "id"] {
752                    match (cloud.field(name).unwrap(), original.field(name).unwrap()) {
753                        (PointBuffer::F64(actual), PointBuffer::F64(expected)) => {
754                            assert_eq!(actual, &expected[index..index + 1])
755                        }
756                        (PointBuffer::I32(actual), PointBuffer::I32(expected)) => {
757                            assert_eq!(actual, &expected[index..index + 1])
758                        }
759                        (PointBuffer::U32(actual), PointBuffer::U32(expected)) => {
760                            assert_eq!(actual, &expected[index..index + 1])
761                        }
762                        _ => panic!("attribute dtype changed"),
763                    }
764                }
765            }
766            assert!(source.next_chunk().is_none());
767            assert!(source.memory_tracker().snapshot().peak_bytes <= 56);
768        }
769    }
770
771    #[test]
772    fn packed_rgb_ascii_and_binary_roundtrip_preserves_channels() {
773        use spatialrust_core::PointBuffer;
774        #[cfg(feature = "streaming")]
775        use spatialrust_records::{BoundedSpatialRecordSource, CancellationToken, StreamOptions};
776        let input = b"FIELDS x y z rgb\nSIZE 4 4 4 4\nTYPE F F F U\nCOUNT 1 1 1 1\nWIDTH 3\nHEIGHT 1\nPOINTS 3\nDATA ascii\n0 0 0 16711680\n1 0 0 65280\n2 0 0 255\n";
777        let original = read_pcd(&mut Cursor::new(input)).unwrap();
778        for format in [PcdWriteFormat::Ascii, PcdWriteFormat::Binary] {
779            let mut bytes = Vec::new();
780            write_pcd(&mut bytes, &original, format).unwrap();
781            let decoded = read_pcd(&mut Cursor::new(&bytes)).unwrap();
782            for (name, expected) in [("r", [255, 0, 0]), ("g", [0, 255, 0]), ("b", [0, 0, 255])] {
783                assert!(
784                    matches!(decoded.field(name).unwrap(), PointBuffer::U8(v) if v == &expected)
785                );
786            }
787            #[cfg(feature = "streaming")]
788            {
789                let options =
790                    StreamOptions::new(1, spatialrust_records::MemoryBudget::new(64).unwrap())
791                        .unwrap();
792                let mut source = super::PcdChunkSource::new(
793                    Cursor::new(bytes),
794                    options,
795                    CancellationToken::default(),
796                )
797                .unwrap();
798                for index in 0..3 {
799                    let chunk = source.next_chunk().unwrap().unwrap();
800                    let cloud = chunk.record().cloud();
801                    for name in ["r", "g", "b"] {
802                        match (cloud.field(name).unwrap(), decoded.field(name).unwrap()) {
803                            (PointBuffer::U8(actual), PointBuffer::U8(expected)) => {
804                                assert_eq!(actual, &expected[index..index + 1])
805                            }
806                            _ => panic!("color dtype changed"),
807                        }
808                    }
809                }
810                assert!(source.next_chunk().is_none());
811            }
812        }
813    }
814
815    #[test]
816    fn rejects_malformed_packed_rgb_schema() {
817        for (size, kind, count) in [(8, "F", 1), (4, "I", 1), (4, "F", 2), (1, "U", 1)] {
818            let input = format!("FIELDS x y z rgb\nSIZE 4 4 4 {size}\nTYPE F F F {kind}\nCOUNT 1 1 1 {count}\nPOINTS 1\nDATA ascii\n");
819            let error = read_pcd(&mut Cursor::new(input)).unwrap_err();
820            assert!(error.to_string().contains("packed rgb requires"));
821        }
822    }
823
824    #[test]
825    fn ascii_integer_attributes_reject_fractional_nonfinite_and_out_of_range_values() {
826        for (kind, size, invalid, valid) in [
827            ("U", 1, vec!["-1", "256", "0.5", "NaN", "inf"], "255"),
828            ("U", 2, vec!["-1", "65536", "1.5", "NaN", "-inf"], "65535"),
829            ("U", 4, vec!["-1", "4294967296", "1.5", "NaN", "inf"], "4294967295"),
830            ("I", 4, vec!["-2147483649", "2147483648", "-1.5", "NaN", "inf"], "-2147483648"),
831        ] {
832            let header = format!("FIELDS x y z label\nSIZE 4 4 4 {size}\nTYPE F F F {kind}\nCOUNT 1 1 1 1\nPOINTS 1\nDATA ascii\n");
833            for value in invalid {
834                let input = format!("{header}0 0 0 {value}\n");
835                let error = read_pcd(&mut Cursor::new(&input)).unwrap_err();
836                assert!(error.to_string().contains("invalid integer value"), "{error}");
837                #[cfg(feature = "streaming")]
838                {
839                    use spatialrust_records::{
840                        BoundedSpatialRecordSource, CancellationToken, MemoryBudget, StreamOptions,
841                    };
842                    let mut source = super::PcdChunkSource::new(
843                        Cursor::new(input),
844                        StreamOptions::new(1, MemoryBudget::new(32).unwrap()).unwrap(),
845                        CancellationToken::default(),
846                    )
847                    .unwrap();
848                    assert!(source.next_chunk().unwrap().is_err());
849                }
850            }
851            assert!(read_pcd(&mut Cursor::new(format!("{header}0 0 0 {valid}\n"))).is_ok());
852        }
853    }
854
855    const SAMPLE_XYZ_ASCII: &str = "\
856# .PCD v0.7 - Point Cloud Data file format
857VERSION 0.7
858FIELDS x y z
859SIZE 4 4 4
860TYPE F F F
861COUNT 1 1 1
862WIDTH 3
863HEIGHT 1
864VIEWPOINT 0 0 0 1 0 0 0
865POINTS 3
866DATA ascii
8670.0 0.0 0.0
8681.0 0.0 0.0
8690.0 1.0 0.0
870";
871
872    const SAMPLE_XYZI_ASCII: &str = "\
873VERSION 0.7
874FIELDS x y z intensity
875SIZE 4 4 4 4
876TYPE F F F F
877COUNT 1 1 1 1
878WIDTH 2
879HEIGHT 1
880VIEWPOINT 0 0 0 1 0 0 0
881POINTS 2
882DATA ascii
8830.0 0.0 0.0 0.5
8841.0 0.0 0.0 0.8
885";
886
887    fn binary_compressed_xyz_sample() -> Vec<u8> {
888        let header = b"\
889# .PCD v0.7 - Point Cloud Data file format
890VERSION 0.7
891FIELDS x y z
892SIZE 4 4 4
893TYPE F F F
894COUNT 1 1 1
895WIDTH 2
896HEIGHT 1
897VIEWPOINT 0 0 0 1 0 0 0
898POINTS 2
899DATA binary_compressed
900";
901        let mut uncompressed = Vec::new();
902        // PCL binary_compressed stores fields as structure-of-arrays:
903        // x0, x1, y0, y1, z0, z1 for this XYZ sample.
904        for value in [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0] {
905            uncompressed.extend_from_slice(&value.to_le_bytes());
906        }
907
908        let mut compressed = Vec::with_capacity(uncompressed.len() + 1);
909        compressed.push((uncompressed.len() - 1) as u8);
910        compressed.extend_from_slice(&uncompressed);
911
912        let mut data = header.to_vec();
913        data.extend_from_slice(&(compressed.len() as u32).to_le_bytes());
914        data.extend_from_slice(&(uncompressed.len() as u32).to_le_bytes());
915        data.extend_from_slice(&compressed);
916        data
917    }
918
919    #[test]
920    fn reads_ascii_xyz() {
921        let mut reader = Cursor::new(SAMPLE_XYZ_ASCII.as_bytes());
922        let cloud = read_pcd(&mut reader).unwrap();
923        assert_eq!(cloud.len(), 3);
924        let (x, y, z) = cloud.positions3().unwrap();
925        assert_eq!(x, &[0.0, 1.0, 0.0]);
926        assert_eq!(y, &[0.0, 0.0, 1.0]);
927        assert_eq!(z, &[0.0, 0.0, 0.0]);
928    }
929
930    #[test]
931    fn reads_ascii_xyzi() {
932        let mut reader = Cursor::new(SAMPLE_XYZI_ASCII.as_bytes());
933        let cloud = read_pcd(&mut reader).unwrap();
934        assert_eq!(cloud.intensity().unwrap(), &[0.5, 0.8]);
935    }
936
937    #[test]
938    fn roundtrip_ascii_xyz() {
939        let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
940        builder.push_point([0.0, 0.0, 0.0]).unwrap();
941        builder.push_point([1.0, 2.0, 3.0]).unwrap();
942        let cloud = builder.build().unwrap();
943
944        let mut buffer = Vec::new();
945        write_pcd(&mut buffer, &cloud, PcdWriteFormat::Ascii).unwrap();
946
947        let mut reader = Cursor::new(buffer);
948        let loaded = read_pcd(&mut reader).unwrap();
949        assert_eq!(loaded.len(), cloud.len());
950        let (x, y, z) = loaded.positions3().unwrap();
951        assert_eq!(x, cloud.field("x").unwrap().as_f32().unwrap());
952        assert_eq!(y, cloud.field("y").unwrap().as_f32().unwrap());
953        assert_eq!(z, cloud.field("z").unwrap().as_f32().unwrap());
954    }
955
956    #[test]
957    fn roundtrip_binary_xyz() {
958        let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
959        builder.push_point([0.5, 1.5, 2.5]).unwrap();
960        let cloud = builder.build().unwrap();
961
962        let mut buffer = Vec::new();
963        write_pcd(&mut buffer, &cloud, PcdWriteFormat::Binary).unwrap();
964
965        let mut reader = Cursor::new(buffer);
966        let loaded = read_pcd(&mut reader).unwrap();
967        let (x, _, _) = loaded.positions3().unwrap();
968        assert!((x[0] - 0.5).abs() < 1e-6);
969    }
970
971    #[test]
972    fn reads_binary_compressed_xyz() {
973        let data = binary_compressed_xyz_sample();
974        let mut reader = Cursor::new(data);
975        let loaded = read_pcd(&mut reader).unwrap();
976        let (x, y, z) = loaded.positions3().unwrap();
977        assert_eq!(x, &[1.0, 2.0]);
978        assert_eq!(y, &[3.0, 4.0]);
979        assert_eq!(z, &[5.0, 6.0]);
980    }
981}