An open API service indexing awesome lists of open source software.

https://github.com/avakar/grope

Generalized rope data structure for Python
https://github.com/avakar/grope

Last synced: about 2 months ago
JSON representation

Generalized rope data structure for Python

Awesome Lists containing this project

README

        

# grope

[![Build Status](https://travis-ci.org/avakar/grope.svg?branch=master)](https://travis-ci.org/avakar/grope)
[![PyPI](https://img.shields.io/pypi/v/grope.svg)](https://pypi.python.org/pypi/grope)
[![Coverage Status](https://coveralls.io/repos/github/avakar/grope/badge.svg?branch=master)](https://coveralls.io/github/avakar/grope?branch=master)

An implementation of a generalized rope data structure for Python.

## Installation

Install from PyPI.

pip install grope

Requires Python 2.7+ or Python 3.4+.

## Getting started

The library defines a new type object, `rope`. Ropes are efficient concatenations
of strings. Whereas `s + t` is a linear operation over the length of the strings
`s` and `t`, constructing the rope `rope(s, t)` is logarithmic.

Otherwise, ropes behave like normal strings, in that they are immutable,
can be indexed, sliced and iterated over.

from grope import rope

r = rope('Tirion', ' ', 'Fordring')

assert len(r) == len('Tirion Fordring')
assert r[0] == 'T'
assert r[5] == 'n'
assert r[7] == 'F'

assert ''.join(r) == 'Tirion Fordring'

# Equivalent to the previous expression, but faster
assert str(r) == 'Tirion Fordring'

When we say *string*, we actually mean any object `s` that

* is immutable,
* has a length (`len(s)`),
* can be sliced without stride (`s[i:j]`),
* optionally can be indexed (`s[i]`), and
* optionally can be iterated over.

Such objects include those of type `str`, `bytes`, `unicode`, and `tuple`.
Additionally, `rope` objects are also considered strings in this context.
As such, ropes can be nested.

r2 = rope(r, " says to put one's faith in the light")
assert str(r) == "Tirion Fordring says to put one's faith in the light"

Ropes will only be indexable if all contained strings are indexable. Similarly,
iteration will only work if the contained strings are iterable.

## Rope I/O

Any readable file can be converted to a rope using `wrap_io`. The contents
of the file will not be physically present in memory, instead, they will
be selectively read from the file on demand.

You can efficiently (as in with bounded memory requirements) write a rope that
contains only `bytes` objects with `grope.dump`.

import grope
from grope import rope

with open('input.bin', 'rb') as fin:
r = grope.wrap_io(fin)

# recompute checksum at index 0x10
chksum = _checksum(rope(r[:0x10], b'\0\0\0\0', r[0x14:]))
r = rope(r[:0x10], struct.pack('