// Copyright Earl Warren <contact@earl-warren.org>
// Copyright Loïc Dachary <loic@dachary.org>
// SPDX-License-Identifier: MIT

package util

import (
	"context"
)

// Terminated terminated
type Terminated struct{}

func (err Terminated) Error() string {
	return "execution is terminated"
}

func MaybeTerminate(ctx context.Context) {
	select {
	case <-ctx.Done():
		panic(Terminated{})
	default:
	}
}

func CatchTerminate(f func()) (status bool) {
	status = false
	defer func() {
		if r := recover(); r != nil {
			_, ok := r.(Terminated)
			if ok {
				status = true
			} else {
				panic(r)
			}
		}
	}()

	f()

	return status
}
