Created
August 14, 2016 22:09
-
-
Save danyx23/852d793f44a74008868d37596069d49a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- This is a naive brainstorm draft for a binary parser for an imaginary binary image format. | |
-- The image format is assumed to be: | |
-- Little endian | |
-- 4 bytes: magic identifier 0x23 0x23 0x23 0x23 | |
-- 2 bytes: width of image in pixels | |
-- 2 bytes: height of image in pixels | |
-- (width * height * 3) bytes: R G B values stored for each pixel (unsigned int) | |
import Binary.DataView.UInt8 exposing (uint8ViewLittleEndian, getBytes, getUInt16) | |
-- signatures of library functions: | |
uint8ViewLittleEndian : ArrayBuffer -> UInt8DataView | |
getBytes : Int -> Int -> UInt8DataView -> List Int | |
getUInt16 : Int -> UInt8DataView -> Int | |
ArrayBufferHelpers.areEqual : List Int -> List Int -> Bool | |
readPixelAt : Int -> Int -> ArrayBuffer -> Maybe Color | |
readPixelAt x y arrayBuffer = | |
let | |
uint8View = uint8ViewLittleEndian arrayBuffer | |
first4Bytes = getBytes 0 4 uint8View | |
identifierCorrect = | |
Maybe.withDefault false (Maybe.map (\bytes -> ArrayBufferHelpers.areEqual bytes [0x23, 0x23, 0x23, 0x23])) first4Bytes | |
maybeWidth = getUInt16 4 uint8View | |
maybeHeight = getUInt16 6 uint8View | |
extractPixel isValid width height = | |
if isValid then | |
let | |
maybePixelBytes = getBytes (8 + (y * width + x) * 3) 3 uint8View | |
maybeColor = | |
maybePixelBytes | |
`Maybe.andThen` | |
(\pixelBytes -> | |
case pixeBytes of | |
[] -> Nothing | |
_ :: [] -> Nothing | |
_ :: _ :: [] -> Nothing | |
r :: g :: b :: [] -> Just <| rgb r g b | |
_ -> Nothing | |
) | |
in | |
maybeColor | |
else | |
Nothing | |
maybeColor = Maybe.map3 extractPixel identifierCorrect maybeWidth maybeHeight | |
in | |
maybeColor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment