ffindex.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env python
  2. '''
  3. Created on Apr 30, 2014
  4. @author: meiermark
  5. '''
  6. import mmap
  7. from collections import namedtuple
  8. FFindexEntry = namedtuple("FFindexEntry", "name, offset, length")
  9. def read_index(ffindex_filename):
  10. entries = []
  11. fh = open(ffindex_filename)
  12. for line in fh:
  13. tokens = line.split("\t")
  14. entries.append(FFindexEntry(tokens[0], int(tokens[1]), int(tokens[2])))
  15. fh.close()
  16. return entries
  17. def read_data(ffdata_filename):
  18. fh = open(ffdata_filename, "r")
  19. data = mmap.mmap(fh.fileno(), 0, prot=mmap.PROT_READ)
  20. fh.close()
  21. return data
  22. def get_entry_by_name(name, index):
  23. #TODO: bsearch
  24. for entry in index:
  25. if(name == entry.name):
  26. return entry
  27. return None
  28. def read_lines(entry, data):
  29. lines = data[entry.offset:entry.offset + entry.length - 1].decode("utf-8").split("\n")
  30. return lines
  31. def read_entry_data(entry, data):
  32. return data[entry.offset:entry.offset + entry.length - 1]
  33. def write_entry(entries, data_fh, entry_name, offset, data):
  34. data_fh.write(data[:-1])
  35. data_fh.write(bytearray(1))
  36. entry = FFindexEntry(entry_name, offset, len(data))
  37. entries.append(entry)
  38. return offset + len(data)
  39. def write_entry_with_file(entries, data_fh, entry_name, offset, file_name):
  40. with open(file_name, "rb") as fh:
  41. data = bytearray(fh.read())
  42. return write_entry(entries, data_fh, entry_name, offset, data)
  43. def finish_db(entries, ffindex_filename, data_fh):
  44. data_fh.close()
  45. write_entries_to_db(entries, ffindex_filename)
  46. def write_entries_to_db(entries, ffindex_filename):
  47. sorted(entries, key=lambda x: x.name)
  48. index_fh = open(ffindex_filename, "w")
  49. for entry in entries:
  50. index_fh.write("{name:.64}\t{offset}\t{length}\n".format(name=entry.name, offset=entry.offset, length=entry.length))
  51. index_fh.close()
  52. def write_entry_to_file(entry, data, file):
  53. lines = read_lines(entry, data)
  54. fh = open(file, "w")
  55. for line in lines:
  56. fh.write(line+"\n")
  57. fh.close()