common.odin 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. // TODO: Make these return compress.Error errors.
  154. input_size_from_memory :: proc(z: ^Context_Memory_Input) -> (res: i64, err: Error) {
  155. return i64(len(z.input_data)), nil
  156. }
  157. input_size_from_stream :: proc(z: ^Context_Stream_Input) -> (res: i64, err: Error) {
  158. return io.size(z.input), nil
  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. b := make([]u8, size, context.temp_allocator)
  179. _, e := z.input->impl_read(b[:])
  180. if e == .None {
  181. return b, .None
  182. }
  183. return []u8{}, e
  184. }
  185. read_slice :: proc{read_slice_from_memory, read_slice_from_stream}
  186. @(optimization_mode="speed")
  187. read_data :: #force_inline proc(z: ^$C, $T: typeid) -> (res: T, err: io.Error) {
  188. b, e := read_slice(z, size_of(T))
  189. if e == .None {
  190. return (^T)(&b[0])^, .None
  191. }
  192. return T{}, e
  193. }
  194. @(optimization_mode="speed")
  195. read_u8_from_memory :: #force_inline proc(z: ^Context_Memory_Input) -> (res: u8, err: io.Error) {
  196. #no_bounds_check {
  197. if len(z.input_data) >= 1 {
  198. res = z.input_data[0]
  199. z.input_data = z.input_data[1:]
  200. return res, .None
  201. }
  202. }
  203. return 0, .EOF
  204. }
  205. @(optimization_mode="speed")
  206. read_u8_from_stream :: #force_inline proc(z: ^Context_Stream_Input) -> (res: u8, err: io.Error) {
  207. b, e := read_slice_from_stream(z, 1)
  208. if e == .None {
  209. return b[0], .None
  210. }
  211. return 0, e
  212. }
  213. read_u8 :: proc{read_u8_from_memory, read_u8_from_stream}
  214. /*
  215. You would typically only use this at the end of Inflate, to drain bits from the code buffer
  216. preferentially.
  217. */
  218. @(optimization_mode="speed")
  219. read_u8_prefer_code_buffer_lsb :: #force_inline proc(z: ^$C) -> (res: u8, err: io.Error) {
  220. if z.num_bits >= 8 {
  221. res = u8(read_bits_no_refill_lsb(z, 8))
  222. } else {
  223. size, _ := input_size(z)
  224. if size > 0 {
  225. res, err = read_u8(z)
  226. } else {
  227. err = .EOF
  228. }
  229. }
  230. return
  231. }
  232. @(optimization_mode="speed")
  233. peek_data_from_memory :: #force_inline proc(z: ^Context_Memory_Input, $T: typeid) -> (res: T, err: io.Error) {
  234. size :: size_of(T)
  235. #no_bounds_check {
  236. if len(z.input_data) >= size {
  237. buf := z.input_data[:size]
  238. return (^T)(&buf[0])^, .None
  239. }
  240. }
  241. if len(z.input_data) == 0 {
  242. return T{}, .EOF
  243. } else {
  244. return T{}, .Short_Buffer
  245. }
  246. }
  247. @(optimization_mode="speed")
  248. peek_data_from_stream :: #force_inline proc(z: ^Context_Stream_Input, $T: typeid) -> (res: T, err: io.Error) {
  249. size :: size_of(T)
  250. // Get current position to read from.
  251. curr, e1 := z.input->impl_seek(0, .Current)
  252. if e1 != .None {
  253. return T{}, e1
  254. }
  255. r, e2 := io.to_reader_at(z.input)
  256. if !e2 {
  257. return T{}, .Empty
  258. }
  259. when size <= 128 {
  260. b: [size]u8
  261. } else {
  262. b := make([]u8, size, context.temp_allocator)
  263. }
  264. _, e3 := io.read_at(r, b[:], curr)
  265. if e3 != .None {
  266. return T{}, .Empty
  267. }
  268. res = (^T)(&b[0])^
  269. return res, .None
  270. }
  271. peek_data :: proc{peek_data_from_memory, peek_data_from_stream}
  272. // Sliding window read back
  273. @(optimization_mode="speed")
  274. peek_back_byte :: #force_inline proc(z: ^$C, offset: i64) -> (res: u8, err: io.Error) {
  275. // Look back into the sliding window.
  276. return z.output.buf[z.bytes_written - offset], .None
  277. }
  278. // Generalized bit reader LSB
  279. @(optimization_mode="speed")
  280. refill_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width := i8(48)) {
  281. refill := u64(width)
  282. b := u64(0)
  283. if z.num_bits > refill {
  284. return
  285. }
  286. for {
  287. if len(z.input_data) != 0 {
  288. b = u64(z.input_data[0])
  289. z.input_data = z.input_data[1:]
  290. } else {
  291. b = 0
  292. }
  293. z.code_buffer |= b << u8(z.num_bits)
  294. z.num_bits += 8
  295. if z.num_bits > refill {
  296. break
  297. }
  298. }
  299. }
  300. // Generalized bit reader LSB
  301. @(optimization_mode="speed")
  302. refill_lsb_from_stream :: proc(z: ^Context_Stream_Input, width := i8(24)) {
  303. refill := u64(width)
  304. for {
  305. if z.num_bits > refill {
  306. break
  307. }
  308. if z.code_buffer == 0 && z.num_bits > 63 {
  309. z.num_bits = 0
  310. }
  311. if z.code_buffer >= 1 << uint(z.num_bits) {
  312. // Code buffer is malformed.
  313. z.num_bits = max(u64)
  314. return
  315. }
  316. b, err := read_u8(z)
  317. if err != .None {
  318. // This is fine at the end of the file.
  319. return
  320. }
  321. z.code_buffer |= (u64(b) << u8(z.num_bits))
  322. z.num_bits += 8
  323. }
  324. }
  325. refill_lsb :: proc{refill_lsb_from_memory, refill_lsb_from_stream}
  326. @(optimization_mode="speed")
  327. consume_bits_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) {
  328. z.code_buffer >>= width
  329. z.num_bits -= u64(width)
  330. }
  331. @(optimization_mode="speed")
  332. consume_bits_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) {
  333. z.code_buffer >>= width
  334. z.num_bits -= u64(width)
  335. }
  336. consume_bits_lsb :: proc{consume_bits_lsb_from_memory, consume_bits_lsb_from_stream}
  337. @(optimization_mode="speed")
  338. peek_bits_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_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. @(optimization_mode="speed")
  345. peek_bits_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) -> u32 {
  346. if z.num_bits < u64(width) {
  347. refill_lsb(z)
  348. }
  349. return u32(z.code_buffer & ~(~u64(0) << width))
  350. }
  351. peek_bits_lsb :: proc{peek_bits_lsb_from_memory, peek_bits_lsb_from_stream}
  352. @(optimization_mode="speed")
  353. peek_bits_no_refill_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) -> u32 {
  354. assert(z.num_bits >= u64(width))
  355. return u32(z.code_buffer & ~(~u64(0) << width))
  356. }
  357. @(optimization_mode="speed")
  358. peek_bits_no_refill_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) -> u32 {
  359. assert(z.num_bits >= u64(width))
  360. return u32(z.code_buffer & ~(~u64(0) << width))
  361. }
  362. peek_bits_no_refill_lsb :: proc{peek_bits_no_refill_lsb_from_memory, peek_bits_no_refill_lsb_from_stream}
  363. @(optimization_mode="speed")
  364. read_bits_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) -> u32 {
  365. k := #force_inline peek_bits_lsb(z, width)
  366. #force_inline consume_bits_lsb(z, width)
  367. return k
  368. }
  369. @(optimization_mode="speed")
  370. read_bits_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) -> u32 {
  371. k := peek_bits_lsb(z, width)
  372. consume_bits_lsb(z, width)
  373. return k
  374. }
  375. read_bits_lsb :: proc{read_bits_lsb_from_memory, read_bits_lsb_from_stream}
  376. @(optimization_mode="speed")
  377. read_bits_no_refill_lsb_from_memory :: #force_inline proc(z: ^Context_Memory_Input, width: u8) -> u32 {
  378. k := #force_inline peek_bits_no_refill_lsb(z, width)
  379. #force_inline consume_bits_lsb(z, width)
  380. return k
  381. }
  382. @(optimization_mode="speed")
  383. read_bits_no_refill_lsb_from_stream :: #force_inline proc(z: ^Context_Stream_Input, width: u8) -> u32 {
  384. k := peek_bits_no_refill_lsb(z, width)
  385. consume_bits_lsb(z, width)
  386. return k
  387. }
  388. read_bits_no_refill_lsb :: proc{read_bits_no_refill_lsb_from_memory, read_bits_no_refill_lsb_from_stream}
  389. @(optimization_mode="speed")
  390. discard_to_next_byte_lsb_from_memory :: proc(z: ^Context_Memory_Input) {
  391. discard := u8(z.num_bits & 7)
  392. #force_inline consume_bits_lsb(z, discard)
  393. }
  394. @(optimization_mode="speed")
  395. discard_to_next_byte_lsb_from_stream :: proc(z: ^Context_Stream_Input) {
  396. discard := u8(z.num_bits & 7)
  397. consume_bits_lsb(z, discard)
  398. }
  399. discard_to_next_byte_lsb :: proc{discard_to_next_byte_lsb_from_memory, discard_to_next_byte_lsb_from_stream}