hypr/utils.go

74 lines
1.2 KiB
Go
Raw Permalink Normal View History

2024-02-09 20:24:48 +01:00
package hypr
import (
2024-08-26 21:48:18 +02:00
"context"
2024-02-09 20:24:48 +01:00
"encoding/json"
"io"
"net"
2024-08-26 21:43:18 +02:00
"time"
2024-02-09 20:24:48 +01:00
)
func readSocketRaw(socket string, body io.Reader) (io.ReadCloser, error) {
conn, err := net.Dial("unix", socket)
if err != nil {
return nil, err
}
if _, err := io.Copy(conn, body); err != nil {
conn.Close()
return nil, err
}
return conn, nil
}
func readSocketString(socket string, body io.Reader) (string, error) {
r, err := readSocketRaw(socket, body)
if err != nil {
return "", err
}
defer r.Close()
data, err := io.ReadAll(r)
if err != nil {
return "", err
}
return string(data), nil
}
func readSocket[T any](socket string, body io.Reader) (T, error) {
r, err := readSocketRaw(socket, body)
if err != nil {
return *new(T), err
}
defer r.Close()
value := new(T)
if err := json.NewDecoder(r).Decode(value); err != nil {
return *new(T), err
}
return *value, nil
}
2024-08-26 21:43:18 +02:00
2024-08-26 21:48:18 +02:00
func waitFor(ctx context.Context, condition func() bool) bool {
2024-08-26 21:43:18 +02:00
if condition() {
2024-08-26 21:48:18 +02:00
return true
2024-08-26 21:43:18 +02:00
}
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
2024-08-26 21:48:18 +02:00
for {
select {
case <-ticker.C:
if condition() {
return true
}
case <-ctx.Done():
return false
2024-08-26 21:43:18 +02:00
}
}
}