Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/validators/encoding.py: 73%

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

15 statements  

1"""Encoding.""" 

2 

3# standard 

4import re 

5 

6# local 

7from .utils import validator 

8 

9 

10@validator 

11def base16(value: str, /): 

12 """Return whether or not given value is a valid base16 encoding. 

13 

14 Each encoded byte requires two hexadecimal characters. 

15 

16 Examples: 

17 >>> base16('a3f4b2') 

18 True 

19 >>> base16('a3f4Z1') 

20 ValidationError(func=base16, args={'value': 'a3f4Z1'}) 

21 

22 Args: 

23 value: 

24 base16 string to validate. 

25 

26 Returns: 

27 (Literal[True]): If `value` is a valid base16 encoding. 

28 (ValidationError): If `value` is an invalid base16 encoding. 

29 """ 

30 return re.fullmatch(r"(?:[0-9A-Fa-f]{2})+", value) if value else False 

31 

32 

33@validator 

34def base32(value: str, /): 

35 """Return whether or not given value is a valid base32 encoding. 

36 

37 Examples: 

38 >>> base32('MFZWIZLTOQ======') 

39 True 

40 >>> base32('MfZW3zLT9Q======') 

41 ValidationError(func=base32, args={'value': 'MfZW3zLT9Q======'}) 

42 

43 Args: 

44 value: 

45 base32 string to validate. 

46 

47 Returns: 

48 (Literal[True]): If `value` is a valid base32 encoding. 

49 (ValidationError): If `value` is an invalid base32 encoding. 

50 """ 

51 return ( 

52 re.fullmatch( 

53 r"(?:[A-Z2-7]{8})*(?:[A-Z2-7]{2}(?:={6})?|[A-Z2-7]{4}(?:={4})?|" 

54 r"[A-Z2-7]{5}(?:={3})?|[A-Z2-7]{7}=?)?", 

55 value, 

56 ) 

57 if value 

58 else False 

59 ) 

60 

61 

62@validator 

63def base58(value: str, /): 

64 """Return whether or not given value is a valid base58 encoding. 

65 

66 Examples: 

67 >>> base58('14pq6y9H2DLGahPsM4s7ugsNSD2uxpHsJx') 

68 True 

69 >>> base58('cUSECm5YzcXJwP') 

70 True 

71 

72 Args: 

73 value: 

74 base58 string to validate. 

75 

76 Returns: 

77 (Literal[True]): If `value` is a valid base58 encoding. 

78 (ValidationError): If `value` is an invalid base58 encoding. 

79 """ 

80 return re.fullmatch(r"^[1-9A-HJ-NP-Za-km-z]+$", value) if value else False 

81 

82 

83@validator 

84def base64(value: str, /): 

85 """Return whether or not given value is a valid base64 encoding. 

86 

87 Examples: 

88 >>> base64('Y2hhcmFjdGVyIHNldA==') 

89 True 

90 >>> base64('cUSECm5YzcXJwP') 

91 ValidationError(func=base64, args={'value': 'cUSECm5YzcXJwP'}) 

92 

93 Args: 

94 value: 

95 base64 string to validate. 

96 

97 Returns: 

98 (Literal[True]): If `value` is a valid base64 encoding. 

99 (ValidationError): If `value` is an invalid base64 encoding. 

100 """ 

101 return ( 

102 re.fullmatch(r"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$", value) 

103 if value 

104 else False 

105 )