Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added match algorithms and tests #11

Merged
merged 4 commits into from
Jul 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
*.swo
venv
docs/build/
sniffpy.egg-info
3 changes: 2 additions & 1 deletion sniffpy/constants.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
# This document contains all of the tables specified in https://mimesniff.spec.whatwg.org/
# Each table is implemented as an Array and a comment before each
# table indicates title of the table and meaning of each column.
from mimetype import MIMEtype

# Bytes that the specification defines as whitespace
WHITESPACE = b'\x09\x0a\x0c\x0d\x20'

UNDEFINED = MIMEType('undefined', 'undefined')

# Apache Bug Flag Table
# Bytes as Bytes | Bytes as String
Expand Down
34 changes: 33 additions & 1 deletion sniffpy/match.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,39 @@
from .mimetype import MIMEType
""" This module implements matching algorithms as described in
https://mimesniff.spec.whatwg.org/#matching-a-mime-type-pattern"""

from sniffpy.mimetype import MIMEType

def match_image_type_pattern(resource: bytes) -> MIMEType:
raise NotImplementedError

def match_video_audio_type_pattern(resource: bytes) -> MIMEType:
raise NotImplementedError

def match_pattern(resource: bytes, pattern: bytes, mask: bytes, ignored: bytes):
"""
Implementation of algorithm in:x
https://mimesniff.spec.whatwg.org/#matching-a-mime-type-pattern
True if pattern matches the resource. False otherwise.
"""
resource = bytearray(resource)
pattern = bytearray(pattern)
mask = bytearray(mask)

if len(pattern) != len(mask):
return False
if len(resource) < len(pattern):
return False

start = 0
for byte in resource:
if byte in ignored:
start += 1
else:
break

iteration_tuples = zip(resource[start:], pattern, mask)
for resource_byte, pattern_byte, mask_byte in iteration_tuples:
masked_byte = resource_byte & mask_byte
if masked_byte != pattern_byte:
return False
return True
2 changes: 2 additions & 0 deletions sniffpy/ref.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import List

def check_condition(code_point: str, condition: List[str]) -> bool:
for char in condition:
if code_point == char:
Expand Down