Created
March 29, 2012 18:34
-
-
Save bts/2241714 to your computer and use it in GitHub Desktop.
Fast XML escaping in Ruby 1.9 using FFI/libxml2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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