example.odin 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #+build ignore
  2. package custom_formatter_example
  3. import "core:fmt"
  4. import "core:io"
  5. SomeType :: struct {
  6. value: int,
  7. }
  8. My_Custom_Base_Type :: distinct u32
  9. main :: proc() {
  10. // Ensure the fmt._user_formatters map is initialized
  11. fmt.set_user_formatters(new(map[typeid]fmt.User_Formatter))
  12. // Register custom formatters for my favorite types
  13. err := fmt.register_user_formatter(type_info_of(SomeType).id, SomeType_Formatter)
  14. assert(err == .None)
  15. err = fmt.register_user_formatter(type_info_of(My_Custom_Base_Type).id, My_Custom_Base_Formatter)
  16. assert(err == .None)
  17. // Use the custom formatters.
  18. fmt.printfln("SomeType{{42}}: '%v'", SomeType{42})
  19. fmt.printfln("My_Custom_Base_Type(0xdeadbeef): '%v'", My_Custom_Base_Type(0xdeadbeef))
  20. }
  21. SomeType_Formatter :: proc(fi: ^fmt.Info, arg: any, verb: rune) -> bool {
  22. m := cast(^SomeType)arg.data
  23. switch verb {
  24. case 'v', 'd': // We handle `%v` and `%d`
  25. fmt.fmt_int(fi, u64(m.value), true, 8 * size_of(SomeType), verb)
  26. case:
  27. return false
  28. }
  29. return true
  30. }
  31. My_Custom_Base_Formatter :: proc(fi: ^fmt.Info, arg: any, verb: rune) -> bool {
  32. m := cast(^My_Custom_Base_Type)arg.data
  33. switch verb {
  34. case 'v', 'b':
  35. value := u64(m^)
  36. for value > 0 {
  37. if value & 1 == 1 {
  38. io.write_string(fi.writer, "Hellope!", &fi.n)
  39. } else {
  40. io.write_string(fi.writer, "Hellope?", &fi.n)
  41. }
  42. value >>= 1
  43. }
  44. case:
  45. return false
  46. }
  47. return true
  48. }