common.odin 13 KB

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