Nmap Development mailing list archives

[NSE][PATCH] string_ext library


From: Sven Klemm <sven () c3d2 de>
Date: Fri, 19 Sep 2008 10:38:43 +0200

Hi everyone,

i've attached a library that adds a to_hex function to string. I think this library would be a good place for adding further string enhancements like for example moving stdnse.strsplit() here.

example usage:

require "string_ext"

("abc"):to_hex() => "616263"
("abc"):to_hex(":") => "61:62:63"
("abc"):to_hex(":",2) => "6162:63"

Cheers,
Sven

--
Sven Klemm
http://cthulhu.c3d2.de/~sven/

--- Extension for the lua string class

module(... or "string_ext", package.seeall)

setmetatable( string, {__index=string_ext})

--- encode string to hexadecimal
-- example: string.to_hex("abc") => "616263"
--          string.to_hex("abc",{separator=":"}) => "61:62:63"
--          string.to_hex("abc",{separator=":",group=2}) => "6162:63"
--@param s string to be encoded
--@param options table specifiying formatting options
--@return hexadecimal encoded string
to_hex = function( s, options ) 
  options = options or {}
  local fmt

  if options.separator then
    local group = options.group or 1
    local fmt_table = {}
    for i=1,#s,group do
      if #s - i < group then
        table.insert( fmt_table, string.rep("%02x", #s - i + 1))
      else
        table.insert( fmt_table, string.rep("%02x", group))
      end
    end
    fmt = table.concat( fmt_table, options.separator:gsub("%%","%%%%") )
  else
    fmt = string.rep("%02x",#s)
  end

  return fmt:format(s:byte(1, #s))
end


_______________________________________________
Sent through the nmap-dev mailing list
http://cgi.insecure.org/mailman/listinfo/nmap-dev
Archived at http://SecLists.Org

Current thread: