1use scroll::{LE, Pread, Pwrite};
30use utz_common::{CellTag, NO_ZONE, PayloadHeader};
31pub use utz_common::{Dataset, MAGIC, PAYLOAD_HEADER_LEN, PROLOGUE_LEN, VERSION};
32
33use crate::error::ensure;
34use crate::grid::{self, Order};
35use crate::topo::{put_varint, zigzag};
36use crate::{Arc, Error, Feat, clean, dq_lat, dq_lon, q_lat, q_lon, qmax_for, topo};
37fn c32(value: usize) -> u32 {
43 u32::try_from(value).expect("exceeds u32 format width")
44}
45fn c16(value: usize) -> u16 {
46 u16::try_from(value).expect("exceeds u16 format width")
47}
48
49pub use utz_common::{Codec, GeomEncoding, QuantBits, SimplifyAlgorithm};
50
51#[must_use]
56pub fn to_simplify(algorithm: SimplifyAlgorithm, epsilon_deg: f64) -> utz_simplify::Simplify {
57 match algorithm {
58 SimplifyAlgorithm::None => utz_simplify::Simplify::None,
59 SimplifyAlgorithm::Rdp => utz_simplify::Simplify::Rdp {
60 epsilon: epsilon_deg,
61 },
62 SimplifyAlgorithm::ImaiIri => utz_simplify::Simplify::ImaiIri {
63 epsilon: epsilon_deg,
64 },
65 SimplifyAlgorithm::Visvalingam => utz_simplify::Simplify::Visvalingam {
66 min_area: epsilon_deg * epsilon_deg,
67 },
68 }
69}
70
71#[derive(Clone, Copy)]
74pub struct Params<'a> {
75 pub dataset: Dataset,
78 pub tzbb_release: &'a str,
81 pub epsilon_m: f64,
82 pub quant_bits: u32,
84 pub grid_deg: f64,
87 pub codec: Codec,
88 pub simplify: SimplifyAlgorithm,
91 pub geom: GeomEncoding,
93 pub density_weight_floor: Option<f64>,
98}
99
100#[derive(Clone, Copy, Default, Debug)]
103pub struct PayloadStats {
104 pub header: u32,
105 pub zones: u32,
106 pub arcs: u32,
107 pub rings: u32,
108 pub grid: u32,
109 pub n_arcs: u32,
110 pub n_verts: u32,
113 pub clean: clean::CleanStats,
116}
117
118pub fn encode(feats: &[Feat], params: &Params) -> crate::Result<Vec<u8>> {
128 finish(&build_payload(feats, params)?, params.codec)
129}
130
131pub fn build_payload(feats: &[Feat], params: &Params) -> crate::Result<Vec<u8>> {
138 let algorithm = to_simplify(params.simplify, params.epsilon_m / crate::METERS_PER_DEG);
139 let topology = topo::build_topology_algorithm(feats, algorithm);
140 Ok(payload_from_topology(&topology, &topology.arc_coords, feats, params)?.0)
141}
142
143fn density_weight_floor_e4(floor: Option<f64>) -> crate::Result<u16> {
151 match floor {
152 None => Ok(0),
153 Some(floor) => {
154 ensure!(
155 floor.is_finite() && floor > 0.0 && floor < 1.0,
156 Error::DensityWeightFloor { floor }
157 );
158 #[expect(
159 clippy::cast_possible_truncation,
160 clippy::cast_sign_loss,
161 reason = "validated into (0, 1) above, so the product is in (0, 10_000)"
162 )]
163 Ok(((floor * 1e4).round() as u16).max(1))
164 }
165 }
166}
167
168pub fn payload_from_topology(
186 topology: &topo::Topology,
187 arc_coords: &[Arc],
188 feats: &[Feat],
189 params: &Params,
190) -> crate::Result<(Vec<u8>, PayloadStats)> {
191 let quant_bits = u8::try_from(params.quant_bits)
193 .ok()
194 .and_then(QuantBits::from_byte)
195 .ok_or(Error::QuantBits {
196 bits: params.quant_bits,
197 })?;
198 ensure!(
199 (0.1..=45.0).contains(¶ms.grid_deg),
200 Error::GridDeg {
201 deg: params.grid_deg
202 }
203 );
204 let density_weight_floor_e4 = density_weight_floor_e4(params.density_weight_floor)?;
205 ensure!(
206 feats.len() < usize::from(NO_ZONE),
207 Error::FormatLimit {
208 what: "feature count (15-bit zone ids)",
209 n: feats.len(),
210 max: usize::from(NO_ZONE) - 1
211 }
212 );
213 let qmax = qmax_for(quant_bits.bits());
214 let clean_geom = quantize_clean(topology, arc_coords, qmax);
215 let (cell_grid, csr, parent) = poly_grid(&clean_geom, feats, params, qmax)?;
216 let full_rings = (params.geom == GeomEncoding::FullRings)
217 .then(|| flatten_full_rings(&clean_geom, feats.len()));
218
219 let mut stats = PayloadStats {
220 n_arcs: c32(clean_geom.arcs_q.len()),
221 n_verts: clean_geom.arcs_q.iter().map(|arc| c32(arc.len())).sum(),
222 clean: clean_geom.stats,
223 ..Default::default()
224 };
225 let counts = eager_counts(
226 full_rings.as_ref(),
227 &clean_geom,
228 feats.len(),
229 parent.len(),
230 params.geom,
231 );
232 ensure_header_limits(params, counts, parent.len())?;
233 let (eager_coords, eager_rings, eager_polys) = counts;
234 let mut out = vec![0u8; PAYLOAD_HEADER_LEN];
237 stats.header = c32(out.len());
238 write_zone_table(&mut out, feats)?;
239 let (arcs_off, rings_off) = write_geometry_sections(
240 &mut out,
241 params,
242 quant_bits,
243 &clean_geom,
244 full_rings.as_ref(),
245 &parent,
246 &mut stats,
247 );
248
249 let grid_off = c32(out.len());
250 stats.rings = grid_off - rings_off;
251 write_grid(&mut out, &csr);
252 stats.grid = c32(out.len()) - grid_off;
253
254 let release_off = c32(out.len());
255 out.extend_from_slice(params.tzbb_release.as_bytes());
256
257 #[expect(clippy::cast_possible_truncation, reason = "f32 header fields")]
258 let (grid_deg, epsilon_m) = (params.grid_deg as f32, params.epsilon_m as f32);
259 let header_len = c32(PAYLOAD_HEADER_LEN);
260 let header = PayloadHeader {
261 arcs_off: arcs_off - header_len,
262 rings_off: rings_off - header_len,
263 grid_off: grid_off - header_len,
264 release_off: release_off - header_len,
265 eager_coords: u32::try_from(eager_coords).expect("guarded by ensure_header_limits"),
266 eager_rings,
267 eager_polys,
268 n_arcs: match params.geom {
270 GeomEncoding::VarintArcs | GeomEncoding::FixedWidthArcs => stats.n_arcs,
271 GeomEncoding::FullRings | GeomEncoding::Coarse => 0,
272 },
273 raw_len: c32(out.len() - PAYLOAD_HEADER_LEN),
274 grid_deg,
275 epsilon_m,
276 n_features: c16(feats.len()),
277 ncols: c16(cell_grid.ncols()),
278 nrows: c16(cell_grid.nrows()),
279 uniq: c16(csr.uniq_lists),
280 release_len: c16(params.tzbb_release.len()),
281 flags: 0, dataset: params.dataset,
283 quant_bits,
284 simplify_algorithm: params.simplify,
285 geom: params.geom,
286 codec: Codec::Uncompressed, density_weight_floor_e4,
288 reserved: 0,
289 };
290 out.pwrite_with(header, 0, LE)
291 .expect("header buffer reserved at PAYLOAD_HEADER_LEN");
292 Ok((out, stats))
293}
294
295struct CleanGeom {
299 topology: topo::Topology,
301 arcs_q: Vec<Arc<i32>>,
302 stats: clean::CleanStats,
303}
304
305fn quantize_clean(topology: &topo::Topology, arc_coords: &[Arc], qmax: f64) -> CleanGeom {
310 let mut stats = clean::CleanStats::default();
311 let arcs_q: Vec<Arc<i32>> = arc_coords
312 .iter()
313 .map(|arc| {
314 let mut quantized: Arc<i32> = arc
315 .iter()
316 .map(|&(lon, lat)| (q_lon(lon, qmax), q_lat(lat, qmax)))
317 .collect();
318 let closed = arc.len() > 1 && arc.first() == arc.last();
319 clean::clean_arc(&mut quantized, closed, &mut stats);
320 quantized
321 })
322 .collect();
323 let (ring_refs, structure, arcs_q) =
324 clean::drop_degenerate_rings(&topology.ring_refs, &topology.structure, arcs_q, &mut stats);
325 CleanGeom {
326 topology: topo::Topology {
327 arc_coords: Vec::new(),
328 ring_refs,
329 structure,
330 },
331 arcs_q,
332 stats,
333 }
334}
335
336fn poly_grid(
348 clean_geom: &CleanGeom,
349 feats: &[Feat],
350 params: &Params,
351 qmax: f64,
352) -> crate::Result<(grid::CellGrid, grid::Csr, Vec<u16>)> {
353 let arcs_snapped: Vec<Arc> = clean_geom
354 .arcs_q
355 .iter()
356 .map(|arc| {
357 arc.iter()
358 .map(|&(x, y)| (dq_lon(f64::from(x), qmax), dq_lat(f64::from(y), qmax)))
359 .collect()
360 })
361 .collect();
362 let snapped = clean_geom.topology.reconstruct(feats, &arcs_snapped);
363 let mut poly_feats: Vec<Feat> = Vec::new();
364 let mut parent: Vec<u16> = Vec::new(); for (feature_index, snapped_feature) in snapped.iter().enumerate() {
366 for poly in &snapped_feature.polys {
367 poly_feats.push(Feat {
368 offset: 0.0,
369 tzid: None,
370 polys: vec![poly.clone()],
371 });
372 parent.push(c16(feature_index));
373 }
374 }
375 ensure!(
376 poly_feats.len() < usize::from(NO_ZONE),
377 Error::FormatLimit {
378 what: "polygon count (15-bit ids)",
379 n: poly_feats.len(),
380 max: usize::from(NO_ZONE) - 1
381 }
382 );
383 let cell_grid = grid::build(&poly_feats, params.grid_deg, 8);
384 let areas = grid::feat_areas(&poly_feats);
385 let mut csr = grid::intern_csr(&cell_grid, Order::CellDominantFirst, &areas);
386 for cell in &mut csr.primary {
387 if let CellTag::Zone(poly) = CellTag::from_cell(*cell) {
388 *cell = parent[usize::from(poly)];
389 }
390 }
391 ensure!(
396 csr.uniq_lists < usize::from(NO_ZONE),
397 Error::GridLists {
398 deg: params.grid_deg,
399 n: csr.uniq_lists
400 }
401 );
402 ensure!(
403 u16::try_from(csr.list_ids.len()).is_ok(),
404 Error::GridListIds {
405 deg: params.grid_deg,
406 n: csr.list_ids.len()
407 }
408 );
409 Ok((cell_grid, csr, parent))
410}
411
412struct FullRingsSections {
416 coords: Vec<(i32, i32)>,
417 ring_ends: Vec<u32>,
418 polys: Vec<([i32; 4], u32)>,
421}
422
423fn flatten_full_rings(clean_geom: &CleanGeom, n_features: usize) -> FullRingsSections {
426 let (mut coords, mut ring_ends, mut polys) = (Vec::new(), Vec::new(), Vec::new());
427 for feature_index in 0..n_features {
428 for poly in &clean_geom.topology.structure[feature_index] {
429 let mut bbox = [i32::MAX, i32::MAX, i32::MIN, i32::MIN];
430 for &ring_index in poly {
431 let ring_start = coords.len();
432 for &arc_ref in &clean_geom.topology.ring_refs[ring_index] {
433 let (id, reversed) = ((arc_ref >> 1) as usize, (arc_ref & 1) == 1);
434 let arc_start = coords.len();
435 let arc = &clean_geom.arcs_q[id];
436 if reversed {
437 coords.extend(arc.iter().rev());
438 } else {
439 coords.extend(arc.iter());
440 }
441 if arc_start > ring_start && coords.get(arc_start - 1) == coords.get(arc_start)
443 {
444 coords.remove(arc_start);
445 }
446 }
447 if coords.len() > ring_start + 1 && coords.last() == coords.get(ring_start) {
449 coords.pop();
450 }
451 for &(x, y) in &coords[ring_start..] {
452 bbox = [
453 bbox[0].min(x),
454 bbox[1].min(y),
455 bbox[2].max(x),
456 bbox[3].max(y),
457 ];
458 }
459 ring_ends.push(c32(coords.len()));
460 }
461 polys.push((bbox, c32(ring_ends.len())));
462 }
463 }
464 FullRingsSections {
465 coords,
466 ring_ends,
467 polys,
468 }
469}
470
471fn eager_counts(
477 full_rings: Option<&FullRingsSections>,
478 clean_geom: &CleanGeom,
479 n_features: usize,
480 n_parent: usize,
481 geom: GeomEncoding,
482) -> (u64, u32, u32) {
483 match full_rings {
484 Some(rings) => (
485 rings.coords.len() as u64,
486 c32(rings.ring_ends.len()),
487 c32(rings.polys.len()),
488 ),
489 None if geom == GeomEncoding::Coarse => (0, 0, c32(n_parent)),
491 None => {
492 let mut coords: u64 = 0;
493 let (mut rings, mut polys) = (0u32, 0u32);
494 for feature_index in 0..n_features {
495 for poly in &clean_geom.topology.structure[feature_index] {
496 polys += 1;
497 for &ring_index in poly {
498 rings += 1;
499 coords += clean_geom.topology.ring_refs[ring_index]
500 .iter()
501 .map(|&arc_ref| clean_geom.arcs_q[(arc_ref >> 1) as usize].len() as u64)
502 .sum::<u64>();
503 }
504 }
505 }
506 (coords, rings, polys)
507 }
508 }
509}
510
511fn write_geometry_sections(
514 out: &mut Vec<u8>,
515 params: &Params,
516 quant_bits: QuantBits,
517 clean_geom: &CleanGeom,
518 full_rings: Option<&FullRingsSections>,
519 parent: &[u16],
520 stats: &mut PayloadStats,
521) -> (u32, u32) {
522 let (arcs_off, rings_off);
523 if params.geom == GeomEncoding::Coarse {
524 arcs_off = c32(out.len());
527 stats.zones = arcs_off - stats.header;
528 rings_off = c32(out.len());
529 for &parent_feature in parent {
530 out.extend_from_slice(&parent_feature.to_le_bytes());
531 }
532 } else if let Some(rings) = full_rings {
533 while !out.len().is_multiple_of(4) {
536 out.push(0);
537 }
538 arcs_off = c32(out.len());
539 stats.zones = arcs_off - stats.header;
540 write_full_rings(out, rings, quant_bits);
541 rings_off = c32(out.len());
543 stats.arcs = rings_off - arcs_off;
544 for &parent_feature in parent {
545 out.extend_from_slice(&parent_feature.to_le_bytes());
546 }
547 } else {
548 arcs_off = c32(out.len());
549 stats.zones = arcs_off - stats.header;
550 write_arc_store(out, &clean_geom.arcs_q, params.geom, quant_bits);
551 rings_off = c32(out.len());
552 stats.arcs = rings_off - arcs_off;
553 for &parent_feature in parent {
554 out.extend_from_slice(&parent_feature.to_le_bytes());
555 }
556 write_ring_index(out, clean_geom, parent.len(), quant_bits);
557 }
558 (arcs_off, rings_off)
559}
560
561fn ensure_header_limits(
564 params: &Params,
565 counts: (u64, u32, u32),
566 n_parent: usize,
567) -> crate::Result<()> {
568 let (eager_coords, _, eager_polys) = counts;
569 ensure!(
570 u32::try_from(eager_coords).is_ok(),
571 Error::FormatLimit {
572 what: "eager_coords",
573 n: usize::try_from(eager_coords).unwrap_or(usize::MAX),
574 max: u32::MAX as usize
575 }
576 );
577 ensure!(
578 eager_polys as usize == n_parent,
579 Error::FormatLimit {
580 what: "eager_polys (must equal parent count)",
581 n: eager_polys as usize,
582 max: n_parent
583 }
584 );
585 ensure!(
586 u16::try_from(params.tzbb_release.len()).is_ok(),
587 Error::FormatLimit {
588 what: "tzbb_release bytes",
589 n: params.tzbb_release.len(),
590 max: u16::MAX as usize
591 }
592 );
593 Ok(())
594}
595
596fn write_zone_table(out: &mut Vec<u8>, feats: &[Feat]) -> crate::Result<()> {
598 let total_pool: usize = feats
601 .iter()
602 .map(|feature| feature.tzid.as_deref().unwrap_or("").len())
603 .sum();
604 ensure!(
605 u16::try_from(total_pool).is_ok(),
606 Error::FormatLimit {
607 what: "tzid pool bytes (u16 offsets)",
608 n: total_pool,
609 max: u16::MAX as usize
610 }
611 );
612 let mut str_offsets: Vec<u16> = Vec::with_capacity(feats.len() + 1);
613 let mut pool: Vec<u8> = Vec::new();
614 for feature in feats {
615 str_offsets.push(c16(pool.len()));
616 pool.extend_from_slice(feature.tzid.as_deref().unwrap_or("").as_bytes());
617 }
618 str_offsets.push(c16(pool.len()));
619 for offset in &str_offsets {
620 out.extend_from_slice(&offset.to_le_bytes());
621 }
622 out.extend_from_slice(&pool);
623 Ok(())
624}
625
626pub fn push_fixed(out: &mut Vec<u8>, value: i32, quant_bits: QuantBits) {
631 out.extend_from_slice(&value.to_le_bytes()[0..quant_bits.bytes()]);
632}
633
634fn write_full_rings(out: &mut Vec<u8>, rings: &FullRingsSections, quant_bits: QuantBits) {
638 for &(x, y) in &rings.coords {
639 push_fixed(out, x, quant_bits);
640 push_fixed(out, y, quant_bits);
641 }
642 for ring_end in &rings.ring_ends {
643 out.extend_from_slice(&ring_end.to_le_bytes());
644 }
645 for &(bbox, rings_end) in &rings.polys {
646 for value in bbox {
647 out.extend_from_slice(&value.to_le_bytes());
648 }
649 out.extend_from_slice(&rings_end.to_le_bytes());
650 }
651}
652
653fn write_arc_store(
657 out: &mut Vec<u8>,
658 arcs_q: &[Arc<i32>],
659 geom: GeomEncoding,
660 quant_bits: QuantBits,
661) {
662 let mut arc_data = Vec::new();
663 let mut arc_offsets: Vec<u32> = Vec::with_capacity(arcs_q.len() + 1);
664 for arc in arcs_q {
665 arc_offsets.push(c32(arc_data.len()));
666 put_varint(&mut arc_data, arc.len() as u64);
667 match geom {
668 GeomEncoding::VarintArcs => {
669 let (mut previous_x, mut previous_y) = (0i64, 0i64);
670 for (i, &(x, y)) in arc.iter().enumerate() {
671 if i == 0 {
672 push_fixed(&mut arc_data, x, quant_bits);
673 push_fixed(&mut arc_data, y, quant_bits);
674 } else {
675 put_varint(&mut arc_data, zigzag(i64::from(x) - previous_x));
676 put_varint(&mut arc_data, zigzag(i64::from(y) - previous_y));
677 }
678 (previous_x, previous_y) = (i64::from(x), i64::from(y));
679 }
680 }
681 GeomEncoding::FixedWidthArcs => {
682 for &(x, y) in arc {
683 push_fixed(&mut arc_data, x, quant_bits);
684 push_fixed(&mut arc_data, y, quant_bits);
685 }
686 }
687 GeomEncoding::FullRings | GeomEncoding::Coarse => {
688 unreachable!("handled by the caller")
689 }
690 }
691 }
692 arc_offsets.push(c32(arc_data.len()));
693 for offset in &arc_offsets {
694 out.extend_from_slice(&offset.to_le_bytes());
695 }
696 out.extend_from_slice(&arc_data);
697}
698
699fn write_ring_index(
703 out: &mut Vec<u8>,
704 clean_geom: &CleanGeom,
705 n_polys: usize,
706 quant_bits: QuantBits,
707) {
708 let mut ring_data = Vec::new();
709 let mut poly_offsets: Vec<u32> = Vec::with_capacity(n_polys + 1);
710 for feature_polys in &clean_geom.topology.structure {
712 for poly in feature_polys {
713 poly_offsets.push(c32(ring_data.len()));
714 let mut bbox = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);
719 for &ring_index in poly {
720 for &arc_ref in &clean_geom.topology.ring_refs[ring_index] {
721 for &(x, y) in &clean_geom.arcs_q[(arc_ref >> 1) as usize] {
722 bbox = (bbox.0.min(x), bbox.1.min(y), bbox.2.max(x), bbox.3.max(y));
723 }
724 }
725 }
726 for value in [bbox.0, bbox.1, bbox.2, bbox.3] {
727 push_fixed(&mut ring_data, value, quant_bits);
728 }
729 ring_data.extend_from_slice(&c16(poly.len()).to_le_bytes());
730 for &ring_index in poly {
731 put_varint(
732 &mut ring_data,
733 clean_geom.topology.ring_refs[ring_index].len() as u64,
734 );
735 for &arc_ref in &clean_geom.topology.ring_refs[ring_index] {
736 put_varint(&mut ring_data, u64::from(arc_ref));
737 }
738 }
739 }
740 }
741 poly_offsets.push(c32(ring_data.len()));
742 for offset in &poly_offsets {
743 out.extend_from_slice(&offset.to_le_bytes());
744 }
745 out.extend_from_slice(&ring_data);
746}
747
748fn write_grid(out: &mut Vec<u8>, csr: &grid::Csr) {
751 for cell in &csr.primary {
752 out.extend_from_slice(&cell.to_le_bytes());
753 }
754 for offset in &csr.list_offsets {
755 out.extend_from_slice(&offset.to_le_bytes());
756 }
757 for id in &csr.list_ids {
758 out.extend_from_slice(&id.to_le_bytes());
759 }
760}
761
762pub fn finish(payload: &[u8], codec: Codec) -> crate::Result<Vec<u8>> {
773 let (header_bytes, sections) = payload.split_at(PAYLOAD_HEADER_LEN);
775 let mut header: PayloadHeader = header_bytes
776 .pread_with(0, LE)
777 .expect("build_payload wrote a valid header");
778 header.codec = codec;
779 let body = compress(sections, codec)?;
780 let mut out = Vec::with_capacity(PROLOGUE_LEN + PAYLOAD_HEADER_LEN + body.len());
781 out.extend_from_slice(&MAGIC);
782 out.push(VERSION);
783 out.extend_from_slice(&[0u8; 3]); out.resize(PROLOGUE_LEN + PAYLOAD_HEADER_LEN, 0);
785 out.pwrite_with(header, PROLOGUE_LEN, LE)
786 .expect("header space reserved");
787 out.extend_from_slice(&body);
788 Ok(out)
789}
790
791pub fn compress(raw: &[u8], codec: Codec) -> crate::Result<Vec<u8>> {
799 let xz_err = |error| Error::Xz(format!("{error:?}"));
800 Ok(match codec {
801 Codec::Uncompressed => raw.to_vec(),
802 Codec::Gzip => miniz_oxide::deflate::compress_to_vec_zlib(raw, 10),
803 #[cfg(feature = "zstd")]
804 Codec::Zstd => {
805 use std::io::Write as _;
806 let window_log = raw.len().next_power_of_two().trailing_zeros().clamp(10, 26);
811 let mut encoder = zstd::stream::write::Encoder::new(Vec::new(), 22)?;
812 encoder.set_pledged_src_size(Some(raw.len() as u64))?;
813 encoder.window_log(window_log)?;
814 encoder.write_all(raw)?;
815 encoder.finish()?
816 }
817 #[cfg(not(feature = "zstd"))]
818 Codec::Zstd => return Err(Error::ZstdNotCompiled),
819 Codec::Brotli => {
820 let mut out = Vec::new();
821 let params = brotli::enc::BrotliEncoderParams {
822 quality: 11,
823 lgwin: 24,
824 ..Default::default()
825 };
826 brotli::BrotliCompress(&mut &raw[..], &mut out, ¶ms)?;
827 out
828 }
829 Codec::Xz => {
830 use lzma_rust2::Write as _; let bits = (usize::BITS - (raw.len().max(1) - 1).leading_zeros()).clamp(12, 26);
832 let mut options = lzma_rust2::XzOptions::with_preset(9);
833 options.lzma_options.dict_size = 1u32 << bits;
834 options.lzma_options.nice_len = 273;
836 options.lzma_options.depth_limit = 512;
837 let mut writer = lzma_rust2::XzWriter::new(Vec::new(), options).map_err(xz_err)?;
838 writer.write_all(raw).map_err(xz_err)?;
839 writer.finish().map_err(xz_err)?
840 }
841 })
842}