diff options
| author | prettyboy <[email protected]> | 2022-12-27 22:16:38 +0300 | 
|---|---|---|
| committer | prettyboy <[email protected]> | 2022-12-27 22:16:38 +0300 | 
| commit | ec1f04b090c6fe1f12ee28b92c680006da5c58f1 (patch) | |
| tree | e2853db3d76e725867da74ec6a941c3abe96a439 /library/python/strings/strings.py | |
| parent | d51beecd387a655ea5c2031f7a8b3e5bde77f22b (diff) | |
[devtools/ya/yalibrary/formatter] Moved string method to library/python/strings
Diffstat (limited to 'library/python/strings/strings.py')
| -rw-r--r-- | library/python/strings/strings.py | 37 | 
1 files changed, 37 insertions, 0 deletions
| diff --git a/library/python/strings/strings.py b/library/python/strings/strings.py index 916ae967429..07b7fc194fb 100644 --- a/library/python/strings/strings.py +++ b/library/python/strings/strings.py @@ -136,3 +136,40 @@ def encode(value, encoding=DEFAULT_ENCODING):      if isinstance(value, six.binary_type):          value = value.decode(encoding, errors='ignore')      return value.encode(encoding) + + +class Whence(object): +    Start = 0 +    End = 1 +    Middle = 2 + + +def truncate(data, limit, whence=None, msg=None): +    msg = "..." if msg is None else msg +    msg = six.ensure_binary(msg) +    whence = Whence.End if whence is None else whence +    data = six.ensure_binary(data) + +    if len(data) <= limit: +        return six.ensure_str(data) +    text_limit = limit - len(msg) +    assert text_limit >= 0 + +    if whence == Whence.Start: +        data = msg + data[-text_limit:] +    elif whence == Whence.End: +        data = data[:text_limit] + msg +    elif whence == Whence.Middle: +        headpos = limit // 2 - len(msg) // 2 +        tailpos = len(data) - (text_limit - headpos) +        data = data[:headpos] + msg + data[tailpos:] +    else: +        raise AssertionError("Unknown whence: %s" % str(whence)) +    return fix_utf8(data) + + +def fix_utf8(data): +    # type: (six.string_types) -> str +    # remove destroyed symbol code +    udata = six.ensure_text(data, 'utf-8', 'ignore') +    return six.ensure_str(udata, 'utf-8', errors='ignore') | 
