Skip to content

Instantly share code, notes, and snippets.

@bts
Created March 29, 2012 18:34
Show Gist options
  • Save bts/2241714 to your computer and use it in GitHub Desktop.
Save bts/2241714 to your computer and use it in GitHub Desktop.
Fast XML escaping in Ruby 1.9 using FFI/libxml2
require 'ffi'
module XmlEscaper
extend FFI::Library
ffi_lib 'xml2'
UTF8 = Encoding.find('UTF-8')
def self.escape(string)
char_ptr = self.xmlEncodeSpecialChars(nil, string)
encoded = char_ptr.read_string
encoded.force_encoding(UTF8)
self.free(char_ptr)
encoded
end
protected
# from xml2; returns char* that must be freed:
attach_function :xmlEncodeSpecialChars, [:pointer, :string], :pointer
# from libc:
attach_function :free, [:pointer], :void
end
XmlEscaper.escape('test&ing')
# => "test&ing"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment