netascii.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package netascii
  2. // TODO: make it work not only on linux
  3. import "io"
  4. const (
  5. CR = '\x0d'
  6. LF = '\x0a'
  7. NUL = '\x00'
  8. )
  9. func ToReader(r io.Reader) io.Reader {
  10. return &toReader{
  11. r: r,
  12. buf: make([]byte, 256),
  13. }
  14. }
  15. type toReader struct {
  16. r io.Reader
  17. buf []byte
  18. n int
  19. i int
  20. err error
  21. lf bool
  22. nul bool
  23. }
  24. func (r *toReader) Read(p []byte) (int, error) {
  25. var n int
  26. for n < len(p) {
  27. if r.lf {
  28. p[n] = LF
  29. n++
  30. r.lf = false
  31. continue
  32. }
  33. if r.nul {
  34. p[n] = NUL
  35. n++
  36. r.nul = false
  37. continue
  38. }
  39. if r.i < r.n {
  40. if r.buf[r.i] == LF {
  41. p[n] = CR
  42. r.lf = true
  43. } else if r.buf[r.i] == CR {
  44. p[n] = CR
  45. r.nul = true
  46. } else {
  47. p[n] = r.buf[r.i]
  48. }
  49. r.i++
  50. n++
  51. continue
  52. }
  53. if r.err == nil {
  54. r.n, r.err = r.r.Read(r.buf)
  55. r.i = 0
  56. } else {
  57. return n, r.err
  58. }
  59. }
  60. return n, r.err
  61. }
  62. type fromWriter struct {
  63. w io.Writer
  64. buf []byte
  65. i int
  66. cr bool
  67. }
  68. func FromWriter(w io.Writer) io.Writer {
  69. return &fromWriter{
  70. w: w,
  71. buf: make([]byte, 256),
  72. }
  73. }
  74. func (w *fromWriter) Write(p []byte) (n int, err error) {
  75. for n < len(p) {
  76. if w.cr {
  77. if p[n] == LF {
  78. w.buf[w.i] = LF
  79. }
  80. if p[n] == NUL {
  81. w.buf[w.i] = CR
  82. }
  83. w.cr = false
  84. w.i++
  85. } else if p[n] == CR {
  86. w.cr = true
  87. } else {
  88. w.buf[w.i] = p[n]
  89. w.i++
  90. }
  91. n++
  92. if w.i == len(w.buf) || n == len(p) {
  93. _, err = w.w.Write(w.buf[:w.i])
  94. w.i = 0
  95. }
  96. }
  97. return n, err
  98. }