writerc.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package yaml
  2. // Set the writer error and return false.
  3. func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool {
  4. emitter.error = yaml_WRITER_ERROR
  5. emitter.problem = problem
  6. return false
  7. }
  8. // Flush the output buffer.
  9. func yaml_emitter_flush(emitter *yaml_emitter_t) bool {
  10. if emitter.write_handler == nil {
  11. panic("write handler not set")
  12. }
  13. // Check if the buffer is empty.
  14. if emitter.buffer_pos == 0 {
  15. return true
  16. }
  17. // If the output encoding is UTF-8, we don't need to recode the buffer.
  18. if emitter.encoding == yaml_UTF8_ENCODING {
  19. if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil {
  20. return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error())
  21. }
  22. emitter.buffer_pos = 0
  23. return true
  24. }
  25. // Recode the buffer into the raw buffer.
  26. var low, high int
  27. if emitter.encoding == yaml_UTF16LE_ENCODING {
  28. low, high = 0, 1
  29. } else {
  30. high, low = 1, 0
  31. }
  32. pos := 0
  33. for pos < emitter.buffer_pos {
  34. // See the "reader.c" code for more details on UTF-8 encoding. Note
  35. // that we assume that the buffer contains a valid UTF-8 sequence.
  36. // Read the next UTF-8 character.
  37. octet := emitter.buffer[pos]
  38. var w int
  39. var value rune
  40. switch {
  41. case octet&0x80 == 0x00:
  42. w, value = 1, rune(octet&0x7F)
  43. case octet&0xE0 == 0xC0:
  44. w, value = 2, rune(octet&0x1F)
  45. case octet&0xF0 == 0xE0:
  46. w, value = 3, rune(octet&0x0F)
  47. case octet&0xF8 == 0xF0:
  48. w, value = 4, rune(octet&0x07)
  49. }
  50. for k := 1; k < w; k++ {
  51. octet = emitter.buffer[pos+k]
  52. value = (value << 6) + (rune(octet) & 0x3F)
  53. }
  54. pos += w
  55. // Write the character.
  56. if value < 0x10000 {
  57. var b [2]byte
  58. b[high] = byte(value >> 8)
  59. b[low] = byte(value & 0xFF)
  60. emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1])
  61. } else {
  62. // Write the character using a surrogate pair (check "reader.c").
  63. var b [4]byte
  64. value -= 0x10000
  65. b[high] = byte(0xD8 + (value >> 18))
  66. b[low] = byte((value >> 10) & 0xFF)
  67. b[high+2] = byte(0xDC + ((value >> 8) & 0xFF))
  68. b[low+2] = byte(value & 0xFF)
  69. emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1], b[2], b[3])
  70. }
  71. }
  72. // Write the raw buffer.
  73. if err := emitter.write_handler(emitter, emitter.raw_buffer); err != nil {
  74. return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error())
  75. }
  76. emitter.buffer_pos = 0
  77. emitter.raw_buffer = emitter.raw_buffer[:0]
  78. return true
  79. }