fun.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. # Copyright (C) 2010, 2011 Sebastian Thiel (byronimo@gmail.com) and contributors
  2. #
  3. # This module is part of GitDB and is released under
  4. # the New BSD License: http://www.opensource.org/licenses/bsd-license.php
  5. """Contains basic c-functions which usually contain performance critical code
  6. Keeping this code separate from the beginning makes it easier to out-source
  7. it into c later, if required"""
  8. import zlib
  9. from gitdb.util import byte_ord
  10. decompressobj = zlib.decompressobj
  11. import mmap
  12. from itertools import islice
  13. from functools import reduce
  14. from gitdb.const import NULL_BYTE, BYTE_SPACE
  15. from gitdb.utils.encoding import force_text
  16. from gitdb.typ import (
  17. str_blob_type,
  18. str_commit_type,
  19. str_tree_type,
  20. str_tag_type,
  21. )
  22. from io import StringIO
  23. # INVARIANTS
  24. OFS_DELTA = 6
  25. REF_DELTA = 7
  26. delta_types = (OFS_DELTA, REF_DELTA)
  27. type_id_to_type_map = {
  28. 0: b'', # EXT 1
  29. 1: str_commit_type,
  30. 2: str_tree_type,
  31. 3: str_blob_type,
  32. 4: str_tag_type,
  33. 5: b'', # EXT 2
  34. OFS_DELTA: "OFS_DELTA", # OFFSET DELTA
  35. REF_DELTA: "REF_DELTA" # REFERENCE DELTA
  36. }
  37. type_to_type_id_map = {
  38. str_commit_type: 1,
  39. str_tree_type: 2,
  40. str_blob_type: 3,
  41. str_tag_type: 4,
  42. "OFS_DELTA": OFS_DELTA,
  43. "REF_DELTA": REF_DELTA,
  44. }
  45. # used when dealing with larger streams
  46. chunk_size = 1000 * mmap.PAGESIZE
  47. __all__ = ('is_loose_object', 'loose_object_header_info', 'msb_size', 'pack_object_header_info',
  48. 'write_object', 'loose_object_header', 'stream_copy', 'apply_delta_data',
  49. 'is_equal_canonical_sha', 'connect_deltas', 'DeltaChunkList', 'create_pack_object_header')
  50. #{ Structures
  51. def _set_delta_rbound(d, size):
  52. """Truncate the given delta to the given size
  53. :param size: size relative to our target offset, may not be 0, must be smaller or equal
  54. to our size
  55. :return: d"""
  56. d.ts = size
  57. # NOTE: data is truncated automatically when applying the delta
  58. # MUST NOT DO THIS HERE
  59. return d
  60. def _move_delta_lbound(d, bytes):
  61. """Move the delta by the given amount of bytes, reducing its size so that its
  62. right bound stays static
  63. :param bytes: amount of bytes to move, must be smaller than delta size
  64. :return: d"""
  65. if bytes == 0:
  66. return
  67. d.to += bytes
  68. d.so += bytes
  69. d.ts -= bytes
  70. if d.data is not None:
  71. d.data = d.data[bytes:]
  72. # END handle data
  73. return d
  74. def delta_duplicate(src):
  75. return DeltaChunk(src.to, src.ts, src.so, src.data)
  76. def delta_chunk_apply(dc, bbuf, write):
  77. """Apply own data to the target buffer
  78. :param bbuf: buffer providing source bytes for copy operations
  79. :param write: write method to call with data to write"""
  80. if dc.data is None:
  81. # COPY DATA FROM SOURCE
  82. write(bbuf[dc.so:dc.so + dc.ts])
  83. else:
  84. # APPEND DATA
  85. # what's faster: if + 4 function calls or just a write with a slice ?
  86. # Considering data can be larger than 127 bytes now, it should be worth it
  87. if dc.ts < len(dc.data):
  88. write(dc.data[:dc.ts])
  89. else:
  90. write(dc.data)
  91. # END handle truncation
  92. # END handle chunk mode
  93. class DeltaChunk:
  94. """Represents a piece of a delta, it can either add new data, or copy existing
  95. one from a source buffer"""
  96. __slots__ = (
  97. 'to', # start offset in the target buffer in bytes
  98. 'ts', # size of this chunk in the target buffer in bytes
  99. 'so', # start offset in the source buffer in bytes or None
  100. 'data', # chunk of bytes to be added to the target buffer,
  101. # DeltaChunkList to use as base, or None
  102. )
  103. def __init__(self, to, ts, so, data):
  104. self.to = to
  105. self.ts = ts
  106. self.so = so
  107. self.data = data
  108. def __repr__(self):
  109. return "DeltaChunk(%i, %i, %s, %s)" % (self.to, self.ts, self.so, self.data or "")
  110. #{ Interface
  111. def rbound(self):
  112. return self.to + self.ts
  113. def has_data(self):
  114. """:return: True if the instance has data to add to the target stream"""
  115. return self.data is not None
  116. #} END interface
  117. def _closest_index(dcl, absofs):
  118. """:return: index at which the given absofs should be inserted. The index points
  119. to the DeltaChunk with a target buffer absofs that equals or is greater than
  120. absofs.
  121. **Note:** global method for performance only, it belongs to DeltaChunkList"""
  122. lo = 0
  123. hi = len(dcl)
  124. while lo < hi:
  125. mid = (lo + hi) / 2
  126. dc = dcl[mid]
  127. if dc.to > absofs:
  128. hi = mid
  129. elif dc.rbound() > absofs or dc.to == absofs:
  130. return mid
  131. else:
  132. lo = mid + 1
  133. # END handle bound
  134. # END for each delta absofs
  135. return len(dcl) - 1
  136. def delta_list_apply(dcl, bbuf, write):
  137. """Apply the chain's changes and write the final result using the passed
  138. write function.
  139. :param bbuf: base buffer containing the base of all deltas contained in this
  140. list. It will only be used if the chunk in question does not have a base
  141. chain.
  142. :param write: function taking a string of bytes to write to the output"""
  143. for dc in dcl:
  144. delta_chunk_apply(dc, bbuf, write)
  145. # END for each dc
  146. def delta_list_slice(dcl, absofs, size, ndcl):
  147. """:return: Subsection of this list at the given absolute offset, with the given
  148. size in bytes.
  149. :return: None"""
  150. cdi = _closest_index(dcl, absofs) # delta start index
  151. cd = dcl[cdi]
  152. slen = len(dcl)
  153. lappend = ndcl.append
  154. if cd.to != absofs:
  155. tcd = DeltaChunk(cd.to, cd.ts, cd.so, cd.data)
  156. _move_delta_lbound(tcd, absofs - cd.to)
  157. tcd.ts = min(tcd.ts, size)
  158. lappend(tcd)
  159. size -= tcd.ts
  160. cdi += 1
  161. # END lbound overlap handling
  162. while cdi < slen and size:
  163. # are we larger than the current block
  164. cd = dcl[cdi]
  165. if cd.ts <= size:
  166. lappend(DeltaChunk(cd.to, cd.ts, cd.so, cd.data))
  167. size -= cd.ts
  168. else:
  169. tcd = DeltaChunk(cd.to, cd.ts, cd.so, cd.data)
  170. tcd.ts = size
  171. lappend(tcd)
  172. size -= tcd.ts
  173. break
  174. # END hadle size
  175. cdi += 1
  176. # END for each chunk
  177. class DeltaChunkList(list):
  178. """List with special functionality to deal with DeltaChunks.
  179. There are two types of lists we represent. The one was created bottom-up, working
  180. towards the latest delta, the other kind was created top-down, working from the
  181. latest delta down to the earliest ancestor. This attribute is queryable
  182. after all processing with is_reversed."""
  183. __slots__ = tuple()
  184. def rbound(self):
  185. """:return: rightmost extend in bytes, absolute"""
  186. if len(self) == 0:
  187. return 0
  188. return self[-1].rbound()
  189. def lbound(self):
  190. """:return: leftmost byte at which this chunklist starts"""
  191. if len(self) == 0:
  192. return 0
  193. return self[0].to
  194. def size(self):
  195. """:return: size of bytes as measured by our delta chunks"""
  196. return self.rbound() - self.lbound()
  197. def apply(self, bbuf, write):
  198. """Only used by public clients, internally we only use the global routines
  199. for performance"""
  200. return delta_list_apply(self, bbuf, write)
  201. def compress(self):
  202. """Alter the list to reduce the amount of nodes. Currently we concatenate
  203. add-chunks
  204. :return: self"""
  205. slen = len(self)
  206. if slen < 2:
  207. return self
  208. i = 0
  209. first_data_index = None
  210. while i < slen:
  211. dc = self[i]
  212. i += 1
  213. if dc.data is None:
  214. if first_data_index is not None and i - 2 - first_data_index > 1:
  215. # if first_data_index is not None:
  216. nd = StringIO() # new data
  217. so = self[first_data_index].to # start offset in target buffer
  218. for x in range(first_data_index, i - 1):
  219. xdc = self[x]
  220. nd.write(xdc.data[:xdc.ts])
  221. # END collect data
  222. del(self[first_data_index:i - 1])
  223. buf = nd.getvalue()
  224. self.insert(first_data_index, DeltaChunk(so, len(buf), 0, buf))
  225. slen = len(self)
  226. i = first_data_index + 1
  227. # END concatenate data
  228. first_data_index = None
  229. continue
  230. # END skip non-data chunks
  231. if first_data_index is None:
  232. first_data_index = i - 1
  233. # END iterate list
  234. # if slen_orig != len(self):
  235. # print "INFO: Reduced delta list len to %f %% of former size" % ((float(len(self)) / slen_orig) * 100)
  236. return self
  237. def check_integrity(self, target_size=-1):
  238. """Verify the list has non-overlapping chunks only, and the total size matches
  239. target_size
  240. :param target_size: if not -1, the total size of the chain must be target_size
  241. :raise AssertionError: if the size doesn't match"""
  242. if target_size > -1:
  243. assert self[-1].rbound() == target_size
  244. assert reduce(lambda x, y: x + y, (d.ts for d in self), 0) == target_size
  245. # END target size verification
  246. if len(self) < 2:
  247. return
  248. # check data
  249. for dc in self:
  250. assert dc.ts > 0
  251. if dc.has_data():
  252. assert len(dc.data) >= dc.ts
  253. # END for each dc
  254. left = islice(self, 0, len(self) - 1)
  255. right = iter(self)
  256. right.next()
  257. # this is very pythonic - we might have just use index based access here,
  258. # but this could actually be faster
  259. for lft, rgt in zip(left, right):
  260. assert lft.rbound() == rgt.to
  261. assert lft.to + lft.ts == rgt.to
  262. # END for each pair
  263. class TopdownDeltaChunkList(DeltaChunkList):
  264. """Represents a list which is generated by feeding its ancestor streams one by
  265. one"""
  266. __slots__ = tuple()
  267. def connect_with_next_base(self, bdcl):
  268. """Connect this chain with the next level of our base delta chunklist.
  269. The goal in this game is to mark as many of our chunks rigid, hence they
  270. cannot be changed by any of the upcoming bases anymore. Once all our
  271. chunks are marked like that, we can stop all processing
  272. :param bdcl: data chunk list being one of our bases. They must be fed in
  273. consecutively and in order, towards the earliest ancestor delta
  274. :return: True if processing was done. Use it to abort processing of
  275. remaining streams if False is returned"""
  276. nfc = 0 # number of frozen chunks
  277. dci = 0 # delta chunk index
  278. slen = len(self) # len of self
  279. ccl = list() # temporary list
  280. while dci < slen:
  281. dc = self[dci]
  282. dci += 1
  283. # all add-chunks which are already topmost don't need additional processing
  284. if dc.data is not None:
  285. nfc += 1
  286. continue
  287. # END skip add chunks
  288. # copy chunks
  289. # integrate the portion of the base list into ourselves. Lists
  290. # dont support efficient insertion ( just one at a time ), but for now
  291. # we live with it. Internally, its all just a 32/64bit pointer, and
  292. # the portions of moved memory should be smallish. Maybe we just rebuild
  293. # ourselves in order to reduce the amount of insertions ...
  294. del(ccl[:])
  295. delta_list_slice(bdcl, dc.so, dc.ts, ccl)
  296. # move the target bounds into place to match with our chunk
  297. ofs = dc.to - dc.so
  298. for cdc in ccl:
  299. cdc.to += ofs
  300. # END update target bounds
  301. if len(ccl) == 1:
  302. self[dci - 1] = ccl[0]
  303. else:
  304. # maybe try to compute the expenses here, and pick the right algorithm
  305. # It would normally be faster than copying everything physically though
  306. # TODO: Use a deque here, and decide by the index whether to extend
  307. # or extend left !
  308. post_dci = self[dci:]
  309. del(self[dci - 1:]) # include deletion of dc
  310. self.extend(ccl)
  311. self.extend(post_dci)
  312. slen = len(self)
  313. dci += len(ccl) - 1 # deleted dc, added rest
  314. # END handle chunk replacement
  315. # END for each chunk
  316. if nfc == slen:
  317. return False
  318. # END handle completeness
  319. return True
  320. #} END structures
  321. #{ Routines
  322. def is_loose_object(m):
  323. """
  324. :return: True the file contained in memory map m appears to be a loose object.
  325. Only the first two bytes are needed"""
  326. b0, b1 = map(ord, m[:2])
  327. word = (b0 << 8) + b1
  328. return b0 == 0x78 and (word % 31) == 0
  329. def loose_object_header_info(m):
  330. """
  331. :return: tuple(type_string, uncompressed_size_in_bytes) the type string of the
  332. object as well as its uncompressed size in bytes.
  333. :param m: memory map from which to read the compressed object data"""
  334. decompress_size = 8192 # is used in cgit as well
  335. hdr = decompressobj().decompress(m, decompress_size)
  336. type_name, size = hdr[:hdr.find(NULL_BYTE)].split(BYTE_SPACE)
  337. return type_name, int(size)
  338. def pack_object_header_info(data):
  339. """
  340. :return: tuple(type_id, uncompressed_size_in_bytes, byte_offset)
  341. The type_id should be interpreted according to the ``type_id_to_type_map`` map
  342. The byte-offset specifies the start of the actual zlib compressed datastream
  343. :param m: random-access memory, like a string or memory map"""
  344. c = byte_ord(data[0]) # first byte
  345. i = 1 # next char to read
  346. type_id = (c >> 4) & 7 # numeric type
  347. size = c & 15 # starting size
  348. s = 4 # starting bit-shift size
  349. while c & 0x80:
  350. c = byte_ord(data[i])
  351. i += 1
  352. size += (c & 0x7f) << s
  353. s += 7
  354. # END character loop
  355. # end performance at expense of maintenance ...
  356. return (type_id, size, i)
  357. def create_pack_object_header(obj_type, obj_size):
  358. """
  359. :return: string defining the pack header comprised of the object type
  360. and its incompressed size in bytes
  361. :param obj_type: pack type_id of the object
  362. :param obj_size: uncompressed size in bytes of the following object stream"""
  363. c = 0 # 1 byte
  364. hdr = bytearray() # output string
  365. c = (obj_type << 4) | (obj_size & 0xf)
  366. obj_size >>= 4
  367. while obj_size:
  368. hdr.append(c | 0x80)
  369. c = obj_size & 0x7f
  370. obj_size >>= 7
  371. # END until size is consumed
  372. hdr.append(c)
  373. # end handle interpreter
  374. return hdr
  375. def msb_size(data, offset=0):
  376. """
  377. :return: tuple(read_bytes, size) read the msb size from the given random
  378. access data starting at the given byte offset"""
  379. size = 0
  380. i = 0
  381. l = len(data)
  382. hit_msb = False
  383. while i < l:
  384. c = data[i + offset]
  385. size |= (c & 0x7f) << i * 7
  386. i += 1
  387. if not c & 0x80:
  388. hit_msb = True
  389. break
  390. # END check msb bit
  391. # END while in range
  392. # end performance ...
  393. if not hit_msb:
  394. raise AssertionError("Could not find terminating MSB byte in data stream")
  395. return i + offset, size
  396. def loose_object_header(type, size):
  397. """
  398. :return: bytes representing the loose object header, which is immediately
  399. followed by the content stream of size 'size'"""
  400. return ('%s %i\0' % (force_text(type), size)).encode('ascii')
  401. def write_object(type, size, read, write, chunk_size=chunk_size):
  402. """
  403. Write the object as identified by type, size and source_stream into the
  404. target_stream
  405. :param type: type string of the object
  406. :param size: amount of bytes to write from source_stream
  407. :param read: read method of a stream providing the content data
  408. :param write: write method of the output stream
  409. :param close_target_stream: if True, the target stream will be closed when
  410. the routine exits, even if an error is thrown
  411. :return: The actual amount of bytes written to stream, which includes the header and a trailing newline"""
  412. tbw = 0 # total num bytes written
  413. # WRITE HEADER: type SP size NULL
  414. tbw += write(loose_object_header(type, size))
  415. tbw += stream_copy(read, write, size, chunk_size)
  416. return tbw
  417. def stream_copy(read, write, size, chunk_size):
  418. """
  419. Copy a stream up to size bytes using the provided read and write methods,
  420. in chunks of chunk_size
  421. **Note:** its much like stream_copy utility, but operates just using methods"""
  422. dbw = 0 # num data bytes written
  423. # WRITE ALL DATA UP TO SIZE
  424. while True:
  425. cs = min(chunk_size, size - dbw)
  426. # NOTE: not all write methods return the amount of written bytes, like
  427. # mmap.write. Its bad, but we just deal with it ... perhaps its not
  428. # even less efficient
  429. # data_len = write(read(cs))
  430. # dbw += data_len
  431. data = read(cs)
  432. data_len = len(data)
  433. dbw += data_len
  434. write(data)
  435. if data_len < cs or dbw == size:
  436. break
  437. # END check for stream end
  438. # END duplicate data
  439. return dbw
  440. def connect_deltas(dstreams):
  441. """
  442. Read the condensed delta chunk information from dstream and merge its information
  443. into a list of existing delta chunks
  444. :param dstreams: iterable of delta stream objects, the delta to be applied last
  445. comes first, then all its ancestors in order
  446. :return: DeltaChunkList, containing all operations to apply"""
  447. tdcl = None # topmost dcl
  448. dcl = tdcl = TopdownDeltaChunkList()
  449. for dsi, ds in enumerate(dstreams):
  450. # print "Stream", dsi
  451. db = ds.read()
  452. delta_buf_size = ds.size
  453. # read header
  454. i, base_size = msb_size(db)
  455. i, target_size = msb_size(db, i)
  456. # interpret opcodes
  457. tbw = 0 # amount of target bytes written
  458. while i < delta_buf_size:
  459. c = ord(db[i])
  460. i += 1
  461. if c & 0x80:
  462. cp_off, cp_size = 0, 0
  463. if (c & 0x01):
  464. cp_off = ord(db[i])
  465. i += 1
  466. if (c & 0x02):
  467. cp_off |= (ord(db[i]) << 8)
  468. i += 1
  469. if (c & 0x04):
  470. cp_off |= (ord(db[i]) << 16)
  471. i += 1
  472. if (c & 0x08):
  473. cp_off |= (ord(db[i]) << 24)
  474. i += 1
  475. if (c & 0x10):
  476. cp_size = ord(db[i])
  477. i += 1
  478. if (c & 0x20):
  479. cp_size |= (ord(db[i]) << 8)
  480. i += 1
  481. if (c & 0x40):
  482. cp_size |= (ord(db[i]) << 16)
  483. i += 1
  484. if not cp_size:
  485. cp_size = 0x10000
  486. rbound = cp_off + cp_size
  487. if (rbound < cp_size or
  488. rbound > base_size):
  489. break
  490. dcl.append(DeltaChunk(tbw, cp_size, cp_off, None))
  491. tbw += cp_size
  492. elif c:
  493. # NOTE: in C, the data chunks should probably be concatenated here.
  494. # In python, we do it as a post-process
  495. dcl.append(DeltaChunk(tbw, c, 0, db[i:i + c]))
  496. i += c
  497. tbw += c
  498. else:
  499. raise ValueError("unexpected delta opcode 0")
  500. # END handle command byte
  501. # END while processing delta data
  502. dcl.compress()
  503. # merge the lists !
  504. if dsi > 0:
  505. if not tdcl.connect_with_next_base(dcl):
  506. break
  507. # END handle merge
  508. # prepare next base
  509. dcl = DeltaChunkList()
  510. # END for each delta stream
  511. return tdcl
  512. def apply_delta_data(src_buf, src_buf_size, delta_buf, delta_buf_size, write):
  513. """
  514. Apply data from a delta buffer using a source buffer to the target file
  515. :param src_buf: random access data from which the delta was created
  516. :param src_buf_size: size of the source buffer in bytes
  517. :param delta_buf_size: size for the delta buffer in bytes
  518. :param delta_buf: random access delta data
  519. :param write: write method taking a chunk of bytes
  520. **Note:** transcribed to python from the similar routine in patch-delta.c"""
  521. i = 0
  522. db = delta_buf
  523. while i < delta_buf_size:
  524. c = db[i]
  525. i += 1
  526. if c & 0x80:
  527. cp_off, cp_size = 0, 0
  528. if (c & 0x01):
  529. cp_off = db[i]
  530. i += 1
  531. if (c & 0x02):
  532. cp_off |= (db[i] << 8)
  533. i += 1
  534. if (c & 0x04):
  535. cp_off |= (db[i] << 16)
  536. i += 1
  537. if (c & 0x08):
  538. cp_off |= (db[i] << 24)
  539. i += 1
  540. if (c & 0x10):
  541. cp_size = db[i]
  542. i += 1
  543. if (c & 0x20):
  544. cp_size |= (db[i] << 8)
  545. i += 1
  546. if (c & 0x40):
  547. cp_size |= (db[i] << 16)
  548. i += 1
  549. if not cp_size:
  550. cp_size = 0x10000
  551. rbound = cp_off + cp_size
  552. if (rbound < cp_size or
  553. rbound > src_buf_size):
  554. break
  555. write(src_buf[cp_off:cp_off + cp_size])
  556. elif c:
  557. write(db[i:i + c])
  558. i += c
  559. else:
  560. raise ValueError("unexpected delta opcode 0")
  561. # END handle command byte
  562. # END while processing delta data
  563. # yes, lets use the exact same error message that git uses :)
  564. assert i == delta_buf_size, "delta replay has gone wild"
  565. def is_equal_canonical_sha(canonical_length, match, sha1):
  566. """
  567. :return: True if the given lhs and rhs 20 byte binary shas
  568. The comparison will take the canonical_length of the match sha into account,
  569. hence the comparison will only use the last 4 bytes for uneven canonical representations
  570. :param match: less than 20 byte sha
  571. :param sha1: 20 byte sha"""
  572. binary_length = canonical_length // 2
  573. if match[:binary_length] != sha1[:binary_length]:
  574. return False
  575. if canonical_length - binary_length and \
  576. (byte_ord(match[-1]) ^ byte_ord(sha1[len(match) - 1])) & 0xf0:
  577. return False
  578. # END handle uneven canonnical length
  579. return True
  580. #} END routines
  581. try:
  582. from gitdb_speedups._perf import connect_deltas
  583. except ImportError:
  584. pass