common.odin 13 KB

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