example.odin 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //+build ignore
  2. package gzip
  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.
  8. Ginger Bill: Cosmetic changes.
  9. A small GZIP implementation as an example.
  10. */
  11. import "core:bytes"
  12. import "core:os"
  13. import "core:compress"
  14. import "core:fmt"
  15. // Small GZIP file with fextra, fname and fcomment present.
  16. @private
  17. TEST: []u8 = {
  18. 0x1f, 0x8b, 0x08, 0x1c, 0xcb, 0x3b, 0x3a, 0x5a,
  19. 0x02, 0x03, 0x07, 0x00, 0x61, 0x62, 0x03, 0x00,
  20. 0x63, 0x64, 0x65, 0x66, 0x69, 0x6c, 0x65, 0x6e,
  21. 0x61, 0x6d, 0x65, 0x00, 0x54, 0x68, 0x69, 0x73,
  22. 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x63, 0x6f,
  23. 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x00, 0x2b, 0x48,
  24. 0xac, 0xcc, 0xc9, 0x4f, 0x4c, 0x01, 0x00, 0x15,
  25. 0x6a, 0x2c, 0x42, 0x07, 0x00, 0x00, 0x00,
  26. }
  27. main :: proc() {
  28. // Set up output buffer.
  29. buf := bytes.Buffer{}
  30. stdout :: proc(s: string) {
  31. os.write_string(os.stdout, s)
  32. }
  33. stderr :: proc(s: string) {
  34. os.write_string(os.stderr, s)
  35. }
  36. args := os.args
  37. if len(args) < 2 {
  38. stderr("No input file specified.\n")
  39. err := load(data=TEST, buf=&buf, known_gzip_size=len(TEST))
  40. if err == nil {
  41. stdout("Displaying test vector: ")
  42. stdout(bytes.buffer_to_string(&buf))
  43. stdout("\n")
  44. } else {
  45. fmt.printf("gzip.load returned %v\n", err)
  46. }
  47. bytes.buffer_destroy(&buf)
  48. os.exit(0)
  49. }
  50. // The rest are all files.
  51. args = args[1:]
  52. err: Error
  53. for file in args {
  54. if file == "-" {
  55. // Read from stdin
  56. s := os.stream_from_handle(os.stdin)
  57. ctx := &compress.Context_Stream_Input{
  58. input = s,
  59. }
  60. err = load(ctx, &buf)
  61. } else {
  62. err = load(file, &buf)
  63. }
  64. if err != nil {
  65. if err != E_General.File_Not_Found {
  66. stderr("File not found: ")
  67. stderr(file)
  68. stderr("\n")
  69. os.exit(1)
  70. }
  71. stderr("GZIP returned an error.\n")
  72. bytes.buffer_destroy(&buf)
  73. os.exit(2)
  74. }
  75. stdout(bytes.buffer_to_string(&buf))
  76. }
  77. bytes.buffer_destroy(&buf)
  78. }