Initial QSfera import

This commit is contained in:
Курнат Андрей
2026-06-07 10:20:04 +03:00
commit 2315f25754
16485 changed files with 4826827 additions and 0 deletions
@@ -0,0 +1,15 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 lestrrat-go
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.
+245
View File
@@ -0,0 +1,245 @@
# option
Base object for the "Optional Parameters Pattern".
# DESCRIPTION
The beauty of this pattern is that you can achieve a method that can
take the following simple calling style
```go
obj.Method(mandatory1, mandatory2)
```
or the following, if you want to modify its behavior with optional parameters
```go
obj.Method(mandatory1, mandatory2, optional1, optional2, optional3)
```
Instead of the more clunky zero value for optionals style
```go
obj.Method(mandatory1, mandatory2, nil, "", 0)
```
or the equally clunky config object style, which requires you to create a
struct with `NamesThatLookReallyLongBecauseItNeedsToIncludeMethodNamesConfig
```go
cfg := &ConfigForMethod{
Optional1: ...,
Optional2: ...,
Optional3: ...,
}
obj.Method(mandatory1, mandatory2, &cfg)
```
# SYNOPSIS
Create an "identifier" for the option. We recommend using an unexported empty struct,
because
1. It is uniquely identifiable globally
1. Takes minimal space
1. Since it's unexported, you do not have to worry about it leaking elsewhere or having it changed by consumers
```go
// an unexported empty struct
type identFeatureX struct{}
```
Then define a method to create an option using this identifier. Here we assume
that the option will be a boolean option.
```go
// this is optional, but for readability we usually use a wrapper
// around option.Interface, or a type alias.
type Option
func WithFeatureX(v bool) Option {
// use the constructor to create a new option
return option.New(identFeatureX{}, v)
}
```
Now you can create an option, which essentially a two element tuple consisting
of an identifier and its associated value.
To consume this, you will need to create a function with variadic parameters,
and iterate over the list looking for a particular identifier:
```go
func MyAwesomeFunc( /* mandatory parameters omitted */, options ...[]Option) {
var enableFeatureX bool
// The nolint directive is recommended if you are using linters such
// as golangci-lint
//nolint:forcetypeassert
for _, option := range options {
switch option.Ident() {
case identFeatureX{}:
enableFeatureX = option.Value().(bool)
// other cases omitted
}
}
if enableFeatureX {
....
}
}
```
# Option objects
Option objects take two arguments, its identifier and the value it contains.
The identifier can be anything, but it's usually better to use a an unexported
empty struct so that only you have the ability to generate said option:
```go
type identOptionalParamOne struct{}
type identOptionalParamTwo struct{}
type identOptionalParamThree struct{}
func WithOptionOne(v ...) Option {
return option.New(identOptionalParamOne{}, v)
}
```
Then you can call the method we described above as
```go
obj.Method(m1, m2, WithOptionOne(...), WithOptionTwo(...), WithOptionThree(...))
```
Options should be parsed in a code that looks somewhat like this
```go
func (obj *Object) Method(m1 Type1, m2 Type2, options ...Option) {
paramOne := defaultValueParamOne
for _, option := range options {
switch option.Ident() {
case identOptionalParamOne{}:
paramOne = option.Value().(...)
}
}
...
}
```
The loop requires a bit of boilerplate, and admittedly, this is the main downside
of this module. However, if you think you want use the Option as a Function pattern,
please check the FAQ below for rationale.
# Simple usage
Most of the times all you need to do is to declare the Option type as an alias
in your code:
```go
package myawesomepkg
import "github.com/lestrrat-go/option"
type Option = option.Interface
```
Then you can start defining options like they are described in the SYNOPSIS section.
# Differentiating Options
When you have multiple methods and options, and those options can only be passed to
each one the methods, it's hard to see which options should be passed to which method.
```go
func WithX() Option { ... }
func WithY() Option { ... }
// Now, which of WithX/WithY go to which method?
func (*Obj) Method1(options ...Option) {}
func (*Obj) Method2(options ...Option) {}
```
In this case the easiest way to make it obvious is to put an extra layer around
the options so that they have different types
```go
type Method1Option interface {
Option
method1Option()
}
type method1Option struct { Option }
func (*method1Option) method1Option() {}
func WithX() Method1Option {
return &methodOption{option.New(...)}
}
func (*Obj) Method1(options ...Method1Option) {}
```
This way the compiler knows if an option can be passed to a given method.
# FAQ
## Why aren't these function-based?
Using a base option type like `type Option func(ctx interface{})` is certainly one way to achieve the same goal. In this case, you are giving the option itself the ability to "configure" the main object. For example:
```go
type Foo struct {
optionaValue bool
}
type Option func(*Foo) error
func WithOptionalValue(v bool) Option {
return Option(func(f *Foo) error {
f.optionalValue = v
return nil
})
}
func NewFoo(options ...Option) (*Foo, error) {
var f Foo
for _, o := range options {
if err := o(&f); err != nil {
return nil, err
}
}
return &f
}
```
This in itself is fine, but we think there are a few problems:
### 1. It's hard to create a reusable "Option" type
We create many libraries using this optional pattern. We would like to provide a default base object. However, this function based approach is not reusuable because each "Option" type requires that it has a context-specific input type. For example, if the "Option" type in the previous example was `func(interface{}) error`, then its usability will significantly decrease because of the type conversion.
This is not to say that this library's approach is better as it also requires type conversion to convert the _value_ of the option. However, part of the beauty of the original function based approach was the ease of its use, and we claim that this significantly decreases the merits of the function based approach.
### 2. The receiver requires exported fields
Part of the appeal for a function-based option pattern is by giving the option itself the ability to do what it wants, you open up the possibility of allowing third-parties to create options that do things that the library authors did not think about.
```go
package thirdparty
, but when I read drum sheet music, I kind of get thrown off b/c many times it says to hit the bass drum where I feel like it's a snare hit.
func WithMyAwesomeOption( ... ) mypkg.Option {
return mypkg.Option(func(f *mypkg) error {
f.X = ...
f.Y = ...
f.Z = ...
return nil
})
}
```
However, for any third party code to access and set field values, these fields (`X`, `Y`, `Z`) must be exported. Basically you will need an "open" struct.
Exported fields are absolutely no problem when you have a struct that represents data alone (i.e., API calls that refer or change state information) happen, but we think that casually expose fields for a library struct is a sure way to maintenance hell in the future. What happens when you want to change the API? What happens when you realize that you want to use the field as state (i.e. use it for more than configuration)? What if they kept referring to that field, and then you have concurrent code accessing it?
Giving third parties complete access to exported fields is like handing out a loaded weapon to the users, and you are at their mercy.
Of course, providing public APIs for everything so you can validate and control concurrency is an option, but then ... it's a lot of work, and you may have to provide APIs _only_ so that users can refer it in the option-configuration phase. That sounds like a lot of extra work.
+47
View File
@@ -0,0 +1,47 @@
package option
import (
"fmt"
"github.com/lestrrat-go/blackmagic"
)
// Interface defines the minimum interface that an option must fulfill
type Interface interface {
// Ident returns the "identity" of this option, a unique identifier that
// can be used to differentiate between options
Ident() any
// Value assigns the stored value into the dst argument, which must be
// a pointer to a variable that can store the value. If the assignment
// is successful, it return nil, otherwise it returns an error.
Value(dst any) error
}
type pair[T any] struct {
ident any
value T
}
// New creates a new Option
func New[T any](ident any, value T) Interface {
return &pair[T]{
ident: ident,
value: value,
}
}
func (p *pair[T]) Ident() any {
return p.ident
}
func (p *pair[T]) Value(dst any) error {
if err := blackmagic.AssignIfCompatible(dst, p.value); err != nil {
return fmt.Errorf("failed to assign value %T to %T: %s", p.value, dst, err)
}
return nil
}
func (p *pair[T]) String() string {
return fmt.Sprintf(`%v(%v)`, p.ident, p.value)
}
+92
View File
@@ -0,0 +1,92 @@
package option
import (
"sync"
)
// Set is a container to store multiple options. Because options are
// usually used all over the place to configure various aspects of
// a system, it is often useful to be able to collect multiple options
// together and pass them around as a single entity.
//
// Note that Set is meant to be add-only; You usually do not remove
// options from a Set.
//
// The intention is to create a set using a sync.Pool; we would like
// to provide a centralized pool of Sets so that you don't need to
// instantiate a new pool for every type of option you want to
// store, but that is not quite possible because of the limitations
// of parameterized types in Go. Instead create a `*option.SetPool`
// with an appropriate type parameter and allocator.
type Set[T Interface] struct {
mu sync.RWMutex
options []T
}
func NewSet[T Interface]() *Set[T] {
return &Set[T]{
options: make([]T, 0, 1),
}
}
func (s *Set[T]) Add(opt T) {
s.mu.Lock()
defer s.mu.Unlock()
s.options = append(s.options, opt)
}
func (s *Set[T]) Reset() {
s.mu.Lock()
defer s.mu.Unlock()
s.options = s.options[:0] // Reset the options slice to avoid memory leaks
}
func (s *Set[T]) Len() int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.options)
}
func (s *Set[T]) Option(i int) T {
var zero T
s.mu.RLock()
defer s.mu.RUnlock()
if i < 0 || i >= len(s.options) {
return zero
}
return s.options[i]
}
// List returns a slice of all options stored in the Set.
// Note that the slice is the same slice that is used internally, so
// you should not modify the contents of the slice directly.
// This to avoid unnecessary allocations and copying of the slice for
// performance reasons.
func (s *Set[T]) List() []T {
s.mu.RLock()
defer s.mu.RUnlock()
return s.options
}
// SetPool is a pool of Sets that can be used to efficiently manage
// the lifecycle of Sets. It uses a sync.Pool to store and retrieve
// Sets, allowing for efficient reuse of memory and reducing the
// number of allocations required when creating new Sets.
type SetPool[T Interface] struct {
pool *sync.Pool // sync.Pool that contains *Set[T]
}
func NewSetPool[T Interface](pool *sync.Pool) *SetPool[T] {
return &SetPool[T]{
pool: pool,
}
}
func (p *SetPool[T]) Get() *Set[T] {
return p.pool.Get().(*Set[T])
}
func (p *SetPool[T]) Put(s *Set[T]) {
s.Reset()
p.pool.Put(s)
}