text_format.lua 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. --
  2. --------------------------------------------------------------------------------
  3. -- FILE: text_format.lua
  4. -- DESCRIPTION: protoc-gen-lua
  5. -- Google's Protocol Buffers project, ported to lua.
  6. -- https://code.google.com/p/protoc-gen-lua/
  7. --
  8. -- Copyright (c) 2010 , 林卓毅 (Zhuoyi Lin) netsnail@gmail.com
  9. -- All rights reserved.
  10. --
  11. -- Use, modification and distribution are subject to the "New BSD License"
  12. -- as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
  13. -- COMPANY: NetEase
  14. -- CREATED: 2010年08月05日 15时14分13秒 CST
  15. --------------------------------------------------------------------------------
  16. --
  17. local string = string
  18. local math = math
  19. local print = print
  20. local getmetatable = getmetatable
  21. local table = table
  22. local ipairs = ipairs
  23. local tostring = tostring
  24. local descriptor = require "protobuf.descriptor"
  25. module "protobuf.text_format"
  26. function format(buffer)
  27. local len = string.len( buffer )
  28. for i = 1, len, 16 do
  29. local text = ""
  30. for j = i, math.min( i + 16 - 1, len ) do
  31. text = string.format( "%s %02x", text, string.byte( buffer, j ) )
  32. end
  33. print( text )
  34. end
  35. end
  36. local FieldDescriptor = descriptor.FieldDescriptor
  37. msg_format_indent = function(write, msg, indent)
  38. for field, value in msg:ListFields() do
  39. local print_field = function(field_value)
  40. local name = field.name
  41. write(string.rep(" ", indent))
  42. if field.type == FieldDescriptor.TYPE_MESSAGE then
  43. local extensions = getmetatable(msg)._extensions_by_name
  44. if extensions[field.full_name] then
  45. write("[" .. name .. "] {\n")
  46. else
  47. write(name .. " {\n")
  48. end
  49. msg_format_indent(write, field_value, indent + 4)
  50. write(string.rep(" ", indent))
  51. write("}\n")
  52. else
  53. write(string.format("%s: %s\n", name, tostring(field_value)))
  54. end
  55. end
  56. if field.label == FieldDescriptor.LABEL_REPEATED then
  57. for _, k in ipairs(value) do
  58. print_field(k)
  59. end
  60. else
  61. print_field(value)
  62. end
  63. end
  64. end
  65. function msg_format(msg)
  66. local out = {}
  67. local write = function(value)
  68. out[#out + 1] = value
  69. end
  70. msg_format_indent(write, msg, 0)
  71. return table.concat(out)
  72. end