predicate

package module
v0.0.0-...-747740f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2024 License: MIT Imports: 8 Imported by: 0

README

Predicate

Runtime predicate evaluation for Go.

Example

package main

import (
	"fmt"

	"github.com/Crystalix007/predicate"
)

const indentedPredicateProgram = `
    import "strings"

    return strings.HasPrefix(arg0, "\t")
`

func main() {
	res, err := predicate.Evaluate(indentedPredicateProgram, "some text")
	if err != nil {
		fmt.Printf("error evaluating predicate: %v\n", err)
	}

	fmt.Printf("1st predicate result: %t\n", res)

	res, err = predicate.Evaluate(indentedPredicateProgram, "\tindented text")
	if err != nil {
		fmt.Printf("error evaluating predicate: %v\n", err)
	}

	fmt.Printf("2nd predicate result: %t\n", res)

	// Output: 1st predicate result: false
	// 2nd predicate result: true
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyPredicate is an error that occurs when the predicate is empty.
	ErrEmptyPredicate = errors.New("predicate: empty predicate")

	// ErrPredicateDefinitionInvalid is an error that occurs when the predicate definition is invalid.
	ErrPredicateDefinitionInvalid = errors.New("predicate: definition is invalid")

	// ErrPredicateCallbackReferenceFailed is an error that occurs when the predicate callback reference failed.
	ErrPredicateCallbackReferenceFailed = errors.New("predicate: failed to get reference to callback")

	// ErrPredicateReturnInvalid is an error that occurs when the predicate return value is invalid.
	ErrPredicateReturnInvalid = errors.New("predicate: invalid return value")
)

Functions

func Evaluate

func Evaluate(predicate string, args ...any) (res bool, err error)

Evaluate evaluates the predicate and returns the result.

Example
package main

import (
	"fmt"

	"github.com/crystalix007/predicate"
)

func main() {
	// A return value of 0 means that the predicate is true, any other value
	// means that it is false.
	predicateProgram := `
		import "net/url"

		u, err := url.Parse(arg0)
		if err != nil {
			return false
		}

		return u.Scheme == "https"
	`

	res, err := predicate.Evaluate(predicateProgram, "https://example.com")
	if err != nil {
		fmt.Printf("error evaluating predicate: %v\n", err)
	}

	fmt.Printf("predicate result: %t\n", res)

}
Output:
predicate result: true

Types

type PanicError

type PanicError struct {
	Panic any
}

PanicError is an error that occurs when a panic occurs in the predicate.

func (*PanicError) Error

func (e *PanicError) Error() string

Error returns the error message.

func (*PanicError) Is

func (e *PanicError) Is(target error) bool

Is checks if the panic error is the same as the target error.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL