common.odin 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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 "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. } else {
  111. // e.g. `-target:windows_i386`
  112. #assert(size_of(Context_Memory_Input) == 52)
  113. }
  114. Context_Stream_Input :: struct #packed {
  115. input_data: []u8,
  116. input: io.Stream,
  117. output: ^bytes.Buffer,
  118. bytes_written: i64,
  119. code_buffer: u64,
  120. num_bits: u64,
  121. // If we know the data size, we can optimize the reads and writes.
  122. size_packed: i64,
  123. size_unpacked: i64,
  124. // Flags:
  125. // `input_fully_in_memory`
  126. // true = This tells us we read input from `input_data` exclusively. [] = EOF.
  127. // false = Try to refill `input_data` from the `input` stream.
  128. input_fully_in_memory: b8,
  129. padding: [1]u8,
  130. }
  131. /*
  132. TODO: The stream versions should really only check if a certain method is available once, perhaps even during setup.
  133. Bit and byte readers may be merged so that reading bytes will grab them from the bit buffer first.
  134. This simplifies end-of-stream handling where bits may be left in the bit buffer.
  135. */
  136. input_size_from_memory :: proc(z: ^Context_Memory_Input) -> (res: i64, err: Error) {
  137. return i64(len(z.input_data)), nil
  138. }
  139. input_size_from_stream :: proc(z: ^Context_Stream_Input) -> (res: i64, err: Error) {
  140. res, _ = io.size(z.input)
  141. return
  142. }
  143. input_size :: proc{input_size_from_memory, input_size_from_stream}
  144. @(optimization_mode="speed")
  145. read_slice_from_memory :: #force_inline proc(z: ^Context_Memory_Input, size: int) -> (res: []u8, err: io.Error) {
  146. #no_bounds_check {
  147. if len(z.input_data) >= size {
  148. res = z.input_data[:size]
  149. z.input_data = z.input_data[size:]
  150. return res, .None
  151. }
  152. }
  153. if len(z.input_data) == 0 {
  154. return []u8{}, .EOF
  155. } else {
  156. return []u8{}, .Short_Buffer
  157. }
  158. }
  159. @(optimization_mode="speed")
  160. read_slice_from_stream :: #force_inline proc(z: ^Context_Stream_Input, size: int) -> (res: []u8, err: io.Error) {
  161. // TODO: REMOVE ALL USE OF context.temp_allocator here
  162. // there is literally no need for it
  163. b := make([]u8, size, context.temp_allocator)
  164. _ = io.read(z.input, b[:]) or_return
  165. return b, nil
  166. }
  167. read_slice :: proc{read_slice_from_memory, read_slice_from_stream}
  168. @(optimization_mode="speed")
  169. read_data :: #force_inline proc(z: ^$C, $T: typeid) -> (res: T, err: io.Error) {
  170. b := read_slice(z, size_of(T)) or_return
  171. return (^T)(&b[0])^, nil
  172. }
  173. @(optimization_mode="speed")
  174. read_u8_from_memory :: #force_inline proc(z: ^Context_Memory_Input) -> (res: u8, err: io.Error) {
  175. #no_bounds_check {
  176. if len(z.input_data) >= 1 {
  177. res = z.input_data[0]
  178. z.input_data = z.input_data[1:]
  179. return res, .None
  180. }
  181. }
  182. return 0, .EOF
  183. }
  184. @(optimization_mode="speed")
  185. read_u8_from_stream :: #force_inline proc(z: ^Context_Stream_Input) -> (res: u8, err: io.Error) {
  186. b := read_slice_from_stream(z, 1) or_return
  187. return b[0], nil
  188. }
  189. read_u8 :: proc{read_u8_from_memory, read_u8_from_stream}
  190. // You would typically only use this at the end of Inflate, to drain bits from the code buffer
  191. // preferentially.
  192. @(optimization_mode="speed")
  193. read_u8_prefer_code_buffer_lsb :: #force_inline proc(z: ^$C) -> (res: u8, err: io.Error) {
  194. if z.num_bits >= 8 {
  195. res = u8(read_bits_no_refill_lsb(z, 8))
  196. } else {
  197. size, _ := input_size(z)
  198. if size > 0 {
  199. res, err = read_u8(z)
  200. } else {
  201. err = .EOF
  202. }
  203. }
  204. return
  205. }
  206. @(optimization_mode="speed")
  207. peek_data_from_memory :: #force_inline proc(z: ^Context_Memory_Input, $T: typeid) -> (res: T, err: io.Error) {
  208. size :: size_of(T)
  209. #no_bounds_check {
  210. if len(z.input_data) >= size {
  211. buf := z.input_data[:size]
  212. return (^T)(&buf[0])^, .None
  213. }
  214. }
  215. if len(z.input_data) == 0 {
  216. return T{}, .EOF
  217. } else {
  218. return T{}, .Short_Buffer
  219. }
  220. }
  221. @(optimization_mode="speed")
  222. peek_data_at_offset_from_memory :: #force_inline proc(z: ^Context_Memory_Input, $T: typeid, #any_int offset: int) -> (res: T, err: io.Error) {
  223. size :: size_of(T)
  224. #no_bounds_check {
  225. if len(z.input_data) >= size + offset {
  226. buf := z.input_data[offset:][:size]
  227. return (^T)(&buf[0])^, .None
  228. }
  229. }
  230. if len(z.input_data) == 0 {
  231. return T{}, .EOF
  232. } else {
  233. return T{}, .Short_Buffer
  234. }
  235. }
  236. @(optimization_mode="speed")
  237. peek_data_from_stream :: #force_inline proc(z: ^Context_Stream_Input, $T: typeid) -> (res: T, err: io.Error) {
  238. size :: size_of(T)
  239. // Get current position to read from.
  240. curr := z.input->impl_seek(0, .Current) or_return
  241. r, e1 := io.to_reader_at(z.input)
  242. if !e1 {
  243. return T{}, .Empty
  244. }
  245. when size <= 128 {
  246. b: [size]u8
  247. } else {
  248. b := make([]u8, size, context.temp_allocator)
  249. }
  250. _, e2 := io.read_at(r, b[:], curr)
  251. if e2 != .None {
  252. return T{}, .Empty
  253. }
  254. res = (^T)(&b[0])^
  255. return res, .None
  256. }
  257. @(optimization_mode="speed")
  258. peek_data_at_offset_from_stream :: #force_inline proc(z: ^Context_Stream_Input, $T: typeid, #any_int offset: int) -> (res: T, err: io.Error) {
  259. size :: size_of(T)
  260. // Get current position to return to.
  261. cur_pos := z.input->impl_seek(0, .Current) or_return
  262. // Seek to offset.
  263. pos := z.input->impl_seek(offset, .Start) or_return
  264. r, e3 := io.to_reader_at(z.input)
  265. if !e3 {
  266. return T{}, .Empty
  267. }
  268. when size <= 128 {
  269. b: [size]u8
  270. } else {
  271. b := make([]u8, size, context.temp_allocator)
  272. }
  273. _, e4 := io.read_at(r, b[:], pos)
  274. if e4 != .None {
  275. return T{}, .Empty
  276. }
  277. // Return read head to original position.
  278. z.input->impl_seek(cur_pos, .Start)
  279. res = (^T)(&b[0])^
  280. return res, .None
  281. }
  282. peek_data :: proc{peek_data_from_memory, peek_data_from_stream, peek_data_at_offset_from_memory, peek_data_at_offset_from_stream}
  283. // Sliding window read back
  284. @(optimization_mode="speed")
  285. peek_back_byte :: #force_inline proc(z: ^$C, offset: i64) -> (res: u8, err: io.Error) {
  286. // Look back into the sliding window.
  287. return z.output.buf[z.bytes_written - offset], .None
  288. }
  289. // Generalized bit reader LSB
  290. @(optimization_mode="speed")
  291. refill_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width := i8(48)) {
  292. refill := u64(width)
  293. b := u64(0)
  294. if z.num_bits > refill {
  295. return
  296. }
  297. for {
  298. if len(z.input_data) != 0 {
  299. b = u64(z.input_data[0])
  300. z.input_data = z.input_data[1:]
  301. } else {
  302. b = 0
  303. }
  304. z.code_buffer |= b << u8(z.num_bits)
  305. z.num_bits += 8
  306. if z.num_bits > refill {
  307. break
  308. }
  309. }
  310. }
  311. // Generalized bit reader LSB
  312. @(optimization_mode="speed")
  313. refill_lsb_from_stream :: proc(z: ^Context_Stream_Input, width := i8(24)) {
  314. refill := u64(width)
  315. for {
  316. if z.num_bits > refill {
  317. break
  318. }
  319. if z.code_buffer == 0 && z.num_bits > 63 {
  320. z.num_bits = 0
  321. }
  322. if z.code_buffer >= 1 << uint(z.num_bits) {
  323. // Code buffer is malformed.
  324. z.num_bits = max(u64)
  325. return
  326. }
  327. b, err := read_u8(z)
  328. if err != .None {
  329. // This is fine at the end of the file.
  330. return
  331. }
  332. z.code_buffer |= (u64(b) << u8(z.num_bits))
  333. z.num_bits += 8
  334. }
  335. }
  336. refill_lsb :: proc{refill_lsb_from_memory, refill_lsb_from_stream}
  337. @(optimization_mode="speed")
  338. consume_bits_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) {
  339. z.code_buffer >>= width
  340. z.num_bits -= u64(width)
  341. }
  342. @(optimization_mode="speed")
  343. consume_bits_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) {
  344. z.code_buffer >>= width
  345. z.num_bits -= u64(width)
  346. }
  347. consume_bits_lsb :: proc{consume_bits_lsb_from_memory, consume_bits_lsb_from_stream}
  348. @(optimization_mode="speed")
  349. peek_bits_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) -> u32 {
  350. if z.num_bits < u64(width) {
  351. refill_lsb(z)
  352. }
  353. return u32(z.code_buffer &~ (~u64(0) << width))
  354. }
  355. @(optimization_mode="speed")
  356. peek_bits_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) -> u32 {
  357. if z.num_bits < u64(width) {
  358. refill_lsb(z)
  359. }
  360. return u32(z.code_buffer &~ (~u64(0) << width))
  361. }
  362. peek_bits_lsb :: proc{peek_bits_lsb_from_memory, peek_bits_lsb_from_stream}
  363. @(optimization_mode="speed")
  364. peek_bits_no_refill_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) -> u32 {
  365. assert(z.num_bits >= u64(width))
  366. return u32(z.code_buffer &~ (~u64(0) << width))
  367. }
  368. @(optimization_mode="speed")
  369. peek_bits_no_refill_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) -> u32 {
  370. assert(z.num_bits >= u64(width))
  371. return u32(z.code_buffer &~ (~u64(0) << width))
  372. }
  373. peek_bits_no_refill_lsb :: proc{peek_bits_no_refill_lsb_from_memory, peek_bits_no_refill_lsb_from_stream}
  374. @(optimization_mode="speed")
  375. read_bits_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) -> u32 {
  376. k := #force_inline peek_bits_lsb(z, width)
  377. #force_inline consume_bits_lsb(z, width)
  378. return k
  379. }
  380. @(optimization_mode="speed")
  381. read_bits_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) -> u32 {
  382. k := peek_bits_lsb(z, width)
  383. consume_bits_lsb(z, width)
  384. return k
  385. }
  386. read_bits_lsb :: proc{read_bits_lsb_from_memory, read_bits_lsb_from_stream}
  387. @(optimization_mode="speed")
  388. read_bits_no_refill_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) -> u32 {
  389. k := #force_inline peek_bits_no_refill_lsb(z, width)
  390. #force_inline consume_bits_lsb(z, width)
  391. return k
  392. }
  393. @(optimization_mode="speed")
  394. read_bits_no_refill_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) -> u32 {
  395. k := peek_bits_no_refill_lsb(z, width)
  396. consume_bits_lsb(z, width)
  397. return k
  398. }
  399. read_bits_no_refill_lsb :: proc{read_bits_no_refill_lsb_from_memory, read_bits_no_refill_lsb_from_stream}
  400. @(optimization_mode="speed")
  401. discard_to_next_byte_lsb_from_memory :: proc(z: ^Context_Memory_Input) {
  402. discard := u8(z.num_bits & 7)
  403. #force_inline consume_bits_lsb(z, discard)
  404. }
  405. @(optimization_mode="speed")
  406. discard_to_next_byte_lsb_from_stream :: proc(z: ^Context_Stream_Input) {
  407. discard := u8(z.num_bits & 7)
  408. consume_bits_lsb(z, discard)
  409. }
  410. discard_to_next_byte_lsb :: proc{discard_to_next_byte_lsb_from_memory, discard_to_next_byte_lsb_from_stream}