Skip to content

Commit

Permalink
Merge pull request #392 from Micha-kun/master
Browse files Browse the repository at this point in the history
Add Option.ofUnchecked function
  • Loading branch information
gdziadkiewicz authored Jun 3, 2020
2 parents 1c30663 + f53c9e1 commit c0c5b25
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/FSharpx.Extras/ComputationExpressions/Option.fs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ module Option =
| Ok a -> Some a
| _ -> None

/// Maps Unchecked object when null to None, otherwise Some value.
/// It's useful when getting data from external sources, pe.
let inline ofUnchecked (x: 'a when 'a : not struct) =
match box x with
| null -> None
| _ -> Some x

/// Gets the value associated with the option or the supplied default value.
let inline getOrElse v =
Expand Down
19 changes: 19 additions & 0 deletions tests/FSharpx.Tests/OptionTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,22 @@ let someIfBoolTestCases = [
[<TestCaseSource(nameof someIfBoolTestCases)>]
let ``someIf with id`` (input:bool, expectedOutput:bool option) =
Option.someIf id input |> shouldEqual expectedOutput

type UncheckedRecordTest =
{ Dummy: int }

[<Test>]
let ``from unchecked value``() =
let test = { Dummy = 4 }
Assert.AreEqual(Some test, Option.ofUnchecked test)
Assert.AreEqual(None, Option.ofUnchecked (Unchecked.defaultof<UncheckedRecordTest>))

[<NoEquality;NoComparison>]
type UncheckedRecordTest2 =
{ Dummy2: int }

[<Test>]
let ``from unchecked value without equality nor comparison``() =
let test = { Dummy2 = 4 }
Assert.AreEqual(Some test, Option.ofUnchecked test)
Assert.AreEqual(None, Option.ofUnchecked (Unchecked.defaultof<UncheckedRecordTest2>))

0 comments on commit c0c5b25

Please sign in to comment.