File: value_safe.go

package info (click to toggle)
golang-golang-x-exp 0.0~git20221028.83b7d23-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-backports
  • size: 6,276 kB
  • sloc: ansic: 1,900; sh: 278; objc: 276; asm: 48; makefile: 14
file content (75 lines) | stat: -rw-r--r-- 2,028 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build safe_values

package slog

// This file defines the most portable representation of Value.

// A Value can represent any Go value, but unlike type any,
// it can represent most small values without an allocation.
// The zero Value corresponds to nil.
type Value struct {
	// num holds the value for Kinds Int64, Uint64, Float64, Bool and Duration,
	// and nanoseconds since the epoch for TimeKind.
	num uint64
	// s holds the value for StringKind.
	s string
	// If any is of type Kind, then the value is in num or s as described above.
	// If any is of type *time.Location, then the Kind is Time and time.Time
	// value can be constructed from the Unix nanos in num and the location
	// (monotonic time is not preserved).
	// Otherwise, the Kind is Any and any is the value.
	// (This implies that Values cannot store Kinds or *time.Locations.)
	any any
}

// Kind returns the Value's Kind.
func (v Value) Kind() Kind {
	switch k := v.any.(type) {
	case Kind:
		return k
	case timeLocation:
		return TimeKind
	case []Attr:
		return GroupKind
	case LogValuer:
		return LogValuerKind
	case kind: // a kind is just a wrapper for a Kind
		return AnyKind
	default:
		return AnyKind
	}
}

func (v Value) str() string {
	return v.s
}

// String returns a new Value for a string.
func StringValue(value string) Value {
	return Value{s: value, any: StringKind}
}

// String returns Value's value as a string, formatted like fmt.Sprint. Unlike
// the methods Int64, Float64, and so on, which panic if the Value is of the
// wrong kind, String never panics.
func (v Value) String() string {
	if v.Kind() == StringKind {
		return v.str()
	}
	var buf []byte
	return string(v.append(buf))
}

func groupValue(as []Attr) Value {
	return Value{any: as}
}

func (v Value) group() []Attr {
	return v.any.([]Attr)
}

func (v Value) uncheckedGroup() []Attr { return v.group() }