common.odin 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. package compress
  2. /*
  3. Copyright 2021 Jeroen van Rijn <[email protected]>.
  4. Made available under Odin's BSD-3 license.
  5. List of contributors:
  6. Jeroen van Rijn: Initial implementation, optimization.
  7. */
  8. import "core:io"
  9. import "core:image"
  10. import "core:bytes"
  11. /*
  12. These settings bound how much compression algorithms will allocate for their output buffer.
  13. If streaming their output, these are unnecessary and will be ignored.
  14. */
  15. /*
  16. When a decompression routine doesn't stream its output, but writes to a buffer,
  17. we pre-allocate an output buffer to speed up decompression. The default is 1 MiB.
  18. */
  19. COMPRESS_OUTPUT_ALLOCATE_MIN :: int(#config(COMPRESS_OUTPUT_ALLOCATE_MIN, 1 << 20))
  20. /*
  21. This bounds the maximum a buffer will resize to as needed, or the maximum we'll
  22. pre-allocate if you inform the decompression routine you know the payload size.
  23. For reference, the largest payload size of a GZIP file is 4 GiB.
  24. */
  25. when size_of(uintptr) == 8 {
  26. /*
  27. For 64-bit platforms, we set the default max buffer size to 4 GiB,
  28. which is GZIP and PKZIP's max payload size.
  29. */
  30. COMPRESS_OUTPUT_ALLOCATE_MAX :: int(#config(COMPRESS_OUTPUT_ALLOCATE_MAX, 1 << 32))
  31. } else {
  32. /*
  33. For 32-bit platforms, we set the default max buffer size to 512 MiB.
  34. */
  35. COMPRESS_OUTPUT_ALLOCATE_MAX :: int(#config(COMPRESS_OUTPUT_ALLOCATE_MAX, 1 << 29))
  36. }
  37. Error :: union {
  38. General_Error,
  39. Deflate_Error,
  40. ZLIB_Error,
  41. GZIP_Error,
  42. ZIP_Error,
  43. /*
  44. This is here because png.load will return a this type of error union,
  45. as it may involve an I/O error, a Deflate error, etc.
  46. */
  47. image.Error,
  48. }
  49. General_Error :: enum {
  50. File_Not_Found,
  51. Cannot_Open_File,
  52. File_Too_Short,
  53. Stream_Too_Short,
  54. Output_Too_Short,
  55. Unknown_Compression_Method,
  56. Checksum_Failed,
  57. Incompatible_Options,
  58. Unimplemented,
  59. /*
  60. Memory errors
  61. */
  62. Allocation_Failed,
  63. Resize_Failed,
  64. }
  65. GZIP_Error :: enum {
  66. Invalid_GZIP_Signature,
  67. Reserved_Flag_Set,
  68. Invalid_Extra_Data,
  69. Original_Name_Too_Long,
  70. Comment_Too_Long,
  71. Payload_Length_Invalid,
  72. Payload_CRC_Invalid,
  73. /*
  74. GZIP's payload can be a maximum of max(u32le), or 4 GiB.
  75. If you tell it you expect it to contain more, that's obviously an error.
  76. */
  77. Payload_Size_Exceeds_Max_Payload,
  78. /*
  79. For buffered instead of streamed output, the payload size can't exceed
  80. the max set by the `COMPRESS_OUTPUT_ALLOCATE_MAX` switch in compress/common.odin.
  81. You can tweak this setting using `-define:COMPRESS_OUTPUT_ALLOCATE_MAX=size_in_bytes`
  82. */
  83. Output_Exceeds_COMPRESS_OUTPUT_ALLOCATE_MAX,
  84. }
  85. ZIP_Error :: enum {
  86. Invalid_ZIP_File_Signature,
  87. Unexpected_Signature,
  88. Insert_Next_Disk,
  89. Expected_End_of_Central_Directory_Record,
  90. }
  91. ZLIB_Error :: enum {
  92. Unsupported_Window_Size,
  93. FDICT_Unsupported,
  94. Unsupported_Compression_Level,
  95. Code_Buffer_Malformed,
  96. }
  97. Deflate_Error :: enum {
  98. Huffman_Bad_Sizes,
  99. Huffman_Bad_Code_Lengths,
  100. Inflate_Error,
  101. Bad_Distance,
  102. Bad_Huffman_Code,
  103. Len_Nlen_Mismatch,
  104. BType_3,
  105. }
  106. // General I/O context for ZLIB, LZW, etc.
  107. Context_Memory_Input :: struct #packed {
  108. input_data: []u8,
  109. output: ^bytes.Buffer,
  110. bytes_written: i64,
  111. code_buffer: u64,
  112. num_bits: u64,
  113. /*
  114. If we know the data size, we can optimize the reads and writes.
  115. */
  116. size_packed: i64,
  117. size_unpacked: i64,
  118. }
  119. #assert(size_of(Context_Memory_Input) == 64)
  120. Context_Stream_Input :: struct #packed {
  121. input_data: []u8,
  122. input: io.Stream,
  123. output: ^bytes.Buffer,
  124. bytes_written: i64,
  125. code_buffer: u64,
  126. num_bits: u64,
  127. /*
  128. If we know the data size, we can optimize the reads and writes.
  129. */
  130. size_packed: i64,
  131. size_unpacked: i64,
  132. /*
  133. Flags:
  134. `input_fully_in_memory`
  135. true = This tells us we read input from `input_data` exclusively. [] = EOF.
  136. false = Try to refill `input_data` from the `input` stream.
  137. */
  138. input_fully_in_memory: b8,
  139. padding: [1]u8,
  140. }
  141. /*
  142. TODO: The stream versions should really only check if a certain method is available once, perhaps even during setup.
  143. Bit and byte readers may be merged so that reading bytes will grab them from the bit buffer first.
  144. This simplifies end-of-stream handling where bits may be left in the bit buffer.
  145. */
  146. // TODO: Make these return compress.Error errors.
  147. input_size_from_memory :: proc(z: ^Context_Memory_Input) -> (res: i64, err: Error) {
  148. return i64(len(z.input_data)), nil
  149. }
  150. input_size_from_stream :: proc(z: ^Context_Stream_Input) -> (res: i64, err: Error) {
  151. return io.size(z.input), nil
  152. }
  153. input_size :: proc{input_size_from_memory, input_size_from_stream}
  154. @(optimization_mode="speed")
  155. read_slice_from_memory :: #force_inline proc(z: ^Context_Memory_Input, size: int) -> (res: []u8, err: io.Error) {
  156. #no_bounds_check {
  157. if len(z.input_data) >= size {
  158. res = z.input_data[:size]
  159. z.input_data = z.input_data[size:]
  160. return res, .None
  161. }
  162. }
  163. if len(z.input_data) == 0 {
  164. return []u8{}, .EOF
  165. } else {
  166. return []u8{}, .Short_Buffer
  167. }
  168. }
  169. @(optimization_mode="speed")
  170. read_slice_from_stream :: #force_inline proc(z: ^Context_Stream_Input, size: int) -> (res: []u8, err: io.Error) {
  171. b := make([]u8, size, context.temp_allocator)
  172. _, e := z.input->impl_read(b[:])
  173. if e == .None {
  174. return b, .None
  175. }
  176. return []u8{}, e
  177. }
  178. read_slice :: proc{read_slice_from_memory, read_slice_from_stream}
  179. @(optimization_mode="speed")
  180. read_data :: #force_inline proc(z: ^$C, $T: typeid) -> (res: T, err: io.Error) {
  181. b, e := read_slice(z, size_of(T))
  182. if e == .None {
  183. return (^T)(&b[0])^, .None
  184. }
  185. return T{}, e
  186. }
  187. @(optimization_mode="speed")
  188. read_u8_from_memory :: #force_inline proc(z: ^Context_Memory_Input) -> (res: u8, err: io.Error) {
  189. #no_bounds_check {
  190. if len(z.input_data) >= 1 {
  191. res = z.input_data[0]
  192. z.input_data = z.input_data[1:]
  193. return res, .None
  194. }
  195. }
  196. return 0, .EOF
  197. }
  198. @(optimization_mode="speed")
  199. read_u8_from_stream :: #force_inline proc(z: ^Context_Stream_Input) -> (res: u8, err: io.Error) {
  200. b, e := read_slice_from_stream(z, 1)
  201. if e == .None {
  202. return b[0], .None
  203. }
  204. return 0, e
  205. }
  206. read_u8 :: proc{read_u8_from_memory, read_u8_from_stream}
  207. /*
  208. You would typically only use this at the end of Inflate, to drain bits from the code buffer
  209. preferentially.
  210. */
  211. @(optimization_mode="speed")
  212. read_u8_prefer_code_buffer_lsb :: #force_inline proc(z: ^$C) -> (res: u8, err: io.Error) {
  213. if z.num_bits >= 8 {
  214. res = u8(read_bits_no_refill_lsb(z, 8))
  215. } else {
  216. size, _ := input_size(z)
  217. if size > 0 {
  218. res, err = read_u8(z)
  219. } else {
  220. err = .EOF
  221. }
  222. }
  223. return
  224. }
  225. @(optimization_mode="speed")
  226. peek_data_from_memory :: #force_inline proc(z: ^Context_Memory_Input, $T: typeid) -> (res: T, err: io.Error) {
  227. size :: size_of(T)
  228. #no_bounds_check {
  229. if len(z.input_data) >= size {
  230. buf := z.input_data[:size]
  231. return (^T)(&buf[0])^, .None
  232. }
  233. }
  234. if len(z.input_data) == 0 {
  235. return T{}, .EOF
  236. } else {
  237. return T{}, .Short_Buffer
  238. }
  239. }
  240. @(optimization_mode="speed")
  241. peek_data_from_stream :: #force_inline proc(z: ^Context_Stream_Input, $T: typeid) -> (res: T, err: io.Error) {
  242. size :: size_of(T)
  243. // Get current position to read from.
  244. curr, e1 := z.input->impl_seek(0, .Current)
  245. if e1 != .None {
  246. return T{}, e1
  247. }
  248. r, e2 := io.to_reader_at(z.input)
  249. if !e2 {
  250. return T{}, .Empty
  251. }
  252. when size <= 128 {
  253. b: [size]u8
  254. } else {
  255. b := make([]u8, size, context.temp_allocator)
  256. }
  257. _, e3 := io.read_at(r, b[:], curr)
  258. if e3 != .None {
  259. return T{}, .Empty
  260. }
  261. res = (^T)(&b[0])^
  262. return res, .None
  263. }
  264. peek_data :: proc{peek_data_from_memory, peek_data_from_stream}
  265. // Sliding window read back
  266. @(optimization_mode="speed")
  267. peek_back_byte :: #force_inline proc(z: ^$C, offset: i64) -> (res: u8, err: io.Error) {
  268. // Look back into the sliding window.
  269. return z.output.buf[z.bytes_written - offset], .None
  270. }
  271. // Generalized bit reader LSB
  272. @(optimization_mode="speed")
  273. refill_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width := i8(48)) {
  274. refill := u64(width)
  275. b := u64(0)
  276. if z.num_bits > refill {
  277. return
  278. }
  279. for {
  280. if len(z.input_data) != 0 {
  281. b = u64(z.input_data[0])
  282. z.input_data = z.input_data[1:]
  283. } else {
  284. b = 0
  285. }
  286. z.code_buffer |= b << u8(z.num_bits)
  287. z.num_bits += 8
  288. if z.num_bits > refill {
  289. break
  290. }
  291. }
  292. }
  293. // Generalized bit reader LSB
  294. @(optimization_mode="speed")
  295. refill_lsb_from_stream :: proc(z: ^Context_Stream_Input, width := i8(24)) {
  296. refill := u64(width)
  297. for {
  298. if z.num_bits > refill {
  299. break
  300. }
  301. if z.code_buffer == 0 && z.num_bits > 63 {
  302. z.num_bits = 0
  303. }
  304. if z.code_buffer >= 1 << uint(z.num_bits) {
  305. // Code buffer is malformed.
  306. z.num_bits = max(u64)
  307. return
  308. }
  309. b, err := read_u8(z)
  310. if err != .None {
  311. // This is fine at the end of the file.
  312. return
  313. }
  314. z.code_buffer |= (u64(b) << u8(z.num_bits))
  315. z.num_bits += 8
  316. }
  317. }
  318. refill_lsb :: proc{refill_lsb_from_memory, refill_lsb_from_stream}
  319. @(optimization_mode="speed")
  320. consume_bits_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) {
  321. z.code_buffer >>= width
  322. z.num_bits -= u64(width)
  323. }
  324. @(optimization_mode="speed")
  325. consume_bits_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) {
  326. z.code_buffer >>= width
  327. z.num_bits -= u64(width)
  328. }
  329. consume_bits_lsb :: proc{consume_bits_lsb_from_memory, consume_bits_lsb_from_stream}
  330. @(optimization_mode="speed")
  331. peek_bits_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) -> u32 {
  332. if z.num_bits < u64(width) {
  333. refill_lsb(z)
  334. }
  335. return u32(z.code_buffer & ~(~u64(0) << width))
  336. }
  337. @(optimization_mode="speed")
  338. peek_bits_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) -> u32 {
  339. if z.num_bits < u64(width) {
  340. refill_lsb(z)
  341. }
  342. return u32(z.code_buffer & ~(~u64(0) << width))
  343. }
  344. peek_bits_lsb :: proc{peek_bits_lsb_from_memory, peek_bits_lsb_from_stream}
  345. @(optimization_mode="speed")
  346. peek_bits_no_refill_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) -> u32 {
  347. assert(z.num_bits >= u64(width))
  348. return u32(z.code_buffer & ~(~u64(0) << width))
  349. }
  350. @(optimization_mode="speed")
  351. peek_bits_no_refill_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) -> u32 {
  352. assert(z.num_bits >= u64(width))
  353. return u32(z.code_buffer & ~(~u64(0) << width))
  354. }
  355. peek_bits_no_refill_lsb :: proc{peek_bits_no_refill_lsb_from_memory, peek_bits_no_refill_lsb_from_stream}
  356. @(optimization_mode="speed")
  357. read_bits_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) -> u32 {
  358. k := #force_inline peek_bits_lsb(z, width)
  359. #force_inline consume_bits_lsb(z, width)
  360. return k
  361. }
  362. @(optimization_mode="speed")
  363. read_bits_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) -> u32 {
  364. k := peek_bits_lsb(z, width)
  365. consume_bits_lsb(z, width)
  366. return k
  367. }
  368. read_bits_lsb :: proc{read_bits_lsb_from_memory, read_bits_lsb_from_stream}
  369. @(optimization_mode="speed")
  370. read_bits_no_refill_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) -> u32 {
  371. k := #force_inline peek_bits_no_refill_lsb(z, width)
  372. #force_inline consume_bits_lsb(z, width)
  373. return k
  374. }
  375. @(optimization_mode="speed")
  376. read_bits_no_refill_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) -> u32 {
  377. k := peek_bits_no_refill_lsb(z, width)
  378. consume_bits_lsb(z, width)
  379. return k
  380. }
  381. read_bits_no_refill_lsb :: proc{read_bits_no_refill_lsb_from_memory, read_bits_no_refill_lsb_from_stream}
  382. @(optimization_mode="speed")
  383. discard_to_next_byte_lsb_from_memory :: proc(z: ^Context_Memory_Input) {
  384. discard := u8(z.num_bits & 7)
  385. #force_inline consume_bits_lsb(z, discard)
  386. }
  387. @(optimization_mode="speed")
  388. discard_to_next_byte_lsb_from_stream :: proc(z: ^Context_Stream_Input) {
  389. discard := u8(z.num_bits & 7)
  390. consume_bits_lsb(z, discard)
  391. }
  392. discard_to_next_byte_lsb :: proc{discard_to_next_byte_lsb_from_memory, discard_to_next_byte_lsb_from_stream};