pg.rs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #[cfg(test)]
  2. use std::str;
  3. use std::io::{self, Write};
  4. /// Write text with PostgreSQL text format encoding.
  5. pub fn write_pgencoded<W: Write>(w: &mut W, buf: &[u8]) -> io::Result<()> {
  6. let mut start = 0;
  7. for i in 0..buf.len() {
  8. match buf[i] {
  9. b'\\' => {
  10. w.write_all(&buf[start..i])?;
  11. start = i + 1;
  12. w.write_all(b"\\\\")?;
  13. },
  14. b'\r' => {
  15. w.write_all(&buf[start..i])?;
  16. start = i + 1;
  17. },
  18. b'\n' => {
  19. w.write_all(&buf[start..i])?;
  20. start = i + 1;
  21. w.write_all(b"\\n")?;
  22. },
  23. b'\t' => {
  24. w.write_all(&buf[start..i])?;
  25. start = i + 1;
  26. w.write_all(b"\\t")?;
  27. },
  28. _ => ()
  29. }
  30. }
  31. if start < buf.len() {
  32. w.write_all(&buf[start..])?;
  33. }
  34. Ok(())
  35. }
  36. #[test]
  37. fn it_writes_empty() {
  38. let mut vec = Vec::new();
  39. write_pgencoded(&mut vec, b"").unwrap();
  40. assert_eq!(vec.len(), 0);
  41. }
  42. #[test]
  43. fn it_writes_str() {
  44. let mut vec = Vec::new();
  45. write_pgencoded(&mut vec, b"foo").unwrap();
  46. assert_eq!(str::from_utf8(&vec).unwrap(), "foo");
  47. }
  48. #[test]
  49. fn encode_backslash() {
  50. let mut vec = Vec::new();
  51. write_pgencoded(&mut vec, b"\\").unwrap();
  52. assert_eq!(str::from_utf8(&vec).unwrap(), "\\\\");
  53. }
  54. #[test]
  55. fn encode_tab() {
  56. let mut vec = Vec::new();
  57. write_pgencoded(&mut vec, b"\t").unwrap();
  58. assert_eq!(str::from_utf8(&vec).unwrap(), "\\t");
  59. }
  60. #[test]
  61. fn encode_nl() {
  62. let mut vec = Vec::new();
  63. write_pgencoded(&mut vec, b"\n").unwrap();
  64. assert_eq!(str::from_utf8(&vec).unwrap(), "\\n");
  65. }
  66. #[test]
  67. fn skip_cr() {
  68. let mut vec = Vec::new();
  69. write_pgencoded(&mut vec, b"\r").unwrap();
  70. assert_eq!(str::from_utf8(&vec).unwrap(), "");
  71. }
  72. #[test]
  73. fn embedded() {
  74. let mut vec = Vec::new();
  75. write_pgencoded(&mut vec, b"foo\nbar\\wombat").unwrap();
  76. assert_eq!(str::from_utf8(&vec).unwrap(), "foo\\nbar\\\\wombat");
  77. }
Tip!

Press p or to see the previous file or, n or to see the next file