001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.data.osm.pbf; 003 004import java.io.ByteArrayInputStream; 005import java.io.IOException; 006import java.io.InputStream; 007import java.util.zip.InflaterInputStream; 008 009import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; 010 011import jakarta.annotation.Nonnull; 012import jakarta.annotation.Nullable; 013 014/** 015 * A "Blob" of data from an OSM PBF file. It, in turn, contains additional data in PBF format, which may be compressed. 016 * @since 18695 017 */ 018public final class Blob { 019 /** The compression types for the blob */ 020 public enum CompressionType { 021 /** No compression */ 022 raw, 023 /** zlib compression */ 024 zlib, 025 /** lzma compression (optional) */ 026 lzma, 027 /** bzip2 compression (deprecated in 2010, so if we ever support saving PBF files, <i>don't use this compression type</i>) */ 028 bzip2, 029 /** lz4 compression (optional) */ 030 lz4, 031 /** zstd compression (optional) */ 032 zstd 033 } 034 035 private final Integer rawSize; 036 private final CompressionType compressionType; 037 private final byte[] bytes; 038 039 /** 040 * Create a new blob 041 * @param rawSize The blob size 042 * @param compressionType The compression type 043 * @param bytes The bytes of the blob 044 */ 045 public Blob(@Nullable Integer rawSize, @Nonnull CompressionType compressionType, @Nonnull byte... bytes) { 046 this.rawSize = rawSize; 047 this.compressionType = compressionType; 048 this.bytes = bytes; 049 } 050 051 /** 052 * The raw size of the blob (after decompression) 053 * @return The raw size 054 */ 055 @Nullable 056 public Integer rawSize() { 057 return this.rawSize; 058 } 059 060 /** 061 * The compression type of the blob 062 * @return The compression type 063 */ 064 @Nonnull 065 public CompressionType compressionType() { 066 return this.compressionType; 067 } 068 069 /** 070 * The bytes that make up the blob data 071 * @return The bytes 072 */ 073 @Nonnull 074 public byte[] bytes() { 075 return this.bytes; 076 } 077 078 /** 079 * Get the decompressed inputstream for this blob 080 * @return The decompressed inputstream 081 * @throws IOException if we don't support the compression type <i>or</i> the decompressor has issues, see 082 * <ul> 083 * <li>{@link BZip2CompressorInputStream}</li> 084 * </ul> 085 */ 086 @Nonnull 087 public InputStream inputStream() throws IOException { 088 final ByteArrayInputStream bais = new ByteArrayInputStream(this.bytes); 089 switch (this.compressionType) { 090 case raw: 091 return bais; 092 case bzip2: 093 return new BZip2CompressorInputStream(bais); 094 case lzma: 095 case zstd: 096 case lz4: 097 throw new IOException(this.compressionType + " pbf is not currently supported"); 098 case zlib: 099 return new InflaterInputStream(bais); 100 } 101 throw new IOException("unknown compression type is not currently supported: " + this.compressionType.name()); 102 } 103}