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 Examples: 

15 >>> base16('a3f4b2') 

16 True 

17 >>> base16('a3f4Z1') 

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

19 

20 Args: 

21 value: 

22 base16 string to validate. 

23 

24 Returns: 

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

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

27 """ 

28 return re.match(r"^[0-9A-Fa-f]+$", value) if value else False 

29 

30 

31@validator 

32def base32(value: str, /): 

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

34 

35 Examples: 

36 >>> base32('MFZWIZLTOQ======') 

37 True 

38 >>> base32('MfZW3zLT9Q======') 

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

40 

41 Args: 

42 value: 

43 base32 string to validate. 

44 

45 Returns: 

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

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

48 """ 

49 return re.match(r"^[A-Z2-7]+=*$", value) if value else False 

50 

51 

52@validator 

53def base58(value: str, /): 

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

55 

56 Examples: 

57 >>> base58('14pq6y9H2DLGahPsM4s7ugsNSD2uxpHsJx') 

58 True 

59 >>> base58('cUSECm5YzcXJwP') 

60 True 

61 

62 Args: 

63 value: 

64 base58 string to validate. 

65 

66 Returns: 

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

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

69 """ 

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

71 

72 

73@validator 

74def base64(value: str, /): 

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

76 

77 Examples: 

78 >>> base64('Y2hhcmFjdGVyIHNldA==') 

79 True 

80 >>> base64('cUSECm5YzcXJwP') 

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

82 

83 Args: 

84 value: 

85 base64 string to validate. 

86 

87 Returns: 

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

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

90 """ 

91 return ( 

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

93 if value 

94 else False 

95 )