Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/prison/encoder.py: 27%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

97 statements  

1import re 

2 

3from six import string_types 

4 

5from .utils import quote 

6from .constants import ID_OK_RE 

7 

8 

9class Encoder(object): 

10 

11 def __init__(self): 

12 pass 

13 

14 @staticmethod 

15 def encoder(v): 

16 if isinstance(v, list): 

17 return Encoder.list 

18 elif isinstance(v, string_types): 

19 return Encoder.string 

20 elif isinstance(v, bool): 

21 return Encoder.bool 

22 elif isinstance(v, (float, int)): 

23 return Encoder.number 

24 elif isinstance(v, type(None)): 

25 return Encoder.none 

26 elif isinstance(v, dict): 

27 return Encoder.dict 

28 else: 

29 raise AssertionError('Unable to encode type: {0}'.format(type(v))) 

30 

31 @staticmethod 

32 def encode(v): 

33 encoder = Encoder.encoder(v) 

34 return encoder(v) 

35 

36 @staticmethod 

37 def list(x): 

38 a = ['!('] 

39 b = None 

40 for i in range(len(x)): 

41 v = x[i] 

42 f = Encoder.encoder(v) 

43 if f: 

44 v = f(v) 

45 if isinstance(v, string_types): 

46 if b: 

47 a.append(',') 

48 a.append(v) 

49 b = True 

50 a.append(')') 

51 return ''.join(a) 

52 

53 @staticmethod 

54 def number(v): 

55 return str(v).replace('+', '') 

56 

57 @staticmethod 

58 def none(_): 

59 return '!n' 

60 

61 @staticmethod 

62 def bool(v): 

63 return '!t' if v else '!f' 

64 

65 @staticmethod 

66 def string(v): 

67 if v == '': 

68 return "''" 

69 

70 if ID_OK_RE.match(v): 

71 return v 

72 

73 def replace(match): 

74 if match.group(0) in ["'", '!']: 

75 return '!' + match.group(0) 

76 return match.group(0) 

77 

78 v = re.sub(r'([\'!])', replace, v) 

79 

80 return "'" + v + "'" 

81 

82 @staticmethod 

83 def dict(x): 

84 a = ['('] 

85 b = None 

86 ks = sorted(x.keys()) 

87 for i in ks: 

88 v = x[i] 

89 f = Encoder.encoder(v) 

90 if f: 

91 v = f(v) 

92 if isinstance(v, string_types): 

93 if b: 

94 a.append(',') 

95 a.append(Encoder.string(i)) 

96 a.append(':') 

97 a.append(v) 

98 b = True 

99 

100 a.append(')') 

101 return ''.join(a) 

102 

103 

104def encode_array(v): 

105 if not isinstance(v, list): 

106 raise AssertionError('encode_array expects a list argument') 

107 r = dumps(v) 

108 return r[2, len(r)-1] 

109 

110 

111def encode_object(v): 

112 if not isinstance(v, dict) or v is None or isinstance(v, list): 

113 raise AssertionError('encode_object expects an dict argument') 

114 r = dumps(v) 

115 return r[1, len(r)-1] 

116 

117 

118def encode_uri(v): 

119 return quote(dumps(v)) 

120 

121 

122def dumps(string): 

123 return Encoder.encode(string)