Verified Commit 0917055b authored by Dmitry Volodin's avatar Dmitry Volodin
Browse files

Cleanup noc.core.comp bord/bchr/make_bytes functions

parent fd914ac6
......@@ -6,9 +6,6 @@
# See LICENSE for details
# ----------------------------------------------------------------------
# Third-party modules
from typing import List
DEFAULT_ENCODING = "utf-8"
......@@ -34,18 +31,6 @@ def smart_text(s, errors="strict", encoding=DEFAULT_ENCODING):
return str(s)
def bord(x: int) -> int:
return x
def bchr(x: int) -> bytes:
return bytes([x])
def make_bytes(x: List[int]) -> bytes:
return bytes(x)
def reraise(tp, value, tb=None):
try:
if value is None:
......
......@@ -14,7 +14,7 @@ import hashlib
from typing import Optional
# NOC modules
from noc.core.comp import smart_bytes, bord, bchr, make_bytes
from noc.core.comp import smart_bytes
# Symbols used in salt
ITOA64 = b"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
......@@ -28,7 +28,7 @@ def gen_salt(salt_len):
>>> len(gen_salt(10)) == 10
True
"""
return make_bytes([random.choice(SALT_SYMBOLS) for _ in range(salt_len)])
return bytes([random.choice(SALT_SYMBOLS) for _ in range(salt_len)])
def md5crypt(password: bytes, salt: Optional[bytes] = None, magic: bytes = b"$1$") -> bytes:
......@@ -50,7 +50,7 @@ def md5crypt(password: bytes, salt: Optional[bytes] = None, magic: bytes = b"$1$
# /* Then just as many characters of the MD5(pw,salt,pw) */
mixin = hashlib.md5(smart_bytes(password + salt + password)).digest()
for i in range(len(password)):
m.update(bchr(mixin[i % 16]))
m.update(bytes([mixin[i % 16]]))
# /* Then something really weird... */
# Also really broken, as far as I can tell. -m
i = len(password)
......@@ -58,7 +58,7 @@ def md5crypt(password: bytes, salt: Optional[bytes] = None, magic: bytes = b"$1$
if i & 1:
m.update(b"\x00")
else:
m.update(bchr(password[0]))
m.update(bytes([password[0]]))
i >>= 1
final = m.digest()
# /* and now, just to make sure things don't run too fast */
......@@ -80,12 +80,12 @@ def md5crypt(password: bytes, salt: Optional[bytes] = None, magic: bytes = b"$1$
# This is the bit that uses to64() in the original code.
rearranged = []
for a, b, c in REARRANGED_BITS:
v = bord(final[a]) << 16 | bord(final[b]) << 8 | bord(final[c])
v = final[a] << 16 | final[b] << 8 | final[c]
for i in range(4):
rearranged += [ITOA64[v & 0x3F]]
v >>= 6
v = bord(final[11])
v = final[11]
for i in range(2):
rearranged += [ITOA64[v & 0x3F]]
v >>= 6
return magic + salt + b"$" + make_bytes(rearranged)
return magic + salt + b"$" + bytes(rearranged)
......@@ -28,7 +28,7 @@ from noc.core.text import replace_re_group
from noc.config import config
from noc.core.span import Span
from noc.core.perf import metrics
from noc.core.comp import smart_bytes, smart_text, bchr
from noc.core.comp import smart_bytes, smart_text
from .error import (
CLIError,
CLIAuthFailed,
......@@ -707,7 +707,7 @@ class CLI(object):
if v:
k = smart_bytes(k)
if k == b"hostname" and sl and len(v) > sl:
ss = [bchr(x) for x in reversed(v[sl:])]
ss = [bytes([x]) for x in reversed(v[sl:])]
v = re.escape(v[:sl]) + reduce(
lambda x, y: b"(?:%s%s)?" % (re.escape(y), x),
ss[1:],
......
......@@ -17,7 +17,6 @@ from typing import List, Optional
# NOC modules
from noc.core.perf import metrics
from noc.core.comp import bord
from .base import CLI
_logger = logging.getLogger(__name__)
......@@ -145,7 +144,7 @@ class TelnetParser(object):
# Collect for next round
self.iac_seq = B_IAC + right
break
ctl = bord(right[0])
ctl = right[0]
if ctl == IAC:
# <IAC> <IAC> leads to single <IAC>
r += [B_IAC]
......@@ -155,7 +154,7 @@ class TelnetParser(object):
chunk = right[1:]
elif ctl != SB:
# Process IAC <cmd> <opt>
self.process_iac(ctl, bord(right[1]))
self.process_iac(ctl, right[1])
chunk = right[2:]
else:
# Process IAC SB ... SE sequence
......
......@@ -14,7 +14,7 @@ import struct
from typing import Tuple, Any, List, Optional
# NOC modules
from noc.core.comp import bord, smart_bytes, smart_text
from noc.core.comp import smart_bytes, smart_text
from noc.speedup.ber import parse_tlv_header, parse_p_oid, encode_int, encode_oid
from noc.core.mib import mib
......@@ -72,7 +72,7 @@ class BERDecoder(object):
def parse_boolean(self, msg: bytes) -> bool:
if not msg:
return False
return bool(bord(msg[0]))
return bool(msg[0])
INT_MASK = {
1: struct.Struct("!b"),
......@@ -112,8 +112,8 @@ class BERDecoder(object):
# Decode as is
v = 0
for c in msg:
v = (v << 8) + bord(c)
if bord(msg[0]) & 0x80:
v = (v << 8) + c
if msg[0] & 0x80:
# Negative number
m = 1 << (8 * len(msg))
v -= m
......@@ -124,7 +124,7 @@ class BERDecoder(object):
"""
if not msg:
return 0.0
f = bord(msg[0])
f = msg[0]
if f & 0x80: # Binary encoding, 8.5.6
# @todo: Снести в конец
base = {0x00: 2, 0x10: 4, 0x20: 16}[f & 0x30] # 8.5.6.2
......@@ -150,8 +150,8 @@ class BERDecoder(object):
raise ValueError("Unknown REAL encoding: %s" % f)
def parse_p_bitstring(self, msg: bytes) -> bytes:
unused = bord(msg[0])
r = b"".join(BITSTING[bord(c)] for c in msg)
unused = msg[0]
r = b"".join(BITSTING[c] for c in msg)
if unused:
r = r[:-unused]
return r
......@@ -184,7 +184,7 @@ class BERDecoder(object):
def parse_a_ipaddress(self, msg: bytes) -> str:
if not msg:
raise ValueError("Invalid IP Address: '%s'" % msg.encode("hex"))
return "%d.%d.%d.%d" % (bord(msg[0]), bord(msg[1]), bord(msg[2]), bord(msg[3]))
return "%d.%d.%d.%d" % (msg[0], msg[1], msg[2], msg[3])
def parse_p_oid(self, msg: bytes) -> str:
"""
......@@ -199,8 +199,8 @@ class BERDecoder(object):
:param msg:
:return:
"""
pos = bord(msg[0]) - 1
parts = self.last_oid.split(".")[:pos] + [str(bord(d)) for d in msg[1:]]
pos = msg[0] - 1
parts = self.last_oid.split(".")[:pos] + [str(d) for d in msg[1:]]
self.last_oid = ".".join(parts)
return smart_text(self.last_oid)
......@@ -402,7 +402,7 @@ class BEREncoder(object):
comp <<= 8
r = self.struct_Q.pack(comp - data).lstrip(b"\x00")
if r:
r = self.struct_B.pack(bord(r[0]) | 0x80) + r[1:]
r = self.struct_B.pack(r[0] | 0x80) + r[1:]
else:
r = b"\x80" + b"\x00" * (ln - 1)
return self.encode_tlv(2, True, r)
......
......@@ -10,7 +10,7 @@
from typing import Optional, Callable
# NOC modules
from noc.core.comp import smart_text, bord
from noc.core.comp import smart_text
def render_bin(oid: str, value: bytes) -> bytes:
......@@ -65,7 +65,7 @@ def render_mac(oid: str, value: bytes) -> str:
"""
if len(value) != 6:
return ""
return "%02X:%02X:%02X:%02X:%02X:%02X" % tuple(bord(x) for x in value)
return "%02X:%02X:%02X:%02X:%02X:%02X" % tuple(value)
def get_string_renderer(v: str) -> Callable[[str, bytes], str]:
......
......@@ -13,7 +13,7 @@ import re
from typing import Any, Optional, Union
# NOC modules
from noc.core.comp import smart_text, bord
from noc.core.comp import smart_text
rx_os_format = re.compile(
......@@ -49,7 +49,7 @@ def render_tc_int(value: int, format: str) -> str:
def render_tc_octetstring(value, format: Union[bytes, str]) -> str:
if isinstance(value, bytes):
value = [bord(c) for c in value]
value = list(value)
else:
value = [ord(c) for c in value]
r = ""
......
......@@ -14,9 +14,6 @@ from itertools import zip_longest
from numpy import array
from typing import List, Union, Iterable
# NOC modules
from noc.core.comp import bord
rx_header_start = re.compile(r"^\s*[-=]+[\s\+]+[-=]+")
rx_col = re.compile(r"^([\s\+]*)([\-]+|[=]+)")
......@@ -331,7 +328,7 @@ def _replace_re_group_binary(expr: bytes, group: bytes, pattern: bytes) -> bytes
expr = expr[idx + lg :]
level = 1 # Level of parenthesis nesting
while expr:
c = bord(expr[0])
c = expr[0]
expr = expr[1:]
if c == 0x5C: # "\\"
# Skip quoted character
......
......@@ -10,7 +10,7 @@
import pytest
# NOC modules
from noc.core.comp import smart_bytes, smart_text, bord
from noc.core.comp import smart_bytes, smart_text
def bin(s):
......@@ -51,8 +51,3 @@ def test_smart_bytes(input, expected):
v = smart_bytes(input)
assert isinstance(v, bytes)
assert v == expected
@pytest.mark.parametrize("input,expected", [(b"\x00", 0), (b"\x01", 1), (b"\x10", 16)])
def test_bord(input, expected):
assert bord(input[0]) == expected
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment