common.odin 12 KB

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