Skip to content

Instantly share code, notes, and snippets.

@allykzam
Forked from TIHan/FParsec.Binary.fs
Last active August 29, 2015 14:00
Show Gist options
  • Save allykzam/0fbc41c8bc2e4ee90724 to your computer and use it in GitHub Desktop.
Save allykzam/0fbc41c8bc2e4ee90724 to your computer and use it in GitHub Desktop.
module FParsec.Binary
open System
open System.Text
open System.Text.RegularExpressions
open FParsec
[<RequireQualifiedAccess>]
module File =
let readAllString path =
let data =
System.IO.File.ReadAllBytes path
|> Array.map char
String data
let ExpectedError (message: string) = FParsec.ErrorMessageList(FParsec.ErrorMessage.Expected(message))
let anyByte : Parser<byte, unit> = anyChar |>> byte
let anyBytes n : Parser<byte array, unit> =
anyString n |>> (fun x -> Array.map byte <| x.ToCharArray ())
let anyInt16 : Parser<int16, unit> =
anyBytes 2
|>> (fun x -> BitConverter.ToInt16 (x, 0))
let anyInt32 : Parser<int, unit> =
anyBytes 4
|>> (fun x -> BitConverter.ToInt32 (x, 0))
let skipAnyByte : Parser<unit, _> =
fun stream ->
stream.Skip (1)
Reply (())
let skipAnyBytes (n: int) : Parser<unit, _> =
fun stream ->
stream.Skip (n)
Reply (())
let pByte (v: byte) : Parser<byte,'u> =
fun stream ->
let c = stream.Peek()
if uint16 c = uint16 v then
stream.Skip()
Reply(byte c)
else
Reply(Error, ExpectedError (String.Format("Byte {0}", v)))
let pByteRange (min: byte) (max: byte) : Parser<byte,'u> =
fun stream ->
let c = stream.Peek()
let uic = uint16 c
if uic >= uint16 min && uic <= uint16 max then
stream.Skip()
Reply(byte c)
else
Reply(Error, ExpectedError(String.Format("Byte value from {0} to {1}", min, max)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment