escape.nim 1002 B

123456789101112131415161718192021222324252627282930313233
  1. # from Nimrod's Runtime Library - xmltree
  2. # (c) Copyright 2012 Andreas Rumpf
  3. # Modifications by Erwan Ameil
  4. proc addEscaped*(result: var string, s: string) =
  5. ## same as ``result.add(escape(s))``, but more efficient.
  6. for c in items(s):
  7. case c
  8. of '<': result.add("&lt;")
  9. of '>': result.add("&gt;")
  10. of '&': result.add("&amp;")
  11. of '"': result.add("&quot;")
  12. of '\'': result.add("&#x27;")
  13. of '/': result.add("&#x2F;")
  14. else: result.add(c)
  15. proc escape*(s: string): string =
  16. ## escapes `s` for inclusion into an XML document.
  17. ## Escapes these characters:
  18. ##
  19. ## ------------ -------------------
  20. ## char is converted to
  21. ## ------------ -------------------
  22. ## ``<`` ``&lt;``
  23. ## ``>`` ``&gt;``
  24. ## ``&`` ``&amp;``
  25. ## ``"`` ``&quot;``
  26. ## ``'`` ``&#x27;``
  27. ## ``/`` ``&#x2F;``
  28. ## ------------ -------------------
  29. result = newStringOfCap(s.len)
  30. addEscaped(result, s)