diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..6ec3fd5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,32 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[Bug 🐛]: " +labels: "bug" +assignees: "" +--- + +**What happened?** + +_Provide a description of the issue._ + +**What did you expect to happen?** + +_Explain what you would have expected to happen instead._ + +**Which version of go-functional were you using?** + +_Provide the version number (such as `v1.0.0`)._ + +**To Reproduce** + +_Provide a code snippet or steps to reproduce the issue._ + +**Do you intend to fix this issue yourself?** + +_Yes or no. This is so that the maintainers know to leave you time to make a +contribution rather than just fixing it themselves._ + +**Additional context** + +_Add any other context about the problem here._ diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..daaa2e8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,33 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[Feature 🔨]: " +labels: "enhancement" +assignees: "" +--- + +**Is your feature request related to a problem? Please describe.** + +A clear and concise description of what the problem is. Ex. I'm always +frustrated when [...]. + +**Describe the solution you'd like** + +A clear and concise description of what you want to happen. + +**Provide code snippets to show how this new feature might be used.** + +Ideally, provide an [`Example`](https://go.dev/blog/examples) test that +demonstrates the feature's usage. + +**Does this incur a breaking change?** + +Yes / no. + +**Do you intend to build this feature yourself?** + +Yes / no (so that it's clear that maintainers should allow you to make a +contribution). + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..1d84ed2 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,5 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: { interval: weekly } diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..e21e54a --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,24 @@ +**Please provide a brief description of the change.** + +A sentence or two is fine, the rest should be clear from the code change and related issue. + +**Which issue does this change relate to?** + +Please provide a link to the issue that this change resolved. + +If there is no such issue, consider creating one first. Discussions concerning proposed changes ought to take place in an issue and not in pull requests. Pull requests not associated with an issue are less likely to be merged and more likely to ask for changes. + +**Contribution checklist.** + +_Replace the space in each box with "X" to check it off._ + +- [ ] I have read and understood the CONTRIBUTING guidelines +- [ ] My code is formatted (`make check`) +- [ ] I have run tests (`make test`) +- [ ] All commits in my PR conform to the commit hygiene section +- [ ] I have added relevant tests +- [ ] I have not added any dependencies + +**Additional context** + +_Add any other context about the problem here._ diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml new file mode 100644 index 0000000..91815e4 --- /dev/null +++ b/.github/workflows/test.yaml @@ -0,0 +1,30 @@ +name: test +on: + push: { branches: [main] } + pull_request: {} +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: "1.22" + cache: false + - run: make check + env: { SKIP_LINT: true } + - uses: golangci/golangci-lint-action@v6 + with: { version: "latest" } + - run: make cov + - uses: codecov/codecov-action@v4 + env: { CODECOV_TOKEN: "${{ secrets.CODECOV_TOKEN }}" } + test: + strategy: { matrix: { go-version: ["1.21", "1.22"] } } + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: "${{ matrix.go-version }}" + cache: false + - run: make test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b5c31cc --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +coverage.txt +.vscode/ diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..f6061c1 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behaviour that contributes to a positive environment for our +community include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +- Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behaviour include: + +- The use of sexualized language or imagery, and sexual attention or + advances of any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email + address, without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behaviour and will take appropriate and fair corrective action in +response to any behaviour that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behaviour may be +reported to the community leaders responsible for enforcement at +tomgodkin@pm.me. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behaviour deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behaviour was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behaviour. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behaviour. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behaviour, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..7111cfc --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,72 @@ +# Contributing to BooleanCat/option + +Contributions to this project are very welcome! This guide should help with +instructions on how to submit changes. Contributions can be made in the form of +GitHub [issues](https://github.com/BooleanCat/option/issues) or [pull +requests](https://github.com/BooleanCat/option/pulls). + +When submitting an issue, please choose the relevant template or choose a blank +issue if your query doesn't naturally fit into an existing template. + +## TL;DR contribution checklist + +- [ ] My code is formatted (`make check`) +- [ ] I have run tests (`make test`) +- [ ] My code has no lint errors (`make lint`) +- [ ] All commits in my PR conform to the commit hygiene section +- [ ] I have added relevant tests +- [ ] I have not added any dependencies + +## Zero-dependency + +This project is a zero-dependency project - which means that consumers using +this project's packages must only incur one dependency: `option`. + +Development dependencies are OK as they will not be included as dependencies to +end-users (such as `golangci-lint`). + +## Commit hygiene + +- Commits should contain only a single change +- Commit messages must use imperative language (e.g. `Add iter.Fold collection +function`) +- Commit messages must explain what is changed, not how it is changed +- The first line of a commit message should be a terse description of the change + containing 72 characters or fewer + +## Running tests + +Run tests with `make test` from the project root directory. + +Tests are written using Go's `testing` package and helpers are available in +`internal/assert`. + +Code is linted using `golangci-lint`. The linter may be run using +`make lint`. + +## Different types of changes + +### Bug fixes + +Bug reports are appreciated ahead of bug fixes as early reporting allows the +community to be aware of any issues ahead of a fix being submitted. If you +intend to fix a bug after reporting, that is greatly appreciated - just make +sure to mention you intend to work on it on the issue report so the maintainers +are aware and leave you the chance to make a contribution. + +When submitting a bug fix PR, a test must be added (or an existing test +modified) that exposes the bug and your change must make that test pass. + +### New features + +Issues should be opened ahead of submitting a PR to added a new feature. This is +to prevent you wasting your time should a feature not be desirable and allows +others to have input into the conversation. + +All new functionality must be fully tested and new public functions must include +an [`Example` test](https://go.dev/blog/examples) that will be used by the +reference docs to demonstrate its use. + +Mark pull requests as "Draft" if you intend to use the pull request as a +workspace but are not yet ready to receive unsolicited feedback on specifics +like commit messages or failing tests. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e468cea --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Tom Godkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..e515662 --- /dev/null +++ b/Makefile @@ -0,0 +1,18 @@ +.phony: test check lint cov + +check: lint + @go vet ./... + @gofmt -l . + @test -z "$$( gofmt -l . )" + +lint: +ifndef SKIP_LINT + @golangci-lint run ./... +endif + +test: + go test -race -v ./... + +cov: SHELL:=/bin/bash +cov: + go test -race -coverprofile=coverage.txt -covermode=atomic $$( go list ./... | grep -v internal ) diff --git a/README.md b/README.md new file mode 100644 index 0000000..493aa28 --- /dev/null +++ b/README.md @@ -0,0 +1,80 @@ +# Optional Values in Go + +[![GitHub release (with filter)](https://img.shields.io/github/v/release/BooleanCat/option?sort=semver&logo=Go&color=%23007D9C)](https://github.com/BooleanCat/option/releases) [![Actions Status](https://github.com/BooleanCat/option/workflows/test/badge.svg)](https://github.com/BooleanCat/option/actions) [![Go Reference](https://pkg.go.dev/badge/github.com/BooleanCat/option.svg)](https://pkg.go.dev/github.com/BooleanCat/option) [![Go Report Card](https://goreportcard.com/badge/github.com/BooleanCat/option)](https://goreportcard.com/report/github.com/BooleanCat/option) [![codecov](https://codecov.io/gh/BooleanCat/option/branch/main/graph/badge.svg?token=N2E43RSR14)](https://codecov.io/gh/BooleanCat/option) + +Support user-friendly optional types in Go. + +```go +value = option.Some(4) +no_value = option.None[int]() +``` + +_[Read the docs.](https://pkg.go.dev/github.com/BooleanCat/option)_ + +## Usage + +This package adds a single type, the `Option`. `Option`'s are instantiated as +one of two variants. `Some` denotes the presence of a value and `None` denotes +the absence. + +Historically pointers have been used to denote optional values, this package +removes the risk of null pointer exceptions by leveraging generics to implement +type-safe optional values. + +`Options` can be tested for the presence of a value: + +```go +two = option.Some(2) +if two.IsSome() { + ... +} +``` + +Values can be extracted along with a boolean test for their presence: + +```go +two = option.Some(2) +if value, ok := two.Value(); ok { + ... +} +``` + +Optionals that you're sure have a value can be "unwrapped": + +```go +two := option.Some(2) +two.Unwrap() // returns 2 +``` + +Accessing a value on a `None` variant will cause a runtime panic. + +```go +none := option.None[int]() +none.Unwrap() // panics +``` + +## Ergonomics + +Use of a package like this may be pervasive if you really commit to it. This +package was inspired by Rust's options implemenation. It might be worth +considering dropping the repetative `option.` preceding the variants. Since +importing names into the global namespace is to be avoided, the following +import pattern may work for you: + +```go +import ( + "fmt" + + "github.com/BooleanCat/option" +) + +var ( + Some = option.Some + None = option.None +) + +func main() { + two := Some(2) + fmt.Println(two) +} +``` diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..451a04d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +# Security Policy + +## Reporting a Vulnerability + +Please send [an email](mailto:tomgodkin@pm.me) to the maintainer. + +Thank you for your report, genuine vulnerabilities reported shall grant you credit as a contributor. Please provide your GitHub username when submitting an issue if you wish to be credited when a new version is released that fixes the issue. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..36a11ad --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/BooleanCat/option + +go 1.22 diff --git a/internal/assert/assert.go b/internal/assert/assert.go new file mode 100644 index 0000000..5d50a35 --- /dev/null +++ b/internal/assert/assert.go @@ -0,0 +1,66 @@ +package assert + +import "testing" + +func Equal[T comparable](t *testing.T, a, b T) { + t.Helper() + + if a != b { + t.Errorf("expected `%v` to equal `%v`", a, b) + } +} + +func True(t *testing.T, b bool) { + t.Helper() + + if !b { + t.Error("expected `false` to be `true`") + } +} + +func False(t *testing.T, b bool) { + t.Helper() + + if b { + t.Error("expected `true` to be `false`") + } +} + +func Nil(t *testing.T, v interface{}) { + t.Helper() + + if v != nil { + t.Errorf("expected `%v` to equal `nil`", v) + } +} + +func NotNil(t *testing.T, v interface{}) { + t.Helper() + + if v == nil { + t.Error("expected `nil` not to equal `nil`") + } +} + +func SliceEqual[T comparable](t *testing.T, a, b []T) { + t.Helper() + + if len(a) != len(b) { + t.Errorf("expected `%v` to equal `%v` but lengths differ", a, b) + return + } + + for i, v := range a { + if v != b[i] { + t.Errorf("expected `%v` to equal `%v`", a, b) + } + } +} + +func Empty[S any, T []S | ~string](t *testing.T, items T) { + t.Helper() + + if len(items) != 0 { + t.Errorf("expected `%v` to be empty", items) + } +} diff --git a/json.go b/json.go new file mode 100644 index 0000000..f325eca --- /dev/null +++ b/json.go @@ -0,0 +1,38 @@ +package option + +import "encoding/json" + +// MarshalJSON implements the [json.Marshaler] interface. +// +// - [Some] variants will be marshaled as their underlying value. +// - [None] variants will be marshaled as "null". +func (o Option[T]) MarshalJSON() ([]byte, error) { + if value, ok := o.Value(); ok { + return json.Marshal(value) + } + + return []byte("null"), nil +} + +// UnmarshalJSON implements the [json.Unmarshaler] interface. +// +// - Values will be unmarshaled as [Some] variants. +// - "null"s will be unmarshaled as [None] variants. +func (o *Option[T]) UnmarshalJSON(data []byte) error { + *o = None[T]() + + if string(data) != "null" { + var value T + if err := json.Unmarshal(data, &value); err != nil { + return err + } + *o = Some(value) + } + + return nil +} + +var ( + _ json.Unmarshaler = new(Option[struct{}]) + _ json.Marshaler = Option[struct{}]{} +) diff --git a/json_test.go b/json_test.go new file mode 100644 index 0000000..e54f753 --- /dev/null +++ b/json_test.go @@ -0,0 +1,73 @@ +package option_test + +import ( + "encoding/json" + "testing" + + "github.com/BooleanCat/option" + "github.com/BooleanCat/option/internal/assert" +) + +func TestMarshalSome(t *testing.T) { + data, err := json.Marshal(option.Some(4)) + assert.Nil(t, err) + assert.Equal(t, string(data), "4") +} + +func TestMarshalNone(t *testing.T) { + data, err := json.Marshal(option.None[int]()) + assert.Nil(t, err) + assert.Equal(t, string(data), "null") +} + +func TestMarshalSomeParsed(t *testing.T) { + type name struct { + MiddleName option.Option[string] `json:"middle_name"` + } + + data, err := json.Marshal(name{MiddleName: option.Some("Barry")}) + assert.Nil(t, err) + assert.Equal(t, string(data), `{"middle_name":"Barry"}`) +} + +func TestMarshalNoneParsed(t *testing.T) { + type name struct { + MiddleName option.Option[string] `json:"middle_name"` + } + + data, err := json.Marshal(name{MiddleName: option.None[string]()}) + assert.Nil(t, err) + assert.Equal(t, string(data), `{"middle_name":null}`) +} + +func TestUnmarshalSome(t *testing.T) { + var number option.Option[int] + err := json.Unmarshal([]byte("4"), &number) + assert.Nil(t, err) + assert.Equal(t, number, option.Some(4)) +} + +func TestUnmarshalNone(t *testing.T) { + var number option.Option[int] + err := json.Unmarshal([]byte("null"), &number) + assert.Nil(t, err) + assert.True(t, number.IsNone()) +} + +func TestUnmarshalEmpty(t *testing.T) { + type name struct { + MiddleName option.Option[string] `json:"middle_name"` + } + + var value name + err := json.Unmarshal([]byte("{}"), &value) + assert.Nil(t, err) + assert.True(t, value.MiddleName.IsNone()) +} + +func TestUnmarshalError(t *testing.T) { + var number option.Option[int] + err := number.UnmarshalJSON([]byte("not a number")) + assert.NotNil(t, err) + assert.True(t, number.IsNone()) +} diff --git a/option.go b/option.go new file mode 100644 index 0000000..29fe890 --- /dev/null +++ b/option.go @@ -0,0 +1,98 @@ +package option + +import "fmt" + +// Option represents an optional value. The [Some] variant contains a value and +// the [None] variant represents the absence of a value. +type Option[T any] struct { + value T + present bool +} + +// Some instantiates an [Option] with a value. +func Some[T any](value T) Option[T] { + return Option[T]{value, true} +} + +// None instantiates an [Option] with no value. +func None[T any]() Option[T] { + return Option[T]{} +} + +// String implements the [fmt.Stringer] interface. +func (o Option[T]) String() string { + if o.present { + return fmt.Sprintf("Some(%v)", o.value) + } + + return "None" +} + +var _ fmt.Stringer = Option[struct{}]{} + +// Unwrap returns the underlying value of a [Some] variant, or panics if called +// on a [None] variant. +func (o Option[T]) Unwrap() T { + if o.present { + return o.value + } + + panic("called `Option.Unwrap()` on a `None` value") +} + +// UnwrapOr returns the underlying value of a [Some] variant, or the provided +// value on a [None] variant. +func (o Option[T]) UnwrapOr(value T) T { + if o.present { + return o.value + } + + return value +} + +// UnwrapOrElse returns the underlying value of a [Some] variant, or the result +// of calling the provided function on a [None] variant. +func (o Option[T]) UnwrapOrElse(f func() T) T { + if o.present { + return o.value + } + + return f() +} + +// UnwrapOrZero returns the underlying value of a [Some] variant, or the zero +// value on a [None] variant. +func (o Option[T]) UnwrapOrZero() T { + if o.present { + return o.value + } + + var value T + return value +} + +// IsSome returns true if the [Option] is a [Some] variant. +func (o Option[T]) IsSome() bool { + return o.present +} + +// IsNone returns true if the [Option] is a [None] variant. +func (o Option[T]) IsNone() bool { + return !o.present +} + +// Value returns the underlying value and true for a [Some] variant, or the +// zero value and false for a [None] variant. +func (o Option[T]) Value() (T, bool) { + return o.value, o.present +} + +// Expect returns the underlying value for a [Some] variant, or panics with the +// provided message for a [None] variant. +func (o Option[T]) Expect(message string) T { + if o.present { + return o.value + } + + panic(message) +} diff --git a/option_test.go b/option_test.go new file mode 100644 index 0000000..31c054a --- /dev/null +++ b/option_test.go @@ -0,0 +1,160 @@ +package option_test + +import ( + "fmt" + "testing" + + "github.com/BooleanCat/option" + "github.com/BooleanCat/option/internal/assert" +) + +func ExampleOption_Unwrap() { + fmt.Println(option.Some(4).Unwrap()) + // Output: 4 +} + +func ExampleOption_UnwrapOr() { + fmt.Println(option.Some(4).UnwrapOr(3)) + fmt.Println(option.None[int]().UnwrapOr(3)) + // Output: + // 4 + // 3 +} + +func ExampleOption_UnwrapOrElse() { + fmt.Println(option.Some(4).UnwrapOrElse(func() int { + return 3 + })) + + fmt.Println(option.None[int]().UnwrapOrElse(func() int { + return 3 + })) + + // Output: + // 4 + // 3 +} + +func ExampleOption_UnwrapOrZero() { + fmt.Println(option.Some(4).UnwrapOrZero()) + fmt.Println(option.None[int]().UnwrapOrZero()) + + // Output + // 4 + // 0 +} + +func ExampleOption_IsSome() { + fmt.Println(option.Some(4).IsSome()) + fmt.Println(option.None[int]().IsSome()) + + // Output: + // true + // false +} + +func ExampleOption_IsNone() { + fmt.Println(option.Some(4).IsNone()) + fmt.Println(option.None[int]().IsNone()) + + // Output: + // false + // true +} + +func ExampleOption_Value() { + value, ok := option.Some(4).Value() + fmt.Println(value) + fmt.Println(ok) + + // Output: + // 4 + // true +} + +func ExampleOption_Expect() { + fmt.Println(option.Some(4).Expect("oops")) + + // Output: 4 +} + +func TestSomeStringer(t *testing.T) { + assert.Equal(t, fmt.Sprintf("%s", option.Some("foo")), "Some(foo)") //nolint:gosimple + assert.Equal(t, fmt.Sprintf("%s", option.Some(42)), "Some(42)") //nolint:gosimple +} + +func TestNoneStringer(t *testing.T) { + assert.Equal(t, fmt.Sprintf("%s", option.None[string]()), "None") //nolint:gosimple +} + +func TestSomeUnwrap(t *testing.T) { + assert.Equal(t, option.Some(42).Unwrap(), 42) +} + +func TestNoneUnwrap(t *testing.T) { + defer func() { + assert.Equal(t, fmt.Sprint(recover()), "called `Option.Unwrap()` on a `None` value") + }() + + option.None[string]().Unwrap() + t.Error("did not panic") +} + +func TestSomeUnwrapOr(t *testing.T) { + assert.Equal(t, option.Some(42).UnwrapOr(3), 42) +} + +func TestNoneUnwrapOr(t *testing.T) { + assert.Equal(t, option.None[int]().UnwrapOr(3), 3) +} + +func TestSomeUnwrapOrElse(t *testing.T) { + assert.Equal(t, option.Some(42).UnwrapOrElse(func() int { return 41 }), 42) +} + +func TestNoneUnwrapOrElse(t *testing.T) { + assert.Equal(t, option.None[int]().UnwrapOrElse(func() int { return 41 }), 41) +} + +func TestSomeUnwrapOrZero(t *testing.T) { + assert.Equal(t, option.Some(42).UnwrapOrZero(), 42) +} + +func TestNoneUnwrapOrZero(t *testing.T) { + assert.Equal(t, option.None[int]().UnwrapOrZero(), 0) +} + +func TestIsSome(t *testing.T) { + assert.True(t, option.Some(42).IsSome()) + assert.False(t, option.None[int]().IsSome()) +} + +func TestIsNone(t *testing.T) { + assert.False(t, option.Some(42).IsNone()) + assert.True(t, option.None[int]().IsNone()) +} + +func TestSomeValue(t *testing.T) { + value, ok := option.Some(42).Value() + assert.Equal(t, value, 42) + assert.True(t, ok) +} + +func TestNoneValue(t *testing.T) { + value, ok := option.None[int]().Value() + assert.Equal(t, value, 0) + assert.False(t, ok) +} + +func TestSomeExpect(t *testing.T) { + assert.Equal(t, option.Some(42).Expect("oops"), 42) +} + +func TestNoneExpect(t *testing.T) { + defer func() { + assert.Equal(t, fmt.Sprint(recover()), "oops") + }() + + option.None[int]().Expect("oops") + t.Error("did not panic") +}