repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/qemu.go
vendor/libvirt.org/go/libvirt/qemu.go
//go:build !libvirt_without_qemu // +build !libvirt_without_qemu /* * This file is part of the libvirt-go-module project * * 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. * * Copyright (c) 2013 Alex Zorin * Copyright (C) 2016 Red Hat, Inc. * */ package libvirt /* #cgo !libvirt_dlopen pkg-config: libvirt // Can't rely on pkg-config for libvirt-qemu since it was not // installed until 2.6.0 onwards #cgo !libvirt_dlopen LDFLAGS: -lvirt-qemu #cgo libvirt_dlopen LDFLAGS: -ldl #cgo libvirt_dlopen CFLAGS: -DLIBVIRT_DLOPEN #include <stdlib.h> #include "qemu_helper.h" */ import "C" import ( "os" "unsafe" ) /* * QMP has two different kinds of ways to talk to QEMU. One is legacy (HMP, * or 'human' monitor protocol. The default is QMP, which is all-JSON. * * QMP json commands are of the format: * {"execute" : "query-cpus"} * * whereas the same command in 'HMP' would be: * 'info cpus' */ type DomainQemuMonitorCommandFlags uint const ( DOMAIN_QEMU_MONITOR_COMMAND_DEFAULT = DomainQemuMonitorCommandFlags(C.VIR_DOMAIN_QEMU_MONITOR_COMMAND_DEFAULT) DOMAIN_QEMU_MONITOR_COMMAND_HMP = DomainQemuMonitorCommandFlags(C.VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP) ) type DomainQemuAgentCommandTimeout int const ( DOMAIN_QEMU_AGENT_COMMAND_MIN = DomainQemuAgentCommandTimeout(C.VIR_DOMAIN_QEMU_AGENT_COMMAND_MIN) DOMAIN_QEMU_AGENT_COMMAND_BLOCK = DomainQemuAgentCommandTimeout(C.VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) DOMAIN_QEMU_AGENT_COMMAND_DEFAULT = DomainQemuAgentCommandTimeout(C.VIR_DOMAIN_QEMU_AGENT_COMMAND_DEFAULT) DOMAIN_QEMU_AGENT_COMMAND_NOWAIT = DomainQemuAgentCommandTimeout(C.VIR_DOMAIN_QEMU_AGENT_COMMAND_NOWAIT) DOMAIN_QEMU_AGENT_COMMAND_SHUTDOWN = DomainQemuAgentCommandTimeout(C.VIR_DOMAIN_QEMU_AGENT_COMMAND_SHUTDOWN) ) type DomainQemuMonitorEventFlags uint const ( CONNECT_DOMAIN_QEMU_MONITOR_EVENT_REGISTER_REGEX = DomainQemuMonitorEventFlags(C.VIR_CONNECT_DOMAIN_QEMU_MONITOR_EVENT_REGISTER_REGEX) CONNECT_DOMAIN_QEMU_MONITOR_EVENT_REGISTER_NOCASE = DomainQemuMonitorEventFlags(C.VIR_CONNECT_DOMAIN_QEMU_MONITOR_EVENT_REGISTER_NOCASE) ) // See also https://libvirt.org/html/libvirt-libvirt-qemu.html#virDomainQemuMonitorCommand func (d *Domain) QemuMonitorCommand(command string, flags DomainQemuMonitorCommandFlags) (string, error) { var cResult *C.char cCommand := C.CString(command) defer C.free(unsafe.Pointer(cCommand)) var err C.virError result := C.virDomainQemuMonitorCommandWrapper(d.ptr, cCommand, &cResult, C.uint(flags), &err) if result != 0 { return "", makeError(&err) } rstring := C.GoString(cResult) C.free(unsafe.Pointer(cResult)) return rstring, nil } // See also https://libvirt.org/html/libvirt-libvirt-qemu.html#virDomainQemuMonitorCommandWithFiles func (d *Domain) QemuMonitorCommandWithFiles(command string, infiles []os.File, flags DomainQemuMonitorCommandFlags) (string, []*os.File, error) { ninfiles := len(infiles) cinfiles := make([]C.int, ninfiles) for i := 0; i < ninfiles; i++ { cinfiles[i] = C.int(infiles[i].Fd()) } cCommand := C.CString(command) defer C.free(unsafe.Pointer(cCommand)) var cResult *C.char var cnoutfiles C.uint var coutfiles *C.int var err C.virError var cinfilesPtr *C.int = nil if ninfiles > 0 { cinfilesPtr = &cinfiles[0] } result := C.virDomainQemuMonitorCommandWithFilesWrapper(d.ptr, cCommand, C.uint(ninfiles), cinfilesPtr, &cnoutfiles, &coutfiles, &cResult, C.uint(flags), &err) if result != 0 { return "", []*os.File{}, makeError(&err) } outfiles := []*os.File{} for i := 0; i < int(cnoutfiles); i++ { coutfile := *(*C.int)(unsafe.Pointer(uintptr(unsafe.Pointer(coutfiles)) + (unsafe.Sizeof(*coutfiles) * uintptr(i)))) outfiles = append(outfiles, os.NewFile(uintptr(coutfile), "mon-cmd-out")) } C.free(unsafe.Pointer(coutfiles)) rstring := C.GoString(cResult) C.free(unsafe.Pointer(cResult)) return rstring, outfiles, nil } // See also https://libvirt.org/html/libvirt-libvirt-qemu.html#virDomainQemuAgentCommand func (d *Domain) QemuAgentCommand(command string, timeout DomainQemuAgentCommandTimeout, flags uint32) (string, error) { cCommand := C.CString(command) defer C.free(unsafe.Pointer(cCommand)) var err C.virError result := C.virDomainQemuAgentCommandWrapper(d.ptr, cCommand, C.int(timeout), C.uint(flags), &err) if result == nil { return "", makeError(&err) } rstring := C.GoString(result) C.free(unsafe.Pointer(result)) return rstring, nil } // See also https://libvirt.org/html/libvirt-libvirt-qemu.html#virDomainQemuAttach func (c *Connect) DomainQemuAttach(pid uint32, flags uint32) (*Domain, error) { var err C.virError ptr := C.virDomainQemuAttachWrapper(c.ptr, C.uint(pid), C.uint(flags), &err) if ptr == nil { return nil, makeError(&err) } return &Domain{ptr: ptr}, nil } type DomainQemuMonitorEvent struct { Event string Seconds int64 Micros uint Details string } type DomainQemuMonitorEventCallback func(c *Connect, d *Domain, event *DomainQemuMonitorEvent) //export domainQemuMonitorEventCallback func domainQemuMonitorEventCallback(c C.virConnectPtr, d C.virDomainPtr, event *C.char, seconds C.longlong, micros C.uint, details *C.char, goCallbackId int) { domain := &Domain{ptr: d} connection := &Connect{ptr: c} eventDetails := &DomainQemuMonitorEvent{ Event: C.GoString(event), Seconds: int64(seconds), Micros: uint(micros), Details: C.GoString(details), } callbackFunc := getCallbackId(goCallbackId) callback, ok := callbackFunc.(DomainQemuMonitorEventCallback) if !ok { panic("Inappropriate callback type called") } callback(connection, domain, eventDetails) } // See also https://libvirt.org/html/libvirt-libvirt-qemu.html#virConnectDomainQemuMonitorEventRegister func (c *Connect) DomainQemuMonitorEventRegister(dom *Domain, event string, callback DomainQemuMonitorEventCallback, flags DomainQemuMonitorEventFlags) (int, error) { cEvent := C.CString(event) defer C.free(unsafe.Pointer(cEvent)) goCallBackId := registerCallbackId(callback) var cdom C.virDomainPtr if dom != nil { cdom = dom.ptr } var err C.virError ret := C.virConnectDomainQemuMonitorEventRegisterHelper(c.ptr, cdom, cEvent, C.long(goCallBackId), C.uint(flags), &err) if ret < 0 { freeCallbackId(goCallBackId) return 0, makeError(&err) } return int(ret), nil } // See also https://libvirt.org/html/libvirt-libvirt-qemu.html#virConnectDomainQemuMonitorEventDeregister func (c *Connect) DomainQemuEventDeregister(callbackId int) error { // Deregister the callback var err C.virError ret := int(C.virConnectDomainQemuMonitorEventDeregisterWrapper(c.ptr, C.int(callbackId), &err)) if ret < 0 { return makeError(&err) } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/libvirt_qemu_generated_functions_static.go
vendor/libvirt.org/go/libvirt/libvirt_qemu_generated_functions_static.go
//go:build !libvirt_without_qemu && !libvirt_dlopen // +build !libvirt_without_qemu,!libvirt_dlopen /* * This file is part of the libvirt-go-module project * * 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. * * Copyright (C) 2022 Red Hat, Inc. * */ /**************************************************************************** * THIS CODE HAS BEEN GENERATED. DO NOT CHANGE IT DIRECTLY * ****************************************************************************/ package libvirt /* #cgo pkg-config: libvirt-qemu #include <assert.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include "libvirt_qemu_generated.h" #include "error_helper.h" int virConnectDomainQemuMonitorEventDeregisterWrapper(virConnectPtr conn, int callbackID, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 2, 3) setVirError(err, "Function virConnectDomainQemuMonitorEventDeregister not available prior to libvirt version 1.2.3"); #else ret = virConnectDomainQemuMonitorEventDeregister(conn, callbackID); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virConnectDomainQemuMonitorEventRegisterWrapper(virConnectPtr conn, virDomainPtr dom, const char * event, virConnectDomainQemuMonitorEventCallback cb, void * opaque, virFreeCallback freecb, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 2, 3) setVirError(err, "Function virConnectDomainQemuMonitorEventRegister not available prior to libvirt version 1.2.3"); #else ret = virConnectDomainQemuMonitorEventRegister(conn, dom, event, cb, opaque, freecb, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } char * virDomainQemuAgentCommandWrapper(virDomainPtr domain, const char * cmd, int timeout, unsigned int flags, virErrorPtr err) { char * ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 10, 0) setVirError(err, "Function virDomainQemuAgentCommand not available prior to libvirt version 0.10.0"); #else ret = virDomainQemuAgentCommand(domain, cmd, timeout, flags); if (!ret) { virCopyLastError(err); } #endif return ret; } virDomainPtr virDomainQemuAttachWrapper(virConnectPtr conn, unsigned int pid_value, unsigned int flags, virErrorPtr err) { virDomainPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 9, 4) setVirError(err, "Function virDomainQemuAttach not available prior to libvirt version 0.9.4"); #else ret = virDomainQemuAttach(conn, pid_value, flags); if (!ret) { virCopyLastError(err); } #endif return ret; } int virDomainQemuMonitorCommandWrapper(virDomainPtr domain, const char * cmd, char ** result, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 8, 3) setVirError(err, "Function virDomainQemuMonitorCommand not available prior to libvirt version 0.8.3"); #else ret = virDomainQemuMonitorCommand(domain, cmd, result, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virDomainQemuMonitorCommandWithFilesWrapper(virDomainPtr domain, const char * cmd, unsigned int ninfiles, int * infiles, unsigned int * noutfiles, int ** outfiles, char ** result, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(8, 2, 0) setVirError(err, "Function virDomainQemuMonitorCommandWithFiles not available prior to libvirt version 8.2.0"); #else ret = virDomainQemuMonitorCommandWithFiles(domain, cmd, ninfiles, infiles, noutfiles, outfiles, result, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } */ import "C"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/secret_events_helper.go
vendor/libvirt.org/go/libvirt/secret_events_helper.go
/* * This file is part of the libvirt-go-module project * * 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. * * Copyright (c) 2013 Alex Zorin * Copyright (C) 2016 Red Hat, Inc. * */ package libvirt /* #cgo !libvirt_dlopen pkg-config: libvirt #cgo libvirt_dlopen LDFLAGS: -ldl #cgo libvirt_dlopen CFLAGS: -DLIBVIRT_DLOPEN #include <stdint.h> #include "secret_events_helper.h" #include "callbacks_helper.h" extern void secretEventLifecycleCallback(virConnectPtr, virSecretPtr, int, int, int); void secretEventLifecycleCallbackHelper(virConnectPtr conn, virSecretPtr secret, int event, int detail, void *data) { secretEventLifecycleCallback(conn, secret, event, detail, (int)(intptr_t)data); } extern void secretEventGenericCallback(virConnectPtr, virSecretPtr, int); void secretEventGenericCallbackHelper(virConnectPtr conn, virSecretPtr secret, void *data) { secretEventGenericCallback(conn, secret, (int)(intptr_t)data); } int virConnectSecretEventRegisterAnyHelper(virConnectPtr conn, virSecretPtr secret, int eventID, virConnectSecretEventGenericCallback cb, long goCallbackId, virErrorPtr err) { void *id = (void *)goCallbackId; return virConnectSecretEventRegisterAnyWrapper(conn, secret, eventID, cb, id, freeGoCallbackHelper, err); } */ import "C"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/doc.go
vendor/libvirt.org/go/libvirt/doc.go
/* * This file is part of the libvirt-go-module project * * 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. * * Copyright (C) 2016 Red Hat, Inc. * */ // Package libvirt provides a Go binding to the libvirt C library // // Through conditional compilation it supports libvirt versions 1.2.0 onwards. // This is done automatically, with no requirement to use magic Go build tags. // If an API was not available in the particular version of libvirt this package // was built against, an error will be returned with a code of ERR_NO_SUPPORT. // This is the same code seen if using a new libvirt library to talk to an old // libvirtd lacking the API, or if a hypervisor does not support a given feature, // so an application can easily handle all scenarios together. // // The Go binding is a fairly direct mapping of the underling C API which seeks // to maximise the use of the Go type system to allow strong compiler type // checking. The following rules describe how APIs/constants are mapped from C // to Go // // For structs, the 'vir' prefix and 'Ptr' suffix are removed from the name. // e.g. virConnectPtr in C becomes 'Connect' in Go. // // For structs which are reference counted at the C level, it is neccessary to // explicitly release the reference at the Go level. e.g. if a Go method returns // a '* Domain' struct, it is neccessary to call 'Free' on this when no longer // required. The use of 'defer' is recommended for this purpose // // dom, err := conn.LookupDomainByName("myguest") // if err != nil { // ... // } // defer dom.Free() // // If multiple goroutines are using the same libvirt object struct, it may // not be possible to determine which goroutine should call 'Free'. In such // scenarios each new goroutine should call 'Ref' to obtain a private reference // on the underlying C struct. All goroutines can call 'Free' unconditionally // with the final one causing the release of the C object. // // For methods, the 'vir' prefix and object name prefix are remove from the name. // The C functions become methods with an object receiver. e.g. // 'virDomainScreenshot' in C becomes 'Screenshot' with a 'Domain *' receiver. // // For methods which accept a 'unsigned int flags' parameter in the C level, // the corresponding Go parameter will be a named type corresponding to the // C enum that defines the valid flags. For example, the ListAllDomains // method takes a 'flags ConnectListAllDomainsFlags' parameter. If there are // not currently any flags defined for a method in the C API, then the Go // method parameter will be declared as a "flags uint32". Callers should always // pass the literal integer value 0 for such parameters, without forcing any // specific type. This will allow compatibility with future updates to the // libvirt-go-module binding which may replace the 'uint32' type with a enum // type at a later date. // // For enums, the VIR_ prefix is removed from the name. The enums get a dedicated // type defined in Go. e.g. the VIR_NODE_SUSPEND_TARGET_MEM enum constant in C, // becomes NODE_SUSPEND_TARGET_MEM with a type of NodeSuspendTarget. // // Methods accepting or returning virTypedParameter arrays in C will map the // parameters into a Go struct. The struct will contain two fields for each // possible parameter. One boolean field with a suffix of 'Set' indicates whether // the parameter has a value set, and the other custom typed field provides the // parameter value. This makes it possible to distinguish a parameter with a // default value of '0' from a parameter which is 0 because it isn't supported by // the hypervisor. If the C API defines additional typed parameters, then the // corresponding Go struct will be extended to have further fields. // e.g. the GetMemoryStats method in Go (which is backed by // virNodeGetMemoryStats in C) will return a NodeMemoryStats struct containing // the typed parameter values. // // stats, err := conn.GetMemoryParameters() // if err != nil { // .... // } // if stats.TotalSet { // fmt.Printf("Total memory: %d KB", stats.Total) // } // // Every method that can fail will include an 'error' object as the last return // value. This will be an instance of the Error struct if an error occurred. To // check for specific libvirt error codes, it is neccessary to cast the error. // // err := storage_vol.Wipe(0) // if err != nil { // lverr, ok := err.(libvirt.Error) // if ok && lverr.Code == libvirt.ERR_NO_SUPPORT { // fmt.Println("Wiping storage volumes is not supported"); // } else { // fmt.Println("Error wiping storage volume: %s", err) // } // } // // # Example usage // // To connect to libvirt // // import ( // "libvirt.org/go/libvirt" // ) // conn, err := libvirt.NewConnect("qemu:///system") // if err != nil { // ... // } // defer conn.Close() // // doms, err := conn.ListAllDomains(libvirt.CONNECT_LIST_DOMAINS_ACTIVE) // if err != nil { // ... // } // // fmt.Printf("%d running domains:\n", len(doms)) // for _, dom := range doms { // name, err := dom.GetName() // if err == nil { // fmt.Printf(" %s\n", name) // } // dom.Free() // } // //go:generate go build -o generator ./gen //go:generate ./generator package libvirt
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/events.go
vendor/libvirt.org/go/libvirt/events.go
/* * This file is part of the libvirt-go-module project * * 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. * * Copyright (c) 2013 Alex Zorin * Copyright (C) 2016 Red Hat, Inc. * */ package libvirt /* #cgo !libvirt_dlopen pkg-config: libvirt #cgo libvirt_dlopen LDFLAGS: -ldl #cgo libvirt_dlopen CFLAGS: -DLIBVIRT_DLOPEN #include <stdint.h> #include "events_helper.h" */ import "C" type EventHandleType int const ( EVENT_HANDLE_READABLE = EventHandleType(C.VIR_EVENT_HANDLE_READABLE) EVENT_HANDLE_WRITABLE = EventHandleType(C.VIR_EVENT_HANDLE_WRITABLE) EVENT_HANDLE_ERROR = EventHandleType(C.VIR_EVENT_HANDLE_ERROR) EVENT_HANDLE_HANGUP = EventHandleType(C.VIR_EVENT_HANDLE_HANGUP) ) // See also https://libvirt.org/html/libvirt-libvirt-event.html#virEventRegisterDefaultImpl // // Note that registering an event loop implementation must be // done before creating any Connect object instance func EventRegisterDefaultImpl() error { var err C.virError if C.virInitializeWrapper(&err) < 0 { return makeError(&err) } if i := int(C.virEventRegisterDefaultImplWrapper(&err)); i != 0 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-event.html#virEventRunDefaultImpl func EventRunDefaultImpl() error { var err C.virError if i := int(C.virEventRunDefaultImplWrapper(&err)); i != 0 { return makeError(&err) } return nil } type EventHandleCallback func(watch int, file int, events EventHandleType) //export eventHandleCallback func eventHandleCallback(watch int, fd int, events int, callbackID int) { callbackFunc := getCallbackId(callbackID) callback, ok := callbackFunc.(EventHandleCallback) if !ok { panic("Incorrect event handle callback data") } callback(watch, fd, (EventHandleType)(events)) } // See also https://libvirt.org/html/libvirt-libvirt-event.html#virEventAddHandle func EventAddHandle(fd int, events EventHandleType, callback EventHandleCallback) (int, error) { callbackID := registerCallbackId(callback) var err C.virError ret := C.virEventAddHandleHelper((C.int)(fd), (C.int)(events), (C.int)(callbackID), &err) if ret == -1 { return 0, makeError(&err) } return int(ret), nil } // See also https://libvirt.org/html/libvirt-libvirt-event.html#virEventUpdateHandle func EventUpdateHandle(watch int, events EventHandleType) { C.virEventUpdateHandleWrapper((C.int)(watch), (C.int)(events)) } // See also https://libvirt.org/html/libvirt-libvirt-event.html#virEventRemoveHandle func EventRemoveHandle(watch int) error { var err C.virError ret := C.virEventRemoveHandleWrapper((C.int)(watch), &err) if ret < 0 { return makeError(&err) } return nil } type EventTimeoutCallback func(timer int) //export eventTimeoutCallback func eventTimeoutCallback(timer int, callbackID int) { callbackFunc := getCallbackId(callbackID) callback, ok := callbackFunc.(EventTimeoutCallback) if !ok { panic("Incorrect event timeout callback data") } callback(timer) } // See also https://libvirt.org/html/libvirt-libvirt-event.html#virEventAddTimeout func EventAddTimeout(freq int, callback EventTimeoutCallback) (int, error) { callbackID := registerCallbackId(callback) var err C.virError ret := C.virEventAddTimeoutHelper((C.int)(freq), (C.int)(callbackID), &err) if ret == -1 { return 0, makeError(&err) } return int(ret), nil } // See also https://libvirt.org/html/libvirt-libvirt-event.html#virEventUpdateTimeout func EventUpdateTimeout(timer int, freq int) { C.virEventUpdateTimeoutWrapper((C.int)(timer), (C.int)(freq)) } // See also https://libvirt.org/html/libvirt-libvirt-event.html#virEventRemoveTimeout func EventRemoveTimeout(timer int) error { var err C.virError ret := C.virEventRemoveTimeoutWrapper((C.int)(timer), &err) if ret < 0 { return makeError(&err) } return nil } type EventHandleCallbackInfo struct { callback uintptr opaque uintptr free uintptr } type EventTimeoutCallbackInfo struct { callback uintptr opaque uintptr free uintptr } func (i *EventHandleCallbackInfo) Invoke(watch int, fd int, event EventHandleType) { C.eventHandleCallbackInvoke(C.int(watch), C.int(fd), C.int(event), C.uintptr_t(i.callback), C.uintptr_t(i.opaque)) } func (i *EventTimeoutCallbackInfo) Invoke(timer int) { C.eventTimeoutCallbackInvoke(C.int(timer), C.uintptr_t(i.callback), C.uintptr_t(i.opaque)) } func (i *EventHandleCallbackInfo) Free() { C.eventHandleCallbackFree(C.uintptr_t(i.free), C.uintptr_t(i.opaque)) } func (i *EventTimeoutCallbackInfo) Free() { C.eventTimeoutCallbackFree(C.uintptr_t(i.free), C.uintptr_t(i.opaque)) } type EventLoop interface { AddHandleFunc(fd int, event EventHandleType, callback *EventHandleCallbackInfo) int UpdateHandleFunc(watch int, event EventHandleType) RemoveHandleFunc(watch int) int AddTimeoutFunc(freq int, callback *EventTimeoutCallbackInfo) int UpdateTimeoutFunc(timer int, freq int) RemoveTimeoutFunc(timer int) int } var eventLoopImpl EventLoop // See also https://libvirt.org/html/libvirt-libvirt-event.html#virEventRegisterImpl // // Note that registering an event loop implementation must be // done before creating any Connect object instance func EventRegisterImpl(impl EventLoop) error { var err C.virError eventLoopImpl = impl if C.virInitializeWrapper(&err) < 0 { return makeError(&err) } C.virEventRegisterImplHelper() return nil } //export eventAddHandleFunc func eventAddHandleFunc(fd C.int, event C.int, callback uintptr, opaque uintptr, free uintptr) C.int { if eventLoopImpl == nil { panic("Event loop impl is missing") } cbinfo := &EventHandleCallbackInfo{ callback: callback, opaque: opaque, free: free, } return C.int(eventLoopImpl.AddHandleFunc(int(fd), EventHandleType(event), cbinfo)) } //export eventUpdateHandleFunc func eventUpdateHandleFunc(watch C.int, event C.int) { if eventLoopImpl == nil { panic("Event loop impl is missing") } eventLoopImpl.UpdateHandleFunc(int(watch), EventHandleType(event)) } //export eventRemoveHandleFunc func eventRemoveHandleFunc(watch C.int) { if eventLoopImpl == nil { panic("Event loop impl is missing") } eventLoopImpl.RemoveHandleFunc(int(watch)) } //export eventAddTimeoutFunc func eventAddTimeoutFunc(freq C.int, callback uintptr, opaque uintptr, free uintptr) C.int { if eventLoopImpl == nil { panic("Event loop impl is missing") } cbinfo := &EventTimeoutCallbackInfo{ callback: callback, opaque: opaque, free: free, } return C.int(eventLoopImpl.AddTimeoutFunc(int(freq), cbinfo)) } //export eventUpdateTimeoutFunc func eventUpdateTimeoutFunc(timer C.int, freq C.int) { if eventLoopImpl == nil { panic("Event loop impl is missing") } eventLoopImpl.UpdateTimeoutFunc(int(timer), int(freq)) } //export eventRemoveTimeoutFunc func eventRemoveTimeoutFunc(timer C.int) { if eventLoopImpl == nil { panic("Event loop impl is missing") } eventLoopImpl.RemoveTimeoutFunc(int(timer)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/storage_pool.go
vendor/libvirt.org/go/libvirt/storage_pool.go
/* * This file is part of the libvirt-go-module project * * 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. * * Copyright (c) 2013 Alex Zorin * Copyright (C) 2016 Red Hat, Inc. * */ package libvirt /* #cgo !libvirt_dlopen pkg-config: libvirt #cgo libvirt_dlopen LDFLAGS: -ldl #cgo libvirt_dlopen CFLAGS: -DLIBVIRT_DLOPEN #include <stdlib.h> #include "libvirt_generated.h" */ import "C" import ( "reflect" "unsafe" ) type StoragePoolState int const ( STORAGE_POOL_INACTIVE = StoragePoolState(C.VIR_STORAGE_POOL_INACTIVE) // Not running STORAGE_POOL_BUILDING = StoragePoolState(C.VIR_STORAGE_POOL_BUILDING) // Initializing pool,not available STORAGE_POOL_RUNNING = StoragePoolState(C.VIR_STORAGE_POOL_RUNNING) // Running normally STORAGE_POOL_DEGRADED = StoragePoolState(C.VIR_STORAGE_POOL_DEGRADED) // Running degraded STORAGE_POOL_INACCESSIBLE = StoragePoolState(C.VIR_STORAGE_POOL_INACCESSIBLE) // Running,but not accessible ) type StoragePoolBuildFlags uint const ( STORAGE_POOL_BUILD_NEW = StoragePoolBuildFlags(C.VIR_STORAGE_POOL_BUILD_NEW) // Regular build from scratch STORAGE_POOL_BUILD_REPAIR = StoragePoolBuildFlags(C.VIR_STORAGE_POOL_BUILD_REPAIR) // Repair / reinitialize STORAGE_POOL_BUILD_RESIZE = StoragePoolBuildFlags(C.VIR_STORAGE_POOL_BUILD_RESIZE) // Extend existing pool STORAGE_POOL_BUILD_NO_OVERWRITE = StoragePoolBuildFlags(C.VIR_STORAGE_POOL_BUILD_NO_OVERWRITE) // Do not overwrite existing pool STORAGE_POOL_BUILD_OVERWRITE = StoragePoolBuildFlags(C.VIR_STORAGE_POOL_BUILD_OVERWRITE) // Overwrite data ) type StoragePoolCreateFlags uint const ( STORAGE_POOL_CREATE_NORMAL = StoragePoolCreateFlags(C.VIR_STORAGE_POOL_CREATE_NORMAL) STORAGE_POOL_CREATE_WITH_BUILD = StoragePoolCreateFlags(C.VIR_STORAGE_POOL_CREATE_WITH_BUILD) STORAGE_POOL_CREATE_WITH_BUILD_OVERWRITE = StoragePoolCreateFlags(C.VIR_STORAGE_POOL_CREATE_WITH_BUILD_OVERWRITE) STORAGE_POOL_CREATE_WITH_BUILD_NO_OVERWRITE = StoragePoolCreateFlags(C.VIR_STORAGE_POOL_CREATE_WITH_BUILD_NO_OVERWRITE) ) type StoragePoolDefineFlags uint const ( STORAGE_POOL_DEFINE_VALIDATE = StoragePoolDefineFlags(C.VIR_STORAGE_POOL_DEFINE_VALIDATE) ) type StoragePoolDeleteFlags uint const ( STORAGE_POOL_DELETE_NORMAL = StoragePoolDeleteFlags(C.VIR_STORAGE_POOL_DELETE_NORMAL) STORAGE_POOL_DELETE_ZEROED = StoragePoolDeleteFlags(C.VIR_STORAGE_POOL_DELETE_ZEROED) ) type StoragePoolEventID int const ( STORAGE_POOL_EVENT_ID_LIFECYCLE = StoragePoolEventID(C.VIR_STORAGE_POOL_EVENT_ID_LIFECYCLE) STORAGE_POOL_EVENT_ID_REFRESH = StoragePoolEventID(C.VIR_STORAGE_POOL_EVENT_ID_REFRESH) ) type StoragePoolEventLifecycleType int const ( STORAGE_POOL_EVENT_DEFINED = StoragePoolEventLifecycleType(C.VIR_STORAGE_POOL_EVENT_DEFINED) STORAGE_POOL_EVENT_UNDEFINED = StoragePoolEventLifecycleType(C.VIR_STORAGE_POOL_EVENT_UNDEFINED) STORAGE_POOL_EVENT_STARTED = StoragePoolEventLifecycleType(C.VIR_STORAGE_POOL_EVENT_STARTED) STORAGE_POOL_EVENT_STOPPED = StoragePoolEventLifecycleType(C.VIR_STORAGE_POOL_EVENT_STOPPED) STORAGE_POOL_EVENT_CREATED = StoragePoolEventLifecycleType(C.VIR_STORAGE_POOL_EVENT_CREATED) STORAGE_POOL_EVENT_DELETED = StoragePoolEventLifecycleType(C.VIR_STORAGE_POOL_EVENT_DELETED) ) type StoragePool struct { ptr C.virStoragePoolPtr } type StoragePoolInfo struct { State StoragePoolState Capacity uint64 Allocation uint64 Available uint64 } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolBuild func (p *StoragePool) Build(flags StoragePoolBuildFlags) error { var err C.virError result := C.virStoragePoolBuildWrapper(p.ptr, C.uint(flags), &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolCreate func (p *StoragePool) Create(flags StoragePoolCreateFlags) error { var err C.virError result := C.virStoragePoolCreateWrapper(p.ptr, C.uint(flags), &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolDelete func (p *StoragePool) Delete(flags StoragePoolDeleteFlags) error { var err C.virError result := C.virStoragePoolDeleteWrapper(p.ptr, C.uint(flags), &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolDestroy func (p *StoragePool) Destroy() error { var err C.virError result := C.virStoragePoolDestroyWrapper(p.ptr, &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolFree func (p *StoragePool) Free() error { var err C.virError ret := C.virStoragePoolFreeWrapper(p.ptr, &err) if ret == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolRef func (c *StoragePool) Ref() error { var err C.virError ret := C.virStoragePoolRefWrapper(c.ptr, &err) if ret == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolGetAutostart func (p *StoragePool) GetAutostart() (bool, error) { var out C.int var err C.virError result := C.virStoragePoolGetAutostartWrapper(p.ptr, (*C.int)(unsafe.Pointer(&out)), &err) if result == -1 { return false, makeError(&err) } switch out { case 1: return true, nil default: return false, nil } } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolGetInfo func (p *StoragePool) GetInfo() (*StoragePoolInfo, error) { var cinfo C.virStoragePoolInfo var err C.virError result := C.virStoragePoolGetInfoWrapper(p.ptr, &cinfo, &err) if result == -1 { return nil, makeError(&err) } return &StoragePoolInfo{ State: StoragePoolState(cinfo.state), Capacity: uint64(cinfo.capacity), Allocation: uint64(cinfo.allocation), Available: uint64(cinfo.available), }, nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolGetName func (p *StoragePool) GetName() (string, error) { var err C.virError name := C.virStoragePoolGetNameWrapper(p.ptr, &err) if name == nil { return "", makeError(&err) } return C.GoString(name), nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolGetUUID func (p *StoragePool) GetUUID() ([]byte, error) { var cUuid [C.VIR_UUID_BUFLEN](byte) cuidPtr := unsafe.Pointer(&cUuid) var err C.virError result := C.virStoragePoolGetUUIDWrapper(p.ptr, (*C.uchar)(cuidPtr), &err) if result != 0 { return []byte{}, makeError(&err) } return C.GoBytes(cuidPtr, C.VIR_UUID_BUFLEN), nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolGetUUIDString func (p *StoragePool) GetUUIDString() (string, error) { var cUuid [C.VIR_UUID_STRING_BUFLEN](C.char) cuidPtr := unsafe.Pointer(&cUuid) var err C.virError result := C.virStoragePoolGetUUIDStringWrapper(p.ptr, (*C.char)(cuidPtr), &err) if result != 0 { return "", makeError(&err) } return C.GoString((*C.char)(cuidPtr)), nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolGetXMLDesc func (p *StoragePool) GetXMLDesc(flags StorageXMLFlags) (string, error) { var err C.virError result := C.virStoragePoolGetXMLDescWrapper(p.ptr, C.uint(flags), &err) if result == nil { return "", makeError(&err) } xml := C.GoString(result) C.free(unsafe.Pointer(result)) return xml, nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolIsActive func (p *StoragePool) IsActive() (bool, error) { var err C.virError result := C.virStoragePoolIsActiveWrapper(p.ptr, &err) if result == -1 { return false, makeError(&err) } if result == 1 { return true, nil } return false, nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolIsPersistent func (p *StoragePool) IsPersistent() (bool, error) { var err C.virError result := C.virStoragePoolIsPersistentWrapper(p.ptr, &err) if result == -1 { return false, makeError(&err) } if result == 1 { return true, nil } return false, nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolSetAutostart func (p *StoragePool) SetAutostart(autostart bool) error { var cAutostart C.int switch autostart { case true: cAutostart = 1 default: cAutostart = 0 } var err C.virError result := C.virStoragePoolSetAutostartWrapper(p.ptr, cAutostart, &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolRefresh func (p *StoragePool) Refresh(flags uint32) error { var err C.virError result := C.virStoragePoolRefreshWrapper(p.ptr, C.uint(flags), &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolUndefine func (p *StoragePool) Undefine() error { var err C.virError result := C.virStoragePoolUndefineWrapper(p.ptr, &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStorageVolCreateXML func (p *StoragePool) StorageVolCreateXML(xmlConfig string, flags StorageVolCreateFlags) (*StorageVol, error) { cXml := C.CString(string(xmlConfig)) defer C.free(unsafe.Pointer(cXml)) var err C.virError ptr := C.virStorageVolCreateXMLWrapper(p.ptr, cXml, C.uint(flags), &err) if ptr == nil { return nil, makeError(&err) } return &StorageVol{ptr: ptr}, nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStorageVolCreateXMLFrom func (p *StoragePool) StorageVolCreateXMLFrom(xmlConfig string, clonevol *StorageVol, flags StorageVolCreateFlags) (*StorageVol, error) { cXml := C.CString(string(xmlConfig)) defer C.free(unsafe.Pointer(cXml)) var err C.virError ptr := C.virStorageVolCreateXMLFromWrapper(p.ptr, cXml, clonevol.ptr, C.uint(flags), &err) if ptr == nil { return nil, makeError(&err) } return &StorageVol{ptr: ptr}, nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStorageVolLookupByName func (p *StoragePool) LookupStorageVolByName(name string) (*StorageVol, error) { cName := C.CString(name) defer C.free(unsafe.Pointer(cName)) var err C.virError ptr := C.virStorageVolLookupByNameWrapper(p.ptr, cName, &err) if ptr == nil { return nil, makeError(&err) } return &StorageVol{ptr: ptr}, nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolNumOfVolumes func (p *StoragePool) NumOfStorageVolumes() (int, error) { var err C.virError result := int(C.virStoragePoolNumOfVolumesWrapper(p.ptr, &err)) if result == -1 { return 0, makeError(&err) } return result, nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolListVolumes func (p *StoragePool) ListStorageVolumes() ([]string, error) { const maxVols = 1024 var names [maxVols](*C.char) namesPtr := unsafe.Pointer(&names) var err C.virError numStorageVols := C.virStoragePoolListVolumesWrapper( p.ptr, (**C.char)(namesPtr), maxVols, &err) if numStorageVols == -1 { return nil, makeError(&err) } goNames := make([]string, numStorageVols) for k := 0; k < int(numStorageVols); k++ { goNames[k] = C.GoString(names[k]) C.free(unsafe.Pointer(names[k])) } return goNames, nil } // See also https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolListAllVolumes func (p *StoragePool) ListAllStorageVolumes(flags uint32) ([]StorageVol, error) { var cList *C.virStorageVolPtr var err C.virError numVols := C.virStoragePoolListAllVolumesWrapper(p.ptr, (**C.virStorageVolPtr)(&cList), C.uint(flags), &err) if numVols == -1 { return nil, makeError(&err) } hdr := reflect.SliceHeader{ Data: uintptr(unsafe.Pointer(cList)), Len: int(numVols), Cap: int(numVols), } var pools []StorageVol slice := *(*[]C.virStorageVolPtr)(unsafe.Pointer(&hdr)) for _, ptr := range slice { pools = append(pools, StorageVol{ptr}) } C.free(unsafe.Pointer(cList)) return pools, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/node_device.go
vendor/libvirt.org/go/libvirt/node_device.go
/* * This file is part of the libvirt-go-module project * * 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. * * Copyright (c) 2013 Alex Zorin * Copyright (C) 2016 Red Hat, Inc. * */ package libvirt /* #cgo !libvirt_dlopen pkg-config: libvirt #cgo libvirt_dlopen LDFLAGS: -ldl #cgo libvirt_dlopen CFLAGS: -DLIBVIRT_DLOPEN #include <stdlib.h> #include "libvirt_generated.h" */ import "C" import ( "unsafe" ) type NodeDeviceEventID int const ( NODE_DEVICE_EVENT_ID_LIFECYCLE = NodeDeviceEventID(C.VIR_NODE_DEVICE_EVENT_ID_LIFECYCLE) NODE_DEVICE_EVENT_ID_UPDATE = NodeDeviceEventID(C.VIR_NODE_DEVICE_EVENT_ID_UPDATE) ) type NodeDeviceEventLifecycleType int const ( NODE_DEVICE_EVENT_CREATED = NodeDeviceEventLifecycleType(C.VIR_NODE_DEVICE_EVENT_CREATED) NODE_DEVICE_EVENT_DELETED = NodeDeviceEventLifecycleType(C.VIR_NODE_DEVICE_EVENT_DELETED) NODE_DEVICE_EVENT_DEFINED = NodeDeviceEventLifecycleType(C.VIR_NODE_DEVICE_EVENT_DEFINED) NODE_DEVICE_EVENT_UNDEFINED = NodeDeviceEventLifecycleType(C.VIR_NODE_DEVICE_EVENT_UNDEFINED) ) type NodeDeviceCreateXMLFlags int const ( NODE_DEVICE_CREATE_XML_VALIDATE = NodeDeviceCreateXMLFlags(C.VIR_NODE_DEVICE_CREATE_XML_VALIDATE) ) type NodeDeviceDefineXMLFlags int const ( NODE_DEVICE_DEFINE_XML_VALIDATE = NodeDeviceDefineXMLFlags(C.VIR_NODE_DEVICE_DEFINE_XML_VALIDATE) ) type NodeDeviceXMLFlags int const ( NODE_DEVICE_XML_INACTIVE = NodeDeviceXMLFlags(C.VIR_NODE_DEVICE_XML_INACTIVE) ) type NodeDeviceUpdateFlags int const ( NODE_DEVICE_UPDATE_AFFECT_CURRENT = NodeDeviceUpdateFlags(C.VIR_NODE_DEVICE_UPDATE_AFFECT_CURRENT) NODE_DEVICE_UPDATE_AFFECT_CONFIG = NodeDeviceUpdateFlags(C.VIR_NODE_DEVICE_UPDATE_AFFECT_CONFIG) NODE_DEVICE_UPDATE_AFFECT_LIVE = NodeDeviceUpdateFlags(C.VIR_NODE_DEVICE_UPDATE_AFFECT_LIVE) ) type NodeDevice struct { ptr C.virNodeDevicePtr } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceFree func (n *NodeDevice) Free() error { var err C.virError ret := C.virNodeDeviceFreeWrapper(n.ptr, &err) if ret == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceRef func (c *NodeDevice) Ref() error { var err C.virError ret := C.virNodeDeviceRefWrapper(c.ptr, &err) if ret == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceDestroy func (n *NodeDevice) Destroy() error { var err C.virError result := C.virNodeDeviceDestroyWrapper(n.ptr, &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceReset func (n *NodeDevice) Reset() error { var err C.virError result := C.virNodeDeviceResetWrapper(n.ptr, &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceDettach func (n *NodeDevice) Detach() error { var err C.virError result := C.virNodeDeviceDettachWrapper(n.ptr, &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceDetachFlags func (n *NodeDevice) DetachFlags(driverName string, flags uint32) error { cDriverName := C.CString(driverName) defer C.free(unsafe.Pointer(cDriverName)) var err C.virError result := C.virNodeDeviceDetachFlagsWrapper(n.ptr, cDriverName, C.uint(flags), &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceReAttach func (n *NodeDevice) ReAttach() error { var err C.virError result := C.virNodeDeviceReAttachWrapper(n.ptr, &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceGetName func (n *NodeDevice) GetName() (string, error) { var err C.virError name := C.virNodeDeviceGetNameWrapper(n.ptr, &err) if name == nil { return "", makeError(&err) } return C.GoString(name), nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceGetXMLDesc func (n *NodeDevice) GetXMLDesc(flags NodeDeviceXMLFlags) (string, error) { var err C.virError result := C.virNodeDeviceGetXMLDescWrapper(n.ptr, C.uint(flags), &err) if result == nil { return "", makeError(&err) } xml := C.GoString(result) C.free(unsafe.Pointer(result)) return xml, nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceGetParent func (n *NodeDevice) GetParent() (string, error) { var err C.virError result := C.virNodeDeviceGetParentWrapper(n.ptr, &err) if result == nil { return "", makeError(&err) } defer C.free(unsafe.Pointer(result)) return C.GoString(result), nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceNumOfCaps func (p *NodeDevice) NumOfCaps() (int, error) { var err C.virError result := int(C.virNodeDeviceNumOfCapsWrapper(p.ptr, &err)) if result == -1 { return 0, makeError(&err) } return result, nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceListCaps func (p *NodeDevice) ListCaps() ([]string, error) { const maxCaps = 1024 var names [maxCaps](*C.char) namesPtr := unsafe.Pointer(&names) var err C.virError numCaps := C.virNodeDeviceListCapsWrapper( p.ptr, (**C.char)(namesPtr), maxCaps, &err) if numCaps == -1 { return nil, makeError(&err) } goNames := make([]string, numCaps) for k := 0; k < int(numCaps); k++ { goNames[k] = C.GoString(names[k]) C.free(unsafe.Pointer(names[k])) } return goNames, nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceCreate func (p *NodeDevice) Create(flags uint32) error { var err C.virError result := C.virNodeDeviceCreateWrapper(p.ptr, C.uint(flags), &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-nodedev.html#virNodeDeviceUndefine func (p *NodeDevice) Undefine(flags uint32) error { var err C.virError result := C.virNodeDeviceUndefineWrapper(p.ptr, C.uint(flags), &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-network.html#virNodeDeviceGetAutostart func (n *NodeDevice) GetAutostart() (bool, error) { var out C.int var err C.virError result := C.virNodeDeviceGetAutostartWrapper(n.ptr, (*C.int)(unsafe.Pointer(&out)), &err) if result == -1 { return false, makeError(&err) } switch out { case 1: return true, nil default: return false, nil } } // See also https://libvirt.org/html/libvirt-libvirt-network.html#virNodeDeviceSetAutostart func (n *NodeDevice) SetAutostart(autostart bool) error { var cAutostart C.int switch autostart { case true: cAutostart = 1 default: cAutostart = 0 } var err C.virError result := C.virNodeDeviceSetAutostartWrapper(n.ptr, cAutostart, &err) if result == -1 { return makeError(&err) } return nil } // See also https://libvirt.org/html/libvirt-libvirt-network.html#virNodeDeviceIsActive func (n *NodeDevice) IsActive() (bool, error) { var err C.virError result := C.virNodeDeviceIsActiveWrapper(n.ptr, &err) if result == -1 { return false, makeError(&err) } if result == 1 { return true, nil } return false, nil } // See also https://libvirt.org/html/libvirt-libvirt-network.html#virNodeDeviceIsPersistent func (n *NodeDevice) IsPersistent() (bool, error) { var err C.virError result := C.virNodeDeviceIsPersistentWrapper(n.ptr, &err) if result == -1 { return false, makeError(&err) } if result == 1 { return true, nil } return false, nil } // See also https://libvirt.org/html/libvirt-libvirt-network.html#virNodeDeviceUpdate func (n *NodeDevice) Update(xml string, flags NodeDeviceUpdateFlags) error { cXml := C.CString(xml) defer C.free(unsafe.Pointer(cXml)) var err C.virError result := C.virNodeDeviceUpdateWrapper(n.ptr, cXml, C.uint(flags), &err) if result == -1 { return makeError(&err) } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/libvirt_lxc_generated_dlopen.go
vendor/libvirt.org/go/libvirt/libvirt_lxc_generated_dlopen.go
//go:build !libvirt_without_lxc && libvirt_dlopen // +build !libvirt_without_lxc,libvirt_dlopen /* * This file is part of the libvirt-go-module project * * 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. * * Copyright (C) 2022 Red Hat, Inc. * */ /**************************************************************************** * THIS CODE HAS BEEN GENERATED. DO NOT CHANGE IT DIRECTLY * ****************************************************************************/ package libvirt /* #cgo libvirt_dlopen LDFLAGS: -ldl #cgo libvirt_dlopen CFLAGS: -DLIBVIRT_DLOPEN #include <dlfcn.h> #include <stdbool.h> #include <stdio.h> #include "libvirt_lxc_generated_dlopen.h" #include "error_helper.h" static void *handle; static bool once; static void * libvirtLxcLoad(virErrorPtr err) { char *errMsg; if (once) { if (handle == NULL) { setVirError(err, "Failed to open libvirt-lxc.so.0"); } return handle; } handle = dlopen("libvirt-lxc.so.0", RTLD_NOW|RTLD_LOCAL); once = true; if (handle == NULL) { setVirError(err, dlerror()); return handle; } return handle; } bool libvirtLxcSymbol(const char *name, void **symbol, bool *once, bool *success, virErrorPtr err) { char *errMsg; if (!libvirtLxcLoad(err)) { return *success; } if (*once) { if (!*success) { // Set error for successive calls char msg[100]; snprintf(msg, 100, "Failed to load %s", name); setVirError(err, msg); } return *success; } // Documentation of dlsym says we should use dlerror() to check for failure // in dlsym() as a NULL might be the right address for a given symbol. // This is also the reason to have the @success argument. *symbol = dlsym(handle, name); if ((errMsg = dlerror()) != NULL) { setVirError(err, errMsg); *once = true; return *success; } *once = true; *success = true; return *success; } */ import "C"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/callbacks.go
vendor/libvirt.org/go/libvirt/callbacks.go
/* * This file is part of the libvirt-go-module project * * 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. * * Copyright (c) 2013 Alex Zorin * Copyright (C) 2016 Red Hat, Inc. * */ package libvirt // Helpers functions to register a Go callback function to a C // function. For a simple example, look at how SetErrorFunc works in // error.go. // // - Create a struct that will contain at least the Go callback to // invoke (errorContext). // // - Create an exported Golang function whose job will be to retrieve // the context and execute the callback in it // (connErrCallback). Such a function should receive a callback ID // and will use it to retrive the context. // // - Create a CGO function similar to the above function but with the // appropriate signature to be registered as a callback in C code // (connErrCallbackHelper). Notably, it will have a void * argument // that should be cast to long to retrieve the callback ID. It // should be just a thin wrapper to transform the opaque argument to // a callback ID. // // - Create a CGO function which will be a wrapper around the C // function to register the callback (virConnSetErrorFuncWrapper). Its // only role is to transform a callback ID (long) to an opaque (void *) // and call the C function. // // - When setting up a callback (SetErrorFunc), register the struct from first step // with registerCallbackId and invoke the CGO function from the // previous step with the appropriate ID. // // - When unregistering the callback, don't forget to call freecallbackId. // // If you need to associate some additional data with the connection, // look at saveConnectionData, getConnectionData and // releaseConnectionData. import "C" import ( "sync" ) const firstGoCallbackId int = 100 // help catch some additional errors during test var goCallbackLock sync.RWMutex var goCallbacks = make(map[int]interface{}) var nextGoCallbackId int = firstGoCallbackId //export freeCallbackId func freeCallbackId(goCallbackId int) { goCallbackLock.Lock() defer goCallbackLock.Unlock() delete(goCallbacks, goCallbackId) } func getCallbackId(goCallbackId int) interface{} { goCallbackLock.RLock() defer goCallbackLock.RUnlock() ctx := goCallbacks[goCallbackId] if ctx == nil { // If this happens there must be a bug in libvirt panic("Callback arrived after freeCallbackId was called") } return ctx } func registerCallbackId(ctx interface{}) int { goCallbackLock.Lock() defer goCallbackLock.Unlock() goCallBackId := nextGoCallbackId nextGoCallbackId++ for goCallbacks[nextGoCallbackId] != nil { nextGoCallbackId++ } goCallbacks[goCallBackId] = ctx return goCallBackId }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/node_device_events.go
vendor/libvirt.org/go/libvirt/node_device_events.go
/* * This file is part of the libvirt-go-module project * * 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. * * Copyright (c) 2013 Alex Zorin * Copyright (C) 2016 Red Hat, Inc. * */ package libvirt import ( "fmt" "unsafe" ) /* #cgo !libvirt_dlopen pkg-config: libvirt #cgo libvirt_dlopen LDFLAGS: -ldl #cgo libvirt_dlopen CFLAGS: -DLIBVIRT_DLOPEN #include "node_device_events_helper.h" */ import "C" type NodeDeviceEventGenericCallback func(c *Connect, d *NodeDevice) type NodeDeviceEventLifecycle struct { Event NodeDeviceEventLifecycleType // TODO: we can make Detail typesafe somehow ? Detail int } type NodeDeviceEventLifecycleCallback func(c *Connect, n *NodeDevice, event *NodeDeviceEventLifecycle) //export nodeDeviceEventLifecycleCallback func nodeDeviceEventLifecycleCallback(c C.virConnectPtr, s C.virNodeDevicePtr, event int, detail int, goCallbackId int) { node_device := &NodeDevice{ptr: s} connection := &Connect{ptr: c} eventDetails := &NodeDeviceEventLifecycle{ Event: NodeDeviceEventLifecycleType(event), Detail: detail, } callbackFunc := getCallbackId(goCallbackId) callback, ok := callbackFunc.(NodeDeviceEventLifecycleCallback) if !ok { panic("Inappropriate callback type called") } callback(connection, node_device, eventDetails) } //export nodeDeviceEventGenericCallback func nodeDeviceEventGenericCallback(c C.virConnectPtr, d C.virNodeDevicePtr, goCallbackId int) { node_device := &NodeDevice{ptr: d} connection := &Connect{ptr: c} callbackFunc := getCallbackId(goCallbackId) callback, ok := callbackFunc.(NodeDeviceEventGenericCallback) if !ok { panic("Inappropriate callback type called") } callback(connection, node_device) } func (c *Connect) NodeDeviceEventLifecycleRegister(device *NodeDevice, callback NodeDeviceEventLifecycleCallback) (int, error) { goCallBackId := registerCallbackId(callback) callbackPtr := unsafe.Pointer(C.nodeDeviceEventLifecycleCallbackHelper) var cdevice C.virNodeDevicePtr if device != nil { cdevice = device.ptr } var err C.virError ret := C.virConnectNodeDeviceEventRegisterAnyHelper(c.ptr, cdevice, C.VIR_NODE_DEVICE_EVENT_ID_LIFECYCLE, C.virConnectNodeDeviceEventGenericCallback(callbackPtr), C.long(goCallBackId), &err) if ret == -1 { freeCallbackId(goCallBackId) return 0, makeError(&err) } return int(ret), nil } func (c *Connect) NodeDeviceEventUpdateRegister(device *NodeDevice, callback NodeDeviceEventGenericCallback) (int, error) { goCallBackId := registerCallbackId(callback) callbackPtr := unsafe.Pointer(C.nodeDeviceEventGenericCallbackHelper) var cdevice C.virNodeDevicePtr if device != nil { cdevice = device.ptr } var err C.virError ret := C.virConnectNodeDeviceEventRegisterAnyHelper(c.ptr, cdevice, C.VIR_NODE_DEVICE_EVENT_ID_UPDATE, C.virConnectNodeDeviceEventGenericCallback(callbackPtr), C.long(goCallBackId), &err) if ret == -1 { freeCallbackId(goCallBackId) return 0, makeError(&err) } return int(ret), nil } func (c *Connect) NodeDeviceEventDeregister(callbackId int) error { // Deregister the callback var err C.virError ret := int(C.virConnectNodeDeviceEventDeregisterAnyWrapper(c.ptr, C.int(callbackId), &err)) if ret < 0 { return makeError(&err) } return nil } func (e NodeDeviceEventLifecycle) String() string { var event string switch e.Event { case NODE_DEVICE_EVENT_CREATED: event = "created" case NODE_DEVICE_EVENT_DELETED: event = "deleted" default: event = "unknown" } return fmt.Sprintf("NodeDevice event=%q", event) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/libvirt_generated_dlopen.go
vendor/libvirt.org/go/libvirt/libvirt_generated_dlopen.go
//go:build libvirt_dlopen // +build libvirt_dlopen /* * This file is part of the libvirt-go-module project * * 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. * * Copyright (C) 2022 Red Hat, Inc. * */ /**************************************************************************** * THIS CODE HAS BEEN GENERATED. DO NOT CHANGE IT DIRECTLY * ****************************************************************************/ package libvirt /* #cgo libvirt_dlopen LDFLAGS: -ldl #cgo libvirt_dlopen CFLAGS: -DLIBVIRT_DLOPEN #include <dlfcn.h> #include <stdbool.h> #include <stdio.h> #include "libvirt_generated_dlopen.h" #include "error_helper.h" static void *handle; static bool once; virConnectAuthPtr *virConnectAuthPtrDefaultVar; static void * libvirtLoad(virErrorPtr err) { char *errMsg; if (once) { if (handle == NULL) { setVirError(err, "Failed to open libvirt.so.0"); } return handle; } handle = dlopen("libvirt.so.0", RTLD_NOW|RTLD_LOCAL); once = true; if (handle == NULL) { setVirError(err, dlerror()); return handle; } virConnectAuthPtrDefaultVar = dlsym(handle, "virConnectAuthPtrDefault"); if ((errMsg = dlerror()) != NULL) { setVirError(err, errMsg); dlclose(handle); return NULL; } return handle; } bool libvirtSymbol(const char *name, void **symbol, bool *once, bool *success, virErrorPtr err) { char *errMsg; if (!libvirtLoad(err)) { return *success; } if (*once) { if (!*success) { // Set error for successive calls char msg[100]; snprintf(msg, 100, "Failed to load %s", name); setVirError(err, msg); } return *success; } // Documentation of dlsym says we should use dlerror() to check for failure // in dlsym() as a NULL might be the right address for a given symbol. // This is also the reason to have the @success argument. *symbol = dlsym(handle, name); if ((errMsg = dlerror()) != NULL) { setVirError(err, errMsg); *once = true; return *success; } *once = true; *success = true; return *success; } */ import "C"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/libvirt_generated_functions_static_common.go
vendor/libvirt.org/go/libvirt/libvirt_generated_functions_static_common.go
//go:build !libvirt_dlopen // +build !libvirt_dlopen /* * This file is part of the libvirt-go-module project * * 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. * * Copyright (C) 2022 Red Hat, Inc. * */ /**************************************************************************** * THIS CODE HAS BEEN GENERATED. DO NOT CHANGE IT DIRECTLY * ****************************************************************************/ package libvirt /* #cgo pkg-config: libvirt #include <assert.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include "libvirt_generated.h" #include "error_helper.h" int virTypedParamsAddBooleanWrapper(virTypedParameterPtr * params, int * nparams, int * maxparams, const char * name, int value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsAddBoolean not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsAddBoolean(params, nparams, maxparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsAddDoubleWrapper(virTypedParameterPtr * params, int * nparams, int * maxparams, const char * name, double value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsAddDouble not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsAddDouble(params, nparams, maxparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsAddFromStringWrapper(virTypedParameterPtr * params, int * nparams, int * maxparams, const char * name, int type, const char * value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsAddFromString not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsAddFromString(params, nparams, maxparams, name, type, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsAddIntWrapper(virTypedParameterPtr * params, int * nparams, int * maxparams, const char * name, int value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsAddInt not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsAddInt(params, nparams, maxparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsAddLLongWrapper(virTypedParameterPtr * params, int * nparams, int * maxparams, const char * name, long long value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsAddLLong not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsAddLLong(params, nparams, maxparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsAddStringWrapper(virTypedParameterPtr * params, int * nparams, int * maxparams, const char * name, const char * value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsAddString not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsAddString(params, nparams, maxparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsAddStringListWrapper(virTypedParameterPtr * params, int * nparams, int * maxparams, const char * name, const char ** values, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 2, 17) setVirError(err, "Function virTypedParamsAddStringList not available prior to libvirt version 1.2.17"); #else ret = virTypedParamsAddStringList(params, nparams, maxparams, name, values); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsAddUIntWrapper(virTypedParameterPtr * params, int * nparams, int * maxparams, const char * name, unsigned int value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsAddUInt not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsAddUInt(params, nparams, maxparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsAddULLongWrapper(virTypedParameterPtr * params, int * nparams, int * maxparams, const char * name, unsigned long long value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsAddULLong not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsAddULLong(params, nparams, maxparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } void virTypedParamsClearWrapper(virTypedParameterPtr params, int nparams) { #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(NULL, "Function virTypedParamsClear not available prior to libvirt version 1.0.2"); #else virTypedParamsClear(params, nparams); #endif return; } void virTypedParamsFreeWrapper(virTypedParameterPtr params, int nparams) { #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(NULL, "Function virTypedParamsFree not available prior to libvirt version 1.0.2"); #else virTypedParamsFree(params, nparams); #endif return; } virTypedParameterPtr virTypedParamsGetWrapper(virTypedParameterPtr params, int nparams, const char * name, virErrorPtr err) { virTypedParameterPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsGet not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsGet(params, nparams, name); if (!ret) { virCopyLastError(err); } #endif return ret; } int virTypedParamsGetBooleanWrapper(virTypedParameterPtr params, int nparams, const char * name, int * value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsGetBoolean not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsGetBoolean(params, nparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsGetDoubleWrapper(virTypedParameterPtr params, int nparams, const char * name, double * value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsGetDouble not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsGetDouble(params, nparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsGetIntWrapper(virTypedParameterPtr params, int nparams, const char * name, int * value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsGetInt not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsGetInt(params, nparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsGetLLongWrapper(virTypedParameterPtr params, int nparams, const char * name, long long * value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsGetLLong not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsGetLLong(params, nparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsGetStringWrapper(virTypedParameterPtr params, int nparams, const char * name, const char ** value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsGetString not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsGetString(params, nparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsGetUIntWrapper(virTypedParameterPtr params, int nparams, const char * name, unsigned int * value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsGetUInt not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsGetUInt(params, nparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virTypedParamsGetULLongWrapper(virTypedParameterPtr params, int nparams, const char * name, unsigned long long * value, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(1, 0, 2) setVirError(err, "Function virTypedParamsGetULLong not available prior to libvirt version 1.0.2"); #else ret = virTypedParamsGetULLong(params, nparams, name, value); if (ret < 0) { virCopyLastError(err); } #endif return ret; } */ import "C"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/network_events_helper.go
vendor/libvirt.org/go/libvirt/network_events_helper.go
/* * This file is part of the libvirt-go-module project * * 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. * * Copyright (c) 2013 Alex Zorin * Copyright (C) 2016 Red Hat, Inc. * */ package libvirt /* #cgo !libvirt_dlopen pkg-config: libvirt #cgo libvirt_dlopen LDFLAGS: -ldl #cgo libvirt_dlopen CFLAGS: -DLIBVIRT_DLOPEN #include <stdint.h> #include "network_events_helper.h" #include "callbacks_helper.h" extern void networkEventLifecycleCallback(virConnectPtr, virNetworkPtr, int, int, int); void networkEventLifecycleCallbackHelper(virConnectPtr conn, virNetworkPtr net, int event, int detail, void *data) { networkEventLifecycleCallback(conn, net, event, detail, (int)(intptr_t)data); } extern void networkEventMetadataChangeCallback(virConnectPtr, virNetworkPtr, int, const char *, int); void networkEventMetadataChangeCallbackHelper(virConnectPtr conn, virNetworkPtr net, int type, const char *nsuri, void *opaque) { networkEventMetadataChangeCallback(conn, net, type, nsuri, (int)(intptr_t)opaque); } int virConnectNetworkEventRegisterAnyHelper(virConnectPtr conn, virNetworkPtr net, int eventID, virConnectNetworkEventGenericCallback cb, long goCallbackId, virErrorPtr err) { void *id = (void *)goCallbackId; return virConnectNetworkEventRegisterAnyWrapper(conn, net, eventID, cb, id, freeGoCallbackHelper, err); } */ import "C"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/libvirt_generated_functions_static_storage.go
vendor/libvirt.org/go/libvirt/libvirt_generated_functions_static_storage.go
//go:build !libvirt_dlopen // +build !libvirt_dlopen /* * This file is part of the libvirt-go-module project * * 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. * * Copyright (C) 2022 Red Hat, Inc. * */ /**************************************************************************** * THIS CODE HAS BEEN GENERATED. DO NOT CHANGE IT DIRECTLY * ****************************************************************************/ package libvirt /* #cgo pkg-config: libvirt #include <assert.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include "libvirt_generated.h" #include "error_helper.h" char * virConnectFindStoragePoolSourcesWrapper(virConnectPtr conn, const char * type, const char * srcSpec, unsigned int flags, virErrorPtr err) { char * ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 5) setVirError(err, "Function virConnectFindStoragePoolSources not available prior to libvirt version 0.4.5"); #else ret = virConnectFindStoragePoolSources(conn, type, srcSpec, flags); if (!ret) { virCopyLastError(err); } #endif return ret; } char * virConnectGetStoragePoolCapabilitiesWrapper(virConnectPtr conn, unsigned int flags, virErrorPtr err) { char * ret = NULL; #if !LIBVIR_CHECK_VERSION(5, 2, 0) setVirError(err, "Function virConnectGetStoragePoolCapabilities not available prior to libvirt version 5.2.0"); #else ret = virConnectGetStoragePoolCapabilities(conn, flags); if (!ret) { virCopyLastError(err); } #endif return ret; } int virConnectListAllStoragePoolsWrapper(virConnectPtr conn, virStoragePoolPtr ** pools, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 10, 2) setVirError(err, "Function virConnectListAllStoragePools not available prior to libvirt version 0.10.2"); #else ret = virConnectListAllStoragePools(conn, pools, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virConnectListDefinedStoragePoolsWrapper(virConnectPtr conn, char ** const names, int maxnames, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virConnectListDefinedStoragePools not available prior to libvirt version 0.4.1"); #else ret = virConnectListDefinedStoragePools(conn, names, maxnames); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virConnectListStoragePoolsWrapper(virConnectPtr conn, char ** const names, int maxnames, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virConnectListStoragePools not available prior to libvirt version 0.4.1"); #else ret = virConnectListStoragePools(conn, names, maxnames); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virConnectNumOfDefinedStoragePoolsWrapper(virConnectPtr conn, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virConnectNumOfDefinedStoragePools not available prior to libvirt version 0.4.1"); #else ret = virConnectNumOfDefinedStoragePools(conn); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virConnectNumOfStoragePoolsWrapper(virConnectPtr conn, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virConnectNumOfStoragePools not available prior to libvirt version 0.4.1"); #else ret = virConnectNumOfStoragePools(conn); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virConnectStoragePoolEventDeregisterAnyWrapper(virConnectPtr conn, int callbackID, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(2, 0, 0) setVirError(err, "Function virConnectStoragePoolEventDeregisterAny not available prior to libvirt version 2.0.0"); #else ret = virConnectStoragePoolEventDeregisterAny(conn, callbackID); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virConnectStoragePoolEventRegisterAnyWrapper(virConnectPtr conn, virStoragePoolPtr pool, int eventID, virConnectStoragePoolEventGenericCallback cb, void * opaque, virFreeCallback freecb, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(2, 0, 0) setVirError(err, "Function virConnectStoragePoolEventRegisterAny not available prior to libvirt version 2.0.0"); #else ret = virConnectStoragePoolEventRegisterAny(conn, pool, eventID, cb, opaque, freecb); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolBuildWrapper(virStoragePoolPtr pool, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolBuild not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolBuild(pool, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolCreateWrapper(virStoragePoolPtr pool, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolCreate not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolCreate(pool, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } virStoragePoolPtr virStoragePoolCreateXMLWrapper(virConnectPtr conn, const char * xmlDesc, unsigned int flags, virErrorPtr err) { virStoragePoolPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolCreateXML not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolCreateXML(conn, xmlDesc, flags); if (!ret) { virCopyLastError(err); } #endif return ret; } virStoragePoolPtr virStoragePoolDefineXMLWrapper(virConnectPtr conn, const char * xml, unsigned int flags, virErrorPtr err) { virStoragePoolPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolDefineXML not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolDefineXML(conn, xml, flags); if (!ret) { virCopyLastError(err); } #endif return ret; } int virStoragePoolDeleteWrapper(virStoragePoolPtr pool, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolDelete not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolDelete(pool, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolDestroyWrapper(virStoragePoolPtr pool, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolDestroy not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolDestroy(pool); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolFreeWrapper(virStoragePoolPtr pool, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolFree not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolFree(pool); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolGetAutostartWrapper(virStoragePoolPtr pool, int * autostart, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolGetAutostart not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolGetAutostart(pool, autostart); if (ret < 0) { virCopyLastError(err); } #endif return ret; } virConnectPtr virStoragePoolGetConnectWrapper(virStoragePoolPtr pool, virErrorPtr err) { virConnectPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolGetConnect not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolGetConnect(pool); if (!ret) { virCopyLastError(err); } #endif return ret; } int virStoragePoolGetInfoWrapper(virStoragePoolPtr pool, virStoragePoolInfoPtr info, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolGetInfo not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolGetInfo(pool, info); if (ret < 0) { virCopyLastError(err); } #endif return ret; } const char * virStoragePoolGetNameWrapper(virStoragePoolPtr pool, virErrorPtr err) { const char * ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolGetName not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolGetName(pool); if (!ret) { virCopyLastError(err); } #endif return ret; } int virStoragePoolGetUUIDWrapper(virStoragePoolPtr pool, unsigned char * uuid, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolGetUUID not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolGetUUID(pool, uuid); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolGetUUIDStringWrapper(virStoragePoolPtr pool, char * buf, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolGetUUIDString not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolGetUUIDString(pool, buf); if (ret < 0) { virCopyLastError(err); } #endif return ret; } char * virStoragePoolGetXMLDescWrapper(virStoragePoolPtr pool, unsigned int flags, virErrorPtr err) { char * ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolGetXMLDesc not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolGetXMLDesc(pool, flags); if (!ret) { virCopyLastError(err); } #endif return ret; } int virStoragePoolIsActiveWrapper(virStoragePoolPtr pool, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 7, 3) setVirError(err, "Function virStoragePoolIsActive not available prior to libvirt version 0.7.3"); #else ret = virStoragePoolIsActive(pool); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolIsPersistentWrapper(virStoragePoolPtr pool, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 7, 3) setVirError(err, "Function virStoragePoolIsPersistent not available prior to libvirt version 0.7.3"); #else ret = virStoragePoolIsPersistent(pool); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolListAllVolumesWrapper(virStoragePoolPtr pool, virStorageVolPtr ** vols, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 10, 2) setVirError(err, "Function virStoragePoolListAllVolumes not available prior to libvirt version 0.10.2"); #else ret = virStoragePoolListAllVolumes(pool, vols, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolListVolumesWrapper(virStoragePoolPtr pool, char ** const names, int maxnames, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolListVolumes not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolListVolumes(pool, names, maxnames); if (ret < 0) { virCopyLastError(err); } #endif return ret; } virStoragePoolPtr virStoragePoolLookupByNameWrapper(virConnectPtr conn, const char * name, virErrorPtr err) { virStoragePoolPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolLookupByName not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolLookupByName(conn, name); if (!ret) { virCopyLastError(err); } #endif return ret; } virStoragePoolPtr virStoragePoolLookupByTargetPathWrapper(virConnectPtr conn, const char * path, virErrorPtr err) { virStoragePoolPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(4, 1, 0) setVirError(err, "Function virStoragePoolLookupByTargetPath not available prior to libvirt version 4.1.0"); #else ret = virStoragePoolLookupByTargetPath(conn, path); if (!ret) { virCopyLastError(err); } #endif return ret; } virStoragePoolPtr virStoragePoolLookupByUUIDWrapper(virConnectPtr conn, const unsigned char * uuid, virErrorPtr err) { virStoragePoolPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolLookupByUUID not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolLookupByUUID(conn, uuid); if (!ret) { virCopyLastError(err); } #endif return ret; } virStoragePoolPtr virStoragePoolLookupByUUIDStringWrapper(virConnectPtr conn, const char * uuidstr, virErrorPtr err) { virStoragePoolPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolLookupByUUIDString not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolLookupByUUIDString(conn, uuidstr); if (!ret) { virCopyLastError(err); } #endif return ret; } virStoragePoolPtr virStoragePoolLookupByVolumeWrapper(virStorageVolPtr vol, virErrorPtr err) { virStoragePoolPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolLookupByVolume not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolLookupByVolume(vol); if (!ret) { virCopyLastError(err); } #endif return ret; } int virStoragePoolNumOfVolumesWrapper(virStoragePoolPtr pool, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolNumOfVolumes not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolNumOfVolumes(pool); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolRefWrapper(virStoragePoolPtr pool, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 6, 0) setVirError(err, "Function virStoragePoolRef not available prior to libvirt version 0.6.0"); #else ret = virStoragePoolRef(pool); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolRefreshWrapper(virStoragePoolPtr pool, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolRefresh not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolRefresh(pool, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolSetAutostartWrapper(virStoragePoolPtr pool, int autostart, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolSetAutostart not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolSetAutostart(pool, autostart); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStoragePoolUndefineWrapper(virStoragePoolPtr pool, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStoragePoolUndefine not available prior to libvirt version 0.4.1"); #else ret = virStoragePoolUndefine(pool); if (ret < 0) { virCopyLastError(err); } #endif return ret; } virStorageVolPtr virStorageVolCreateXMLWrapper(virStoragePoolPtr pool, const char * xmlDesc, unsigned int flags, virErrorPtr err) { virStorageVolPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStorageVolCreateXML not available prior to libvirt version 0.4.1"); #else ret = virStorageVolCreateXML(pool, xmlDesc, flags); if (!ret) { virCopyLastError(err); } #endif return ret; } virStorageVolPtr virStorageVolCreateXMLFromWrapper(virStoragePoolPtr pool, const char * xmlDesc, virStorageVolPtr clonevol, unsigned int flags, virErrorPtr err) { virStorageVolPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 6, 4) setVirError(err, "Function virStorageVolCreateXMLFrom not available prior to libvirt version 0.6.4"); #else ret = virStorageVolCreateXMLFrom(pool, xmlDesc, clonevol, flags); if (!ret) { virCopyLastError(err); } #endif return ret; } int virStorageVolDeleteWrapper(virStorageVolPtr vol, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStorageVolDelete not available prior to libvirt version 0.4.1"); #else ret = virStorageVolDelete(vol, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStorageVolDownloadWrapper(virStorageVolPtr vol, virStreamPtr stream, unsigned long long offset, unsigned long long length, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 9, 0) setVirError(err, "Function virStorageVolDownload not available prior to libvirt version 0.9.0"); #else ret = virStorageVolDownload(vol, stream, offset, length, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStorageVolFreeWrapper(virStorageVolPtr vol, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStorageVolFree not available prior to libvirt version 0.4.1"); #else ret = virStorageVolFree(vol); if (ret < 0) { virCopyLastError(err); } #endif return ret; } virConnectPtr virStorageVolGetConnectWrapper(virStorageVolPtr vol, virErrorPtr err) { virConnectPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStorageVolGetConnect not available prior to libvirt version 0.4.1"); #else ret = virStorageVolGetConnect(vol); if (!ret) { virCopyLastError(err); } #endif return ret; } int virStorageVolGetInfoWrapper(virStorageVolPtr vol, virStorageVolInfoPtr info, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStorageVolGetInfo not available prior to libvirt version 0.4.1"); #else ret = virStorageVolGetInfo(vol, info); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStorageVolGetInfoFlagsWrapper(virStorageVolPtr vol, virStorageVolInfoPtr info, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(3, 0, 0) setVirError(err, "Function virStorageVolGetInfoFlags not available prior to libvirt version 3.0.0"); #else ret = virStorageVolGetInfoFlags(vol, info, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } const char * virStorageVolGetKeyWrapper(virStorageVolPtr vol, virErrorPtr err) { const char * ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStorageVolGetKey not available prior to libvirt version 0.4.1"); #else ret = virStorageVolGetKey(vol); if (!ret) { virCopyLastError(err); } #endif return ret; } const char * virStorageVolGetNameWrapper(virStorageVolPtr vol, virErrorPtr err) { const char * ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStorageVolGetName not available prior to libvirt version 0.4.1"); #else ret = virStorageVolGetName(vol); if (!ret) { virCopyLastError(err); } #endif return ret; } char * virStorageVolGetPathWrapper(virStorageVolPtr vol, virErrorPtr err) { char * ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStorageVolGetPath not available prior to libvirt version 0.4.1"); #else ret = virStorageVolGetPath(vol); if (!ret) { virCopyLastError(err); } #endif return ret; } char * virStorageVolGetXMLDescWrapper(virStorageVolPtr vol, unsigned int flags, virErrorPtr err) { char * ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStorageVolGetXMLDesc not available prior to libvirt version 0.4.1"); #else ret = virStorageVolGetXMLDesc(vol, flags); if (!ret) { virCopyLastError(err); } #endif return ret; } virStorageVolPtr virStorageVolLookupByKeyWrapper(virConnectPtr conn, const char * key, virErrorPtr err) { virStorageVolPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStorageVolLookupByKey not available prior to libvirt version 0.4.1"); #else ret = virStorageVolLookupByKey(conn, key); if (!ret) { virCopyLastError(err); } #endif return ret; } virStorageVolPtr virStorageVolLookupByNameWrapper(virStoragePoolPtr pool, const char * name, virErrorPtr err) { virStorageVolPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStorageVolLookupByName not available prior to libvirt version 0.4.1"); #else ret = virStorageVolLookupByName(pool, name); if (!ret) { virCopyLastError(err); } #endif return ret; } virStorageVolPtr virStorageVolLookupByPathWrapper(virConnectPtr conn, const char * path, virErrorPtr err) { virStorageVolPtr ret = NULL; #if !LIBVIR_CHECK_VERSION(0, 4, 1) setVirError(err, "Function virStorageVolLookupByPath not available prior to libvirt version 0.4.1"); #else ret = virStorageVolLookupByPath(conn, path); if (!ret) { virCopyLastError(err); } #endif return ret; } int virStorageVolRefWrapper(virStorageVolPtr vol, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 6, 0) setVirError(err, "Function virStorageVolRef not available prior to libvirt version 0.6.0"); #else ret = virStorageVolRef(vol); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStorageVolResizeWrapper(virStorageVolPtr vol, unsigned long long capacity, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 9, 10) setVirError(err, "Function virStorageVolResize not available prior to libvirt version 0.9.10"); #else ret = virStorageVolResize(vol, capacity, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStorageVolUploadWrapper(virStorageVolPtr vol, virStreamPtr stream, unsigned long long offset, unsigned long long length, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 9, 0) setVirError(err, "Function virStorageVolUpload not available prior to libvirt version 0.9.0"); #else ret = virStorageVolUpload(vol, stream, offset, length, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStorageVolWipeWrapper(virStorageVolPtr vol, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 8, 0) setVirError(err, "Function virStorageVolWipe not available prior to libvirt version 0.8.0"); #else ret = virStorageVolWipe(vol, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } int virStorageVolWipePatternWrapper(virStorageVolPtr vol, unsigned int algorithm, unsigned int flags, virErrorPtr err) { int ret = -1; #if !LIBVIR_CHECK_VERSION(0, 9, 10) setVirError(err, "Function virStorageVolWipePattern not available prior to libvirt version 0.9.10"); #else ret = virStorageVolWipePattern(vol, algorithm, flags); if (ret < 0) { virCopyLastError(err); } #endif return ret; } */ import "C"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/libvirt.org/go/libvirt/events_helper.go
vendor/libvirt.org/go/libvirt/events_helper.go
/* * This file is part of the libvirt-go-module project * * 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. * * Copyright (c) 2013 Alex Zorin * Copyright (C) 2016 Red Hat, Inc. * */ package libvirt /* #cgo !libvirt_dlopen pkg-config: libvirt #cgo libvirt_dlopen LDFLAGS: -ldl #cgo libvirt_dlopen CFLAGS: -DLIBVIRT_DLOPEN #include <stdint.h> #include "events_helper.h" void eventHandleCallback(int watch, int fd, int events, int callbackID); static void eventAddHandleHelper(int watch, int fd, int events, void *opaque) { eventHandleCallback(watch, fd, events, (int)(intptr_t)opaque); } void eventTimeoutCallback(int timer, int callbackID); static void eventAddTimeoutHelper(int timer, void *opaque) { eventTimeoutCallback(timer, (int)(intptr_t)opaque); } int eventAddHandleFunc(int fd, int event, uintptr_t callback, uintptr_t opaque, uintptr_t freecb); void eventUpdateHandleFunc(int watch, int event); int eventRemoveHandleFunc(int watch); int eventAddTimeoutFunc(int freq, uintptr_t callback, uintptr_t opaque, uintptr_t freecb); void eventUpdateTimeoutFunc(int timer, int freq); int eventRemoveTimeoutFunc(int timer); int eventAddHandleFuncHelper(int fd, int event, virEventHandleCallback callback, void *opaque, virFreeCallback freecb) { return eventAddHandleFunc(fd, event, (uintptr_t)callback, (uintptr_t)opaque, (uintptr_t)freecb); } void eventUpdateHandleFuncHelper(int watch, int event) { eventUpdateHandleFunc(watch, event); } int eventRemoveHandleFuncHelper(int watch) { return eventRemoveHandleFunc(watch); } int eventAddTimeoutFuncHelper(int freq, virEventTimeoutCallback callback, void *opaque, virFreeCallback freecb) { return eventAddTimeoutFunc(freq, (uintptr_t)callback, (uintptr_t)opaque, (uintptr_t)freecb); } void eventUpdateTimeoutFuncHelper(int timer, int freq) { eventUpdateTimeoutFunc(timer, freq); } int eventRemoveTimeoutFuncHelper(int timer) { return eventRemoveTimeoutFunc(timer); } void virEventRegisterImplHelper(void) { virEventRegisterImplWrapper(eventAddHandleFuncHelper, eventUpdateHandleFuncHelper, eventRemoveHandleFuncHelper, eventAddTimeoutFuncHelper, eventUpdateTimeoutFuncHelper, eventRemoveTimeoutFuncHelper); } void eventHandleCallbackInvoke(int watch, int fd, int events, uintptr_t callback, uintptr_t opaque) { ((virEventHandleCallback)callback)(watch, fd, events, (void *)opaque); } void eventTimeoutCallbackInvoke(int timer, uintptr_t callback, uintptr_t opaque) { ((virEventTimeoutCallback)callback)(timer, (void *)opaque); } void eventHandleCallbackFree(uintptr_t callback, uintptr_t opaque) { ((virFreeCallback)callback)((void *)opaque); } void eventTimeoutCallbackFree(uintptr_t callback, uintptr_t opaque) { ((virFreeCallback)callback)((void *)opaque); } int virEventAddHandleHelper(int fd, int events, int callbackID, virErrorPtr err) { return virEventAddHandleWrapper(fd, events, eventAddHandleHelper, (void *)(intptr_t)callbackID, NULL, err); } int virEventAddTimeoutHelper(int timeout, int callbackID, virErrorPtr err) { return virEventAddTimeoutWrapper(timeout, eventAddTimeoutHelper, (void *)(intptr_t)callbackID, NULL, err); } */ import "C"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/multierr/error.go
vendor/go.uber.org/multierr/error.go
// Copyright (c) 2017-2023 Uber Technologies, Inc. // // 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. // Package multierr allows combining one or more errors together. // // # Overview // // Errors can be combined with the use of the Combine function. // // multierr.Combine( // reader.Close(), // writer.Close(), // conn.Close(), // ) // // If only two errors are being combined, the Append function may be used // instead. // // err = multierr.Append(reader.Close(), writer.Close()) // // The underlying list of errors for a returned error object may be retrieved // with the Errors function. // // errors := multierr.Errors(err) // if len(errors) > 0 { // fmt.Println("The following errors occurred:", errors) // } // // # Appending from a loop // // You sometimes need to append into an error from a loop. // // var err error // for _, item := range items { // err = multierr.Append(err, process(item)) // } // // Cases like this may require knowledge of whether an individual instance // failed. This usually requires introduction of a new variable. // // var err error // for _, item := range items { // if perr := process(item); perr != nil { // log.Warn("skipping item", item) // err = multierr.Append(err, perr) // } // } // // multierr includes AppendInto to simplify cases like this. // // var err error // for _, item := range items { // if multierr.AppendInto(&err, process(item)) { // log.Warn("skipping item", item) // } // } // // This will append the error into the err variable, and return true if that // individual error was non-nil. // // See [AppendInto] for more information. // // # Deferred Functions // // Go makes it possible to modify the return value of a function in a defer // block if the function was using named returns. This makes it possible to // record resource cleanup failures from deferred blocks. // // func sendRequest(req Request) (err error) { // conn, err := openConnection() // if err != nil { // return err // } // defer func() { // err = multierr.Append(err, conn.Close()) // }() // // ... // } // // multierr provides the Invoker type and AppendInvoke function to make cases // like the above simpler and obviate the need for a closure. The following is // roughly equivalent to the example above. // // func sendRequest(req Request) (err error) { // conn, err := openConnection() // if err != nil { // return err // } // defer multierr.AppendInvoke(&err, multierr.Close(conn)) // // ... // } // // See [AppendInvoke] and [Invoker] for more information. // // NOTE: If you're modifying an error from inside a defer, you MUST use a named // return value for that function. // // # Advanced Usage // // Errors returned by Combine and Append MAY implement the following // interface. // // type errorGroup interface { // // Returns a slice containing the underlying list of errors. // // // // This slice MUST NOT be modified by the caller. // Errors() []error // } // // Note that if you need access to list of errors behind a multierr error, you // should prefer using the Errors function. That said, if you need cheap // read-only access to the underlying errors slice, you can attempt to cast // the error to this interface. You MUST handle the failure case gracefully // because errors returned by Combine and Append are not guaranteed to // implement this interface. // // var errors []error // group, ok := err.(errorGroup) // if ok { // errors = group.Errors() // } else { // errors = []error{err} // } package multierr // import "go.uber.org/multierr" import ( "bytes" "errors" "fmt" "io" "strings" "sync" "sync/atomic" ) var ( // Separator for single-line error messages. _singlelineSeparator = []byte("; ") // Prefix for multi-line messages _multilinePrefix = []byte("the following errors occurred:") // Prefix for the first and following lines of an item in a list of // multi-line error messages. // // For example, if a single item is: // // foo // bar // // It will become, // // - foo // bar _multilineSeparator = []byte("\n - ") _multilineIndent = []byte(" ") ) // _bufferPool is a pool of bytes.Buffers. var _bufferPool = sync.Pool{ New: func() interface{} { return &bytes.Buffer{} }, } type errorGroup interface { Errors() []error } // Errors returns a slice containing zero or more errors that the supplied // error is composed of. If the error is nil, a nil slice is returned. // // err := multierr.Append(r.Close(), w.Close()) // errors := multierr.Errors(err) // // If the error is not composed of other errors, the returned slice contains // just the error that was passed in. // // Callers of this function are free to modify the returned slice. func Errors(err error) []error { return extractErrors(err) } // multiError is an error that holds one or more errors. // // An instance of this is guaranteed to be non-empty and flattened. That is, // none of the errors inside multiError are other multiErrors. // // multiError formats to a semi-colon delimited list of error messages with // %v and with a more readable multi-line format with %+v. type multiError struct { copyNeeded atomic.Bool errors []error } // Errors returns the list of underlying errors. // // This slice MUST NOT be modified. func (merr *multiError) Errors() []error { if merr == nil { return nil } return merr.errors } func (merr *multiError) Error() string { if merr == nil { return "" } buff := _bufferPool.Get().(*bytes.Buffer) buff.Reset() merr.writeSingleline(buff) result := buff.String() _bufferPool.Put(buff) return result } // Every compares every error in the given err against the given target error // using [errors.Is], and returns true only if every comparison returned true. func Every(err error, target error) bool { for _, e := range extractErrors(err) { if !errors.Is(e, target) { return false } } return true } func (merr *multiError) Format(f fmt.State, c rune) { if c == 'v' && f.Flag('+') { merr.writeMultiline(f) } else { merr.writeSingleline(f) } } func (merr *multiError) writeSingleline(w io.Writer) { first := true for _, item := range merr.errors { if first { first = false } else { w.Write(_singlelineSeparator) } io.WriteString(w, item.Error()) } } func (merr *multiError) writeMultiline(w io.Writer) { w.Write(_multilinePrefix) for _, item := range merr.errors { w.Write(_multilineSeparator) writePrefixLine(w, _multilineIndent, fmt.Sprintf("%+v", item)) } } // Writes s to the writer with the given prefix added before each line after // the first. func writePrefixLine(w io.Writer, prefix []byte, s string) { first := true for len(s) > 0 { if first { first = false } else { w.Write(prefix) } idx := strings.IndexByte(s, '\n') if idx < 0 { idx = len(s) - 1 } io.WriteString(w, s[:idx+1]) s = s[idx+1:] } } type inspectResult struct { // Number of top-level non-nil errors Count int // Total number of errors including multiErrors Capacity int // Index of the first non-nil error in the list. Value is meaningless if // Count is zero. FirstErrorIdx int // Whether the list contains at least one multiError ContainsMultiError bool } // Inspects the given slice of errors so that we can efficiently allocate // space for it. func inspect(errors []error) (res inspectResult) { first := true for i, err := range errors { if err == nil { continue } res.Count++ if first { first = false res.FirstErrorIdx = i } if merr, ok := err.(*multiError); ok { res.Capacity += len(merr.errors) res.ContainsMultiError = true } else { res.Capacity++ } } return } // fromSlice converts the given list of errors into a single error. func fromSlice(errors []error) error { // Don't pay to inspect small slices. switch len(errors) { case 0: return nil case 1: return errors[0] } res := inspect(errors) switch res.Count { case 0: return nil case 1: // only one non-nil entry return errors[res.FirstErrorIdx] case len(errors): if !res.ContainsMultiError { // Error list is flat. Make a copy of it // Otherwise "errors" escapes to the heap // unconditionally for all other cases. // This lets us optimize for the "no errors" case. out := append(([]error)(nil), errors...) return &multiError{errors: out} } } nonNilErrs := make([]error, 0, res.Capacity) for _, err := range errors[res.FirstErrorIdx:] { if err == nil { continue } if nested, ok := err.(*multiError); ok { nonNilErrs = append(nonNilErrs, nested.errors...) } else { nonNilErrs = append(nonNilErrs, err) } } return &multiError{errors: nonNilErrs} } // Combine combines the passed errors into a single error. // // If zero arguments were passed or if all items are nil, a nil error is // returned. // // Combine(nil, nil) // == nil // // If only a single error was passed, it is returned as-is. // // Combine(err) // == err // // Combine skips over nil arguments so this function may be used to combine // together errors from operations that fail independently of each other. // // multierr.Combine( // reader.Close(), // writer.Close(), // pipe.Close(), // ) // // If any of the passed errors is a multierr error, it will be flattened along // with the other errors. // // multierr.Combine(multierr.Combine(err1, err2), err3) // // is the same as // multierr.Combine(err1, err2, err3) // // The returned error formats into a readable multi-line error message if // formatted with %+v. // // fmt.Sprintf("%+v", multierr.Combine(err1, err2)) func Combine(errors ...error) error { return fromSlice(errors) } // Append appends the given errors together. Either value may be nil. // // This function is a specialization of Combine for the common case where // there are only two errors. // // err = multierr.Append(reader.Close(), writer.Close()) // // The following pattern may also be used to record failure of deferred // operations without losing information about the original error. // // func doSomething(..) (err error) { // f := acquireResource() // defer func() { // err = multierr.Append(err, f.Close()) // }() // // Note that the variable MUST be a named return to append an error to it from // the defer statement. See also [AppendInvoke]. func Append(left error, right error) error { switch { case left == nil: return right case right == nil: return left } if _, ok := right.(*multiError); !ok { if l, ok := left.(*multiError); ok && !l.copyNeeded.Swap(true) { // Common case where the error on the left is constantly being // appended to. errs := append(l.errors, right) return &multiError{errors: errs} } else if !ok { // Both errors are single errors. return &multiError{errors: []error{left, right}} } } // Either right or both, left and right, are multiErrors. Rely on usual // expensive logic. errors := [2]error{left, right} return fromSlice(errors[0:]) } // AppendInto appends an error into the destination of an error pointer and // returns whether the error being appended was non-nil. // // var err error // multierr.AppendInto(&err, r.Close()) // multierr.AppendInto(&err, w.Close()) // // The above is equivalent to, // // err := multierr.Append(r.Close(), w.Close()) // // As AppendInto reports whether the provided error was non-nil, it may be // used to build a multierr error in a loop more ergonomically. For example: // // var err error // for line := range lines { // var item Item // if multierr.AppendInto(&err, parse(line, &item)) { // continue // } // items = append(items, item) // } // // Compare this with a version that relies solely on Append: // // var err error // for line := range lines { // var item Item // if parseErr := parse(line, &item); parseErr != nil { // err = multierr.Append(err, parseErr) // continue // } // items = append(items, item) // } func AppendInto(into *error, err error) (errored bool) { if into == nil { // We panic if 'into' is nil. This is not documented above // because suggesting that the pointer must be non-nil may // confuse users into thinking that the error that it points // to must be non-nil. panic("misuse of multierr.AppendInto: into pointer must not be nil") } if err == nil { return false } *into = Append(*into, err) return true } // Invoker is an operation that may fail with an error. Use it with // AppendInvoke to append the result of calling the function into an error. // This allows you to conveniently defer capture of failing operations. // // See also, [Close] and [Invoke]. type Invoker interface { Invoke() error } // Invoke wraps a function which may fail with an error to match the Invoker // interface. Use it to supply functions matching this signature to // AppendInvoke. // // For example, // // func processReader(r io.Reader) (err error) { // scanner := bufio.NewScanner(r) // defer multierr.AppendInvoke(&err, multierr.Invoke(scanner.Err)) // for scanner.Scan() { // // ... // } // // ... // } // // In this example, the following line will construct the Invoker right away, // but defer the invocation of scanner.Err() until the function returns. // // defer multierr.AppendInvoke(&err, multierr.Invoke(scanner.Err)) // // Note that the error you're appending to from the defer statement MUST be a // named return. type Invoke func() error // Invoke calls the supplied function and returns its result. func (i Invoke) Invoke() error { return i() } // Close builds an Invoker that closes the provided io.Closer. Use it with // AppendInvoke to close io.Closers and append their results into an error. // // For example, // // func processFile(path string) (err error) { // f, err := os.Open(path) // if err != nil { // return err // } // defer multierr.AppendInvoke(&err, multierr.Close(f)) // return processReader(f) // } // // In this example, multierr.Close will construct the Invoker right away, but // defer the invocation of f.Close until the function returns. // // defer multierr.AppendInvoke(&err, multierr.Close(f)) // // Note that the error you're appending to from the defer statement MUST be a // named return. func Close(closer io.Closer) Invoker { return Invoke(closer.Close) } // AppendInvoke appends the result of calling the given Invoker into the // provided error pointer. Use it with named returns to safely defer // invocation of fallible operations until a function returns, and capture the // resulting errors. // // func doSomething(...) (err error) { // // ... // f, err := openFile(..) // if err != nil { // return err // } // // // multierr will call f.Close() when this function returns and // // if the operation fails, its append its error into the // // returned error. // defer multierr.AppendInvoke(&err, multierr.Close(f)) // // scanner := bufio.NewScanner(f) // // Similarly, this scheduled scanner.Err to be called and // // inspected when the function returns and append its error // // into the returned error. // defer multierr.AppendInvoke(&err, multierr.Invoke(scanner.Err)) // // // ... // } // // NOTE: If used with a defer, the error variable MUST be a named return. // // Without defer, AppendInvoke behaves exactly like AppendInto. // // err := // ... // multierr.AppendInvoke(&err, mutltierr.Invoke(foo)) // // // ...is roughly equivalent to... // // err := // ... // multierr.AppendInto(&err, foo()) // // The advantage of the indirection introduced by Invoker is to make it easy // to defer the invocation of a function. Without this indirection, the // invoked function will be evaluated at the time of the defer block rather // than when the function returns. // // // BAD: This is likely not what the caller intended. This will evaluate // // foo() right away and append its result into the error when the // // function returns. // defer multierr.AppendInto(&err, foo()) // // // GOOD: This will defer invocation of foo unutil the function returns. // defer multierr.AppendInvoke(&err, multierr.Invoke(foo)) // // multierr provides a few Invoker implementations out of the box for // convenience. See [Invoker] for more information. func AppendInvoke(into *error, invoker Invoker) { AppendInto(into, invoker.Invoke()) } // AppendFunc is a shorthand for [AppendInvoke]. // It allows using function or method value directly // without having to wrap it into an [Invoker] interface. // // func doSomething(...) (err error) { // w, err := startWorker(...) // if err != nil { // return err // } // // // multierr will call w.Stop() when this function returns and // // if the operation fails, it appends its error into the // // returned error. // defer multierr.AppendFunc(&err, w.Stop) // } func AppendFunc(into *error, fn func() error) { AppendInvoke(into, Invoke(fn)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/multierr/error_post_go120.go
vendor/go.uber.org/multierr/error_post_go120.go
// Copyright (c) 2017-2023 Uber Technologies, Inc. // // 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. //go:build go1.20 // +build go1.20 package multierr // Unwrap returns a list of errors wrapped by this multierr. func (merr *multiError) Unwrap() []error { return merr.Errors() } type multipleErrors interface { Unwrap() []error } func extractErrors(err error) []error { if err == nil { return nil } // check if the given err is an Unwrapable error that // implements multipleErrors interface. eg, ok := err.(multipleErrors) if !ok { return []error{err} } return append(([]error)(nil), eg.Unwrap()...) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/multierr/error_pre_go120.go
vendor/go.uber.org/multierr/error_pre_go120.go
// Copyright (c) 2017-2023 Uber Technologies, Inc. // // 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. //go:build !go1.20 // +build !go1.20 package multierr import "errors" // Versions of Go before 1.20 did not support the Unwrap() []error method. // This provides a similar behavior by implementing the Is(..) and As(..) // methods. // See the errors.Join proposal for details: // https://github.com/golang/go/issues/53435 // As attempts to find the first error in the error list that matches the type // of the value that target points to. // // This function allows errors.As to traverse the values stored on the // multierr error. func (merr *multiError) As(target interface{}) bool { for _, err := range merr.Errors() { if errors.As(err, target) { return true } } return false } // Is attempts to match the provided error against errors in the error list. // // This function allows errors.Is to traverse the values stored on the // multierr error. func (merr *multiError) Is(target error) bool { for _, err := range merr.Errors() { if errors.Is(err, target) { return true } } return false } func extractErrors(err error) []error { if err == nil { return nil } // Note that we're casting to multiError, not errorGroup. Our contract is // that returned errors MAY implement errorGroup. Errors, however, only // has special behavior for multierr-specific error objects. // // This behavior can be expanded in the future but I think it's prudent to // start with as little as possible in terms of contract and possibility // of misuse. eg, ok := err.(*multiError) if !ok { return []error{err} } return append(([]error)(nil), eg.Errors()...) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/mock/gomock/matchers.go
vendor/go.uber.org/mock/gomock/matchers.go
// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gomock import ( "fmt" "reflect" "regexp" "strings" ) // A Matcher is a representation of a class of values. // It is used to represent the valid or expected arguments to a mocked method. type Matcher interface { // Matches returns whether x is a match. Matches(x any) bool // String describes what the matcher matches. String() string } // WantFormatter modifies the given Matcher's String() method to the given // Stringer. This allows for control on how the "Want" is formatted when // printing . func WantFormatter(s fmt.Stringer, m Matcher) Matcher { type matcher interface { Matches(x any) bool } return struct { matcher fmt.Stringer }{ matcher: m, Stringer: s, } } // StringerFunc type is an adapter to allow the use of ordinary functions as // a Stringer. If f is a function with the appropriate signature, // StringerFunc(f) is a Stringer that calls f. type StringerFunc func() string // String implements fmt.Stringer. func (f StringerFunc) String() string { return f() } // GotFormatter is used to better print failure messages. If a matcher // implements GotFormatter, it will use the result from Got when printing // the failure message. type GotFormatter interface { // Got is invoked with the received value. The result is used when // printing the failure message. Got(got any) string } // GotFormatterFunc type is an adapter to allow the use of ordinary // functions as a GotFormatter. If f is a function with the appropriate // signature, GotFormatterFunc(f) is a GotFormatter that calls f. type GotFormatterFunc func(got any) string // Got implements GotFormatter. func (f GotFormatterFunc) Got(got any) string { return f(got) } // GotFormatterAdapter attaches a GotFormatter to a Matcher. func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher { return struct { GotFormatter Matcher }{ GotFormatter: s, Matcher: m, } } type anyMatcher struct{} func (anyMatcher) Matches(any) bool { return true } func (anyMatcher) String() string { return "is anything" } type condMatcher struct { fn func(x any) bool } func (c condMatcher) Matches(x any) bool { return c.fn(x) } func (condMatcher) String() string { return "adheres to a custom condition" } type eqMatcher struct { x any } func (e eqMatcher) Matches(x any) bool { // In case, some value is nil if e.x == nil || x == nil { return reflect.DeepEqual(e.x, x) } // Check if types assignable and convert them to common type x1Val := reflect.ValueOf(e.x) x2Val := reflect.ValueOf(x) if x1Val.Type().AssignableTo(x2Val.Type()) { x1ValConverted := x1Val.Convert(x2Val.Type()) return reflect.DeepEqual(x1ValConverted.Interface(), x2Val.Interface()) } return false } func (e eqMatcher) String() string { return fmt.Sprintf("is equal to %v (%T)", e.x, e.x) } type nilMatcher struct{} func (nilMatcher) Matches(x any) bool { if x == nil { return true } v := reflect.ValueOf(x) switch v.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return v.IsNil() } return false } func (nilMatcher) String() string { return "is nil" } type notMatcher struct { m Matcher } func (n notMatcher) Matches(x any) bool { return !n.m.Matches(x) } func (n notMatcher) String() string { return "not(" + n.m.String() + ")" } type regexMatcher struct { regex *regexp.Regexp } func (m regexMatcher) Matches(x any) bool { switch t := x.(type) { case string: return m.regex.MatchString(t) case []byte: return m.regex.Match(t) default: return false } } func (m regexMatcher) String() string { return "matches regex " + m.regex.String() } type assignableToTypeOfMatcher struct { targetType reflect.Type } func (m assignableToTypeOfMatcher) Matches(x any) bool { return reflect.TypeOf(x).AssignableTo(m.targetType) } func (m assignableToTypeOfMatcher) String() string { return "is assignable to " + m.targetType.Name() } type anyOfMatcher struct { matchers []Matcher } func (am anyOfMatcher) Matches(x any) bool { for _, m := range am.matchers { if m.Matches(x) { return true } } return false } func (am anyOfMatcher) String() string { ss := make([]string, 0, len(am.matchers)) for _, matcher := range am.matchers { ss = append(ss, matcher.String()) } return strings.Join(ss, " | ") } type allMatcher struct { matchers []Matcher } func (am allMatcher) Matches(x any) bool { for _, m := range am.matchers { if !m.Matches(x) { return false } } return true } func (am allMatcher) String() string { ss := make([]string, 0, len(am.matchers)) for _, matcher := range am.matchers { ss = append(ss, matcher.String()) } return strings.Join(ss, "; ") } type lenMatcher struct { i int } func (m lenMatcher) Matches(x any) bool { v := reflect.ValueOf(x) switch v.Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String: return v.Len() == m.i default: return false } } func (m lenMatcher) String() string { return fmt.Sprintf("has length %d", m.i) } type inAnyOrderMatcher struct { x any } func (m inAnyOrderMatcher) Matches(x any) bool { given, ok := m.prepareValue(x) if !ok { return false } wanted, ok := m.prepareValue(m.x) if !ok { return false } if given.Len() != wanted.Len() { return false } usedFromGiven := make([]bool, given.Len()) foundFromWanted := make([]bool, wanted.Len()) for i := 0; i < wanted.Len(); i++ { wantedMatcher := Eq(wanted.Index(i).Interface()) for j := 0; j < given.Len(); j++ { if usedFromGiven[j] { continue } if wantedMatcher.Matches(given.Index(j).Interface()) { foundFromWanted[i] = true usedFromGiven[j] = true break } } } missingFromWanted := 0 for _, found := range foundFromWanted { if !found { missingFromWanted++ } } extraInGiven := 0 for _, used := range usedFromGiven { if !used { extraInGiven++ } } return extraInGiven == 0 && missingFromWanted == 0 } func (m inAnyOrderMatcher) prepareValue(x any) (reflect.Value, bool) { xValue := reflect.ValueOf(x) switch xValue.Kind() { case reflect.Slice, reflect.Array: return xValue, true default: return reflect.Value{}, false } } func (m inAnyOrderMatcher) String() string { return fmt.Sprintf("has the same elements as %v", m.x) } // Constructors // All returns a composite Matcher that returns true if and only all of the // matchers return true. func All(ms ...Matcher) Matcher { return allMatcher{ms} } // Any returns a matcher that always matches. func Any() Matcher { return anyMatcher{} } // Cond returns a matcher that matches when the given function returns true // after passing it the parameter to the mock function. // This is particularly useful in case you want to match over a field of a custom struct, or dynamic logic. // // Example usage: // // Cond(func(x any){return x.(int) == 1}).Matches(1) // returns true // Cond(func(x any){return x.(int) == 2}).Matches(1) // returns false func Cond(fn func(x any) bool) Matcher { return condMatcher{fn} } // AnyOf returns a composite Matcher that returns true if at least one of the // matchers returns true. // // Example usage: // // AnyOf(1, 2, 3).Matches(2) // returns true // AnyOf(1, 2, 3).Matches(10) // returns false // AnyOf(Nil(), Len(2)).Matches(nil) // returns true // AnyOf(Nil(), Len(2)).Matches("hi") // returns true // AnyOf(Nil(), Len(2)).Matches("hello") // returns false func AnyOf(xs ...any) Matcher { ms := make([]Matcher, 0, len(xs)) for _, x := range xs { if m, ok := x.(Matcher); ok { ms = append(ms, m) } else { ms = append(ms, Eq(x)) } } return anyOfMatcher{ms} } // Eq returns a matcher that matches on equality. // // Example usage: // // Eq(5).Matches(5) // returns true // Eq(5).Matches(4) // returns false func Eq(x any) Matcher { return eqMatcher{x} } // Len returns a matcher that matches on length. This matcher returns false if // is compared to a type that is not an array, chan, map, slice, or string. func Len(i int) Matcher { return lenMatcher{i} } // Nil returns a matcher that matches if the received value is nil. // // Example usage: // // var x *bytes.Buffer // Nil().Matches(x) // returns true // x = &bytes.Buffer{} // Nil().Matches(x) // returns false func Nil() Matcher { return nilMatcher{} } // Not reverses the results of its given child matcher. // // Example usage: // // Not(Eq(5)).Matches(4) // returns true // Not(Eq(5)).Matches(5) // returns false func Not(x any) Matcher { if m, ok := x.(Matcher); ok { return notMatcher{m} } return notMatcher{Eq(x)} } // Regex checks whether parameter matches the associated regex. // // Example usage: // // Regex("[0-9]{2}:[0-9]{2}").Matches("23:02") // returns true // Regex("[0-9]{2}:[0-9]{2}").Matches([]byte{'2', '3', ':', '0', '2'}) // returns true // Regex("[0-9]{2}:[0-9]{2}").Matches("hello world") // returns false // Regex("[0-9]{2}").Matches(21) // returns false as it's not a valid type func Regex(regexStr string) Matcher { return regexMatcher{regex: regexp.MustCompile(regexStr)} } // AssignableToTypeOf is a Matcher that matches if the parameter to the mock // function is assignable to the type of the parameter to this function. // // Example usage: // // var s fmt.Stringer = &bytes.Buffer{} // AssignableToTypeOf(s).Matches(time.Second) // returns true // AssignableToTypeOf(s).Matches(99) // returns false // // var ctx = reflect.TypeOf((*context.Context)(nil)).Elem() // AssignableToTypeOf(ctx).Matches(context.Background()) // returns true func AssignableToTypeOf(x any) Matcher { if xt, ok := x.(reflect.Type); ok { return assignableToTypeOfMatcher{xt} } return assignableToTypeOfMatcher{reflect.TypeOf(x)} } // InAnyOrder is a Matcher that returns true for collections of the same elements ignoring the order. // // Example usage: // // InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 3, 2}) // returns true // InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 2}) // returns false func InAnyOrder(x any) Matcher { return inAnyOrderMatcher{x} }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/mock/gomock/callset.go
vendor/go.uber.org/mock/gomock/callset.go
// Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gomock import ( "bytes" "errors" "fmt" "sync" ) // callSet represents a set of expected calls, indexed by receiver and method // name. type callSet struct { // Calls that are still expected. expected map[callSetKey][]*Call expectedMu *sync.Mutex // Calls that have been exhausted. exhausted map[callSetKey][]*Call // when set to true, existing call expectations are overridden when new call expectations are made allowOverride bool } // callSetKey is the key in the maps in callSet type callSetKey struct { receiver any fname string } func newCallSet() *callSet { return &callSet{ expected: make(map[callSetKey][]*Call), expectedMu: &sync.Mutex{}, exhausted: make(map[callSetKey][]*Call), } } func newOverridableCallSet() *callSet { return &callSet{ expected: make(map[callSetKey][]*Call), expectedMu: &sync.Mutex{}, exhausted: make(map[callSetKey][]*Call), allowOverride: true, } } // Add adds a new expected call. func (cs callSet) Add(call *Call) { key := callSetKey{call.receiver, call.method} cs.expectedMu.Lock() defer cs.expectedMu.Unlock() m := cs.expected if call.exhausted() { m = cs.exhausted } if cs.allowOverride { m[key] = make([]*Call, 0) } m[key] = append(m[key], call) } // Remove removes an expected call. func (cs callSet) Remove(call *Call) { key := callSetKey{call.receiver, call.method} cs.expectedMu.Lock() defer cs.expectedMu.Unlock() calls := cs.expected[key] for i, c := range calls { if c == call { // maintain order for remaining calls cs.expected[key] = append(calls[:i], calls[i+1:]...) cs.exhausted[key] = append(cs.exhausted[key], call) break } } } // FindMatch searches for a matching call. Returns error with explanation message if no call matched. func (cs callSet) FindMatch(receiver any, method string, args []any) (*Call, error) { key := callSetKey{receiver, method} cs.expectedMu.Lock() defer cs.expectedMu.Unlock() // Search through the expected calls. expected := cs.expected[key] var callsErrors bytes.Buffer for _, call := range expected { err := call.matches(args) if err != nil { _, _ = fmt.Fprintf(&callsErrors, "\n%v", err) } else { return call, nil } } // If we haven't found a match then search through the exhausted calls so we // get useful error messages. exhausted := cs.exhausted[key] for _, call := range exhausted { if err := call.matches(args); err != nil { _, _ = fmt.Fprintf(&callsErrors, "\n%v", err) continue } _, _ = fmt.Fprintf( &callsErrors, "all expected calls for method %q have been exhausted", method, ) } if len(expected)+len(exhausted) == 0 { _, _ = fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method) } return nil, errors.New(callsErrors.String()) } // Failures returns the calls that are not satisfied. func (cs callSet) Failures() []*Call { cs.expectedMu.Lock() defer cs.expectedMu.Unlock() failures := make([]*Call, 0, len(cs.expected)) for _, calls := range cs.expected { for _, call := range calls { if !call.satisfied() { failures = append(failures, call) } } } return failures } // Satisfied returns true in case all expected calls in this callSet are satisfied. func (cs callSet) Satisfied() bool { cs.expectedMu.Lock() defer cs.expectedMu.Unlock() for _, calls := range cs.expected { for _, call := range calls { if !call.satisfied() { return false } } } return true }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/mock/gomock/call.go
vendor/go.uber.org/mock/gomock/call.go
// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gomock import ( "fmt" "reflect" "strconv" "strings" ) // Call represents an expected call to a mock. type Call struct { t TestHelper // for triggering test failures on invalid call setup receiver any // the receiver of the method call method string // the name of the method methodType reflect.Type // the type of the method args []Matcher // the args origin string // file and line number of call setup preReqs []*Call // prerequisite calls // Expectations minCalls, maxCalls int numCalls int // actual number made // actions are called when this Call is called. Each action gets the args and // can set the return values by returning a non-nil slice. Actions run in the // order they are created. actions []func([]any) []any } // newCall creates a *Call. It requires the method type in order to support // unexported methods. func newCall(t TestHelper, receiver any, method string, methodType reflect.Type, args ...any) *Call { t.Helper() // TODO: check arity, types. mArgs := make([]Matcher, len(args)) for i, arg := range args { if m, ok := arg.(Matcher); ok { mArgs[i] = m } else if arg == nil { // Handle nil specially so that passing a nil interface value // will match the typed nils of concrete args. mArgs[i] = Nil() } else { mArgs[i] = Eq(arg) } } // callerInfo's skip should be updated if the number of calls between the user's test // and this line changes, i.e. this code is wrapped in another anonymous function. // 0 is us, 1 is RecordCallWithMethodType(), 2 is the generated recorder, and 3 is the user's test. origin := callerInfo(3) actions := []func([]any) []any{func([]any) []any { // Synthesize the zero value for each of the return args' types. rets := make([]any, methodType.NumOut()) for i := 0; i < methodType.NumOut(); i++ { rets[i] = reflect.Zero(methodType.Out(i)).Interface() } return rets }} return &Call{t: t, receiver: receiver, method: method, methodType: methodType, args: mArgs, origin: origin, minCalls: 1, maxCalls: 1, actions: actions} } // AnyTimes allows the expectation to be called 0 or more times func (c *Call) AnyTimes() *Call { c.minCalls, c.maxCalls = 0, 1e8 // close enough to infinity return c } // MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called or if MaxTimes // was previously called with 1, MinTimes also sets the maximum number of calls to infinity. func (c *Call) MinTimes(n int) *Call { c.minCalls = n if c.maxCalls == 1 { c.maxCalls = 1e8 } return c } // MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called or if MinTimes was // previously called with 1, MaxTimes also sets the minimum number of calls to 0. func (c *Call) MaxTimes(n int) *Call { c.maxCalls = n if c.minCalls == 1 { c.minCalls = 0 } return c } // DoAndReturn declares the action to run when the call is matched. // The return values from this function are returned by the mocked function. // It takes an any argument to support n-arity functions. // The anonymous function must match the function signature mocked method. func (c *Call) DoAndReturn(f any) *Call { // TODO: Check arity and types here, rather than dying badly elsewhere. v := reflect.ValueOf(f) c.addAction(func(args []any) []any { c.t.Helper() ft := v.Type() if c.methodType.NumIn() != ft.NumIn() { if ft.IsVariadic() { c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v The function signature must match the mocked method, a variadic function cannot be used.", c.receiver, c.method) } else { c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v: got %d, want %d [%s]", c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin) } return nil } vArgs := make([]reflect.Value, len(args)) for i := 0; i < len(args); i++ { if args[i] != nil { vArgs[i] = reflect.ValueOf(args[i]) } else { // Use the zero value for the arg. vArgs[i] = reflect.Zero(ft.In(i)) } } vRets := v.Call(vArgs) rets := make([]any, len(vRets)) for i, ret := range vRets { rets[i] = ret.Interface() } return rets }) return c } // Do declares the action to run when the call is matched. The function's // return values are ignored to retain backward compatibility. To use the // return values call DoAndReturn. // It takes an any argument to support n-arity functions. // The anonymous function must match the function signature mocked method. func (c *Call) Do(f any) *Call { // TODO: Check arity and types here, rather than dying badly elsewhere. v := reflect.ValueOf(f) c.addAction(func(args []any) []any { c.t.Helper() ft := v.Type() if c.methodType.NumIn() != ft.NumIn() { if ft.IsVariadic() { c.t.Fatalf("wrong number of arguments in Do func for %T.%v The function signature must match the mocked method, a variadic function cannot be used.", c.receiver, c.method) } else { c.t.Fatalf("wrong number of arguments in Do func for %T.%v: got %d, want %d [%s]", c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin) } return nil } vArgs := make([]reflect.Value, len(args)) for i := 0; i < len(args); i++ { if args[i] != nil { vArgs[i] = reflect.ValueOf(args[i]) } else { // Use the zero value for the arg. vArgs[i] = reflect.Zero(ft.In(i)) } } v.Call(vArgs) return nil }) return c } // Return declares the values to be returned by the mocked function call. func (c *Call) Return(rets ...any) *Call { c.t.Helper() mt := c.methodType if len(rets) != mt.NumOut() { c.t.Fatalf("wrong number of arguments to Return for %T.%v: got %d, want %d [%s]", c.receiver, c.method, len(rets), mt.NumOut(), c.origin) } for i, ret := range rets { if got, want := reflect.TypeOf(ret), mt.Out(i); got == want { // Identical types; nothing to do. } else if got == nil { // Nil needs special handling. switch want.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: // ok default: c.t.Fatalf("argument %d to Return for %T.%v is nil, but %v is not nillable [%s]", i, c.receiver, c.method, want, c.origin) } } else if got.AssignableTo(want) { // Assignable type relation. Make the assignment now so that the generated code // can return the values with a type assertion. v := reflect.New(want).Elem() v.Set(reflect.ValueOf(ret)) rets[i] = v.Interface() } else { c.t.Fatalf("wrong type of argument %d to Return for %T.%v: %v is not assignable to %v [%s]", i, c.receiver, c.method, got, want, c.origin) } } c.addAction(func([]any) []any { return rets }) return c } // Times declares the exact number of times a function call is expected to be executed. func (c *Call) Times(n int) *Call { c.minCalls, c.maxCalls = n, n return c } // SetArg declares an action that will set the nth argument's value, // indirected through a pointer. Or, in the case of a slice and map, SetArg // will copy value's elements/key-value pairs into the nth argument. func (c *Call) SetArg(n int, value any) *Call { c.t.Helper() mt := c.methodType // TODO: This will break on variadic methods. // We will need to check those at invocation time. if n < 0 || n >= mt.NumIn() { c.t.Fatalf("SetArg(%d, ...) called for a method with %d args [%s]", n, mt.NumIn(), c.origin) } // Permit setting argument through an interface. // In the interface case, we don't (nay, can't) check the type here. at := mt.In(n) switch at.Kind() { case reflect.Ptr: dt := at.Elem() if vt := reflect.TypeOf(value); !vt.AssignableTo(dt) { c.t.Fatalf("SetArg(%d, ...) argument is a %v, not assignable to %v [%s]", n, vt, dt, c.origin) } case reflect.Interface: // nothing to do case reflect.Slice: // nothing to do case reflect.Map: // nothing to do default: c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice non-map type %v [%s]", n, at, c.origin) } c.addAction(func(args []any) []any { v := reflect.ValueOf(value) switch reflect.TypeOf(args[n]).Kind() { case reflect.Slice: setSlice(args[n], v) case reflect.Map: setMap(args[n], v) default: reflect.ValueOf(args[n]).Elem().Set(v) } return nil }) return c } // isPreReq returns true if other is a direct or indirect prerequisite to c. func (c *Call) isPreReq(other *Call) bool { for _, preReq := range c.preReqs { if other == preReq || preReq.isPreReq(other) { return true } } return false } // After declares that the call may only match after preReq has been exhausted. func (c *Call) After(preReq *Call) *Call { c.t.Helper() if c == preReq { c.t.Fatalf("A call isn't allowed to be its own prerequisite") } if preReq.isPreReq(c) { c.t.Fatalf("Loop in call order: %v is a prerequisite to %v (possibly indirectly).", c, preReq) } c.preReqs = append(c.preReqs, preReq) return c } // Returns true if the minimum number of calls have been made. func (c *Call) satisfied() bool { return c.numCalls >= c.minCalls } // Returns true if the maximum number of calls have been made. func (c *Call) exhausted() bool { return c.numCalls >= c.maxCalls } func (c *Call) String() string { args := make([]string, len(c.args)) for i, arg := range c.args { args[i] = arg.String() } arguments := strings.Join(args, ", ") return fmt.Sprintf("%T.%v(%s) %s", c.receiver, c.method, arguments, c.origin) } // Tests if the given call matches the expected call. // If yes, returns nil. If no, returns error with message explaining why it does not match. func (c *Call) matches(args []any) error { if !c.methodType.IsVariadic() { if len(args) != len(c.args) { return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d", c.origin, len(args), len(c.args)) } for i, m := range c.args { if !m.Matches(args[i]) { return fmt.Errorf( "expected call at %s doesn't match the argument at index %d.\nGot: %v\nWant: %v", c.origin, i, formatGottenArg(m, args[i]), m, ) } } } else { if len(c.args) < c.methodType.NumIn()-1 { return fmt.Errorf("expected call at %s has the wrong number of matchers. Got: %d, want: %d", c.origin, len(c.args), c.methodType.NumIn()-1) } if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) { return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d", c.origin, len(args), len(c.args)) } if len(args) < len(c.args)-1 { return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d", c.origin, len(args), len(c.args)-1) } for i, m := range c.args { if i < c.methodType.NumIn()-1 { // Non-variadic args if !m.Matches(args[i]) { return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", c.origin, strconv.Itoa(i), formatGottenArg(m, args[i]), m) } continue } // The last arg has a possibility of a variadic argument, so let it branch // sample: Foo(a int, b int, c ...int) if i < len(c.args) && i < len(args) { if m.Matches(args[i]) { // Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any()) // Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher) // Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC) // Got Foo(a, b) want Foo(matcherA, matcherB) // Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD) continue } } // The number of actual args don't match the number of matchers, // or the last matcher is a slice and the last arg is not. // If this function still matches it is because the last matcher // matches all the remaining arguments or the lack of any. // Convert the remaining arguments, if any, into a slice of the // expected type. vArgsType := c.methodType.In(c.methodType.NumIn() - 1) vArgs := reflect.MakeSlice(vArgsType, 0, len(args)-i) for _, arg := range args[i:] { vArgs = reflect.Append(vArgs, reflect.ValueOf(arg)) } if m.Matches(vArgs.Interface()) { // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any()) // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher) // Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any()) // Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher) break } // Wrong number of matchers or not match. Fail. // Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD) // Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD) // Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE) // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD) // Got Foo(a, b, c) want Foo(matcherA, matcherB) return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", c.origin, strconv.Itoa(i), formatGottenArg(m, args[i:]), c.args[i]) } } // Check that all prerequisite calls have been satisfied. for _, preReqCall := range c.preReqs { if !preReqCall.satisfied() { return fmt.Errorf("expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v", c.origin, preReqCall, c) } } // Check that the call is not exhausted. if c.exhausted() { return fmt.Errorf("expected call at %s has already been called the max number of times", c.origin) } return nil } // dropPrereqs tells the expected Call to not re-check prerequisite calls any // longer, and to return its current set. func (c *Call) dropPrereqs() (preReqs []*Call) { preReqs = c.preReqs c.preReqs = nil return } func (c *Call) call() []func([]any) []any { c.numCalls++ return c.actions } // InOrder declares that the given calls should occur in order. // It panics if the type of any of the arguments isn't *Call or a generated // mock with an embedded *Call. func InOrder(args ...any) { calls := make([]*Call, 0, len(args)) for i := 0; i < len(args); i++ { if call := getCall(args[i]); call != nil { calls = append(calls, call) continue } panic(fmt.Sprintf( "invalid argument at position %d of type %T, InOrder expects *gomock.Call or generated mock types with an embedded *gomock.Call", i, args[i], )) } for i := 1; i < len(calls); i++ { calls[i].After(calls[i-1]) } } // getCall checks if the parameter is a *Call or a generated struct // that wraps a *Call and returns the *Call pointer - if neither, it returns nil. func getCall(arg any) *Call { if call, ok := arg.(*Call); ok { return call } t := reflect.ValueOf(arg) if t.Kind() != reflect.Ptr && t.Kind() != reflect.Interface { return nil } t = t.Elem() for i := 0; i < t.NumField(); i++ { f := t.Field(i) if !f.CanInterface() { continue } if call, ok := f.Interface().(*Call); ok { return call } } return nil } func setSlice(arg any, v reflect.Value) { va := reflect.ValueOf(arg) for i := 0; i < v.Len(); i++ { va.Index(i).Set(v.Index(i)) } } func setMap(arg any, v reflect.Value) { va := reflect.ValueOf(arg) for _, e := range va.MapKeys() { va.SetMapIndex(e, reflect.Value{}) } for _, e := range v.MapKeys() { va.SetMapIndex(e, v.MapIndex(e)) } } func (c *Call) addAction(action func([]any) []any) { c.actions = append(c.actions, action) } func formatGottenArg(m Matcher, arg any) string { got := fmt.Sprintf("%v (%T)", arg, arg) if gs, ok := m.(GotFormatter); ok { got = gs.Got(arg) } return got }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/mock/gomock/controller.go
vendor/go.uber.org/mock/gomock/controller.go
// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gomock import ( "context" "fmt" "reflect" "runtime" "sync" ) // A TestReporter is something that can be used to report test failures. It // is satisfied by the standard library's *testing.T. type TestReporter interface { Errorf(format string, args ...any) Fatalf(format string, args ...any) } // TestHelper is a TestReporter that has the Helper method. It is satisfied // by the standard library's *testing.T. type TestHelper interface { TestReporter Helper() } // cleanuper is used to check if TestHelper also has the `Cleanup` method. A // common pattern is to pass in a `*testing.T` to // `NewController(t TestReporter)`. In Go 1.14+, `*testing.T` has a cleanup // method. This can be utilized to call `Finish()` so the caller of this library // does not have to. type cleanuper interface { Cleanup(func()) } // A Controller represents the top-level control of a mock ecosystem. It // defines the scope and lifetime of mock objects, as well as their // expectations. It is safe to call Controller's methods from multiple // goroutines. Each test should create a new Controller and invoke Finish via // defer. // // func TestFoo(t *testing.T) { // ctrl := gomock.NewController(t) // // .. // } // // func TestBar(t *testing.T) { // t.Run("Sub-Test-1", st) { // ctrl := gomock.NewController(st) // // .. // }) // t.Run("Sub-Test-2", st) { // ctrl := gomock.NewController(st) // // .. // }) // }) type Controller struct { // T should only be called within a generated mock. It is not intended to // be used in user code and may be changed in future versions. T is the // TestReporter passed in when creating the Controller via NewController. // If the TestReporter does not implement a TestHelper it will be wrapped // with a nopTestHelper. T TestHelper mu sync.Mutex expectedCalls *callSet finished bool } // NewController returns a new Controller. It is the preferred way to create a Controller. // // Passing [*testing.T] registers cleanup function to automatically call [Controller.Finish] // when the test and all its subtests complete. func NewController(t TestReporter, opts ...ControllerOption) *Controller { h, ok := t.(TestHelper) if !ok { h = &nopTestHelper{t} } ctrl := &Controller{ T: h, expectedCalls: newCallSet(), } for _, opt := range opts { opt.apply(ctrl) } if c, ok := isCleanuper(ctrl.T); ok { c.Cleanup(func() { ctrl.T.Helper() ctrl.finish(true, nil) }) } return ctrl } // ControllerOption configures how a Controller should behave. type ControllerOption interface { apply(*Controller) } type overridableExpectationsOption struct{} // WithOverridableExpectations allows for overridable call expectations // i.e., subsequent call expectations override existing call expectations func WithOverridableExpectations() overridableExpectationsOption { return overridableExpectationsOption{} } func (o overridableExpectationsOption) apply(ctrl *Controller) { ctrl.expectedCalls = newOverridableCallSet() } type cancelReporter struct { t TestHelper cancel func() } func (r *cancelReporter) Errorf(format string, args ...any) { r.t.Errorf(format, args...) } func (r *cancelReporter) Fatalf(format string, args ...any) { defer r.cancel() r.t.Fatalf(format, args...) } func (r *cancelReporter) Helper() { r.t.Helper() } // WithContext returns a new Controller and a Context, which is cancelled on any // fatal failure. func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) { h, ok := t.(TestHelper) if !ok { h = &nopTestHelper{t: t} } ctx, cancel := context.WithCancel(ctx) return NewController(&cancelReporter{t: h, cancel: cancel}), ctx } type nopTestHelper struct { t TestReporter } func (h *nopTestHelper) Errorf(format string, args ...any) { h.t.Errorf(format, args...) } func (h *nopTestHelper) Fatalf(format string, args ...any) { h.t.Fatalf(format, args...) } func (h nopTestHelper) Helper() {} // RecordCall is called by a mock. It should not be called by user code. func (ctrl *Controller) RecordCall(receiver any, method string, args ...any) *Call { ctrl.T.Helper() recv := reflect.ValueOf(receiver) for i := 0; i < recv.Type().NumMethod(); i++ { if recv.Type().Method(i).Name == method { return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...) } } ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver) panic("unreachable") } // RecordCallWithMethodType is called by a mock. It should not be called by user code. func (ctrl *Controller) RecordCallWithMethodType(receiver any, method string, methodType reflect.Type, args ...any) *Call { ctrl.T.Helper() call := newCall(ctrl.T, receiver, method, methodType, args...) ctrl.mu.Lock() defer ctrl.mu.Unlock() ctrl.expectedCalls.Add(call) return call } // Call is called by a mock. It should not be called by user code. func (ctrl *Controller) Call(receiver any, method string, args ...any) []any { ctrl.T.Helper() // Nest this code so we can use defer to make sure the lock is released. actions := func() []func([]any) []any { ctrl.T.Helper() ctrl.mu.Lock() defer ctrl.mu.Unlock() expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args) if err != nil { // callerInfo's skip should be updated if the number of calls between the user's test // and this line changes, i.e. this code is wrapped in another anonymous function. // 0 is us, 1 is controller.Call(), 2 is the generated mock, and 3 is the user's test. origin := callerInfo(3) ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err) } // Two things happen here: // * the matching call no longer needs to check prerequite calls, // * and the prerequite calls are no longer expected, so remove them. preReqCalls := expected.dropPrereqs() for _, preReqCall := range preReqCalls { ctrl.expectedCalls.Remove(preReqCall) } actions := expected.call() if expected.exhausted() { ctrl.expectedCalls.Remove(expected) } return actions }() var rets []any for _, action := range actions { if r := action(args); r != nil { rets = r } } return rets } // Finish checks to see if all the methods that were expected to be called were called. // It is not idempotent and therefore can only be invoked once. func (ctrl *Controller) Finish() { // If we're currently panicking, probably because this is a deferred call. // This must be recovered in the deferred function. err := recover() ctrl.finish(false, err) } // Satisfied returns whether all expected calls bound to this Controller have been satisfied. // Calling Finish is then guaranteed to not fail due to missing calls. func (ctrl *Controller) Satisfied() bool { ctrl.mu.Lock() defer ctrl.mu.Unlock() return ctrl.expectedCalls.Satisfied() } func (ctrl *Controller) finish(cleanup bool, panicErr any) { ctrl.T.Helper() ctrl.mu.Lock() defer ctrl.mu.Unlock() if ctrl.finished { if _, ok := isCleanuper(ctrl.T); !ok { ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.") } return } ctrl.finished = true // Short-circuit, pass through the panic. if panicErr != nil { panic(panicErr) } // Check that all remaining expected calls are satisfied. failures := ctrl.expectedCalls.Failures() for _, call := range failures { ctrl.T.Errorf("missing call(s) to %v", call) } if len(failures) != 0 { if !cleanup { ctrl.T.Fatalf("aborting test due to missing call(s)") return } ctrl.T.Errorf("aborting test due to missing call(s)") } } // callerInfo returns the file:line of the call site. skip is the number // of stack frames to skip when reporting. 0 is callerInfo's call site. func callerInfo(skip int) string { if _, file, line, ok := runtime.Caller(skip + 1); ok { return fmt.Sprintf("%s:%d", file, line) } return "unknown file" } // isCleanuper checks it if t's base TestReporter has a Cleanup method. func isCleanuper(t TestReporter) (cleanuper, bool) { tr := unwrapTestReporter(t) c, ok := tr.(cleanuper) return c, ok } // unwrapTestReporter unwraps TestReporter to the base implementation. func unwrapTestReporter(t TestReporter) TestReporter { tr := t switch nt := t.(type) { case *cancelReporter: tr = nt.t if h, check := tr.(*nopTestHelper); check { tr = h.t } case *nopTestHelper: tr = nt.t default: // not wrapped } return tr }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/mock/gomock/doc.go
vendor/go.uber.org/mock/gomock/doc.go
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package gomock is a mock framework for Go. // // Standard usage: // // (1) Define an interface that you wish to mock. // type MyInterface interface { // SomeMethod(x int64, y string) // } // (2) Use mockgen to generate a mock from the interface. // (3) Use the mock in a test: // func TestMyThing(t *testing.T) { // mockCtrl := gomock.NewController(t) // mockObj := something.NewMockMyInterface(mockCtrl) // mockObj.EXPECT().SomeMethod(4, "blah") // // pass mockObj to a real object and play with it. // } // // By default, expected calls are not enforced to run in any particular order. // Call order dependency can be enforced by use of InOrder and/or Call.After. // Call.After can create more varied call order dependencies, but InOrder is // often more convenient. // // The following examples create equivalent call order dependencies. // // Example of using Call.After to chain expected call order: // // firstCall := mockObj.EXPECT().SomeMethod(1, "first") // secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall) // mockObj.EXPECT().SomeMethod(3, "third").After(secondCall) // // Example of using InOrder to declare expected call order: // // gomock.InOrder( // mockObj.EXPECT().SomeMethod(1, "first"), // mockObj.EXPECT().SomeMethod(2, "second"), // mockObj.EXPECT().SomeMethod(3, "third"), // ) // // The standard TestReporter most users will pass to `NewController` is a // `*testing.T` from the context of the test. Note that this will use the // standard `t.Error` and `t.Fatal` methods to report what happened in the test. // In some cases this can leave your testing package in a weird state if global // state is used since `t.Fatal` is like calling panic in the middle of a // function. In these cases it is recommended that you pass in your own // `TestReporter`. package gomock
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/flag.go
vendor/go.uber.org/zap/flag.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zap import ( "flag" "go.uber.org/zap/zapcore" ) // LevelFlag uses the standard library's flag.Var to declare a global flag // with the specified name, default, and usage guidance. The returned value is // a pointer to the value of the flag. // // If you don't want to use the flag package's global state, you can use any // non-nil *Level as a flag.Value with your own *flag.FlagSet. func LevelFlag(name string, defaultLevel zapcore.Level, usage string) *zapcore.Level { lvl := defaultLevel flag.Var(&lvl, name, usage) return &lvl }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/time.go
vendor/go.uber.org/zap/time.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zap import "time" func timeToMillis(t time.Time) int64 { return t.UnixNano() / int64(time.Millisecond) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/level.go
vendor/go.uber.org/zap/level.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zap import ( "sync/atomic" "go.uber.org/zap/internal" "go.uber.org/zap/zapcore" ) const ( // DebugLevel logs are typically voluminous, and are usually disabled in // production. DebugLevel = zapcore.DebugLevel // InfoLevel is the default logging priority. InfoLevel = zapcore.InfoLevel // WarnLevel logs are more important than Info, but don't need individual // human review. WarnLevel = zapcore.WarnLevel // ErrorLevel logs are high-priority. If an application is running smoothly, // it shouldn't generate any error-level logs. ErrorLevel = zapcore.ErrorLevel // DPanicLevel logs are particularly important errors. In development the // logger panics after writing the message. DPanicLevel = zapcore.DPanicLevel // PanicLevel logs a message, then panics. PanicLevel = zapcore.PanicLevel // FatalLevel logs a message, then calls os.Exit(1). FatalLevel = zapcore.FatalLevel ) // LevelEnablerFunc is a convenient way to implement zapcore.LevelEnabler with // an anonymous function. // // It's particularly useful when splitting log output between different // outputs (e.g., standard error and standard out). For sample code, see the // package-level AdvancedConfiguration example. type LevelEnablerFunc func(zapcore.Level) bool // Enabled calls the wrapped function. func (f LevelEnablerFunc) Enabled(lvl zapcore.Level) bool { return f(lvl) } // An AtomicLevel is an atomically changeable, dynamic logging level. It lets // you safely change the log level of a tree of loggers (the root logger and // any children created by adding context) at runtime. // // The AtomicLevel itself is an http.Handler that serves a JSON endpoint to // alter its level. // // AtomicLevels must be created with the NewAtomicLevel constructor to allocate // their internal atomic pointer. type AtomicLevel struct { l *atomic.Int32 } var _ internal.LeveledEnabler = AtomicLevel{} // NewAtomicLevel creates an AtomicLevel with InfoLevel and above logging // enabled. func NewAtomicLevel() AtomicLevel { lvl := AtomicLevel{l: new(atomic.Int32)} lvl.l.Store(int32(InfoLevel)) return lvl } // NewAtomicLevelAt is a convenience function that creates an AtomicLevel // and then calls SetLevel with the given level. func NewAtomicLevelAt(l zapcore.Level) AtomicLevel { a := NewAtomicLevel() a.SetLevel(l) return a } // ParseAtomicLevel parses an AtomicLevel based on a lowercase or all-caps ASCII // representation of the log level. If the provided ASCII representation is // invalid an error is returned. // // This is particularly useful when dealing with text input to configure log // levels. func ParseAtomicLevel(text string) (AtomicLevel, error) { a := NewAtomicLevel() l, err := zapcore.ParseLevel(text) if err != nil { return a, err } a.SetLevel(l) return a, nil } // Enabled implements the zapcore.LevelEnabler interface, which allows the // AtomicLevel to be used in place of traditional static levels. func (lvl AtomicLevel) Enabled(l zapcore.Level) bool { return lvl.Level().Enabled(l) } // Level returns the minimum enabled log level. func (lvl AtomicLevel) Level() zapcore.Level { return zapcore.Level(int8(lvl.l.Load())) } // SetLevel alters the logging level. func (lvl AtomicLevel) SetLevel(l zapcore.Level) { lvl.l.Store(int32(l)) } // String returns the string representation of the underlying Level. func (lvl AtomicLevel) String() string { return lvl.Level().String() } // UnmarshalText unmarshals the text to an AtomicLevel. It uses the same text // representations as the static zapcore.Levels ("debug", "info", "warn", // "error", "dpanic", "panic", and "fatal"). func (lvl *AtomicLevel) UnmarshalText(text []byte) error { if lvl.l == nil { lvl.l = &atomic.Int32{} } var l zapcore.Level if err := l.UnmarshalText(text); err != nil { return err } lvl.SetLevel(l) return nil } // MarshalText marshals the AtomicLevel to a byte slice. It uses the same // text representation as the static zapcore.Levels ("debug", "info", "warn", // "error", "dpanic", "panic", and "fatal"). func (lvl AtomicLevel) MarshalText() (text []byte, err error) { return lvl.Level().MarshalText() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/sink.go
vendor/go.uber.org/zap/sink.go
// Copyright (c) 2016-2022 Uber Technologies, Inc. // // 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. package zap import ( "errors" "fmt" "io" "net/url" "os" "path/filepath" "strings" "sync" "go.uber.org/zap/zapcore" ) const schemeFile = "file" var _sinkRegistry = newSinkRegistry() // Sink defines the interface to write to and close logger destinations. type Sink interface { zapcore.WriteSyncer io.Closer } type errSinkNotFound struct { scheme string } func (e *errSinkNotFound) Error() string { return fmt.Sprintf("no sink found for scheme %q", e.scheme) } type nopCloserSink struct{ zapcore.WriteSyncer } func (nopCloserSink) Close() error { return nil } type sinkRegistry struct { mu sync.Mutex factories map[string]func(*url.URL) (Sink, error) // keyed by scheme openFile func(string, int, os.FileMode) (*os.File, error) // type matches os.OpenFile } func newSinkRegistry() *sinkRegistry { sr := &sinkRegistry{ factories: make(map[string]func(*url.URL) (Sink, error)), openFile: os.OpenFile, } // Infallible operation: the registry is empty, so we can't have a conflict. _ = sr.RegisterSink(schemeFile, sr.newFileSinkFromURL) return sr } // RegisterScheme registers the given factory for the specific scheme. func (sr *sinkRegistry) RegisterSink(scheme string, factory func(*url.URL) (Sink, error)) error { sr.mu.Lock() defer sr.mu.Unlock() if scheme == "" { return errors.New("can't register a sink factory for empty string") } normalized, err := normalizeScheme(scheme) if err != nil { return fmt.Errorf("%q is not a valid scheme: %v", scheme, err) } if _, ok := sr.factories[normalized]; ok { return fmt.Errorf("sink factory already registered for scheme %q", normalized) } sr.factories[normalized] = factory return nil } func (sr *sinkRegistry) newSink(rawURL string) (Sink, error) { // URL parsing doesn't work well for Windows paths such as `c:\log.txt`, as scheme is set to // the drive, and path is unset unless `c:/log.txt` is used. // To avoid Windows-specific URL handling, we instead check IsAbs to open as a file. // filepath.IsAbs is OS-specific, so IsAbs('c:/log.txt') is false outside of Windows. if filepath.IsAbs(rawURL) { return sr.newFileSinkFromPath(rawURL) } u, err := url.Parse(rawURL) if err != nil { return nil, fmt.Errorf("can't parse %q as a URL: %v", rawURL, err) } if u.Scheme == "" { u.Scheme = schemeFile } sr.mu.Lock() factory, ok := sr.factories[u.Scheme] sr.mu.Unlock() if !ok { return nil, &errSinkNotFound{u.Scheme} } return factory(u) } // RegisterSink registers a user-supplied factory for all sinks with a // particular scheme. // // All schemes must be ASCII, valid under section 0.1 of RFC 3986 // (https://tools.ietf.org/html/rfc3983#section-3.1), and must not already // have a factory registered. Zap automatically registers a factory for the // "file" scheme. func RegisterSink(scheme string, factory func(*url.URL) (Sink, error)) error { return _sinkRegistry.RegisterSink(scheme, factory) } func (sr *sinkRegistry) newFileSinkFromURL(u *url.URL) (Sink, error) { if u.User != nil { return nil, fmt.Errorf("user and password not allowed with file URLs: got %v", u) } if u.Fragment != "" { return nil, fmt.Errorf("fragments not allowed with file URLs: got %v", u) } if u.RawQuery != "" { return nil, fmt.Errorf("query parameters not allowed with file URLs: got %v", u) } // Error messages are better if we check hostname and port separately. if u.Port() != "" { return nil, fmt.Errorf("ports not allowed with file URLs: got %v", u) } if hn := u.Hostname(); hn != "" && hn != "localhost" { return nil, fmt.Errorf("file URLs must leave host empty or use localhost: got %v", u) } return sr.newFileSinkFromPath(u.Path) } func (sr *sinkRegistry) newFileSinkFromPath(path string) (Sink, error) { switch path { case "stdout": return nopCloserSink{os.Stdout}, nil case "stderr": return nopCloserSink{os.Stderr}, nil } return sr.openFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666) } func normalizeScheme(s string) (string, error) { // https://tools.ietf.org/html/rfc3986#section-3.1 s = strings.ToLower(s) if first := s[0]; 'a' > first || 'z' < first { return "", errors.New("must start with a letter") } for i := 1; i < len(s); i++ { // iterate over bytes, not runes c := s[i] switch { case 'a' <= c && c <= 'z': continue case '0' <= c && c <= '9': continue case c == '.' || c == '+' || c == '-': continue } return "", fmt.Errorf("may not contain %q", c) } return s, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/error.go
vendor/go.uber.org/zap/error.go
// Copyright (c) 2017 Uber Technologies, Inc. // // 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. package zap import ( "go.uber.org/zap/internal/pool" "go.uber.org/zap/zapcore" ) var _errArrayElemPool = pool.New(func() *errArrayElem { return &errArrayElem{} }) // Error is shorthand for the common idiom NamedError("error", err). func Error(err error) Field { return NamedError("error", err) } // NamedError constructs a field that lazily stores err.Error() under the // provided key. Errors which also implement fmt.Formatter (like those produced // by github.com/pkg/errors) will also have their verbose representation stored // under key+"Verbose". If passed a nil error, the field is a no-op. // // For the common case in which the key is simply "error", the Error function // is shorter and less repetitive. func NamedError(key string, err error) Field { if err == nil { return Skip() } return Field{Key: key, Type: zapcore.ErrorType, Interface: err} } type errArray []error func (errs errArray) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range errs { if errs[i] == nil { continue } // To represent each error as an object with an "error" attribute and // potentially an "errorVerbose" attribute, we need to wrap it in a // type that implements LogObjectMarshaler. To prevent this from // allocating, pool the wrapper type. elem := _errArrayElemPool.Get() elem.error = errs[i] err := arr.AppendObject(elem) elem.error = nil _errArrayElemPool.Put(elem) if err != nil { return err } } return nil } type errArrayElem struct { error } func (e *errArrayElem) MarshalLogObject(enc zapcore.ObjectEncoder) error { // Re-use the error field's logic, which supports non-standard error types. Error(e.error).AddTo(enc) return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/config.go
vendor/go.uber.org/zap/config.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zap import ( "errors" "sort" "time" "go.uber.org/zap/zapcore" ) // SamplingConfig sets a sampling strategy for the logger. Sampling caps the // global CPU and I/O load that logging puts on your process while attempting // to preserve a representative subset of your logs. // // If specified, the Sampler will invoke the Hook after each decision. // // Values configured here are per-second. See zapcore.NewSamplerWithOptions for // details. type SamplingConfig struct { Initial int `json:"initial" yaml:"initial"` Thereafter int `json:"thereafter" yaml:"thereafter"` Hook func(zapcore.Entry, zapcore.SamplingDecision) `json:"-" yaml:"-"` } // Config offers a declarative way to construct a logger. It doesn't do // anything that can't be done with New, Options, and the various // zapcore.WriteSyncer and zapcore.Core wrappers, but it's a simpler way to // toggle common options. // // Note that Config intentionally supports only the most common options. More // unusual logging setups (logging to network connections or message queues, // splitting output between multiple files, etc.) are possible, but require // direct use of the zapcore package. For sample code, see the package-level // BasicConfiguration and AdvancedConfiguration examples. // // For an example showing runtime log level changes, see the documentation for // AtomicLevel. type Config struct { // Level is the minimum enabled logging level. Note that this is a dynamic // level, so calling Config.Level.SetLevel will atomically change the log // level of all loggers descended from this config. Level AtomicLevel `json:"level" yaml:"level"` // Development puts the logger in development mode, which changes the // behavior of DPanicLevel and takes stacktraces more liberally. Development bool `json:"development" yaml:"development"` // DisableCaller stops annotating logs with the calling function's file // name and line number. By default, all logs are annotated. DisableCaller bool `json:"disableCaller" yaml:"disableCaller"` // DisableStacktrace completely disables automatic stacktrace capturing. By // default, stacktraces are captured for WarnLevel and above logs in // development and ErrorLevel and above in production. DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace"` // Sampling sets a sampling policy. A nil SamplingConfig disables sampling. Sampling *SamplingConfig `json:"sampling" yaml:"sampling"` // Encoding sets the logger's encoding. Valid values are "json" and // "console", as well as any third-party encodings registered via // RegisterEncoder. Encoding string `json:"encoding" yaml:"encoding"` // EncoderConfig sets options for the chosen encoder. See // zapcore.EncoderConfig for details. EncoderConfig zapcore.EncoderConfig `json:"encoderConfig" yaml:"encoderConfig"` // OutputPaths is a list of URLs or file paths to write logging output to. // See Open for details. OutputPaths []string `json:"outputPaths" yaml:"outputPaths"` // ErrorOutputPaths is a list of URLs to write internal logger errors to. // The default is standard error. // // Note that this setting only affects internal errors; for sample code that // sends error-level logs to a different location from info- and debug-level // logs, see the package-level AdvancedConfiguration example. ErrorOutputPaths []string `json:"errorOutputPaths" yaml:"errorOutputPaths"` // InitialFields is a collection of fields to add to the root logger. InitialFields map[string]interface{} `json:"initialFields" yaml:"initialFields"` } // NewProductionEncoderConfig returns an opinionated EncoderConfig for // production environments. // // Messages encoded with this configuration will be JSON-formatted // and will have the following keys by default: // // - "level": The logging level (e.g. "info", "error"). // - "ts": The current time in number of seconds since the Unix epoch. // - "msg": The message passed to the log statement. // - "caller": If available, a short path to the file and line number // where the log statement was issued. // The logger configuration determines whether this field is captured. // - "stacktrace": If available, a stack trace from the line // where the log statement was issued. // The logger configuration determines whether this field is captured. // // By default, the following formats are used for different types: // // - Time is formatted as floating-point number of seconds since the Unix // epoch. // - Duration is formatted as floating-point number of seconds. // // You may change these by setting the appropriate fields in the returned // object. // For example, use the following to change the time encoding format: // // cfg := zap.NewProductionEncoderConfig() // cfg.EncodeTime = zapcore.ISO8601TimeEncoder func NewProductionEncoderConfig() zapcore.EncoderConfig { return zapcore.EncoderConfig{ TimeKey: "ts", LevelKey: "level", NameKey: "logger", CallerKey: "caller", FunctionKey: zapcore.OmitKey, MessageKey: "msg", StacktraceKey: "stacktrace", LineEnding: zapcore.DefaultLineEnding, EncodeLevel: zapcore.LowercaseLevelEncoder, EncodeTime: zapcore.EpochTimeEncoder, EncodeDuration: zapcore.SecondsDurationEncoder, EncodeCaller: zapcore.ShortCallerEncoder, } } // NewProductionConfig builds a reasonable default production logging // configuration. // Logging is enabled at InfoLevel and above, and uses a JSON encoder. // Logs are written to standard error. // Stacktraces are included on logs of ErrorLevel and above. // DPanicLevel logs will not panic, but will write a stacktrace. // // Sampling is enabled at 100:100 by default, // meaning that after the first 100 log entries // with the same level and message in the same second, // it will log every 100th entry // with the same level and message in the same second. // You may disable this behavior by setting Sampling to nil. // // See [NewProductionEncoderConfig] for information // on the default encoder configuration. func NewProductionConfig() Config { return Config{ Level: NewAtomicLevelAt(InfoLevel), Development: false, Sampling: &SamplingConfig{ Initial: 100, Thereafter: 100, }, Encoding: "json", EncoderConfig: NewProductionEncoderConfig(), OutputPaths: []string{"stderr"}, ErrorOutputPaths: []string{"stderr"}, } } // NewDevelopmentEncoderConfig returns an opinionated EncoderConfig for // development environments. // // Messages encoded with this configuration will use Zap's console encoder // intended to print human-readable output. // It will print log messages with the following information: // // - The log level (e.g. "INFO", "ERROR"). // - The time in ISO8601 format (e.g. "2017-01-01T12:00:00Z"). // - The message passed to the log statement. // - If available, a short path to the file and line number // where the log statement was issued. // The logger configuration determines whether this field is captured. // - If available, a stacktrace from the line // where the log statement was issued. // The logger configuration determines whether this field is captured. // // By default, the following formats are used for different types: // // - Time is formatted in ISO8601 format (e.g. "2017-01-01T12:00:00Z"). // - Duration is formatted as a string (e.g. "1.234s"). // // You may change these by setting the appropriate fields in the returned // object. // For example, use the following to change the time encoding format: // // cfg := zap.NewDevelopmentEncoderConfig() // cfg.EncodeTime = zapcore.ISO8601TimeEncoder func NewDevelopmentEncoderConfig() zapcore.EncoderConfig { return zapcore.EncoderConfig{ // Keys can be anything except the empty string. TimeKey: "T", LevelKey: "L", NameKey: "N", CallerKey: "C", FunctionKey: zapcore.OmitKey, MessageKey: "M", StacktraceKey: "S", LineEnding: zapcore.DefaultLineEnding, EncodeLevel: zapcore.CapitalLevelEncoder, EncodeTime: zapcore.ISO8601TimeEncoder, EncodeDuration: zapcore.StringDurationEncoder, EncodeCaller: zapcore.ShortCallerEncoder, } } // NewDevelopmentConfig builds a reasonable default development logging // configuration. // Logging is enabled at DebugLevel and above, and uses a console encoder. // Logs are written to standard error. // Stacktraces are included on logs of WarnLevel and above. // DPanicLevel logs will panic. // // See [NewDevelopmentEncoderConfig] for information // on the default encoder configuration. func NewDevelopmentConfig() Config { return Config{ Level: NewAtomicLevelAt(DebugLevel), Development: true, Encoding: "console", EncoderConfig: NewDevelopmentEncoderConfig(), OutputPaths: []string{"stderr"}, ErrorOutputPaths: []string{"stderr"}, } } // Build constructs a logger from the Config and Options. func (cfg Config) Build(opts ...Option) (*Logger, error) { enc, err := cfg.buildEncoder() if err != nil { return nil, err } sink, errSink, err := cfg.openSinks() if err != nil { return nil, err } if cfg.Level == (AtomicLevel{}) { return nil, errors.New("missing Level") } log := New( zapcore.NewCore(enc, sink, cfg.Level), cfg.buildOptions(errSink)..., ) if len(opts) > 0 { log = log.WithOptions(opts...) } return log, nil } func (cfg Config) buildOptions(errSink zapcore.WriteSyncer) []Option { opts := []Option{ErrorOutput(errSink)} if cfg.Development { opts = append(opts, Development()) } if !cfg.DisableCaller { opts = append(opts, AddCaller()) } stackLevel := ErrorLevel if cfg.Development { stackLevel = WarnLevel } if !cfg.DisableStacktrace { opts = append(opts, AddStacktrace(stackLevel)) } if scfg := cfg.Sampling; scfg != nil { opts = append(opts, WrapCore(func(core zapcore.Core) zapcore.Core { var samplerOpts []zapcore.SamplerOption if scfg.Hook != nil { samplerOpts = append(samplerOpts, zapcore.SamplerHook(scfg.Hook)) } return zapcore.NewSamplerWithOptions( core, time.Second, cfg.Sampling.Initial, cfg.Sampling.Thereafter, samplerOpts..., ) })) } if len(cfg.InitialFields) > 0 { fs := make([]Field, 0, len(cfg.InitialFields)) keys := make([]string, 0, len(cfg.InitialFields)) for k := range cfg.InitialFields { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { fs = append(fs, Any(k, cfg.InitialFields[k])) } opts = append(opts, Fields(fs...)) } return opts } func (cfg Config) openSinks() (zapcore.WriteSyncer, zapcore.WriteSyncer, error) { sink, closeOut, err := Open(cfg.OutputPaths...) if err != nil { return nil, nil, err } errSink, _, err := Open(cfg.ErrorOutputPaths...) if err != nil { closeOut() return nil, nil, err } return sink, errSink, nil } func (cfg Config) buildEncoder() (zapcore.Encoder, error) { return newEncoder(cfg.Encoding, cfg.EncoderConfig) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/writer.go
vendor/go.uber.org/zap/writer.go
// Copyright (c) 2016-2022 Uber Technologies, Inc. // // 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. package zap import ( "fmt" "io" "go.uber.org/zap/zapcore" "go.uber.org/multierr" ) // Open is a high-level wrapper that takes a variadic number of URLs, opens or // creates each of the specified resources, and combines them into a locked // WriteSyncer. It also returns any error encountered and a function to close // any opened files. // // Passing no URLs returns a no-op WriteSyncer. Zap handles URLs without a // scheme and URLs with the "file" scheme. Third-party code may register // factories for other schemes using RegisterSink. // // URLs with the "file" scheme must use absolute paths on the local // filesystem. No user, password, port, fragments, or query parameters are // allowed, and the hostname must be empty or "localhost". // // Since it's common to write logs to the local filesystem, URLs without a // scheme (e.g., "/var/log/foo.log") are treated as local file paths. Without // a scheme, the special paths "stdout" and "stderr" are interpreted as // os.Stdout and os.Stderr. When specified without a scheme, relative file // paths also work. func Open(paths ...string) (zapcore.WriteSyncer, func(), error) { writers, closeAll, err := open(paths) if err != nil { return nil, nil, err } writer := CombineWriteSyncers(writers...) return writer, closeAll, nil } func open(paths []string) ([]zapcore.WriteSyncer, func(), error) { writers := make([]zapcore.WriteSyncer, 0, len(paths)) closers := make([]io.Closer, 0, len(paths)) closeAll := func() { for _, c := range closers { _ = c.Close() } } var openErr error for _, path := range paths { sink, err := _sinkRegistry.newSink(path) if err != nil { openErr = multierr.Append(openErr, fmt.Errorf("open sink %q: %w", path, err)) continue } writers = append(writers, sink) closers = append(closers, sink) } if openErr != nil { closeAll() return nil, nil, openErr } return writers, closeAll, nil } // CombineWriteSyncers is a utility that combines multiple WriteSyncers into a // single, locked WriteSyncer. If no inputs are supplied, it returns a no-op // WriteSyncer. // // It's provided purely as a convenience; the result is no different from // using zapcore.NewMultiWriteSyncer and zapcore.Lock individually. func CombineWriteSyncers(writers ...zapcore.WriteSyncer) zapcore.WriteSyncer { if len(writers) == 0 { return zapcore.AddSync(io.Discard) } return zapcore.Lock(zapcore.NewMultiWriteSyncer(writers...)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/array.go
vendor/go.uber.org/zap/array.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zap import ( "fmt" "time" "go.uber.org/zap/zapcore" ) // Array constructs a field with the given key and ArrayMarshaler. It provides // a flexible, but still type-safe and efficient, way to add array-like types // to the logging context. The struct's MarshalLogArray method is called lazily. func Array(key string, val zapcore.ArrayMarshaler) Field { return Field{Key: key, Type: zapcore.ArrayMarshalerType, Interface: val} } // Bools constructs a field that carries a slice of bools. func Bools(key string, bs []bool) Field { return Array(key, bools(bs)) } // ByteStrings constructs a field that carries a slice of []byte, each of which // must be UTF-8 encoded text. func ByteStrings(key string, bss [][]byte) Field { return Array(key, byteStringsArray(bss)) } // Complex128s constructs a field that carries a slice of complex numbers. func Complex128s(key string, nums []complex128) Field { return Array(key, complex128s(nums)) } // Complex64s constructs a field that carries a slice of complex numbers. func Complex64s(key string, nums []complex64) Field { return Array(key, complex64s(nums)) } // Durations constructs a field that carries a slice of time.Durations. func Durations(key string, ds []time.Duration) Field { return Array(key, durations(ds)) } // Float64s constructs a field that carries a slice of floats. func Float64s(key string, nums []float64) Field { return Array(key, float64s(nums)) } // Float32s constructs a field that carries a slice of floats. func Float32s(key string, nums []float32) Field { return Array(key, float32s(nums)) } // Ints constructs a field that carries a slice of integers. func Ints(key string, nums []int) Field { return Array(key, ints(nums)) } // Int64s constructs a field that carries a slice of integers. func Int64s(key string, nums []int64) Field { return Array(key, int64s(nums)) } // Int32s constructs a field that carries a slice of integers. func Int32s(key string, nums []int32) Field { return Array(key, int32s(nums)) } // Int16s constructs a field that carries a slice of integers. func Int16s(key string, nums []int16) Field { return Array(key, int16s(nums)) } // Int8s constructs a field that carries a slice of integers. func Int8s(key string, nums []int8) Field { return Array(key, int8s(nums)) } // Objects constructs a field with the given key, holding a list of the // provided objects that can be marshaled by Zap. // // Note that these objects must implement zapcore.ObjectMarshaler directly. // That is, if you're trying to marshal a []Request, the MarshalLogObject // method must be declared on the Request type, not its pointer (*Request). // If it's on the pointer, use ObjectValues. // // Given an object that implements MarshalLogObject on the value receiver, you // can log a slice of those objects with Objects like so: // // type Author struct{ ... } // func (a Author) MarshalLogObject(enc zapcore.ObjectEncoder) error // // var authors []Author = ... // logger.Info("loading article", zap.Objects("authors", authors)) // // Similarly, given a type that implements MarshalLogObject on its pointer // receiver, you can log a slice of pointers to that object with Objects like // so: // // type Request struct{ ... } // func (r *Request) MarshalLogObject(enc zapcore.ObjectEncoder) error // // var requests []*Request = ... // logger.Info("sending requests", zap.Objects("requests", requests)) // // If instead, you have a slice of values of such an object, use the // ObjectValues constructor. // // var requests []Request = ... // logger.Info("sending requests", zap.ObjectValues("requests", requests)) func Objects[T zapcore.ObjectMarshaler](key string, values []T) Field { return Array(key, objects[T](values)) } type objects[T zapcore.ObjectMarshaler] []T func (os objects[T]) MarshalLogArray(arr zapcore.ArrayEncoder) error { for _, o := range os { if err := arr.AppendObject(o); err != nil { return err } } return nil } // ObjectMarshalerPtr is a constraint that specifies that the given type // implements zapcore.ObjectMarshaler on a pointer receiver. type ObjectMarshalerPtr[T any] interface { *T zapcore.ObjectMarshaler } // ObjectValues constructs a field with the given key, holding a list of the // provided objects, where pointers to these objects can be marshaled by Zap. // // Note that pointers to these objects must implement zapcore.ObjectMarshaler. // That is, if you're trying to marshal a []Request, the MarshalLogObject // method must be declared on the *Request type, not the value (Request). // If it's on the value, use Objects. // // Given an object that implements MarshalLogObject on the pointer receiver, // you can log a slice of those objects with ObjectValues like so: // // type Request struct{ ... } // func (r *Request) MarshalLogObject(enc zapcore.ObjectEncoder) error // // var requests []Request = ... // logger.Info("sending requests", zap.ObjectValues("requests", requests)) // // If instead, you have a slice of pointers of such an object, use the Objects // field constructor. // // var requests []*Request = ... // logger.Info("sending requests", zap.Objects("requests", requests)) func ObjectValues[T any, P ObjectMarshalerPtr[T]](key string, values []T) Field { return Array(key, objectValues[T, P](values)) } type objectValues[T any, P ObjectMarshalerPtr[T]] []T func (os objectValues[T, P]) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range os { // It is necessary for us to explicitly reference the "P" type. // We cannot simply pass "&os[i]" to AppendObject because its type // is "*T", which the type system does not consider as // implementing ObjectMarshaler. // Only the type "P" satisfies ObjectMarshaler, which we have // to convert "*T" to explicitly. var p P = &os[i] if err := arr.AppendObject(p); err != nil { return err } } return nil } // Strings constructs a field that carries a slice of strings. func Strings(key string, ss []string) Field { return Array(key, stringArray(ss)) } // Stringers constructs a field with the given key, holding a list of the // output provided by the value's String method // // Given an object that implements String on the value receiver, you // can log a slice of those objects with Objects like so: // // type Request struct{ ... } // func (a Request) String() string // // var requests []Request = ... // logger.Info("sending requests", zap.Stringers("requests", requests)) // // Note that these objects must implement fmt.Stringer directly. // That is, if you're trying to marshal a []Request, the String method // must be declared on the Request type, not its pointer (*Request). func Stringers[T fmt.Stringer](key string, values []T) Field { return Array(key, stringers[T](values)) } type stringers[T fmt.Stringer] []T func (os stringers[T]) MarshalLogArray(arr zapcore.ArrayEncoder) error { for _, o := range os { arr.AppendString(o.String()) } return nil } // Times constructs a field that carries a slice of time.Times. func Times(key string, ts []time.Time) Field { return Array(key, times(ts)) } // Uints constructs a field that carries a slice of unsigned integers. func Uints(key string, nums []uint) Field { return Array(key, uints(nums)) } // Uint64s constructs a field that carries a slice of unsigned integers. func Uint64s(key string, nums []uint64) Field { return Array(key, uint64s(nums)) } // Uint32s constructs a field that carries a slice of unsigned integers. func Uint32s(key string, nums []uint32) Field { return Array(key, uint32s(nums)) } // Uint16s constructs a field that carries a slice of unsigned integers. func Uint16s(key string, nums []uint16) Field { return Array(key, uint16s(nums)) } // Uint8s constructs a field that carries a slice of unsigned integers. func Uint8s(key string, nums []uint8) Field { return Array(key, uint8s(nums)) } // Uintptrs constructs a field that carries a slice of pointer addresses. func Uintptrs(key string, us []uintptr) Field { return Array(key, uintptrs(us)) } // Errors constructs a field that carries a slice of errors. func Errors(key string, errs []error) Field { return Array(key, errArray(errs)) } type bools []bool func (bs bools) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range bs { arr.AppendBool(bs[i]) } return nil } type byteStringsArray [][]byte func (bss byteStringsArray) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range bss { arr.AppendByteString(bss[i]) } return nil } type complex128s []complex128 func (nums complex128s) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendComplex128(nums[i]) } return nil } type complex64s []complex64 func (nums complex64s) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendComplex64(nums[i]) } return nil } type durations []time.Duration func (ds durations) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range ds { arr.AppendDuration(ds[i]) } return nil } type float64s []float64 func (nums float64s) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendFloat64(nums[i]) } return nil } type float32s []float32 func (nums float32s) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendFloat32(nums[i]) } return nil } type ints []int func (nums ints) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendInt(nums[i]) } return nil } type int64s []int64 func (nums int64s) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendInt64(nums[i]) } return nil } type int32s []int32 func (nums int32s) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendInt32(nums[i]) } return nil } type int16s []int16 func (nums int16s) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendInt16(nums[i]) } return nil } type int8s []int8 func (nums int8s) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendInt8(nums[i]) } return nil } type stringArray []string func (ss stringArray) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range ss { arr.AppendString(ss[i]) } return nil } type times []time.Time func (ts times) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range ts { arr.AppendTime(ts[i]) } return nil } type uints []uint func (nums uints) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendUint(nums[i]) } return nil } type uint64s []uint64 func (nums uint64s) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendUint64(nums[i]) } return nil } type uint32s []uint32 func (nums uint32s) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendUint32(nums[i]) } return nil } type uint16s []uint16 func (nums uint16s) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendUint16(nums[i]) } return nil } type uint8s []uint8 func (nums uint8s) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendUint8(nums[i]) } return nil } type uintptrs []uintptr func (nums uintptrs) MarshalLogArray(arr zapcore.ArrayEncoder) error { for i := range nums { arr.AppendUintptr(nums[i]) } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/field.go
vendor/go.uber.org/zap/field.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zap import ( "fmt" "math" "time" "go.uber.org/zap/internal/stacktrace" "go.uber.org/zap/zapcore" ) // Field is an alias for Field. Aliasing this type dramatically // improves the navigability of this package's API documentation. type Field = zapcore.Field var ( _minTimeInt64 = time.Unix(0, math.MinInt64) _maxTimeInt64 = time.Unix(0, math.MaxInt64) ) // Skip constructs a no-op field, which is often useful when handling invalid // inputs in other Field constructors. func Skip() Field { return Field{Type: zapcore.SkipType} } // nilField returns a field which will marshal explicitly as nil. See motivation // in https://github.com/uber-go/zap/issues/753 . If we ever make breaking // changes and add zapcore.NilType and zapcore.ObjectEncoder.AddNil, the // implementation here should be changed to reflect that. func nilField(key string) Field { return Reflect(key, nil) } // Binary constructs a field that carries an opaque binary blob. // // Binary data is serialized in an encoding-appropriate format. For example, // zap's JSON encoder base64-encodes binary blobs. To log UTF-8 encoded text, // use ByteString. func Binary(key string, val []byte) Field { return Field{Key: key, Type: zapcore.BinaryType, Interface: val} } // Bool constructs a field that carries a bool. func Bool(key string, val bool) Field { var ival int64 if val { ival = 1 } return Field{Key: key, Type: zapcore.BoolType, Integer: ival} } // Boolp constructs a field that carries a *bool. The returned Field will safely // and explicitly represent `nil` when appropriate. func Boolp(key string, val *bool) Field { if val == nil { return nilField(key) } return Bool(key, *val) } // ByteString constructs a field that carries UTF-8 encoded text as a []byte. // To log opaque binary blobs (which aren't necessarily valid UTF-8), use // Binary. func ByteString(key string, val []byte) Field { return Field{Key: key, Type: zapcore.ByteStringType, Interface: val} } // Complex128 constructs a field that carries a complex number. Unlike most // numeric fields, this costs an allocation (to convert the complex128 to // interface{}). func Complex128(key string, val complex128) Field { return Field{Key: key, Type: zapcore.Complex128Type, Interface: val} } // Complex128p constructs a field that carries a *complex128. The returned Field will safely // and explicitly represent `nil` when appropriate. func Complex128p(key string, val *complex128) Field { if val == nil { return nilField(key) } return Complex128(key, *val) } // Complex64 constructs a field that carries a complex number. Unlike most // numeric fields, this costs an allocation (to convert the complex64 to // interface{}). func Complex64(key string, val complex64) Field { return Field{Key: key, Type: zapcore.Complex64Type, Interface: val} } // Complex64p constructs a field that carries a *complex64. The returned Field will safely // and explicitly represent `nil` when appropriate. func Complex64p(key string, val *complex64) Field { if val == nil { return nilField(key) } return Complex64(key, *val) } // Float64 constructs a field that carries a float64. The way the // floating-point value is represented is encoder-dependent, so marshaling is // necessarily lazy. func Float64(key string, val float64) Field { return Field{Key: key, Type: zapcore.Float64Type, Integer: int64(math.Float64bits(val))} } // Float64p constructs a field that carries a *float64. The returned Field will safely // and explicitly represent `nil` when appropriate. func Float64p(key string, val *float64) Field { if val == nil { return nilField(key) } return Float64(key, *val) } // Float32 constructs a field that carries a float32. The way the // floating-point value is represented is encoder-dependent, so marshaling is // necessarily lazy. func Float32(key string, val float32) Field { return Field{Key: key, Type: zapcore.Float32Type, Integer: int64(math.Float32bits(val))} } // Float32p constructs a field that carries a *float32. The returned Field will safely // and explicitly represent `nil` when appropriate. func Float32p(key string, val *float32) Field { if val == nil { return nilField(key) } return Float32(key, *val) } // Int constructs a field with the given key and value. func Int(key string, val int) Field { return Int64(key, int64(val)) } // Intp constructs a field that carries a *int. The returned Field will safely // and explicitly represent `nil` when appropriate. func Intp(key string, val *int) Field { if val == nil { return nilField(key) } return Int(key, *val) } // Int64 constructs a field with the given key and value. func Int64(key string, val int64) Field { return Field{Key: key, Type: zapcore.Int64Type, Integer: val} } // Int64p constructs a field that carries a *int64. The returned Field will safely // and explicitly represent `nil` when appropriate. func Int64p(key string, val *int64) Field { if val == nil { return nilField(key) } return Int64(key, *val) } // Int32 constructs a field with the given key and value. func Int32(key string, val int32) Field { return Field{Key: key, Type: zapcore.Int32Type, Integer: int64(val)} } // Int32p constructs a field that carries a *int32. The returned Field will safely // and explicitly represent `nil` when appropriate. func Int32p(key string, val *int32) Field { if val == nil { return nilField(key) } return Int32(key, *val) } // Int16 constructs a field with the given key and value. func Int16(key string, val int16) Field { return Field{Key: key, Type: zapcore.Int16Type, Integer: int64(val)} } // Int16p constructs a field that carries a *int16. The returned Field will safely // and explicitly represent `nil` when appropriate. func Int16p(key string, val *int16) Field { if val == nil { return nilField(key) } return Int16(key, *val) } // Int8 constructs a field with the given key and value. func Int8(key string, val int8) Field { return Field{Key: key, Type: zapcore.Int8Type, Integer: int64(val)} } // Int8p constructs a field that carries a *int8. The returned Field will safely // and explicitly represent `nil` when appropriate. func Int8p(key string, val *int8) Field { if val == nil { return nilField(key) } return Int8(key, *val) } // String constructs a field with the given key and value. func String(key string, val string) Field { return Field{Key: key, Type: zapcore.StringType, String: val} } // Stringp constructs a field that carries a *string. The returned Field will safely // and explicitly represent `nil` when appropriate. func Stringp(key string, val *string) Field { if val == nil { return nilField(key) } return String(key, *val) } // Uint constructs a field with the given key and value. func Uint(key string, val uint) Field { return Uint64(key, uint64(val)) } // Uintp constructs a field that carries a *uint. The returned Field will safely // and explicitly represent `nil` when appropriate. func Uintp(key string, val *uint) Field { if val == nil { return nilField(key) } return Uint(key, *val) } // Uint64 constructs a field with the given key and value. func Uint64(key string, val uint64) Field { return Field{Key: key, Type: zapcore.Uint64Type, Integer: int64(val)} } // Uint64p constructs a field that carries a *uint64. The returned Field will safely // and explicitly represent `nil` when appropriate. func Uint64p(key string, val *uint64) Field { if val == nil { return nilField(key) } return Uint64(key, *val) } // Uint32 constructs a field with the given key and value. func Uint32(key string, val uint32) Field { return Field{Key: key, Type: zapcore.Uint32Type, Integer: int64(val)} } // Uint32p constructs a field that carries a *uint32. The returned Field will safely // and explicitly represent `nil` when appropriate. func Uint32p(key string, val *uint32) Field { if val == nil { return nilField(key) } return Uint32(key, *val) } // Uint16 constructs a field with the given key and value. func Uint16(key string, val uint16) Field { return Field{Key: key, Type: zapcore.Uint16Type, Integer: int64(val)} } // Uint16p constructs a field that carries a *uint16. The returned Field will safely // and explicitly represent `nil` when appropriate. func Uint16p(key string, val *uint16) Field { if val == nil { return nilField(key) } return Uint16(key, *val) } // Uint8 constructs a field with the given key and value. func Uint8(key string, val uint8) Field { return Field{Key: key, Type: zapcore.Uint8Type, Integer: int64(val)} } // Uint8p constructs a field that carries a *uint8. The returned Field will safely // and explicitly represent `nil` when appropriate. func Uint8p(key string, val *uint8) Field { if val == nil { return nilField(key) } return Uint8(key, *val) } // Uintptr constructs a field with the given key and value. func Uintptr(key string, val uintptr) Field { return Field{Key: key, Type: zapcore.UintptrType, Integer: int64(val)} } // Uintptrp constructs a field that carries a *uintptr. The returned Field will safely // and explicitly represent `nil` when appropriate. func Uintptrp(key string, val *uintptr) Field { if val == nil { return nilField(key) } return Uintptr(key, *val) } // Reflect constructs a field with the given key and an arbitrary object. It uses // an encoding-appropriate, reflection-based function to lazily serialize nearly // any object into the logging context, but it's relatively slow and // allocation-heavy. Outside tests, Any is always a better choice. // // If encoding fails (e.g., trying to serialize a map[int]string to JSON), Reflect // includes the error message in the final log output. func Reflect(key string, val interface{}) Field { return Field{Key: key, Type: zapcore.ReflectType, Interface: val} } // Namespace creates a named, isolated scope within the logger's context. All // subsequent fields will be added to the new namespace. // // This helps prevent key collisions when injecting loggers into sub-components // or third-party libraries. func Namespace(key string) Field { return Field{Key: key, Type: zapcore.NamespaceType} } // Stringer constructs a field with the given key and the output of the value's // String method. The Stringer's String method is called lazily. func Stringer(key string, val fmt.Stringer) Field { return Field{Key: key, Type: zapcore.StringerType, Interface: val} } // Time constructs a Field with the given key and value. The encoder // controls how the time is serialized. func Time(key string, val time.Time) Field { if val.Before(_minTimeInt64) || val.After(_maxTimeInt64) { return Field{Key: key, Type: zapcore.TimeFullType, Interface: val} } return Field{Key: key, Type: zapcore.TimeType, Integer: val.UnixNano(), Interface: val.Location()} } // Timep constructs a field that carries a *time.Time. The returned Field will safely // and explicitly represent `nil` when appropriate. func Timep(key string, val *time.Time) Field { if val == nil { return nilField(key) } return Time(key, *val) } // Stack constructs a field that stores a stacktrace of the current goroutine // under provided key. Keep in mind that taking a stacktrace is eager and // expensive (relatively speaking); this function both makes an allocation and // takes about two microseconds. func Stack(key string) Field { return StackSkip(key, 1) // skip Stack } // StackSkip constructs a field similarly to Stack, but also skips the given // number of frames from the top of the stacktrace. func StackSkip(key string, skip int) Field { // Returning the stacktrace as a string costs an allocation, but saves us // from expanding the zapcore.Field union struct to include a byte slice. Since // taking a stacktrace is already so expensive (~10us), the extra allocation // is okay. return String(key, stacktrace.Take(skip+1)) // skip StackSkip } // Duration constructs a field with the given key and value. The encoder // controls how the duration is serialized. func Duration(key string, val time.Duration) Field { return Field{Key: key, Type: zapcore.DurationType, Integer: int64(val)} } // Durationp constructs a field that carries a *time.Duration. The returned Field will safely // and explicitly represent `nil` when appropriate. func Durationp(key string, val *time.Duration) Field { if val == nil { return nilField(key) } return Duration(key, *val) } // Object constructs a field with the given key and ObjectMarshaler. It // provides a flexible, but still type-safe and efficient, way to add map- or // struct-like user-defined types to the logging context. The struct's // MarshalLogObject method is called lazily. func Object(key string, val zapcore.ObjectMarshaler) Field { return Field{Key: key, Type: zapcore.ObjectMarshalerType, Interface: val} } // Inline constructs a Field that is similar to Object, but it // will add the elements of the provided ObjectMarshaler to the // current namespace. func Inline(val zapcore.ObjectMarshaler) Field { return zapcore.Field{ Type: zapcore.InlineMarshalerType, Interface: val, } } // Dict constructs a field containing the provided key-value pairs. // It acts similar to [Object], but with the fields specified as arguments. func Dict(key string, val ...Field) Field { return dictField(key, val) } // We need a function with the signature (string, T) for zap.Any. func dictField(key string, val []Field) Field { return Object(key, dictObject(val)) } type dictObject []Field func (d dictObject) MarshalLogObject(enc zapcore.ObjectEncoder) error { for _, f := range d { f.AddTo(enc) } return nil } // We discovered an issue where zap.Any can cause a performance degradation // when used in new goroutines. // // This happens because the compiler assigns 4.8kb (one zap.Field per arm of // switch statement) of stack space for zap.Any when it takes the form: // // switch v := v.(type) { // case string: // return String(key, v) // case int: // return Int(key, v) // // ... // default: // return Reflect(key, v) // } // // To avoid this, we use the type switch to assign a value to a single local variable // and then call a function on it. // The local variable is just a function reference so it doesn't allocate // when converted to an interface{}. // // A fair bit of experimentation went into this. // See also: // // - https://github.com/uber-go/zap/pull/1301 // - https://github.com/uber-go/zap/pull/1303 // - https://github.com/uber-go/zap/pull/1304 // - https://github.com/uber-go/zap/pull/1305 // - https://github.com/uber-go/zap/pull/1308 // // See https://github.com/golang/go/issues/62077 for upstream issue. type anyFieldC[T any] func(string, T) Field func (f anyFieldC[T]) Any(key string, val any) Field { v, _ := val.(T) // val is guaranteed to be a T, except when it's nil. return f(key, v) } // Any takes a key and an arbitrary value and chooses the best way to represent // them as a field, falling back to a reflection-based approach only if // necessary. // // Since byte/uint8 and rune/int32 are aliases, Any can't differentiate between // them. To minimize surprises, []byte values are treated as binary blobs, byte // values are treated as uint8, and runes are always treated as integers. func Any(key string, value interface{}) Field { var c interface{ Any(string, any) Field } switch value.(type) { case zapcore.ObjectMarshaler: c = anyFieldC[zapcore.ObjectMarshaler](Object) case zapcore.ArrayMarshaler: c = anyFieldC[zapcore.ArrayMarshaler](Array) case []Field: c = anyFieldC[[]Field](dictField) case bool: c = anyFieldC[bool](Bool) case *bool: c = anyFieldC[*bool](Boolp) case []bool: c = anyFieldC[[]bool](Bools) case complex128: c = anyFieldC[complex128](Complex128) case *complex128: c = anyFieldC[*complex128](Complex128p) case []complex128: c = anyFieldC[[]complex128](Complex128s) case complex64: c = anyFieldC[complex64](Complex64) case *complex64: c = anyFieldC[*complex64](Complex64p) case []complex64: c = anyFieldC[[]complex64](Complex64s) case float64: c = anyFieldC[float64](Float64) case *float64: c = anyFieldC[*float64](Float64p) case []float64: c = anyFieldC[[]float64](Float64s) case float32: c = anyFieldC[float32](Float32) case *float32: c = anyFieldC[*float32](Float32p) case []float32: c = anyFieldC[[]float32](Float32s) case int: c = anyFieldC[int](Int) case *int: c = anyFieldC[*int](Intp) case []int: c = anyFieldC[[]int](Ints) case int64: c = anyFieldC[int64](Int64) case *int64: c = anyFieldC[*int64](Int64p) case []int64: c = anyFieldC[[]int64](Int64s) case int32: c = anyFieldC[int32](Int32) case *int32: c = anyFieldC[*int32](Int32p) case []int32: c = anyFieldC[[]int32](Int32s) case int16: c = anyFieldC[int16](Int16) case *int16: c = anyFieldC[*int16](Int16p) case []int16: c = anyFieldC[[]int16](Int16s) case int8: c = anyFieldC[int8](Int8) case *int8: c = anyFieldC[*int8](Int8p) case []int8: c = anyFieldC[[]int8](Int8s) case string: c = anyFieldC[string](String) case *string: c = anyFieldC[*string](Stringp) case []string: c = anyFieldC[[]string](Strings) case uint: c = anyFieldC[uint](Uint) case *uint: c = anyFieldC[*uint](Uintp) case []uint: c = anyFieldC[[]uint](Uints) case uint64: c = anyFieldC[uint64](Uint64) case *uint64: c = anyFieldC[*uint64](Uint64p) case []uint64: c = anyFieldC[[]uint64](Uint64s) case uint32: c = anyFieldC[uint32](Uint32) case *uint32: c = anyFieldC[*uint32](Uint32p) case []uint32: c = anyFieldC[[]uint32](Uint32s) case uint16: c = anyFieldC[uint16](Uint16) case *uint16: c = anyFieldC[*uint16](Uint16p) case []uint16: c = anyFieldC[[]uint16](Uint16s) case uint8: c = anyFieldC[uint8](Uint8) case *uint8: c = anyFieldC[*uint8](Uint8p) case []byte: c = anyFieldC[[]byte](Binary) case uintptr: c = anyFieldC[uintptr](Uintptr) case *uintptr: c = anyFieldC[*uintptr](Uintptrp) case []uintptr: c = anyFieldC[[]uintptr](Uintptrs) case time.Time: c = anyFieldC[time.Time](Time) case *time.Time: c = anyFieldC[*time.Time](Timep) case []time.Time: c = anyFieldC[[]time.Time](Times) case time.Duration: c = anyFieldC[time.Duration](Duration) case *time.Duration: c = anyFieldC[*time.Duration](Durationp) case []time.Duration: c = anyFieldC[[]time.Duration](Durations) case error: c = anyFieldC[error](NamedError) case []error: c = anyFieldC[[]error](Errors) case fmt.Stringer: c = anyFieldC[fmt.Stringer](Stringer) default: c = anyFieldC[any](Reflect) } return c.Any(key, value) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/options.go
vendor/go.uber.org/zap/options.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zap import ( "fmt" "go.uber.org/zap/zapcore" ) // An Option configures a Logger. type Option interface { apply(*Logger) } // optionFunc wraps a func so it satisfies the Option interface. type optionFunc func(*Logger) func (f optionFunc) apply(log *Logger) { f(log) } // WrapCore wraps or replaces the Logger's underlying zapcore.Core. func WrapCore(f func(zapcore.Core) zapcore.Core) Option { return optionFunc(func(log *Logger) { log.core = f(log.core) }) } // Hooks registers functions which will be called each time the Logger writes // out an Entry. Repeated use of Hooks is additive. // // Hooks are useful for simple side effects, like capturing metrics for the // number of emitted logs. More complex side effects, including anything that // requires access to the Entry's structured fields, should be implemented as // a zapcore.Core instead. See zapcore.RegisterHooks for details. func Hooks(hooks ...func(zapcore.Entry) error) Option { return optionFunc(func(log *Logger) { log.core = zapcore.RegisterHooks(log.core, hooks...) }) } // Fields adds fields to the Logger. func Fields(fs ...Field) Option { return optionFunc(func(log *Logger) { log.core = log.core.With(fs) }) } // ErrorOutput sets the destination for errors generated by the Logger. Note // that this option only affects internal errors; for sample code that sends // error-level logs to a different location from info- and debug-level logs, // see the package-level AdvancedConfiguration example. // // The supplied WriteSyncer must be safe for concurrent use. The Open and // zapcore.Lock functions are the simplest ways to protect files with a mutex. func ErrorOutput(w zapcore.WriteSyncer) Option { return optionFunc(func(log *Logger) { log.errorOutput = w }) } // Development puts the logger in development mode, which makes DPanic-level // logs panic instead of simply logging an error. func Development() Option { return optionFunc(func(log *Logger) { log.development = true }) } // AddCaller configures the Logger to annotate each message with the filename, // line number, and function name of zap's caller. See also WithCaller. func AddCaller() Option { return WithCaller(true) } // WithCaller configures the Logger to annotate each message with the filename, // line number, and function name of zap's caller, or not, depending on the // value of enabled. This is a generalized form of AddCaller. func WithCaller(enabled bool) Option { return optionFunc(func(log *Logger) { log.addCaller = enabled }) } // AddCallerSkip increases the number of callers skipped by caller annotation // (as enabled by the AddCaller option). When building wrappers around the // Logger and SugaredLogger, supplying this Option prevents zap from always // reporting the wrapper code as the caller. func AddCallerSkip(skip int) Option { return optionFunc(func(log *Logger) { log.callerSkip += skip }) } // AddStacktrace configures the Logger to record a stack trace for all messages at // or above a given level. func AddStacktrace(lvl zapcore.LevelEnabler) Option { return optionFunc(func(log *Logger) { log.addStack = lvl }) } // IncreaseLevel increase the level of the logger. It has no effect if // the passed in level tries to decrease the level of the logger. func IncreaseLevel(lvl zapcore.LevelEnabler) Option { return optionFunc(func(log *Logger) { core, err := zapcore.NewIncreaseLevelCore(log.core, lvl) if err != nil { fmt.Fprintf(log.errorOutput, "failed to IncreaseLevel: %v\n", err) } else { log.core = core } }) } // WithPanicHook sets a CheckWriteHook to run on Panic/DPanic logs. // Zap will call this hook after writing a log statement with a Panic/DPanic level. // // For example, the following builds a logger that will exit the current // goroutine after writing a Panic/DPanic log message, but it will not start a panic. // // zap.New(core, zap.WithPanicHook(zapcore.WriteThenGoexit)) // // This is useful for testing Panic/DPanic log output. func WithPanicHook(hook zapcore.CheckWriteHook) Option { return optionFunc(func(log *Logger) { log.onPanic = hook }) } // OnFatal sets the action to take on fatal logs. // // Deprecated: Use [WithFatalHook] instead. func OnFatal(action zapcore.CheckWriteAction) Option { return WithFatalHook(action) } // WithFatalHook sets a CheckWriteHook to run on fatal logs. // Zap will call this hook after writing a log statement with a Fatal level. // // For example, the following builds a logger that will exit the current // goroutine after writing a fatal log message, but it will not exit the // program. // // zap.New(core, zap.WithFatalHook(zapcore.WriteThenGoexit)) // // It is important that the provided CheckWriteHook stops the control flow at // the current statement to meet expectations of callers of the logger. // We recommend calling os.Exit or runtime.Goexit inside custom hooks at // minimum. func WithFatalHook(hook zapcore.CheckWriteHook) Option { return optionFunc(func(log *Logger) { log.onFatal = hook }) } // WithClock specifies the clock used by the logger to determine the current // time for logged entries. Defaults to the system clock with time.Now. func WithClock(clock zapcore.Clock) Option { return optionFunc(func(log *Logger) { log.clock = clock }) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/sugar.go
vendor/go.uber.org/zap/sugar.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zap import ( "fmt" "go.uber.org/zap/zapcore" "go.uber.org/multierr" ) const ( _oddNumberErrMsg = "Ignored key without a value." _nonStringKeyErrMsg = "Ignored key-value pairs with non-string keys." _multipleErrMsg = "Multiple errors without a key." ) // A SugaredLogger wraps the base Logger functionality in a slower, but less // verbose, API. Any Logger can be converted to a SugaredLogger with its Sugar // method. // // Unlike the Logger, the SugaredLogger doesn't insist on structured logging. // For each log level, it exposes four methods: // // - methods named after the log level for log.Print-style logging // - methods ending in "w" for loosely-typed structured logging // - methods ending in "f" for log.Printf-style logging // - methods ending in "ln" for log.Println-style logging // // For example, the methods for InfoLevel are: // // Info(...any) Print-style logging // Infow(...any) Structured logging (read as "info with") // Infof(string, ...any) Printf-style logging // Infoln(...any) Println-style logging type SugaredLogger struct { base *Logger } // Desugar unwraps a SugaredLogger, exposing the original Logger. Desugaring // is quite inexpensive, so it's reasonable for a single application to use // both Loggers and SugaredLoggers, converting between them on the boundaries // of performance-sensitive code. func (s *SugaredLogger) Desugar() *Logger { base := s.base.clone() base.callerSkip -= 2 return base } // Named adds a sub-scope to the logger's name. See Logger.Named for details. func (s *SugaredLogger) Named(name string) *SugaredLogger { return &SugaredLogger{base: s.base.Named(name)} } // WithOptions clones the current SugaredLogger, applies the supplied Options, // and returns the result. It's safe to use concurrently. func (s *SugaredLogger) WithOptions(opts ...Option) *SugaredLogger { base := s.base.clone() for _, opt := range opts { opt.apply(base) } return &SugaredLogger{base: base} } // With adds a variadic number of fields to the logging context. It accepts a // mix of strongly-typed Field objects and loosely-typed key-value pairs. When // processing pairs, the first element of the pair is used as the field key // and the second as the field value. // // For example, // // sugaredLogger.With( // "hello", "world", // "failure", errors.New("oh no"), // Stack(), // "count", 42, // "user", User{Name: "alice"}, // ) // // is the equivalent of // // unsugared.With( // String("hello", "world"), // String("failure", "oh no"), // Stack(), // Int("count", 42), // Object("user", User{Name: "alice"}), // ) // // Note that the keys in key-value pairs should be strings. In development, // passing a non-string key panics. In production, the logger is more // forgiving: a separate error is logged, but the key-value pair is skipped // and execution continues. Passing an orphaned key triggers similar behavior: // panics in development and errors in production. func (s *SugaredLogger) With(args ...interface{}) *SugaredLogger { return &SugaredLogger{base: s.base.With(s.sweetenFields(args)...)} } // WithLazy adds a variadic number of fields to the logging context lazily. // The fields are evaluated only if the logger is further chained with [With] // or is written to with any of the log level methods. // Until that occurs, the logger may retain references to objects inside the fields, // and logging will reflect the state of an object at the time of logging, // not the time of WithLazy(). // // Similar to [With], fields added to the child don't affect the parent, // and vice versa. Also, the keys in key-value pairs should be strings. In development, // passing a non-string key panics, while in production it logs an error and skips the pair. // Passing an orphaned key has the same behavior. func (s *SugaredLogger) WithLazy(args ...interface{}) *SugaredLogger { return &SugaredLogger{base: s.base.WithLazy(s.sweetenFields(args)...)} } // Level reports the minimum enabled level for this logger. // // For NopLoggers, this is [zapcore.InvalidLevel]. func (s *SugaredLogger) Level() zapcore.Level { return zapcore.LevelOf(s.base.core) } // Log logs the provided arguments at provided level. // Spaces are added between arguments when neither is a string. func (s *SugaredLogger) Log(lvl zapcore.Level, args ...interface{}) { s.log(lvl, "", args, nil) } // Debug logs the provided arguments at [DebugLevel]. // Spaces are added between arguments when neither is a string. func (s *SugaredLogger) Debug(args ...interface{}) { s.log(DebugLevel, "", args, nil) } // Info logs the provided arguments at [InfoLevel]. // Spaces are added between arguments when neither is a string. func (s *SugaredLogger) Info(args ...interface{}) { s.log(InfoLevel, "", args, nil) } // Warn logs the provided arguments at [WarnLevel]. // Spaces are added between arguments when neither is a string. func (s *SugaredLogger) Warn(args ...interface{}) { s.log(WarnLevel, "", args, nil) } // Error logs the provided arguments at [ErrorLevel]. // Spaces are added between arguments when neither is a string. func (s *SugaredLogger) Error(args ...interface{}) { s.log(ErrorLevel, "", args, nil) } // DPanic logs the provided arguments at [DPanicLevel]. // In development, the logger then panics. (See [DPanicLevel] for details.) // Spaces are added between arguments when neither is a string. func (s *SugaredLogger) DPanic(args ...interface{}) { s.log(DPanicLevel, "", args, nil) } // Panic constructs a message with the provided arguments and panics. // Spaces are added between arguments when neither is a string. func (s *SugaredLogger) Panic(args ...interface{}) { s.log(PanicLevel, "", args, nil) } // Fatal constructs a message with the provided arguments and calls os.Exit. // Spaces are added between arguments when neither is a string. func (s *SugaredLogger) Fatal(args ...interface{}) { s.log(FatalLevel, "", args, nil) } // Logf formats the message according to the format specifier // and logs it at provided level. func (s *SugaredLogger) Logf(lvl zapcore.Level, template string, args ...interface{}) { s.log(lvl, template, args, nil) } // Debugf formats the message according to the format specifier // and logs it at [DebugLevel]. func (s *SugaredLogger) Debugf(template string, args ...interface{}) { s.log(DebugLevel, template, args, nil) } // Infof formats the message according to the format specifier // and logs it at [InfoLevel]. func (s *SugaredLogger) Infof(template string, args ...interface{}) { s.log(InfoLevel, template, args, nil) } // Warnf formats the message according to the format specifier // and logs it at [WarnLevel]. func (s *SugaredLogger) Warnf(template string, args ...interface{}) { s.log(WarnLevel, template, args, nil) } // Errorf formats the message according to the format specifier // and logs it at [ErrorLevel]. func (s *SugaredLogger) Errorf(template string, args ...interface{}) { s.log(ErrorLevel, template, args, nil) } // DPanicf formats the message according to the format specifier // and logs it at [DPanicLevel]. // In development, the logger then panics. (See [DPanicLevel] for details.) func (s *SugaredLogger) DPanicf(template string, args ...interface{}) { s.log(DPanicLevel, template, args, nil) } // Panicf formats the message according to the format specifier // and panics. func (s *SugaredLogger) Panicf(template string, args ...interface{}) { s.log(PanicLevel, template, args, nil) } // Fatalf formats the message according to the format specifier // and calls os.Exit. func (s *SugaredLogger) Fatalf(template string, args ...interface{}) { s.log(FatalLevel, template, args, nil) } // Logw logs a message with some additional context. The variadic key-value // pairs are treated as they are in With. func (s *SugaredLogger) Logw(lvl zapcore.Level, msg string, keysAndValues ...interface{}) { s.log(lvl, msg, nil, keysAndValues) } // Debugw logs a message with some additional context. The variadic key-value // pairs are treated as they are in With. // // When debug-level logging is disabled, this is much faster than // // s.With(keysAndValues).Debug(msg) func (s *SugaredLogger) Debugw(msg string, keysAndValues ...interface{}) { s.log(DebugLevel, msg, nil, keysAndValues) } // Infow logs a message with some additional context. The variadic key-value // pairs are treated as they are in With. func (s *SugaredLogger) Infow(msg string, keysAndValues ...interface{}) { s.log(InfoLevel, msg, nil, keysAndValues) } // Warnw logs a message with some additional context. The variadic key-value // pairs are treated as they are in With. func (s *SugaredLogger) Warnw(msg string, keysAndValues ...interface{}) { s.log(WarnLevel, msg, nil, keysAndValues) } // Errorw logs a message with some additional context. The variadic key-value // pairs are treated as they are in With. func (s *SugaredLogger) Errorw(msg string, keysAndValues ...interface{}) { s.log(ErrorLevel, msg, nil, keysAndValues) } // DPanicw logs a message with some additional context. In development, the // logger then panics. (See DPanicLevel for details.) The variadic key-value // pairs are treated as they are in With. func (s *SugaredLogger) DPanicw(msg string, keysAndValues ...interface{}) { s.log(DPanicLevel, msg, nil, keysAndValues) } // Panicw logs a message with some additional context, then panics. The // variadic key-value pairs are treated as they are in With. func (s *SugaredLogger) Panicw(msg string, keysAndValues ...interface{}) { s.log(PanicLevel, msg, nil, keysAndValues) } // Fatalw logs a message with some additional context, then calls os.Exit. The // variadic key-value pairs are treated as they are in With. func (s *SugaredLogger) Fatalw(msg string, keysAndValues ...interface{}) { s.log(FatalLevel, msg, nil, keysAndValues) } // Logln logs a message at provided level. // Spaces are always added between arguments. func (s *SugaredLogger) Logln(lvl zapcore.Level, args ...interface{}) { s.logln(lvl, args, nil) } // Debugln logs a message at [DebugLevel]. // Spaces are always added between arguments. func (s *SugaredLogger) Debugln(args ...interface{}) { s.logln(DebugLevel, args, nil) } // Infoln logs a message at [InfoLevel]. // Spaces are always added between arguments. func (s *SugaredLogger) Infoln(args ...interface{}) { s.logln(InfoLevel, args, nil) } // Warnln logs a message at [WarnLevel]. // Spaces are always added between arguments. func (s *SugaredLogger) Warnln(args ...interface{}) { s.logln(WarnLevel, args, nil) } // Errorln logs a message at [ErrorLevel]. // Spaces are always added between arguments. func (s *SugaredLogger) Errorln(args ...interface{}) { s.logln(ErrorLevel, args, nil) } // DPanicln logs a message at [DPanicLevel]. // In development, the logger then panics. (See [DPanicLevel] for details.) // Spaces are always added between arguments. func (s *SugaredLogger) DPanicln(args ...interface{}) { s.logln(DPanicLevel, args, nil) } // Panicln logs a message at [PanicLevel] and panics. // Spaces are always added between arguments. func (s *SugaredLogger) Panicln(args ...interface{}) { s.logln(PanicLevel, args, nil) } // Fatalln logs a message at [FatalLevel] and calls os.Exit. // Spaces are always added between arguments. func (s *SugaredLogger) Fatalln(args ...interface{}) { s.logln(FatalLevel, args, nil) } // Sync flushes any buffered log entries. func (s *SugaredLogger) Sync() error { return s.base.Sync() } // log message with Sprint, Sprintf, or neither. func (s *SugaredLogger) log(lvl zapcore.Level, template string, fmtArgs []interface{}, context []interface{}) { // If logging at this level is completely disabled, skip the overhead of // string formatting. if lvl < DPanicLevel && !s.base.Core().Enabled(lvl) { return } msg := getMessage(template, fmtArgs) if ce := s.base.Check(lvl, msg); ce != nil { ce.Write(s.sweetenFields(context)...) } } // logln message with Sprintln func (s *SugaredLogger) logln(lvl zapcore.Level, fmtArgs []interface{}, context []interface{}) { if lvl < DPanicLevel && !s.base.Core().Enabled(lvl) { return } msg := getMessageln(fmtArgs) if ce := s.base.Check(lvl, msg); ce != nil { ce.Write(s.sweetenFields(context)...) } } // getMessage format with Sprint, Sprintf, or neither. func getMessage(template string, fmtArgs []interface{}) string { if len(fmtArgs) == 0 { return template } if template != "" { return fmt.Sprintf(template, fmtArgs...) } if len(fmtArgs) == 1 { if str, ok := fmtArgs[0].(string); ok { return str } } return fmt.Sprint(fmtArgs...) } // getMessageln format with Sprintln. func getMessageln(fmtArgs []interface{}) string { msg := fmt.Sprintln(fmtArgs...) return msg[:len(msg)-1] } func (s *SugaredLogger) sweetenFields(args []interface{}) []Field { if len(args) == 0 { return nil } var ( // Allocate enough space for the worst case; if users pass only structured // fields, we shouldn't penalize them with extra allocations. fields = make([]Field, 0, len(args)) invalid invalidPairs seenError bool ) for i := 0; i < len(args); { // This is a strongly-typed field. Consume it and move on. if f, ok := args[i].(Field); ok { fields = append(fields, f) i++ continue } // If it is an error, consume it and move on. if err, ok := args[i].(error); ok { if !seenError { seenError = true fields = append(fields, Error(err)) } else { s.base.Error(_multipleErrMsg, Error(err)) } i++ continue } // Make sure this element isn't a dangling key. if i == len(args)-1 { s.base.Error(_oddNumberErrMsg, Any("ignored", args[i])) break } // Consume this value and the next, treating them as a key-value pair. If the // key isn't a string, add this pair to the slice of invalid pairs. key, val := args[i], args[i+1] if keyStr, ok := key.(string); !ok { // Subsequent errors are likely, so allocate once up front. if cap(invalid) == 0 { invalid = make(invalidPairs, 0, len(args)/2) } invalid = append(invalid, invalidPair{i, key, val}) } else { fields = append(fields, Any(keyStr, val)) } i += 2 } // If we encountered any invalid key-value pairs, log an error. if len(invalid) > 0 { s.base.Error(_nonStringKeyErrMsg, Array("invalid", invalid)) } return fields } type invalidPair struct { position int key, value interface{} } func (p invalidPair) MarshalLogObject(enc zapcore.ObjectEncoder) error { enc.AddInt64("position", int64(p.position)) Any("key", p.key).AddTo(enc) Any("value", p.value).AddTo(enc) return nil } type invalidPairs []invalidPair func (ps invalidPairs) MarshalLogArray(enc zapcore.ArrayEncoder) error { var err error for i := range ps { err = multierr.Append(err, enc.AppendObject(ps[i])) } return err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/doc.go
vendor/go.uber.org/zap/doc.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. // Package zap provides fast, structured, leveled logging. // // For applications that log in the hot path, reflection-based serialization // and string formatting are prohibitively expensive - they're CPU-intensive // and make many small allocations. Put differently, using json.Marshal and // fmt.Fprintf to log tons of interface{} makes your application slow. // // Zap takes a different approach. It includes a reflection-free, // zero-allocation JSON encoder, and the base Logger strives to avoid // serialization overhead and allocations wherever possible. By building the // high-level SugaredLogger on that foundation, zap lets users choose when // they need to count every allocation and when they'd prefer a more familiar, // loosely typed API. // // # Choosing a Logger // // In contexts where performance is nice, but not critical, use the // SugaredLogger. It's 4-10x faster than other structured logging packages and // supports both structured and printf-style logging. Like log15 and go-kit, // the SugaredLogger's structured logging APIs are loosely typed and accept a // variadic number of key-value pairs. (For more advanced use cases, they also // accept strongly typed fields - see the SugaredLogger.With documentation for // details.) // // sugar := zap.NewExample().Sugar() // defer sugar.Sync() // sugar.Infow("failed to fetch URL", // "url", "http://example.com", // "attempt", 3, // "backoff", time.Second, // ) // sugar.Infof("failed to fetch URL: %s", "http://example.com") // // By default, loggers are unbuffered. However, since zap's low-level APIs // allow buffering, calling Sync before letting your process exit is a good // habit. // // In the rare contexts where every microsecond and every allocation matter, // use the Logger. It's even faster than the SugaredLogger and allocates far // less, but it only supports strongly-typed, structured logging. // // logger := zap.NewExample() // defer logger.Sync() // logger.Info("failed to fetch URL", // zap.String("url", "http://example.com"), // zap.Int("attempt", 3), // zap.Duration("backoff", time.Second), // ) // // Choosing between the Logger and SugaredLogger doesn't need to be an // application-wide decision: converting between the two is simple and // inexpensive. // // logger := zap.NewExample() // defer logger.Sync() // sugar := logger.Sugar() // plain := sugar.Desugar() // // # Configuring Zap // // The simplest way to build a Logger is to use zap's opinionated presets: // NewExample, NewProduction, and NewDevelopment. These presets build a logger // with a single function call: // // logger, err := zap.NewProduction() // if err != nil { // log.Fatalf("can't initialize zap logger: %v", err) // } // defer logger.Sync() // // Presets are fine for small projects, but larger projects and organizations // naturally require a bit more customization. For most users, zap's Config // struct strikes the right balance between flexibility and convenience. See // the package-level BasicConfiguration example for sample code. // // More unusual configurations (splitting output between files, sending logs // to a message queue, etc.) are possible, but require direct use of // go.uber.org/zap/zapcore. See the package-level AdvancedConfiguration // example for sample code. // // # Extending Zap // // The zap package itself is a relatively thin wrapper around the interfaces // in go.uber.org/zap/zapcore. Extending zap to support a new encoding (e.g., // BSON), a new log sink (e.g., Kafka), or something more exotic (perhaps an // exception aggregation service, like Sentry or Rollbar) typically requires // implementing the zapcore.Encoder, zapcore.WriteSyncer, or zapcore.Core // interfaces. See the zapcore documentation for details. // // Similarly, package authors can use the high-performance Encoder and Core // implementations in the zapcore package to build their own loggers. // // # Frequently Asked Questions // // An FAQ covering everything from installation errors to design decisions is // available at https://github.com/uber-go/zap/blob/master/FAQ.md. package zap // import "go.uber.org/zap"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/logger.go
vendor/go.uber.org/zap/logger.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zap import ( "fmt" "io" "os" "strings" "go.uber.org/zap/internal/bufferpool" "go.uber.org/zap/internal/stacktrace" "go.uber.org/zap/zapcore" ) // A Logger provides fast, leveled, structured logging. All methods are safe // for concurrent use. // // The Logger is designed for contexts in which every microsecond and every // allocation matters, so its API intentionally favors performance and type // safety over brevity. For most applications, the SugaredLogger strikes a // better balance between performance and ergonomics. type Logger struct { core zapcore.Core development bool addCaller bool onPanic zapcore.CheckWriteHook // default is WriteThenPanic onFatal zapcore.CheckWriteHook // default is WriteThenFatal name string errorOutput zapcore.WriteSyncer addStack zapcore.LevelEnabler callerSkip int clock zapcore.Clock } // New constructs a new Logger from the provided zapcore.Core and Options. If // the passed zapcore.Core is nil, it falls back to using a no-op // implementation. // // This is the most flexible way to construct a Logger, but also the most // verbose. For typical use cases, the highly-opinionated presets // (NewProduction, NewDevelopment, and NewExample) or the Config struct are // more convenient. // // For sample code, see the package-level AdvancedConfiguration example. func New(core zapcore.Core, options ...Option) *Logger { if core == nil { return NewNop() } log := &Logger{ core: core, errorOutput: zapcore.Lock(os.Stderr), addStack: zapcore.FatalLevel + 1, clock: zapcore.DefaultClock, } return log.WithOptions(options...) } // NewNop returns a no-op Logger. It never writes out logs or internal errors, // and it never runs user-defined hooks. // // Using WithOptions to replace the Core or error output of a no-op Logger can // re-enable logging. func NewNop() *Logger { return &Logger{ core: zapcore.NewNopCore(), errorOutput: zapcore.AddSync(io.Discard), addStack: zapcore.FatalLevel + 1, clock: zapcore.DefaultClock, } } // NewProduction builds a sensible production Logger that writes InfoLevel and // above logs to standard error as JSON. // // It's a shortcut for NewProductionConfig().Build(...Option). func NewProduction(options ...Option) (*Logger, error) { return NewProductionConfig().Build(options...) } // NewDevelopment builds a development Logger that writes DebugLevel and above // logs to standard error in a human-friendly format. // // It's a shortcut for NewDevelopmentConfig().Build(...Option). func NewDevelopment(options ...Option) (*Logger, error) { return NewDevelopmentConfig().Build(options...) } // Must is a helper that wraps a call to a function returning (*Logger, error) // and panics if the error is non-nil. It is intended for use in variable // initialization such as: // // var logger = zap.Must(zap.NewProduction()) func Must(logger *Logger, err error) *Logger { if err != nil { panic(err) } return logger } // NewExample builds a Logger that's designed for use in zap's testable // examples. It writes DebugLevel and above logs to standard out as JSON, but // omits the timestamp and calling function to keep example output // short and deterministic. func NewExample(options ...Option) *Logger { encoderCfg := zapcore.EncoderConfig{ MessageKey: "msg", LevelKey: "level", NameKey: "logger", EncodeLevel: zapcore.LowercaseLevelEncoder, EncodeTime: zapcore.ISO8601TimeEncoder, EncodeDuration: zapcore.StringDurationEncoder, } core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderCfg), os.Stdout, DebugLevel) return New(core).WithOptions(options...) } // Sugar wraps the Logger to provide a more ergonomic, but slightly slower, // API. Sugaring a Logger is quite inexpensive, so it's reasonable for a // single application to use both Loggers and SugaredLoggers, converting // between them on the boundaries of performance-sensitive code. func (log *Logger) Sugar() *SugaredLogger { core := log.clone() core.callerSkip += 2 return &SugaredLogger{core} } // Named adds a new path segment to the logger's name. Segments are joined by // periods. By default, Loggers are unnamed. func (log *Logger) Named(s string) *Logger { if s == "" { return log } l := log.clone() if log.name == "" { l.name = s } else { l.name = strings.Join([]string{l.name, s}, ".") } return l } // WithOptions clones the current Logger, applies the supplied Options, and // returns the resulting Logger. It's safe to use concurrently. func (log *Logger) WithOptions(opts ...Option) *Logger { c := log.clone() for _, opt := range opts { opt.apply(c) } return c } // With creates a child logger and adds structured context to it. Fields added // to the child don't affect the parent, and vice versa. Any fields that // require evaluation (such as Objects) are evaluated upon invocation of With. func (log *Logger) With(fields ...Field) *Logger { if len(fields) == 0 { return log } l := log.clone() l.core = l.core.With(fields) return l } // WithLazy creates a child logger and adds structured context to it lazily. // // The fields are evaluated only if the logger is further chained with [With] // or is written to with any of the log level methods. // Until that occurs, the logger may retain references to objects inside the fields, // and logging will reflect the state of an object at the time of logging, // not the time of WithLazy(). // // WithLazy provides a worthwhile performance optimization for contextual loggers // when the likelihood of using the child logger is low, // such as error paths and rarely taken branches. // // Similar to [With], fields added to the child don't affect the parent, and vice versa. func (log *Logger) WithLazy(fields ...Field) *Logger { if len(fields) == 0 { return log } return log.WithOptions(WrapCore(func(core zapcore.Core) zapcore.Core { return zapcore.NewLazyWith(core, fields) })) } // Level reports the minimum enabled level for this logger. // // For NopLoggers, this is [zapcore.InvalidLevel]. func (log *Logger) Level() zapcore.Level { return zapcore.LevelOf(log.core) } // Check returns a CheckedEntry if logging a message at the specified level // is enabled. It's a completely optional optimization; in high-performance // applications, Check can help avoid allocating a slice to hold fields. func (log *Logger) Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { return log.check(lvl, msg) } // Log logs a message at the specified level. The message includes any fields // passed at the log site, as well as any fields accumulated on the logger. // Any Fields that require evaluation (such as Objects) are evaluated upon // invocation of Log. func (log *Logger) Log(lvl zapcore.Level, msg string, fields ...Field) { if ce := log.check(lvl, msg); ce != nil { ce.Write(fields...) } } // Debug logs a message at DebugLevel. The message includes any fields passed // at the log site, as well as any fields accumulated on the logger. func (log *Logger) Debug(msg string, fields ...Field) { if ce := log.check(DebugLevel, msg); ce != nil { ce.Write(fields...) } } // Info logs a message at InfoLevel. The message includes any fields passed // at the log site, as well as any fields accumulated on the logger. func (log *Logger) Info(msg string, fields ...Field) { if ce := log.check(InfoLevel, msg); ce != nil { ce.Write(fields...) } } // Warn logs a message at WarnLevel. The message includes any fields passed // at the log site, as well as any fields accumulated on the logger. func (log *Logger) Warn(msg string, fields ...Field) { if ce := log.check(WarnLevel, msg); ce != nil { ce.Write(fields...) } } // Error logs a message at ErrorLevel. The message includes any fields passed // at the log site, as well as any fields accumulated on the logger. func (log *Logger) Error(msg string, fields ...Field) { if ce := log.check(ErrorLevel, msg); ce != nil { ce.Write(fields...) } } // DPanic logs a message at DPanicLevel. The message includes any fields // passed at the log site, as well as any fields accumulated on the logger. // // If the logger is in development mode, it then panics (DPanic means // "development panic"). This is useful for catching errors that are // recoverable, but shouldn't ever happen. func (log *Logger) DPanic(msg string, fields ...Field) { if ce := log.check(DPanicLevel, msg); ce != nil { ce.Write(fields...) } } // Panic logs a message at PanicLevel. The message includes any fields passed // at the log site, as well as any fields accumulated on the logger. // // The logger then panics, even if logging at PanicLevel is disabled. func (log *Logger) Panic(msg string, fields ...Field) { if ce := log.check(PanicLevel, msg); ce != nil { ce.Write(fields...) } } // Fatal logs a message at FatalLevel. The message includes any fields passed // at the log site, as well as any fields accumulated on the logger. // // The logger then calls os.Exit(1), even if logging at FatalLevel is // disabled. func (log *Logger) Fatal(msg string, fields ...Field) { if ce := log.check(FatalLevel, msg); ce != nil { ce.Write(fields...) } } // Sync calls the underlying Core's Sync method, flushing any buffered log // entries. Applications should take care to call Sync before exiting. func (log *Logger) Sync() error { return log.core.Sync() } // Core returns the Logger's underlying zapcore.Core. func (log *Logger) Core() zapcore.Core { return log.core } // Name returns the Logger's underlying name, // or an empty string if the logger is unnamed. func (log *Logger) Name() string { return log.name } func (log *Logger) clone() *Logger { clone := *log return &clone } func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { // Logger.check must always be called directly by a method in the // Logger interface (e.g., Check, Info, Fatal). // This skips Logger.check and the Info/Fatal/Check/etc. method that // called it. const callerSkipOffset = 2 // Check the level first to reduce the cost of disabled log calls. // Since Panic and higher may exit, we skip the optimization for those levels. if lvl < zapcore.DPanicLevel && !log.core.Enabled(lvl) { return nil } // Create basic checked entry thru the core; this will be non-nil if the // log message will actually be written somewhere. ent := zapcore.Entry{ LoggerName: log.name, Time: log.clock.Now(), Level: lvl, Message: msg, } ce := log.core.Check(ent, nil) willWrite := ce != nil // Set up any required terminal behavior. switch ent.Level { case zapcore.PanicLevel: ce = ce.After(ent, terminalHookOverride(zapcore.WriteThenPanic, log.onPanic)) case zapcore.FatalLevel: ce = ce.After(ent, terminalHookOverride(zapcore.WriteThenFatal, log.onFatal)) case zapcore.DPanicLevel: if log.development { ce = ce.After(ent, terminalHookOverride(zapcore.WriteThenPanic, log.onPanic)) } } // Only do further annotation if we're going to write this message; checked // entries that exist only for terminal behavior don't benefit from // annotation. if !willWrite { return ce } // Thread the error output through to the CheckedEntry. ce.ErrorOutput = log.errorOutput addStack := log.addStack.Enabled(ce.Level) if !log.addCaller && !addStack { return ce } // Adding the caller or stack trace requires capturing the callers of // this function. We'll share information between these two. stackDepth := stacktrace.First if addStack { stackDepth = stacktrace.Full } stack := stacktrace.Capture(log.callerSkip+callerSkipOffset, stackDepth) defer stack.Free() if stack.Count() == 0 { if log.addCaller { fmt.Fprintf(log.errorOutput, "%v Logger.check error: failed to get caller\n", ent.Time.UTC()) _ = log.errorOutput.Sync() } return ce } frame, more := stack.Next() if log.addCaller { ce.Caller = zapcore.EntryCaller{ Defined: frame.PC != 0, PC: frame.PC, File: frame.File, Line: frame.Line, Function: frame.Function, } } if addStack { buffer := bufferpool.Get() defer buffer.Free() stackfmt := stacktrace.NewFormatter(buffer) // We've already extracted the first frame, so format that // separately and defer to stackfmt for the rest. stackfmt.FormatFrame(frame) if more { stackfmt.FormatStack(stack) } ce.Stack = buffer.String() } return ce } func terminalHookOverride(defaultHook, override zapcore.CheckWriteHook) zapcore.CheckWriteHook { // A nil or WriteThenNoop hook will lead to continued execution after // a Panic or Fatal log entry, which is unexpected. For example, // // f, err := os.Open(..) // if err != nil { // log.Fatal("cannot open", zap.Error(err)) // } // fmt.Println(f.Name()) // // The f.Name() will panic if we continue execution after the log.Fatal. if override == nil || override == zapcore.WriteThenNoop { return defaultHook } return override }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/http_handler.go
vendor/go.uber.org/zap/http_handler.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zap import ( "encoding/json" "errors" "fmt" "io" "net/http" "go.uber.org/zap/zapcore" ) // ServeHTTP is a simple JSON endpoint that can report on or change the current // logging level. // // # GET // // The GET request returns a JSON description of the current logging level like: // // {"level":"info"} // // # PUT // // The PUT request changes the logging level. It is perfectly safe to change the // logging level while a program is running. Two content types are supported: // // Content-Type: application/x-www-form-urlencoded // // With this content type, the level can be provided through the request body or // a query parameter. The log level is URL encoded like: // // level=debug // // The request body takes precedence over the query parameter, if both are // specified. // // This content type is the default for a curl PUT request. Following are two // example curl requests that both set the logging level to debug. // // curl -X PUT localhost:8080/log/level?level=debug // curl -X PUT localhost:8080/log/level -d level=debug // // For any other content type, the payload is expected to be JSON encoded and // look like: // // {"level":"info"} // // An example curl request could look like this: // // curl -X PUT localhost:8080/log/level -H "Content-Type: application/json" -d '{"level":"debug"}' func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request) { if err := lvl.serveHTTP(w, r); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "internal error: %v", err) } } func (lvl AtomicLevel) serveHTTP(w http.ResponseWriter, r *http.Request) error { type errorResponse struct { Error string `json:"error"` } type payload struct { Level zapcore.Level `json:"level"` } enc := json.NewEncoder(w) switch r.Method { case http.MethodGet: return enc.Encode(payload{Level: lvl.Level()}) case http.MethodPut: requestedLvl, err := decodePutRequest(r.Header.Get("Content-Type"), r) if err != nil { w.WriteHeader(http.StatusBadRequest) return enc.Encode(errorResponse{Error: err.Error()}) } lvl.SetLevel(requestedLvl) return enc.Encode(payload{Level: lvl.Level()}) default: w.WriteHeader(http.StatusMethodNotAllowed) return enc.Encode(errorResponse{ Error: "Only GET and PUT are supported.", }) } } // Decodes incoming PUT requests and returns the requested logging level. func decodePutRequest(contentType string, r *http.Request) (zapcore.Level, error) { if contentType == "application/x-www-form-urlencoded" { return decodePutURL(r) } return decodePutJSON(r.Body) } func decodePutURL(r *http.Request) (zapcore.Level, error) { lvl := r.FormValue("level") if lvl == "" { return 0, errors.New("must specify logging level") } var l zapcore.Level if err := l.UnmarshalText([]byte(lvl)); err != nil { return 0, err } return l, nil } func decodePutJSON(body io.Reader) (zapcore.Level, error) { var pld struct { Level *zapcore.Level `json:"level"` } if err := json.NewDecoder(body).Decode(&pld); err != nil { return 0, fmt.Errorf("malformed request body: %v", err) } if pld.Level == nil { return 0, errors.New("must specify logging level") } return *pld.Level, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/global.go
vendor/go.uber.org/zap/global.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zap import ( "bytes" "fmt" "log" "os" "sync" "go.uber.org/zap/zapcore" ) const ( _stdLogDefaultDepth = 1 _loggerWriterDepth = 2 _programmerErrorTemplate = "You've found a bug in zap! Please file a bug at " + "https://github.com/uber-go/zap/issues/new and reference this error: %v" ) var ( _globalMu sync.RWMutex _globalL = NewNop() _globalS = _globalL.Sugar() ) // L returns the global Logger, which can be reconfigured with ReplaceGlobals. // It's safe for concurrent use. func L() *Logger { _globalMu.RLock() l := _globalL _globalMu.RUnlock() return l } // S returns the global SugaredLogger, which can be reconfigured with // ReplaceGlobals. It's safe for concurrent use. func S() *SugaredLogger { _globalMu.RLock() s := _globalS _globalMu.RUnlock() return s } // ReplaceGlobals replaces the global Logger and SugaredLogger, and returns a // function to restore the original values. It's safe for concurrent use. func ReplaceGlobals(logger *Logger) func() { _globalMu.Lock() prev := _globalL _globalL = logger _globalS = logger.Sugar() _globalMu.Unlock() return func() { ReplaceGlobals(prev) } } // NewStdLog returns a *log.Logger which writes to the supplied zap Logger at // InfoLevel. To redirect the standard library's package-global logging // functions, use RedirectStdLog instead. func NewStdLog(l *Logger) *log.Logger { logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth)) f := logger.Info return log.New(&loggerWriter{f}, "" /* prefix */, 0 /* flags */) } // NewStdLogAt returns *log.Logger which writes to supplied zap logger at // required level. func NewStdLogAt(l *Logger, level zapcore.Level) (*log.Logger, error) { logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth)) logFunc, err := levelToFunc(logger, level) if err != nil { return nil, err } return log.New(&loggerWriter{logFunc}, "" /* prefix */, 0 /* flags */), nil } // RedirectStdLog redirects output from the standard library's package-global // logger to the supplied logger at InfoLevel. Since zap already handles caller // annotations, timestamps, etc., it automatically disables the standard // library's annotations and prefixing. // // It returns a function to restore the original prefix and flags and reset the // standard library's output to os.Stderr. func RedirectStdLog(l *Logger) func() { f, err := redirectStdLogAt(l, InfoLevel) if err != nil { // Can't get here, since passing InfoLevel to redirectStdLogAt always // works. panic(fmt.Sprintf(_programmerErrorTemplate, err)) } return f } // RedirectStdLogAt redirects output from the standard library's package-global // logger to the supplied logger at the specified level. Since zap already // handles caller annotations, timestamps, etc., it automatically disables the // standard library's annotations and prefixing. // // It returns a function to restore the original prefix and flags and reset the // standard library's output to os.Stderr. func RedirectStdLogAt(l *Logger, level zapcore.Level) (func(), error) { return redirectStdLogAt(l, level) } func redirectStdLogAt(l *Logger, level zapcore.Level) (func(), error) { flags := log.Flags() prefix := log.Prefix() log.SetFlags(0) log.SetPrefix("") logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth)) logFunc, err := levelToFunc(logger, level) if err != nil { return nil, err } log.SetOutput(&loggerWriter{logFunc}) return func() { log.SetFlags(flags) log.SetPrefix(prefix) log.SetOutput(os.Stderr) }, nil } func levelToFunc(logger *Logger, lvl zapcore.Level) (func(string, ...Field), error) { switch lvl { case DebugLevel: return logger.Debug, nil case InfoLevel: return logger.Info, nil case WarnLevel: return logger.Warn, nil case ErrorLevel: return logger.Error, nil case DPanicLevel: return logger.DPanic, nil case PanicLevel: return logger.Panic, nil case FatalLevel: return logger.Fatal, nil } return nil, fmt.Errorf("unrecognized level: %q", lvl) } type loggerWriter struct { logFunc func(msg string, fields ...Field) } func (l *loggerWriter) Write(p []byte) (int, error) { p = bytes.TrimSpace(p) l.logFunc(string(p)) return len(p), nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/encoder.go
vendor/go.uber.org/zap/encoder.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zap import ( "errors" "fmt" "sync" "go.uber.org/zap/zapcore" ) var ( errNoEncoderNameSpecified = errors.New("no encoder name specified") _encoderNameToConstructor = map[string]func(zapcore.EncoderConfig) (zapcore.Encoder, error){ "console": func(encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) { return zapcore.NewConsoleEncoder(encoderConfig), nil }, "json": func(encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) { return zapcore.NewJSONEncoder(encoderConfig), nil }, } _encoderMutex sync.RWMutex ) // RegisterEncoder registers an encoder constructor, which the Config struct // can then reference. By default, the "json" and "console" encoders are // registered. // // Attempting to register an encoder whose name is already taken returns an // error. func RegisterEncoder(name string, constructor func(zapcore.EncoderConfig) (zapcore.Encoder, error)) error { _encoderMutex.Lock() defer _encoderMutex.Unlock() if name == "" { return errNoEncoderNameSpecified } if _, ok := _encoderNameToConstructor[name]; ok { return fmt.Errorf("encoder already registered for name %q", name) } _encoderNameToConstructor[name] = constructor return nil } func newEncoder(name string, encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) { if encoderConfig.TimeKey != "" && encoderConfig.EncodeTime == nil { return nil, errors.New("missing EncodeTime in EncoderConfig") } _encoderMutex.RLock() defer _encoderMutex.RUnlock() if name == "" { return nil, errNoEncoderNameSpecified } constructor, ok := _encoderNameToConstructor[name] if !ok { return nil, fmt.Errorf("no encoder registered for name %q", name) } return constructor(encoderConfig) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/hook.go
vendor/go.uber.org/zap/zapcore/hook.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore import "go.uber.org/multierr" type hooked struct { Core funcs []func(Entry) error } var ( _ Core = (*hooked)(nil) _ leveledEnabler = (*hooked)(nil) ) // RegisterHooks wraps a Core and runs a collection of user-defined callback // hooks each time a message is logged. Execution of the callbacks is blocking. // // This offers users an easy way to register simple callbacks (e.g., metrics // collection) without implementing the full Core interface. func RegisterHooks(core Core, hooks ...func(Entry) error) Core { funcs := append([]func(Entry) error{}, hooks...) return &hooked{ Core: core, funcs: funcs, } } func (h *hooked) Level() Level { return LevelOf(h.Core) } func (h *hooked) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { // Let the wrapped Core decide whether to log this message or not. This // also gives the downstream a chance to register itself directly with the // CheckedEntry. if downstream := h.Core.Check(ent, ce); downstream != nil { return downstream.AddCore(ent, h) } return ce } func (h *hooked) With(fields []Field) Core { return &hooked{ Core: h.Core.With(fields), funcs: h.funcs, } } func (h *hooked) Write(ent Entry, _ []Field) error { // Since our downstream had a chance to register itself directly with the // CheckedMessage, we don't need to call it here. var err error for i := range h.funcs { err = multierr.Append(err, h.funcs[i](ent)) } return err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/sampler.go
vendor/go.uber.org/zap/zapcore/sampler.go
// Copyright (c) 2016-2022 Uber Technologies, Inc. // // 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. package zapcore import ( "sync/atomic" "time" ) const ( _numLevels = _maxLevel - _minLevel + 1 _countersPerLevel = 4096 ) type counter struct { resetAt atomic.Int64 counter atomic.Uint64 } type counters [_numLevels][_countersPerLevel]counter func newCounters() *counters { return &counters{} } func (cs *counters) get(lvl Level, key string) *counter { i := lvl - _minLevel j := fnv32a(key) % _countersPerLevel return &cs[i][j] } // fnv32a, adapted from "hash/fnv", but without a []byte(string) alloc func fnv32a(s string) uint32 { const ( offset32 = 2166136261 prime32 = 16777619 ) hash := uint32(offset32) for i := 0; i < len(s); i++ { hash ^= uint32(s[i]) hash *= prime32 } return hash } func (c *counter) IncCheckReset(t time.Time, tick time.Duration) uint64 { tn := t.UnixNano() resetAfter := c.resetAt.Load() if resetAfter > tn { return c.counter.Add(1) } c.counter.Store(1) newResetAfter := tn + tick.Nanoseconds() if !c.resetAt.CompareAndSwap(resetAfter, newResetAfter) { // We raced with another goroutine trying to reset, and it also reset // the counter to 1, so we need to reincrement the counter. return c.counter.Add(1) } return 1 } // SamplingDecision is a decision represented as a bit field made by sampler. // More decisions may be added in the future. type SamplingDecision uint32 const ( // LogDropped indicates that the Sampler dropped a log entry. LogDropped SamplingDecision = 1 << iota // LogSampled indicates that the Sampler sampled a log entry. LogSampled ) // optionFunc wraps a func so it satisfies the SamplerOption interface. type optionFunc func(*sampler) func (f optionFunc) apply(s *sampler) { f(s) } // SamplerOption configures a Sampler. type SamplerOption interface { apply(*sampler) } // nopSamplingHook is the default hook used by sampler. func nopSamplingHook(Entry, SamplingDecision) {} // SamplerHook registers a function which will be called when Sampler makes a // decision. // // This hook may be used to get visibility into the performance of the sampler. // For example, use it to track metrics of dropped versus sampled logs. // // var dropped atomic.Int64 // zapcore.SamplerHook(func(ent zapcore.Entry, dec zapcore.SamplingDecision) { // if dec&zapcore.LogDropped > 0 { // dropped.Inc() // } // }) func SamplerHook(hook func(entry Entry, dec SamplingDecision)) SamplerOption { return optionFunc(func(s *sampler) { s.hook = hook }) } // NewSamplerWithOptions creates a Core that samples incoming entries, which // caps the CPU and I/O load of logging while attempting to preserve a // representative subset of your logs. // // Zap samples by logging the first N entries with a given level and message // each tick. If more Entries with the same level and message are seen during // the same interval, every Mth message is logged and the rest are dropped. // // For example, // // core = NewSamplerWithOptions(core, time.Second, 10, 5) // // This will log the first 10 log entries with the same level and message // in a one second interval as-is. Following that, it will allow through // every 5th log entry with the same level and message in that interval. // // If thereafter is zero, the Core will drop all log entries after the first N // in that interval. // // Sampler can be configured to report sampling decisions with the SamplerHook // option. // // Keep in mind that Zap's sampling implementation is optimized for speed over // absolute precision; under load, each tick may be slightly over- or // under-sampled. func NewSamplerWithOptions(core Core, tick time.Duration, first, thereafter int, opts ...SamplerOption) Core { s := &sampler{ Core: core, tick: tick, counts: newCounters(), first: uint64(first), thereafter: uint64(thereafter), hook: nopSamplingHook, } for _, opt := range opts { opt.apply(s) } return s } type sampler struct { Core counts *counters tick time.Duration first, thereafter uint64 hook func(Entry, SamplingDecision) } var ( _ Core = (*sampler)(nil) _ leveledEnabler = (*sampler)(nil) ) // NewSampler creates a Core that samples incoming entries, which // caps the CPU and I/O load of logging while attempting to preserve a // representative subset of your logs. // // Zap samples by logging the first N entries with a given level and message // each tick. If more Entries with the same level and message are seen during // the same interval, every Mth message is logged and the rest are dropped. // // Keep in mind that zap's sampling implementation is optimized for speed over // absolute precision; under load, each tick may be slightly over- or // under-sampled. // // Deprecated: use NewSamplerWithOptions. func NewSampler(core Core, tick time.Duration, first, thereafter int) Core { return NewSamplerWithOptions(core, tick, first, thereafter) } func (s *sampler) Level() Level { return LevelOf(s.Core) } func (s *sampler) With(fields []Field) Core { return &sampler{ Core: s.Core.With(fields), tick: s.tick, counts: s.counts, first: s.first, thereafter: s.thereafter, hook: s.hook, } } func (s *sampler) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { if !s.Enabled(ent.Level) { return ce } if ent.Level >= _minLevel && ent.Level <= _maxLevel { counter := s.counts.get(ent.Level, ent.Message) n := counter.IncCheckReset(ent.Time, s.tick) if n > s.first && (s.thereafter == 0 || (n-s.first)%s.thereafter != 0) { s.hook(ent, LogDropped) return ce } s.hook(ent, LogSampled) } return s.Core.Check(ent, ce) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/tee.go
vendor/go.uber.org/zap/zapcore/tee.go
// Copyright (c) 2016-2022 Uber Technologies, Inc. // // 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. package zapcore import "go.uber.org/multierr" type multiCore []Core var ( _ leveledEnabler = multiCore(nil) _ Core = multiCore(nil) ) // NewTee creates a Core that duplicates log entries into two or more // underlying Cores. // // Calling it with a single Core returns the input unchanged, and calling // it with no input returns a no-op Core. func NewTee(cores ...Core) Core { switch len(cores) { case 0: return NewNopCore() case 1: return cores[0] default: return multiCore(cores) } } func (mc multiCore) With(fields []Field) Core { clone := make(multiCore, len(mc)) for i := range mc { clone[i] = mc[i].With(fields) } return clone } func (mc multiCore) Level() Level { minLvl := _maxLevel // mc is never empty for i := range mc { if lvl := LevelOf(mc[i]); lvl < minLvl { minLvl = lvl } } return minLvl } func (mc multiCore) Enabled(lvl Level) bool { for i := range mc { if mc[i].Enabled(lvl) { return true } } return false } func (mc multiCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { for i := range mc { ce = mc[i].Check(ent, ce) } return ce } func (mc multiCore) Write(ent Entry, fields []Field) error { var err error for i := range mc { err = multierr.Append(err, mc[i].Write(ent, fields)) } return err } func (mc multiCore) Sync() error { var err error for i := range mc { err = multierr.Append(err, mc[i].Sync()) } return err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/entry.go
vendor/go.uber.org/zap/zapcore/entry.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore import ( "fmt" "runtime" "strings" "time" "go.uber.org/multierr" "go.uber.org/zap/internal/bufferpool" "go.uber.org/zap/internal/exit" "go.uber.org/zap/internal/pool" ) var _cePool = pool.New(func() *CheckedEntry { // Pre-allocate some space for cores. return &CheckedEntry{ cores: make([]Core, 4), } }) func getCheckedEntry() *CheckedEntry { ce := _cePool.Get() ce.reset() return ce } func putCheckedEntry(ce *CheckedEntry) { if ce == nil { return } _cePool.Put(ce) } // NewEntryCaller makes an EntryCaller from the return signature of // runtime.Caller. func NewEntryCaller(pc uintptr, file string, line int, ok bool) EntryCaller { if !ok { return EntryCaller{} } return EntryCaller{ PC: pc, File: file, Line: line, Defined: true, } } // EntryCaller represents the caller of a logging function. type EntryCaller struct { Defined bool PC uintptr File string Line int Function string } // String returns the full path and line number of the caller. func (ec EntryCaller) String() string { return ec.FullPath() } // FullPath returns a /full/path/to/package/file:line description of the // caller. func (ec EntryCaller) FullPath() string { if !ec.Defined { return "undefined" } buf := bufferpool.Get() buf.AppendString(ec.File) buf.AppendByte(':') buf.AppendInt(int64(ec.Line)) caller := buf.String() buf.Free() return caller } // TrimmedPath returns a package/file:line description of the caller, // preserving only the leaf directory name and file name. func (ec EntryCaller) TrimmedPath() string { if !ec.Defined { return "undefined" } // nb. To make sure we trim the path correctly on Windows too, we // counter-intuitively need to use '/' and *not* os.PathSeparator here, // because the path given originates from Go stdlib, specifically // runtime.Caller() which (as of Mar/17) returns forward slashes even on // Windows. // // See https://github.com/golang/go/issues/3335 // and https://github.com/golang/go/issues/18151 // // for discussion on the issue on Go side. // // Find the last separator. // idx := strings.LastIndexByte(ec.File, '/') if idx == -1 { return ec.FullPath() } // Find the penultimate separator. idx = strings.LastIndexByte(ec.File[:idx], '/') if idx == -1 { return ec.FullPath() } buf := bufferpool.Get() // Keep everything after the penultimate separator. buf.AppendString(ec.File[idx+1:]) buf.AppendByte(':') buf.AppendInt(int64(ec.Line)) caller := buf.String() buf.Free() return caller } // An Entry represents a complete log message. The entry's structured context // is already serialized, but the log level, time, message, and call site // information are available for inspection and modification. Any fields left // empty will be omitted when encoding. // // Entries are pooled, so any functions that accept them MUST be careful not to // retain references to them. type Entry struct { Level Level Time time.Time LoggerName string Message string Caller EntryCaller Stack string } // CheckWriteHook is a custom action that may be executed after an entry is // written. // // Register one on a CheckedEntry with the After method. // // if ce := logger.Check(...); ce != nil { // ce = ce.After(hook) // ce.Write(...) // } // // You can configure the hook for Fatal log statements at the logger level with // the zap.WithFatalHook option. type CheckWriteHook interface { // OnWrite is invoked with the CheckedEntry that was written and a list // of fields added with that entry. // // The list of fields DOES NOT include fields that were already added // to the logger with the With method. OnWrite(*CheckedEntry, []Field) } // CheckWriteAction indicates what action to take after a log entry is // processed. Actions are ordered in increasing severity. type CheckWriteAction uint8 const ( // WriteThenNoop indicates that nothing special needs to be done. It's the // default behavior. WriteThenNoop CheckWriteAction = iota // WriteThenGoexit runs runtime.Goexit after Write. WriteThenGoexit // WriteThenPanic causes a panic after Write. WriteThenPanic // WriteThenFatal causes an os.Exit(1) after Write. WriteThenFatal ) // OnWrite implements the OnWrite method to keep CheckWriteAction compatible // with the new CheckWriteHook interface which deprecates CheckWriteAction. func (a CheckWriteAction) OnWrite(ce *CheckedEntry, _ []Field) { switch a { case WriteThenGoexit: runtime.Goexit() case WriteThenPanic: panic(ce.Message) case WriteThenFatal: exit.With(1) } } var _ CheckWriteHook = CheckWriteAction(0) // CheckedEntry is an Entry together with a collection of Cores that have // already agreed to log it. // // CheckedEntry references should be created by calling AddCore or After on a // nil *CheckedEntry. References are returned to a pool after Write, and MUST // NOT be retained after calling their Write method. type CheckedEntry struct { Entry ErrorOutput WriteSyncer dirty bool // best-effort detection of pool misuse after CheckWriteHook cores []Core } func (ce *CheckedEntry) reset() { ce.Entry = Entry{} ce.ErrorOutput = nil ce.dirty = false ce.after = nil for i := range ce.cores { // don't keep references to cores ce.cores[i] = nil } ce.cores = ce.cores[:0] } // Write writes the entry to the stored Cores, returns any errors, and returns // the CheckedEntry reference to a pool for immediate re-use. Finally, it // executes any required CheckWriteAction. func (ce *CheckedEntry) Write(fields ...Field) { if ce == nil { return } if ce.dirty { if ce.ErrorOutput != nil { // Make a best effort to detect unsafe re-use of this CheckedEntry. // If the entry is dirty, log an internal error; because the // CheckedEntry is being used after it was returned to the pool, // the message may be an amalgamation from multiple call sites. fmt.Fprintf(ce.ErrorOutput, "%v Unsafe CheckedEntry re-use near Entry %+v.\n", ce.Time, ce.Entry) _ = ce.ErrorOutput.Sync() // ignore error } return } ce.dirty = true var err error for i := range ce.cores { err = multierr.Append(err, ce.cores[i].Write(ce.Entry, fields)) } if err != nil && ce.ErrorOutput != nil { fmt.Fprintf(ce.ErrorOutput, "%v write error: %v\n", ce.Time, err) _ = ce.ErrorOutput.Sync() // ignore error } hook := ce.after if hook != nil { hook.OnWrite(ce, fields) } putCheckedEntry(ce) } // AddCore adds a Core that has agreed to log this CheckedEntry. It's intended to be // used by Core.Check implementations, and is safe to call on nil CheckedEntry // references. func (ce *CheckedEntry) AddCore(ent Entry, core Core) *CheckedEntry { if ce == nil { ce = getCheckedEntry() ce.Entry = ent } ce.cores = append(ce.cores, core) return ce } // Should sets this CheckedEntry's CheckWriteAction, which controls whether a // Core will panic or fatal after writing this log entry. Like AddCore, it's // safe to call on nil CheckedEntry references. // // Deprecated: Use [CheckedEntry.After] instead. func (ce *CheckedEntry) Should(ent Entry, should CheckWriteAction) *CheckedEntry { return ce.After(ent, should) } // After sets this CheckEntry's CheckWriteHook, which will be called after this // log entry has been written. It's safe to call this on nil CheckedEntry // references. func (ce *CheckedEntry) After(ent Entry, hook CheckWriteHook) *CheckedEntry { if ce == nil { ce = getCheckedEntry() ce.Entry = ent } ce.after = hook return ce }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/level.go
vendor/go.uber.org/zap/zapcore/level.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore import ( "bytes" "errors" "fmt" ) var errUnmarshalNilLevel = errors.New("can't unmarshal a nil *Level") // A Level is a logging priority. Higher levels are more important. type Level int8 const ( // DebugLevel logs are typically voluminous, and are usually disabled in // production. DebugLevel Level = iota - 1 // InfoLevel is the default logging priority. InfoLevel // WarnLevel logs are more important than Info, but don't need individual // human review. WarnLevel // ErrorLevel logs are high-priority. If an application is running smoothly, // it shouldn't generate any error-level logs. ErrorLevel // DPanicLevel logs are particularly important errors. In development the // logger panics after writing the message. DPanicLevel // PanicLevel logs a message, then panics. PanicLevel // FatalLevel logs a message, then calls os.Exit(1). FatalLevel _minLevel = DebugLevel _maxLevel = FatalLevel // InvalidLevel is an invalid value for Level. // // Core implementations may panic if they see messages of this level. InvalidLevel = _maxLevel + 1 ) // ParseLevel parses a level based on the lower-case or all-caps ASCII // representation of the log level. If the provided ASCII representation is // invalid an error is returned. // // This is particularly useful when dealing with text input to configure log // levels. func ParseLevel(text string) (Level, error) { var level Level err := level.UnmarshalText([]byte(text)) return level, err } type leveledEnabler interface { LevelEnabler Level() Level } // LevelOf reports the minimum enabled log level for the given LevelEnabler // from Zap's supported log levels, or [InvalidLevel] if none of them are // enabled. // // A LevelEnabler may implement a 'Level() Level' method to override the // behavior of this function. // // func (c *core) Level() Level { // return c.currentLevel // } // // It is recommended that [Core] implementations that wrap other cores use // LevelOf to retrieve the level of the wrapped core. For example, // // func (c *coreWrapper) Level() Level { // return zapcore.LevelOf(c.wrappedCore) // } func LevelOf(enab LevelEnabler) Level { if lvler, ok := enab.(leveledEnabler); ok { return lvler.Level() } for lvl := _minLevel; lvl <= _maxLevel; lvl++ { if enab.Enabled(lvl) { return lvl } } return InvalidLevel } // String returns a lower-case ASCII representation of the log level. func (l Level) String() string { switch l { case DebugLevel: return "debug" case InfoLevel: return "info" case WarnLevel: return "warn" case ErrorLevel: return "error" case DPanicLevel: return "dpanic" case PanicLevel: return "panic" case FatalLevel: return "fatal" default: return fmt.Sprintf("Level(%d)", l) } } // CapitalString returns an all-caps ASCII representation of the log level. func (l Level) CapitalString() string { // Printing levels in all-caps is common enough that we should export this // functionality. switch l { case DebugLevel: return "DEBUG" case InfoLevel: return "INFO" case WarnLevel: return "WARN" case ErrorLevel: return "ERROR" case DPanicLevel: return "DPANIC" case PanicLevel: return "PANIC" case FatalLevel: return "FATAL" default: return fmt.Sprintf("LEVEL(%d)", l) } } // MarshalText marshals the Level to text. Note that the text representation // drops the -Level suffix (see example). func (l Level) MarshalText() ([]byte, error) { return []byte(l.String()), nil } // UnmarshalText unmarshals text to a level. Like MarshalText, UnmarshalText // expects the text representation of a Level to drop the -Level suffix (see // example). // // In particular, this makes it easy to configure logging levels using YAML, // TOML, or JSON files. func (l *Level) UnmarshalText(text []byte) error { if l == nil { return errUnmarshalNilLevel } if !l.unmarshalText(text) && !l.unmarshalText(bytes.ToLower(text)) { return fmt.Errorf("unrecognized level: %q", text) } return nil } func (l *Level) unmarshalText(text []byte) bool { switch string(text) { case "debug", "DEBUG": *l = DebugLevel case "info", "INFO", "": // make the zero value useful *l = InfoLevel case "warn", "WARN": *l = WarnLevel case "error", "ERROR": *l = ErrorLevel case "dpanic", "DPANIC": *l = DPanicLevel case "panic", "PANIC": *l = PanicLevel case "fatal", "FATAL": *l = FatalLevel default: return false } return true } // Set sets the level for the flag.Value interface. func (l *Level) Set(s string) error { return l.UnmarshalText([]byte(s)) } // Get gets the level for the flag.Getter interface. func (l *Level) Get() interface{} { return *l } // Enabled returns true if the given level is at or above this level. func (l Level) Enabled(lvl Level) bool { return lvl >= l } // LevelEnabler decides whether a given logging level is enabled when logging a // message. // // Enablers are intended to be used to implement deterministic filters; // concerns like sampling are better implemented as a Core. // // Each concrete Level value implements a static LevelEnabler which returns // true for itself and all higher logging levels. For example WarnLevel.Enabled() // will return true for WarnLevel, ErrorLevel, DPanicLevel, PanicLevel, and // FatalLevel, but return false for InfoLevel and DebugLevel. type LevelEnabler interface { Enabled(Level) bool }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/error.go
vendor/go.uber.org/zap/zapcore/error.go
// Copyright (c) 2017 Uber Technologies, Inc. // // 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. package zapcore import ( "fmt" "reflect" "go.uber.org/zap/internal/pool" ) // Encodes the given error into fields of an object. A field with the given // name is added for the error message. // // If the error implements fmt.Formatter, a field with the name ${key}Verbose // is also added with the full verbose error message. // // Finally, if the error implements errorGroup (from go.uber.org/multierr) or // causer (from github.com/pkg/errors), a ${key}Causes field is added with an // array of objects containing the errors this error was comprised of. // // { // "error": err.Error(), // "errorVerbose": fmt.Sprintf("%+v", err), // "errorCauses": [ // ... // ], // } func encodeError(key string, err error, enc ObjectEncoder) (retErr error) { // Try to capture panics (from nil references or otherwise) when calling // the Error() method defer func() { if rerr := recover(); rerr != nil { // If it's a nil pointer, just say "<nil>". The likeliest causes are a // error that fails to guard against nil or a nil pointer for a // value receiver, and in either case, "<nil>" is a nice result. if v := reflect.ValueOf(err); v.Kind() == reflect.Ptr && v.IsNil() { enc.AddString(key, "<nil>") return } retErr = fmt.Errorf("PANIC=%v", rerr) } }() basic := err.Error() enc.AddString(key, basic) switch e := err.(type) { case errorGroup: return enc.AddArray(key+"Causes", errArray(e.Errors())) case fmt.Formatter: verbose := fmt.Sprintf("%+v", e) if verbose != basic { // This is a rich error type, like those produced by // github.com/pkg/errors. enc.AddString(key+"Verbose", verbose) } } return nil } type errorGroup interface { // Provides read-only access to the underlying list of errors, preferably // without causing any allocs. Errors() []error } // Note that errArray and errArrayElem are very similar to the version // implemented in the top-level error.go file. We can't re-use this because // that would require exporting errArray as part of the zapcore API. // Encodes a list of errors using the standard error encoding logic. type errArray []error func (errs errArray) MarshalLogArray(arr ArrayEncoder) error { for i := range errs { if errs[i] == nil { continue } el := newErrArrayElem(errs[i]) err := arr.AppendObject(el) el.Free() if err != nil { return err } } return nil } var _errArrayElemPool = pool.New(func() *errArrayElem { return &errArrayElem{} }) // Encodes any error into a {"error": ...} re-using the same errors logic. // // May be passed in place of an array to build a single-element array. type errArrayElem struct{ err error } func newErrArrayElem(err error) *errArrayElem { e := _errArrayElemPool.Get() e.err = err return e } func (e *errArrayElem) MarshalLogArray(arr ArrayEncoder) error { return arr.AppendObject(e) } func (e *errArrayElem) MarshalLogObject(enc ObjectEncoder) error { return encodeError("error", e.err, enc) } func (e *errArrayElem) Free() { e.err = nil _errArrayElemPool.Put(e) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/lazy_with.go
vendor/go.uber.org/zap/zapcore/lazy_with.go
// Copyright (c) 2023 Uber Technologies, Inc. // // 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. package zapcore import "sync" type lazyWithCore struct { Core sync.Once fields []Field } // NewLazyWith wraps a Core with a "lazy" Core that will only encode fields if // the logger is written to (or is further chained in a lon-lazy manner). func NewLazyWith(core Core, fields []Field) Core { return &lazyWithCore{ Core: core, fields: fields, } } func (d *lazyWithCore) initOnce() { d.Once.Do(func() { d.Core = d.Core.With(d.fields) }) } func (d *lazyWithCore) With(fields []Field) Core { d.initOnce() return d.Core.With(fields) } func (d *lazyWithCore) Check(e Entry, ce *CheckedEntry) *CheckedEntry { d.initOnce() return d.Core.Check(e, ce) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/marshaler.go
vendor/go.uber.org/zap/zapcore/marshaler.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore // ObjectMarshaler allows user-defined types to efficiently add themselves to the // logging context, and to selectively omit information which shouldn't be // included in logs (e.g., passwords). // // Note: ObjectMarshaler is only used when zap.Object is used or when // passed directly to zap.Any. It is not used when reflection-based // encoding is used. type ObjectMarshaler interface { MarshalLogObject(ObjectEncoder) error } // ObjectMarshalerFunc is a type adapter that turns a function into an // ObjectMarshaler. type ObjectMarshalerFunc func(ObjectEncoder) error // MarshalLogObject calls the underlying function. func (f ObjectMarshalerFunc) MarshalLogObject(enc ObjectEncoder) error { return f(enc) } // ArrayMarshaler allows user-defined types to efficiently add themselves to the // logging context, and to selectively omit information which shouldn't be // included in logs (e.g., passwords). // // Note: ArrayMarshaler is only used when zap.Array is used or when // passed directly to zap.Any. It is not used when reflection-based // encoding is used. type ArrayMarshaler interface { MarshalLogArray(ArrayEncoder) error } // ArrayMarshalerFunc is a type adapter that turns a function into an // ArrayMarshaler. type ArrayMarshalerFunc func(ArrayEncoder) error // MarshalLogArray calls the underlying function. func (f ArrayMarshalerFunc) MarshalLogArray(enc ArrayEncoder) error { return f(enc) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/reflected_encoder.go
vendor/go.uber.org/zap/zapcore/reflected_encoder.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore import ( "encoding/json" "io" ) // ReflectedEncoder serializes log fields that can't be serialized with Zap's // JSON encoder. These have the ReflectType field type. // Use EncoderConfig.NewReflectedEncoder to set this. type ReflectedEncoder interface { // Encode encodes and writes to the underlying data stream. Encode(interface{}) error } func defaultReflectedEncoder(w io.Writer) ReflectedEncoder { enc := json.NewEncoder(w) // For consistency with our custom JSON encoder. enc.SetEscapeHTML(false) return enc }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/json_encoder.go
vendor/go.uber.org/zap/zapcore/json_encoder.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore import ( "encoding/base64" "math" "time" "unicode/utf8" "go.uber.org/zap/buffer" "go.uber.org/zap/internal/bufferpool" "go.uber.org/zap/internal/pool" ) // For JSON-escaping; see jsonEncoder.safeAddString below. const _hex = "0123456789abcdef" var _jsonPool = pool.New(func() *jsonEncoder { return &jsonEncoder{} }) func putJSONEncoder(enc *jsonEncoder) { if enc.reflectBuf != nil { enc.reflectBuf.Free() } enc.EncoderConfig = nil enc.buf = nil enc.spaced = false enc.openNamespaces = 0 enc.reflectBuf = nil enc.reflectEnc = nil _jsonPool.Put(enc) } type jsonEncoder struct { *EncoderConfig buf *buffer.Buffer spaced bool // include spaces after colons and commas openNamespaces int // for encoding generic values by reflection reflectBuf *buffer.Buffer reflectEnc ReflectedEncoder } // NewJSONEncoder creates a fast, low-allocation JSON encoder. The encoder // appropriately escapes all field keys and values. // // Note that the encoder doesn't deduplicate keys, so it's possible to produce // a message like // // {"foo":"bar","foo":"baz"} // // This is permitted by the JSON specification, but not encouraged. Many // libraries will ignore duplicate key-value pairs (typically keeping the last // pair) when unmarshaling, but users should attempt to avoid adding duplicate // keys. func NewJSONEncoder(cfg EncoderConfig) Encoder { return newJSONEncoder(cfg, false) } func newJSONEncoder(cfg EncoderConfig, spaced bool) *jsonEncoder { if cfg.SkipLineEnding { cfg.LineEnding = "" } else if cfg.LineEnding == "" { cfg.LineEnding = DefaultLineEnding } // If no EncoderConfig.NewReflectedEncoder is provided by the user, then use default if cfg.NewReflectedEncoder == nil { cfg.NewReflectedEncoder = defaultReflectedEncoder } return &jsonEncoder{ EncoderConfig: &cfg, buf: bufferpool.Get(), spaced: spaced, } } func (enc *jsonEncoder) AddArray(key string, arr ArrayMarshaler) error { enc.addKey(key) return enc.AppendArray(arr) } func (enc *jsonEncoder) AddObject(key string, obj ObjectMarshaler) error { enc.addKey(key) return enc.AppendObject(obj) } func (enc *jsonEncoder) AddBinary(key string, val []byte) { enc.AddString(key, base64.StdEncoding.EncodeToString(val)) } func (enc *jsonEncoder) AddByteString(key string, val []byte) { enc.addKey(key) enc.AppendByteString(val) } func (enc *jsonEncoder) AddBool(key string, val bool) { enc.addKey(key) enc.AppendBool(val) } func (enc *jsonEncoder) AddComplex128(key string, val complex128) { enc.addKey(key) enc.AppendComplex128(val) } func (enc *jsonEncoder) AddComplex64(key string, val complex64) { enc.addKey(key) enc.AppendComplex64(val) } func (enc *jsonEncoder) AddDuration(key string, val time.Duration) { enc.addKey(key) enc.AppendDuration(val) } func (enc *jsonEncoder) AddFloat64(key string, val float64) { enc.addKey(key) enc.AppendFloat64(val) } func (enc *jsonEncoder) AddFloat32(key string, val float32) { enc.addKey(key) enc.AppendFloat32(val) } func (enc *jsonEncoder) AddInt64(key string, val int64) { enc.addKey(key) enc.AppendInt64(val) } func (enc *jsonEncoder) resetReflectBuf() { if enc.reflectBuf == nil { enc.reflectBuf = bufferpool.Get() enc.reflectEnc = enc.NewReflectedEncoder(enc.reflectBuf) } else { enc.reflectBuf.Reset() } } var nullLiteralBytes = []byte("null") // Only invoke the standard JSON encoder if there is actually something to // encode; otherwise write JSON null literal directly. func (enc *jsonEncoder) encodeReflected(obj interface{}) ([]byte, error) { if obj == nil { return nullLiteralBytes, nil } enc.resetReflectBuf() if err := enc.reflectEnc.Encode(obj); err != nil { return nil, err } enc.reflectBuf.TrimNewline() return enc.reflectBuf.Bytes(), nil } func (enc *jsonEncoder) AddReflected(key string, obj interface{}) error { valueBytes, err := enc.encodeReflected(obj) if err != nil { return err } enc.addKey(key) _, err = enc.buf.Write(valueBytes) return err } func (enc *jsonEncoder) OpenNamespace(key string) { enc.addKey(key) enc.buf.AppendByte('{') enc.openNamespaces++ } func (enc *jsonEncoder) AddString(key, val string) { enc.addKey(key) enc.AppendString(val) } func (enc *jsonEncoder) AddTime(key string, val time.Time) { enc.addKey(key) enc.AppendTime(val) } func (enc *jsonEncoder) AddUint64(key string, val uint64) { enc.addKey(key) enc.AppendUint64(val) } func (enc *jsonEncoder) AppendArray(arr ArrayMarshaler) error { enc.addElementSeparator() enc.buf.AppendByte('[') err := arr.MarshalLogArray(enc) enc.buf.AppendByte(']') return err } func (enc *jsonEncoder) AppendObject(obj ObjectMarshaler) error { // Close ONLY new openNamespaces that are created during // AppendObject(). old := enc.openNamespaces enc.openNamespaces = 0 enc.addElementSeparator() enc.buf.AppendByte('{') err := obj.MarshalLogObject(enc) enc.buf.AppendByte('}') enc.closeOpenNamespaces() enc.openNamespaces = old return err } func (enc *jsonEncoder) AppendBool(val bool) { enc.addElementSeparator() enc.buf.AppendBool(val) } func (enc *jsonEncoder) AppendByteString(val []byte) { enc.addElementSeparator() enc.buf.AppendByte('"') enc.safeAddByteString(val) enc.buf.AppendByte('"') } // appendComplex appends the encoded form of the provided complex128 value. // precision specifies the encoding precision for the real and imaginary // components of the complex number. func (enc *jsonEncoder) appendComplex(val complex128, precision int) { enc.addElementSeparator() // Cast to a platform-independent, fixed-size type. r, i := float64(real(val)), float64(imag(val)) enc.buf.AppendByte('"') // Because we're always in a quoted string, we can use strconv without // special-casing NaN and +/-Inf. enc.buf.AppendFloat(r, precision) // If imaginary part is less than 0, minus (-) sign is added by default // by AppendFloat. if i >= 0 { enc.buf.AppendByte('+') } enc.buf.AppendFloat(i, precision) enc.buf.AppendByte('i') enc.buf.AppendByte('"') } func (enc *jsonEncoder) AppendDuration(val time.Duration) { cur := enc.buf.Len() if e := enc.EncodeDuration; e != nil { e(val, enc) } if cur == enc.buf.Len() { // User-supplied EncodeDuration is a no-op. Fall back to nanoseconds to keep // JSON valid. enc.AppendInt64(int64(val)) } } func (enc *jsonEncoder) AppendInt64(val int64) { enc.addElementSeparator() enc.buf.AppendInt(val) } func (enc *jsonEncoder) AppendReflected(val interface{}) error { valueBytes, err := enc.encodeReflected(val) if err != nil { return err } enc.addElementSeparator() _, err = enc.buf.Write(valueBytes) return err } func (enc *jsonEncoder) AppendString(val string) { enc.addElementSeparator() enc.buf.AppendByte('"') enc.safeAddString(val) enc.buf.AppendByte('"') } func (enc *jsonEncoder) AppendTimeLayout(time time.Time, layout string) { enc.addElementSeparator() enc.buf.AppendByte('"') enc.buf.AppendTime(time, layout) enc.buf.AppendByte('"') } func (enc *jsonEncoder) AppendTime(val time.Time) { cur := enc.buf.Len() if e := enc.EncodeTime; e != nil { e(val, enc) } if cur == enc.buf.Len() { // User-supplied EncodeTime is a no-op. Fall back to nanos since epoch to keep // output JSON valid. enc.AppendInt64(val.UnixNano()) } } func (enc *jsonEncoder) AppendUint64(val uint64) { enc.addElementSeparator() enc.buf.AppendUint(val) } func (enc *jsonEncoder) AddInt(k string, v int) { enc.AddInt64(k, int64(v)) } func (enc *jsonEncoder) AddInt32(k string, v int32) { enc.AddInt64(k, int64(v)) } func (enc *jsonEncoder) AddInt16(k string, v int16) { enc.AddInt64(k, int64(v)) } func (enc *jsonEncoder) AddInt8(k string, v int8) { enc.AddInt64(k, int64(v)) } func (enc *jsonEncoder) AddUint(k string, v uint) { enc.AddUint64(k, uint64(v)) } func (enc *jsonEncoder) AddUint32(k string, v uint32) { enc.AddUint64(k, uint64(v)) } func (enc *jsonEncoder) AddUint16(k string, v uint16) { enc.AddUint64(k, uint64(v)) } func (enc *jsonEncoder) AddUint8(k string, v uint8) { enc.AddUint64(k, uint64(v)) } func (enc *jsonEncoder) AddUintptr(k string, v uintptr) { enc.AddUint64(k, uint64(v)) } func (enc *jsonEncoder) AppendComplex64(v complex64) { enc.appendComplex(complex128(v), 32) } func (enc *jsonEncoder) AppendComplex128(v complex128) { enc.appendComplex(complex128(v), 64) } func (enc *jsonEncoder) AppendFloat64(v float64) { enc.appendFloat(v, 64) } func (enc *jsonEncoder) AppendFloat32(v float32) { enc.appendFloat(float64(v), 32) } func (enc *jsonEncoder) AppendInt(v int) { enc.AppendInt64(int64(v)) } func (enc *jsonEncoder) AppendInt32(v int32) { enc.AppendInt64(int64(v)) } func (enc *jsonEncoder) AppendInt16(v int16) { enc.AppendInt64(int64(v)) } func (enc *jsonEncoder) AppendInt8(v int8) { enc.AppendInt64(int64(v)) } func (enc *jsonEncoder) AppendUint(v uint) { enc.AppendUint64(uint64(v)) } func (enc *jsonEncoder) AppendUint32(v uint32) { enc.AppendUint64(uint64(v)) } func (enc *jsonEncoder) AppendUint16(v uint16) { enc.AppendUint64(uint64(v)) } func (enc *jsonEncoder) AppendUint8(v uint8) { enc.AppendUint64(uint64(v)) } func (enc *jsonEncoder) AppendUintptr(v uintptr) { enc.AppendUint64(uint64(v)) } func (enc *jsonEncoder) Clone() Encoder { clone := enc.clone() clone.buf.Write(enc.buf.Bytes()) return clone } func (enc *jsonEncoder) clone() *jsonEncoder { clone := _jsonPool.Get() clone.EncoderConfig = enc.EncoderConfig clone.spaced = enc.spaced clone.openNamespaces = enc.openNamespaces clone.buf = bufferpool.Get() return clone } func (enc *jsonEncoder) EncodeEntry(ent Entry, fields []Field) (*buffer.Buffer, error) { final := enc.clone() final.buf.AppendByte('{') if final.LevelKey != "" && final.EncodeLevel != nil { final.addKey(final.LevelKey) cur := final.buf.Len() final.EncodeLevel(ent.Level, final) if cur == final.buf.Len() { // User-supplied EncodeLevel was a no-op. Fall back to strings to keep // output JSON valid. final.AppendString(ent.Level.String()) } } if final.TimeKey != "" && !ent.Time.IsZero() { final.AddTime(final.TimeKey, ent.Time) } if ent.LoggerName != "" && final.NameKey != "" { final.addKey(final.NameKey) cur := final.buf.Len() nameEncoder := final.EncodeName // if no name encoder provided, fall back to FullNameEncoder for backwards // compatibility if nameEncoder == nil { nameEncoder = FullNameEncoder } nameEncoder(ent.LoggerName, final) if cur == final.buf.Len() { // User-supplied EncodeName was a no-op. Fall back to strings to // keep output JSON valid. final.AppendString(ent.LoggerName) } } if ent.Caller.Defined { if final.CallerKey != "" { final.addKey(final.CallerKey) cur := final.buf.Len() final.EncodeCaller(ent.Caller, final) if cur == final.buf.Len() { // User-supplied EncodeCaller was a no-op. Fall back to strings to // keep output JSON valid. final.AppendString(ent.Caller.String()) } } if final.FunctionKey != "" { final.addKey(final.FunctionKey) final.AppendString(ent.Caller.Function) } } if final.MessageKey != "" { final.addKey(enc.MessageKey) final.AppendString(ent.Message) } if enc.buf.Len() > 0 { final.addElementSeparator() final.buf.Write(enc.buf.Bytes()) } addFields(final, fields) final.closeOpenNamespaces() if ent.Stack != "" && final.StacktraceKey != "" { final.AddString(final.StacktraceKey, ent.Stack) } final.buf.AppendByte('}') final.buf.AppendString(final.LineEnding) ret := final.buf putJSONEncoder(final) return ret, nil } func (enc *jsonEncoder) truncate() { enc.buf.Reset() } func (enc *jsonEncoder) closeOpenNamespaces() { for i := 0; i < enc.openNamespaces; i++ { enc.buf.AppendByte('}') } enc.openNamespaces = 0 } func (enc *jsonEncoder) addKey(key string) { enc.addElementSeparator() enc.buf.AppendByte('"') enc.safeAddString(key) enc.buf.AppendByte('"') enc.buf.AppendByte(':') if enc.spaced { enc.buf.AppendByte(' ') } } func (enc *jsonEncoder) addElementSeparator() { last := enc.buf.Len() - 1 if last < 0 { return } switch enc.buf.Bytes()[last] { case '{', '[', ':', ',', ' ': return default: enc.buf.AppendByte(',') if enc.spaced { enc.buf.AppendByte(' ') } } } func (enc *jsonEncoder) appendFloat(val float64, bitSize int) { enc.addElementSeparator() switch { case math.IsNaN(val): enc.buf.AppendString(`"NaN"`) case math.IsInf(val, 1): enc.buf.AppendString(`"+Inf"`) case math.IsInf(val, -1): enc.buf.AppendString(`"-Inf"`) default: enc.buf.AppendFloat(val, bitSize) } } // safeAddString JSON-escapes a string and appends it to the internal buffer. // Unlike the standard library's encoder, it doesn't attempt to protect the // user from browser vulnerabilities or JSONP-related problems. func (enc *jsonEncoder) safeAddString(s string) { safeAppendStringLike( (*buffer.Buffer).AppendString, utf8.DecodeRuneInString, enc.buf, s, ) } // safeAddByteString is no-alloc equivalent of safeAddString(string(s)) for s []byte. func (enc *jsonEncoder) safeAddByteString(s []byte) { safeAppendStringLike( (*buffer.Buffer).AppendBytes, utf8.DecodeRune, enc.buf, s, ) } // safeAppendStringLike is a generic implementation of safeAddString and safeAddByteString. // It appends a string or byte slice to the buffer, escaping all special characters. func safeAppendStringLike[S []byte | string]( // appendTo appends this string-like object to the buffer. appendTo func(*buffer.Buffer, S), // decodeRune decodes the next rune from the string-like object // and returns its value and width in bytes. decodeRune func(S) (rune, int), buf *buffer.Buffer, s S, ) { // The encoding logic below works by skipping over characters // that can be safely copied as-is, // until a character is found that needs special handling. // At that point, we copy everything we've seen so far, // and then handle that special character. // // last is the index of the last byte that was copied to the buffer. last := 0 for i := 0; i < len(s); { if s[i] >= utf8.RuneSelf { // Character >= RuneSelf may be part of a multi-byte rune. // They need to be decoded before we can decide how to handle them. r, size := decodeRune(s[i:]) if r != utf8.RuneError || size != 1 { // No special handling required. // Skip over this rune and continue. i += size continue } // Invalid UTF-8 sequence. // Replace it with the Unicode replacement character. appendTo(buf, s[last:i]) buf.AppendString(`\ufffd`) i++ last = i } else { // Character < RuneSelf is a single-byte UTF-8 rune. if s[i] >= 0x20 && s[i] != '\\' && s[i] != '"' { // No escaping necessary. // Skip over this character and continue. i++ continue } // This character needs to be escaped. appendTo(buf, s[last:i]) switch s[i] { case '\\', '"': buf.AppendByte('\\') buf.AppendByte(s[i]) case '\n': buf.AppendByte('\\') buf.AppendByte('n') case '\r': buf.AppendByte('\\') buf.AppendByte('r') case '\t': buf.AppendByte('\\') buf.AppendByte('t') default: // Encode bytes < 0x20, except for the escape sequences above. buf.AppendString(`\u00`) buf.AppendByte(_hex[s[i]>>4]) buf.AppendByte(_hex[s[i]&0xF]) } i++ last = i } } // add remaining appendTo(buf, s[last:]) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/field.go
vendor/go.uber.org/zap/zapcore/field.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore import ( "bytes" "fmt" "math" "reflect" "time" ) // A FieldType indicates which member of the Field union struct should be used // and how it should be serialized. type FieldType uint8 const ( // UnknownType is the default field type. Attempting to add it to an encoder will panic. UnknownType FieldType = iota // ArrayMarshalerType indicates that the field carries an ArrayMarshaler. ArrayMarshalerType // ObjectMarshalerType indicates that the field carries an ObjectMarshaler. ObjectMarshalerType // BinaryType indicates that the field carries an opaque binary blob. BinaryType // BoolType indicates that the field carries a bool. BoolType // ByteStringType indicates that the field carries UTF-8 encoded bytes. ByteStringType // Complex128Type indicates that the field carries a complex128. Complex128Type // Complex64Type indicates that the field carries a complex64. Complex64Type // DurationType indicates that the field carries a time.Duration. DurationType // Float64Type indicates that the field carries a float64. Float64Type // Float32Type indicates that the field carries a float32. Float32Type // Int64Type indicates that the field carries an int64. Int64Type // Int32Type indicates that the field carries an int32. Int32Type // Int16Type indicates that the field carries an int16. Int16Type // Int8Type indicates that the field carries an int8. Int8Type // StringType indicates that the field carries a string. StringType // TimeType indicates that the field carries a time.Time that is // representable by a UnixNano() stored as an int64. TimeType // TimeFullType indicates that the field carries a time.Time stored as-is. TimeFullType // Uint64Type indicates that the field carries a uint64. Uint64Type // Uint32Type indicates that the field carries a uint32. Uint32Type // Uint16Type indicates that the field carries a uint16. Uint16Type // Uint8Type indicates that the field carries a uint8. Uint8Type // UintptrType indicates that the field carries a uintptr. UintptrType // ReflectType indicates that the field carries an interface{}, which should // be serialized using reflection. ReflectType // NamespaceType signals the beginning of an isolated namespace. All // subsequent fields should be added to the new namespace. NamespaceType // StringerType indicates that the field carries a fmt.Stringer. StringerType // ErrorType indicates that the field carries an error. ErrorType // SkipType indicates that the field is a no-op. SkipType // InlineMarshalerType indicates that the field carries an ObjectMarshaler // that should be inlined. InlineMarshalerType ) // A Field is a marshaling operation used to add a key-value pair to a logger's // context. Most fields are lazily marshaled, so it's inexpensive to add fields // to disabled debug-level log statements. type Field struct { Key string Type FieldType Integer int64 String string Interface interface{} } // AddTo exports a field through the ObjectEncoder interface. It's primarily // useful to library authors, and shouldn't be necessary in most applications. func (f Field) AddTo(enc ObjectEncoder) { var err error switch f.Type { case ArrayMarshalerType: err = enc.AddArray(f.Key, f.Interface.(ArrayMarshaler)) case ObjectMarshalerType: err = enc.AddObject(f.Key, f.Interface.(ObjectMarshaler)) case InlineMarshalerType: err = f.Interface.(ObjectMarshaler).MarshalLogObject(enc) case BinaryType: enc.AddBinary(f.Key, f.Interface.([]byte)) case BoolType: enc.AddBool(f.Key, f.Integer == 1) case ByteStringType: enc.AddByteString(f.Key, f.Interface.([]byte)) case Complex128Type: enc.AddComplex128(f.Key, f.Interface.(complex128)) case Complex64Type: enc.AddComplex64(f.Key, f.Interface.(complex64)) case DurationType: enc.AddDuration(f.Key, time.Duration(f.Integer)) case Float64Type: enc.AddFloat64(f.Key, math.Float64frombits(uint64(f.Integer))) case Float32Type: enc.AddFloat32(f.Key, math.Float32frombits(uint32(f.Integer))) case Int64Type: enc.AddInt64(f.Key, f.Integer) case Int32Type: enc.AddInt32(f.Key, int32(f.Integer)) case Int16Type: enc.AddInt16(f.Key, int16(f.Integer)) case Int8Type: enc.AddInt8(f.Key, int8(f.Integer)) case StringType: enc.AddString(f.Key, f.String) case TimeType: if f.Interface != nil { enc.AddTime(f.Key, time.Unix(0, f.Integer).In(f.Interface.(*time.Location))) } else { // Fall back to UTC if location is nil. enc.AddTime(f.Key, time.Unix(0, f.Integer)) } case TimeFullType: enc.AddTime(f.Key, f.Interface.(time.Time)) case Uint64Type: enc.AddUint64(f.Key, uint64(f.Integer)) case Uint32Type: enc.AddUint32(f.Key, uint32(f.Integer)) case Uint16Type: enc.AddUint16(f.Key, uint16(f.Integer)) case Uint8Type: enc.AddUint8(f.Key, uint8(f.Integer)) case UintptrType: enc.AddUintptr(f.Key, uintptr(f.Integer)) case ReflectType: err = enc.AddReflected(f.Key, f.Interface) case NamespaceType: enc.OpenNamespace(f.Key) case StringerType: err = encodeStringer(f.Key, f.Interface, enc) case ErrorType: err = encodeError(f.Key, f.Interface.(error), enc) case SkipType: break default: panic(fmt.Sprintf("unknown field type: %v", f)) } if err != nil { enc.AddString(fmt.Sprintf("%sError", f.Key), err.Error()) } } // Equals returns whether two fields are equal. For non-primitive types such as // errors, marshalers, or reflect types, it uses reflect.DeepEqual. func (f Field) Equals(other Field) bool { if f.Type != other.Type { return false } if f.Key != other.Key { return false } switch f.Type { case BinaryType, ByteStringType: return bytes.Equal(f.Interface.([]byte), other.Interface.([]byte)) case ArrayMarshalerType, ObjectMarshalerType, ErrorType, ReflectType: return reflect.DeepEqual(f.Interface, other.Interface) default: return f == other } } func addFields(enc ObjectEncoder, fields []Field) { for i := range fields { fields[i].AddTo(enc) } } func encodeStringer(key string, stringer interface{}, enc ObjectEncoder) (retErr error) { // Try to capture panics (from nil references or otherwise) when calling // the String() method, similar to https://golang.org/src/fmt/print.go#L540 defer func() { if err := recover(); err != nil { // If it's a nil pointer, just say "<nil>". The likeliest causes are a // Stringer that fails to guard against nil or a nil pointer for a // value receiver, and in either case, "<nil>" is a nice result. if v := reflect.ValueOf(stringer); v.Kind() == reflect.Ptr && v.IsNil() { enc.AddString(key, "<nil>") return } retErr = fmt.Errorf("PANIC=%v", err) } }() enc.AddString(key, stringer.(fmt.Stringer).String()) return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go
vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go
// Copyright (c) 2021 Uber Technologies, Inc. // // 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. package zapcore import ( "bufio" "sync" "time" "go.uber.org/multierr" ) const ( // _defaultBufferSize specifies the default size used by Buffer. _defaultBufferSize = 256 * 1024 // 256 kB // _defaultFlushInterval specifies the default flush interval for // Buffer. _defaultFlushInterval = 30 * time.Second ) // A BufferedWriteSyncer is a WriteSyncer that buffers writes in-memory before // flushing them to a wrapped WriteSyncer after reaching some limit, or at some // fixed interval--whichever comes first. // // BufferedWriteSyncer is safe for concurrent use. You don't need to use // zapcore.Lock for WriteSyncers with BufferedWriteSyncer. // // To set up a BufferedWriteSyncer, construct a WriteSyncer for your log // destination (*os.File is a valid WriteSyncer), wrap it with // BufferedWriteSyncer, and defer a Stop() call for when you no longer need the // object. // // func main() { // ws := ... // your log destination // bws := &zapcore.BufferedWriteSyncer{WS: ws} // defer bws.Stop() // // // ... // core := zapcore.NewCore(enc, bws, lvl) // logger := zap.New(core) // // // ... // } // // By default, a BufferedWriteSyncer will buffer up to 256 kilobytes of logs, // waiting at most 30 seconds between flushes. // You can customize these parameters by setting the Size or FlushInterval // fields. // For example, the following buffers up to 512 kB of logs before flushing them // to Stderr, with a maximum of one minute between each flush. // // ws := &BufferedWriteSyncer{ // WS: os.Stderr, // Size: 512 * 1024, // 512 kB // FlushInterval: time.Minute, // } // defer ws.Stop() type BufferedWriteSyncer struct { // WS is the WriteSyncer around which BufferedWriteSyncer will buffer // writes. // // This field is required. WS WriteSyncer // Size specifies the maximum amount of data the writer will buffered // before flushing. // // Defaults to 256 kB if unspecified. Size int // FlushInterval specifies how often the writer should flush data if // there have been no writes. // // Defaults to 30 seconds if unspecified. FlushInterval time.Duration // Clock, if specified, provides control of the source of time for the // writer. // // Defaults to the system clock. Clock Clock // unexported fields for state mu sync.Mutex initialized bool // whether initialize() has run stopped bool // whether Stop() has run writer *bufio.Writer ticker *time.Ticker stop chan struct{} // closed when flushLoop should stop done chan struct{} // closed when flushLoop has stopped } func (s *BufferedWriteSyncer) initialize() { size := s.Size if size == 0 { size = _defaultBufferSize } flushInterval := s.FlushInterval if flushInterval == 0 { flushInterval = _defaultFlushInterval } if s.Clock == nil { s.Clock = DefaultClock } s.ticker = s.Clock.NewTicker(flushInterval) s.writer = bufio.NewWriterSize(s.WS, size) s.stop = make(chan struct{}) s.done = make(chan struct{}) s.initialized = true go s.flushLoop() } // Write writes log data into buffer syncer directly, multiple Write calls will be batched, // and log data will be flushed to disk when the buffer is full or periodically. func (s *BufferedWriteSyncer) Write(bs []byte) (int, error) { s.mu.Lock() defer s.mu.Unlock() if !s.initialized { s.initialize() } // To avoid partial writes from being flushed, we manually flush the existing buffer if: // * The current write doesn't fit into the buffer fully, and // * The buffer is not empty (since bufio will not split large writes when the buffer is empty) if len(bs) > s.writer.Available() && s.writer.Buffered() > 0 { if err := s.writer.Flush(); err != nil { return 0, err } } return s.writer.Write(bs) } // Sync flushes buffered log data into disk directly. func (s *BufferedWriteSyncer) Sync() error { s.mu.Lock() defer s.mu.Unlock() var err error if s.initialized { err = s.writer.Flush() } return multierr.Append(err, s.WS.Sync()) } // flushLoop flushes the buffer at the configured interval until Stop is // called. func (s *BufferedWriteSyncer) flushLoop() { defer close(s.done) for { select { case <-s.ticker.C: // we just simply ignore error here // because the underlying bufio writer stores any errors // and we return any error from Sync() as part of the close _ = s.Sync() case <-s.stop: return } } } // Stop closes the buffer, cleans up background goroutines, and flushes // remaining unwritten data. func (s *BufferedWriteSyncer) Stop() (err error) { var stopped bool // Critical section. func() { s.mu.Lock() defer s.mu.Unlock() if !s.initialized { return } stopped = s.stopped if stopped { return } s.stopped = true s.ticker.Stop() close(s.stop) // tell flushLoop to stop <-s.done // and wait until it has }() // Don't call Sync on consecutive Stops. if !stopped { err = s.Sync() } return err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/write_syncer.go
vendor/go.uber.org/zap/zapcore/write_syncer.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore import ( "io" "sync" "go.uber.org/multierr" ) // A WriteSyncer is an io.Writer that can also flush any buffered data. Note // that *os.File (and thus, os.Stderr and os.Stdout) implement WriteSyncer. type WriteSyncer interface { io.Writer Sync() error } // AddSync converts an io.Writer to a WriteSyncer. It attempts to be // intelligent: if the concrete type of the io.Writer implements WriteSyncer, // we'll use the existing Sync method. If it doesn't, we'll add a no-op Sync. func AddSync(w io.Writer) WriteSyncer { switch w := w.(type) { case WriteSyncer: return w default: return writerWrapper{w} } } type lockedWriteSyncer struct { sync.Mutex ws WriteSyncer } // Lock wraps a WriteSyncer in a mutex to make it safe for concurrent use. In // particular, *os.Files must be locked before use. func Lock(ws WriteSyncer) WriteSyncer { if _, ok := ws.(*lockedWriteSyncer); ok { // no need to layer on another lock return ws } return &lockedWriteSyncer{ws: ws} } func (s *lockedWriteSyncer) Write(bs []byte) (int, error) { s.Lock() n, err := s.ws.Write(bs) s.Unlock() return n, err } func (s *lockedWriteSyncer) Sync() error { s.Lock() err := s.ws.Sync() s.Unlock() return err } type writerWrapper struct { io.Writer } func (w writerWrapper) Sync() error { return nil } type multiWriteSyncer []WriteSyncer // NewMultiWriteSyncer creates a WriteSyncer that duplicates its writes // and sync calls, much like io.MultiWriter. func NewMultiWriteSyncer(ws ...WriteSyncer) WriteSyncer { if len(ws) == 1 { return ws[0] } return multiWriteSyncer(ws) } // See https://golang.org/src/io/multi.go // When not all underlying syncers write the same number of bytes, // the smallest number is returned even though Write() is called on // all of them. func (ws multiWriteSyncer) Write(p []byte) (int, error) { var writeErr error nWritten := 0 for _, w := range ws { n, err := w.Write(p) writeErr = multierr.Append(writeErr, err) if nWritten == 0 && n != 0 { nWritten = n } else if n < nWritten { nWritten = n } } return nWritten, writeErr } func (ws multiWriteSyncer) Sync() error { var err error for _, w := range ws { err = multierr.Append(err, w.Sync()) } return err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/memory_encoder.go
vendor/go.uber.org/zap/zapcore/memory_encoder.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore import "time" // MapObjectEncoder is an ObjectEncoder backed by a simple // map[string]interface{}. It's not fast enough for production use, but it's // helpful in tests. type MapObjectEncoder struct { // Fields contains the entire encoded log context. Fields map[string]interface{} // cur is a pointer to the namespace we're currently writing to. cur map[string]interface{} } // NewMapObjectEncoder creates a new map-backed ObjectEncoder. func NewMapObjectEncoder() *MapObjectEncoder { m := make(map[string]interface{}) return &MapObjectEncoder{ Fields: m, cur: m, } } // AddArray implements ObjectEncoder. func (m *MapObjectEncoder) AddArray(key string, v ArrayMarshaler) error { arr := &sliceArrayEncoder{elems: make([]interface{}, 0)} err := v.MarshalLogArray(arr) m.cur[key] = arr.elems return err } // AddObject implements ObjectEncoder. func (m *MapObjectEncoder) AddObject(k string, v ObjectMarshaler) error { newMap := NewMapObjectEncoder() m.cur[k] = newMap.Fields return v.MarshalLogObject(newMap) } // AddBinary implements ObjectEncoder. func (m *MapObjectEncoder) AddBinary(k string, v []byte) { m.cur[k] = v } // AddByteString implements ObjectEncoder. func (m *MapObjectEncoder) AddByteString(k string, v []byte) { m.cur[k] = string(v) } // AddBool implements ObjectEncoder. func (m *MapObjectEncoder) AddBool(k string, v bool) { m.cur[k] = v } // AddDuration implements ObjectEncoder. func (m MapObjectEncoder) AddDuration(k string, v time.Duration) { m.cur[k] = v } // AddComplex128 implements ObjectEncoder. func (m *MapObjectEncoder) AddComplex128(k string, v complex128) { m.cur[k] = v } // AddComplex64 implements ObjectEncoder. func (m *MapObjectEncoder) AddComplex64(k string, v complex64) { m.cur[k] = v } // AddFloat64 implements ObjectEncoder. func (m *MapObjectEncoder) AddFloat64(k string, v float64) { m.cur[k] = v } // AddFloat32 implements ObjectEncoder. func (m *MapObjectEncoder) AddFloat32(k string, v float32) { m.cur[k] = v } // AddInt implements ObjectEncoder. func (m *MapObjectEncoder) AddInt(k string, v int) { m.cur[k] = v } // AddInt64 implements ObjectEncoder. func (m *MapObjectEncoder) AddInt64(k string, v int64) { m.cur[k] = v } // AddInt32 implements ObjectEncoder. func (m *MapObjectEncoder) AddInt32(k string, v int32) { m.cur[k] = v } // AddInt16 implements ObjectEncoder. func (m *MapObjectEncoder) AddInt16(k string, v int16) { m.cur[k] = v } // AddInt8 implements ObjectEncoder. func (m *MapObjectEncoder) AddInt8(k string, v int8) { m.cur[k] = v } // AddString implements ObjectEncoder. func (m *MapObjectEncoder) AddString(k string, v string) { m.cur[k] = v } // AddTime implements ObjectEncoder. func (m MapObjectEncoder) AddTime(k string, v time.Time) { m.cur[k] = v } // AddUint implements ObjectEncoder. func (m *MapObjectEncoder) AddUint(k string, v uint) { m.cur[k] = v } // AddUint64 implements ObjectEncoder. func (m *MapObjectEncoder) AddUint64(k string, v uint64) { m.cur[k] = v } // AddUint32 implements ObjectEncoder. func (m *MapObjectEncoder) AddUint32(k string, v uint32) { m.cur[k] = v } // AddUint16 implements ObjectEncoder. func (m *MapObjectEncoder) AddUint16(k string, v uint16) { m.cur[k] = v } // AddUint8 implements ObjectEncoder. func (m *MapObjectEncoder) AddUint8(k string, v uint8) { m.cur[k] = v } // AddUintptr implements ObjectEncoder. func (m *MapObjectEncoder) AddUintptr(k string, v uintptr) { m.cur[k] = v } // AddReflected implements ObjectEncoder. func (m *MapObjectEncoder) AddReflected(k string, v interface{}) error { m.cur[k] = v return nil } // OpenNamespace implements ObjectEncoder. func (m *MapObjectEncoder) OpenNamespace(k string) { ns := make(map[string]interface{}) m.cur[k] = ns m.cur = ns } // sliceArrayEncoder is an ArrayEncoder backed by a simple []interface{}. Like // the MapObjectEncoder, it's not designed for production use. type sliceArrayEncoder struct { elems []interface{} } func (s *sliceArrayEncoder) AppendArray(v ArrayMarshaler) error { enc := &sliceArrayEncoder{} err := v.MarshalLogArray(enc) s.elems = append(s.elems, enc.elems) return err } func (s *sliceArrayEncoder) AppendObject(v ObjectMarshaler) error { m := NewMapObjectEncoder() err := v.MarshalLogObject(m) s.elems = append(s.elems, m.Fields) return err } func (s *sliceArrayEncoder) AppendReflected(v interface{}) error { s.elems = append(s.elems, v) return nil } func (s *sliceArrayEncoder) AppendBool(v bool) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendByteString(v []byte) { s.elems = append(s.elems, string(v)) } func (s *sliceArrayEncoder) AppendComplex128(v complex128) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendComplex64(v complex64) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendDuration(v time.Duration) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendFloat64(v float64) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendFloat32(v float32) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendInt(v int) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendInt64(v int64) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendInt32(v int32) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendInt16(v int16) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendInt8(v int8) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendString(v string) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendTime(v time.Time) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendUint(v uint) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendUint64(v uint64) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendUint32(v uint32) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendUint16(v uint16) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendUint8(v uint8) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendUintptr(v uintptr) { s.elems = append(s.elems, v) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/console_encoder.go
vendor/go.uber.org/zap/zapcore/console_encoder.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore import ( "fmt" "go.uber.org/zap/buffer" "go.uber.org/zap/internal/bufferpool" "go.uber.org/zap/internal/pool" ) var _sliceEncoderPool = pool.New(func() *sliceArrayEncoder { return &sliceArrayEncoder{ elems: make([]interface{}, 0, 2), } }) func getSliceEncoder() *sliceArrayEncoder { return _sliceEncoderPool.Get() } func putSliceEncoder(e *sliceArrayEncoder) { e.elems = e.elems[:0] _sliceEncoderPool.Put(e) } type consoleEncoder struct { *jsonEncoder } // NewConsoleEncoder creates an encoder whose output is designed for human - // rather than machine - consumption. It serializes the core log entry data // (message, level, timestamp, etc.) in a plain-text format and leaves the // structured context as JSON. // // Note that although the console encoder doesn't use the keys specified in the // encoder configuration, it will omit any element whose key is set to the empty // string. func NewConsoleEncoder(cfg EncoderConfig) Encoder { if cfg.ConsoleSeparator == "" { // Use a default delimiter of '\t' for backwards compatibility cfg.ConsoleSeparator = "\t" } return consoleEncoder{newJSONEncoder(cfg, true)} } func (c consoleEncoder) Clone() Encoder { return consoleEncoder{c.jsonEncoder.Clone().(*jsonEncoder)} } func (c consoleEncoder) EncodeEntry(ent Entry, fields []Field) (*buffer.Buffer, error) { line := bufferpool.Get() // We don't want the entry's metadata to be quoted and escaped (if it's // encoded as strings), which means that we can't use the JSON encoder. The // simplest option is to use the memory encoder and fmt.Fprint. // // If this ever becomes a performance bottleneck, we can implement // ArrayEncoder for our plain-text format. arr := getSliceEncoder() if c.TimeKey != "" && c.EncodeTime != nil && !ent.Time.IsZero() { c.EncodeTime(ent.Time, arr) } if c.LevelKey != "" && c.EncodeLevel != nil { c.EncodeLevel(ent.Level, arr) } if ent.LoggerName != "" && c.NameKey != "" { nameEncoder := c.EncodeName if nameEncoder == nil { // Fall back to FullNameEncoder for backward compatibility. nameEncoder = FullNameEncoder } nameEncoder(ent.LoggerName, arr) } if ent.Caller.Defined { if c.CallerKey != "" && c.EncodeCaller != nil { c.EncodeCaller(ent.Caller, arr) } if c.FunctionKey != "" { arr.AppendString(ent.Caller.Function) } } for i := range arr.elems { if i > 0 { line.AppendString(c.ConsoleSeparator) } fmt.Fprint(line, arr.elems[i]) } putSliceEncoder(arr) // Add the message itself. if c.MessageKey != "" { c.addSeparatorIfNecessary(line) line.AppendString(ent.Message) } // Add any structured context. c.writeContext(line, fields) // If there's no stacktrace key, honor that; this allows users to force // single-line output. if ent.Stack != "" && c.StacktraceKey != "" { line.AppendByte('\n') line.AppendString(ent.Stack) } line.AppendString(c.LineEnding) return line, nil } func (c consoleEncoder) writeContext(line *buffer.Buffer, extra []Field) { context := c.jsonEncoder.Clone().(*jsonEncoder) defer func() { // putJSONEncoder assumes the buffer is still used, but we write out the buffer so // we can free it. context.buf.Free() putJSONEncoder(context) }() addFields(context, extra) context.closeOpenNamespaces() if context.buf.Len() == 0 { return } c.addSeparatorIfNecessary(line) line.AppendByte('{') line.Write(context.buf.Bytes()) line.AppendByte('}') } func (c consoleEncoder) addSeparatorIfNecessary(line *buffer.Buffer) { if line.Len() > 0 { line.AppendString(c.ConsoleSeparator) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/core.go
vendor/go.uber.org/zap/zapcore/core.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore // Core is a minimal, fast logger interface. It's designed for library authors // to wrap in a more user-friendly API. type Core interface { LevelEnabler // With adds structured context to the Core. With([]Field) Core // Check determines whether the supplied Entry should be logged (using the // embedded LevelEnabler and possibly some extra logic). If the entry // should be logged, the Core adds itself to the CheckedEntry and returns // the result. // // Callers must use Check before calling Write. Check(Entry, *CheckedEntry) *CheckedEntry // Write serializes the Entry and any Fields supplied at the log site and // writes them to their destination. // // If called, Write should always log the Entry and Fields; it should not // replicate the logic of Check. Write(Entry, []Field) error // Sync flushes buffered logs (if any). Sync() error } type nopCore struct{} // NewNopCore returns a no-op Core. func NewNopCore() Core { return nopCore{} } func (nopCore) Enabled(Level) bool { return false } func (n nopCore) With([]Field) Core { return n } func (nopCore) Check(_ Entry, ce *CheckedEntry) *CheckedEntry { return ce } func (nopCore) Write(Entry, []Field) error { return nil } func (nopCore) Sync() error { return nil } // NewCore creates a Core that writes logs to a WriteSyncer. func NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler) Core { return &ioCore{ LevelEnabler: enab, enc: enc, out: ws, } } type ioCore struct { LevelEnabler enc Encoder out WriteSyncer } var ( _ Core = (*ioCore)(nil) _ leveledEnabler = (*ioCore)(nil) ) func (c *ioCore) Level() Level { return LevelOf(c.LevelEnabler) } func (c *ioCore) With(fields []Field) Core { clone := c.clone() addFields(clone.enc, fields) return clone } func (c *ioCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { if c.Enabled(ent.Level) { return ce.AddCore(ent, c) } return ce } func (c *ioCore) Write(ent Entry, fields []Field) error { buf, err := c.enc.EncodeEntry(ent, fields) if err != nil { return err } _, err = c.out.Write(buf.Bytes()) buf.Free() if err != nil { return err } if ent.Level > ErrorLevel { // Since we may be crashing the program, sync the output. // Ignore Sync errors, pending a clean solution to issue #370. _ = c.Sync() } return nil } func (c *ioCore) Sync() error { return c.out.Sync() } func (c *ioCore) clone() *ioCore { return &ioCore{ LevelEnabler: c.LevelEnabler, enc: c.enc.Clone(), out: c.out, } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/clock.go
vendor/go.uber.org/zap/zapcore/clock.go
// Copyright (c) 2021 Uber Technologies, Inc. // // 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. package zapcore import "time" // DefaultClock is the default clock used by Zap in operations that require // time. This clock uses the system clock for all operations. var DefaultClock = systemClock{} // Clock is a source of time for logged entries. type Clock interface { // Now returns the current local time. Now() time.Time // NewTicker returns *time.Ticker that holds a channel // that delivers "ticks" of a clock. NewTicker(time.Duration) *time.Ticker } // systemClock implements default Clock that uses system time. type systemClock struct{} func (systemClock) Now() time.Time { return time.Now() } func (systemClock) NewTicker(duration time.Duration) *time.Ticker { return time.NewTicker(duration) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/doc.go
vendor/go.uber.org/zap/zapcore/doc.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. // Package zapcore defines and implements the low-level interfaces upon which // zap is built. By providing alternate implementations of these interfaces, // external packages can extend zap's capabilities. package zapcore // import "go.uber.org/zap/zapcore"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/increase_level.go
vendor/go.uber.org/zap/zapcore/increase_level.go
// Copyright (c) 2020 Uber Technologies, Inc. // // 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. package zapcore import "fmt" type levelFilterCore struct { core Core level LevelEnabler } var ( _ Core = (*levelFilterCore)(nil) _ leveledEnabler = (*levelFilterCore)(nil) ) // NewIncreaseLevelCore creates a core that can be used to increase the level of // an existing Core. It cannot be used to decrease the logging level, as it acts // as a filter before calling the underlying core. If level decreases the log level, // an error is returned. func NewIncreaseLevelCore(core Core, level LevelEnabler) (Core, error) { for l := _maxLevel; l >= _minLevel; l-- { if !core.Enabled(l) && level.Enabled(l) { return nil, fmt.Errorf("invalid increase level, as level %q is allowed by increased level, but not by existing core", l) } } return &levelFilterCore{core, level}, nil } func (c *levelFilterCore) Enabled(lvl Level) bool { return c.level.Enabled(lvl) } func (c *levelFilterCore) Level() Level { return LevelOf(c.level) } func (c *levelFilterCore) With(fields []Field) Core { return &levelFilterCore{c.core.With(fields), c.level} } func (c *levelFilterCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { if !c.Enabled(ent.Level) { return ce } return c.core.Check(ent, ce) } func (c *levelFilterCore) Write(ent Entry, fields []Field) error { return c.core.Write(ent, fields) } func (c *levelFilterCore) Sync() error { return c.core.Sync() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/encoder.go
vendor/go.uber.org/zap/zapcore/encoder.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore import ( "encoding/json" "io" "time" "go.uber.org/zap/buffer" ) // DefaultLineEnding defines the default line ending when writing logs. // Alternate line endings specified in EncoderConfig can override this // behavior. const DefaultLineEnding = "\n" // OmitKey defines the key to use when callers want to remove a key from log output. const OmitKey = "" // A LevelEncoder serializes a Level to a primitive type. // // This function must make exactly one call // to a PrimitiveArrayEncoder's Append* method. type LevelEncoder func(Level, PrimitiveArrayEncoder) // LowercaseLevelEncoder serializes a Level to a lowercase string. For example, // InfoLevel is serialized to "info". func LowercaseLevelEncoder(l Level, enc PrimitiveArrayEncoder) { enc.AppendString(l.String()) } // LowercaseColorLevelEncoder serializes a Level to a lowercase string and adds coloring. // For example, InfoLevel is serialized to "info" and colored blue. func LowercaseColorLevelEncoder(l Level, enc PrimitiveArrayEncoder) { s, ok := _levelToLowercaseColorString[l] if !ok { s = _unknownLevelColor.Add(l.String()) } enc.AppendString(s) } // CapitalLevelEncoder serializes a Level to an all-caps string. For example, // InfoLevel is serialized to "INFO". func CapitalLevelEncoder(l Level, enc PrimitiveArrayEncoder) { enc.AppendString(l.CapitalString()) } // CapitalColorLevelEncoder serializes a Level to an all-caps string and adds color. // For example, InfoLevel is serialized to "INFO" and colored blue. func CapitalColorLevelEncoder(l Level, enc PrimitiveArrayEncoder) { s, ok := _levelToCapitalColorString[l] if !ok { s = _unknownLevelColor.Add(l.CapitalString()) } enc.AppendString(s) } // UnmarshalText unmarshals text to a LevelEncoder. "capital" is unmarshaled to // CapitalLevelEncoder, "coloredCapital" is unmarshaled to CapitalColorLevelEncoder, // "colored" is unmarshaled to LowercaseColorLevelEncoder, and anything else // is unmarshaled to LowercaseLevelEncoder. func (e *LevelEncoder) UnmarshalText(text []byte) error { switch string(text) { case "capital": *e = CapitalLevelEncoder case "capitalColor": *e = CapitalColorLevelEncoder case "color": *e = LowercaseColorLevelEncoder default: *e = LowercaseLevelEncoder } return nil } // A TimeEncoder serializes a time.Time to a primitive type. // // This function must make exactly one call // to a PrimitiveArrayEncoder's Append* method. type TimeEncoder func(time.Time, PrimitiveArrayEncoder) // EpochTimeEncoder serializes a time.Time to a floating-point number of seconds // since the Unix epoch. func EpochTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { nanos := t.UnixNano() sec := float64(nanos) / float64(time.Second) enc.AppendFloat64(sec) } // EpochMillisTimeEncoder serializes a time.Time to a floating-point number of // milliseconds since the Unix epoch. func EpochMillisTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { nanos := t.UnixNano() millis := float64(nanos) / float64(time.Millisecond) enc.AppendFloat64(millis) } // EpochNanosTimeEncoder serializes a time.Time to an integer number of // nanoseconds since the Unix epoch. func EpochNanosTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { enc.AppendInt64(t.UnixNano()) } func encodeTimeLayout(t time.Time, layout string, enc PrimitiveArrayEncoder) { type appendTimeEncoder interface { AppendTimeLayout(time.Time, string) } if enc, ok := enc.(appendTimeEncoder); ok { enc.AppendTimeLayout(t, layout) return } enc.AppendString(t.Format(layout)) } // ISO8601TimeEncoder serializes a time.Time to an ISO8601-formatted string // with millisecond precision. // // If enc supports AppendTimeLayout(t time.Time,layout string), it's used // instead of appending a pre-formatted string value. func ISO8601TimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { encodeTimeLayout(t, "2006-01-02T15:04:05.000Z0700", enc) } // RFC3339TimeEncoder serializes a time.Time to an RFC3339-formatted string. // // If enc supports AppendTimeLayout(t time.Time,layout string), it's used // instead of appending a pre-formatted string value. func RFC3339TimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { encodeTimeLayout(t, time.RFC3339, enc) } // RFC3339NanoTimeEncoder serializes a time.Time to an RFC3339-formatted string // with nanosecond precision. // // If enc supports AppendTimeLayout(t time.Time,layout string), it's used // instead of appending a pre-formatted string value. func RFC3339NanoTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { encodeTimeLayout(t, time.RFC3339Nano, enc) } // TimeEncoderOfLayout returns TimeEncoder which serializes a time.Time using // given layout. func TimeEncoderOfLayout(layout string) TimeEncoder { return func(t time.Time, enc PrimitiveArrayEncoder) { encodeTimeLayout(t, layout, enc) } } // UnmarshalText unmarshals text to a TimeEncoder. // "rfc3339nano" and "RFC3339Nano" are unmarshaled to RFC3339NanoTimeEncoder. // "rfc3339" and "RFC3339" are unmarshaled to RFC3339TimeEncoder. // "iso8601" and "ISO8601" are unmarshaled to ISO8601TimeEncoder. // "millis" is unmarshaled to EpochMillisTimeEncoder. // "nanos" is unmarshaled to EpochNanosEncoder. // Anything else is unmarshaled to EpochTimeEncoder. func (e *TimeEncoder) UnmarshalText(text []byte) error { switch string(text) { case "rfc3339nano", "RFC3339Nano": *e = RFC3339NanoTimeEncoder case "rfc3339", "RFC3339": *e = RFC3339TimeEncoder case "iso8601", "ISO8601": *e = ISO8601TimeEncoder case "millis": *e = EpochMillisTimeEncoder case "nanos": *e = EpochNanosTimeEncoder default: *e = EpochTimeEncoder } return nil } // UnmarshalYAML unmarshals YAML to a TimeEncoder. // If value is an object with a "layout" field, it will be unmarshaled to TimeEncoder with given layout. // // timeEncoder: // layout: 06/01/02 03:04pm // // If value is string, it uses UnmarshalText. // // timeEncoder: iso8601 func (e *TimeEncoder) UnmarshalYAML(unmarshal func(interface{}) error) error { var o struct { Layout string `json:"layout" yaml:"layout"` } if err := unmarshal(&o); err == nil { *e = TimeEncoderOfLayout(o.Layout) return nil } var s string if err := unmarshal(&s); err != nil { return err } return e.UnmarshalText([]byte(s)) } // UnmarshalJSON unmarshals JSON to a TimeEncoder as same way UnmarshalYAML does. func (e *TimeEncoder) UnmarshalJSON(data []byte) error { return e.UnmarshalYAML(func(v interface{}) error { return json.Unmarshal(data, v) }) } // A DurationEncoder serializes a time.Duration to a primitive type. // // This function must make exactly one call // to a PrimitiveArrayEncoder's Append* method. type DurationEncoder func(time.Duration, PrimitiveArrayEncoder) // SecondsDurationEncoder serializes a time.Duration to a floating-point number of seconds elapsed. func SecondsDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { enc.AppendFloat64(float64(d) / float64(time.Second)) } // NanosDurationEncoder serializes a time.Duration to an integer number of // nanoseconds elapsed. func NanosDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { enc.AppendInt64(int64(d)) } // MillisDurationEncoder serializes a time.Duration to an integer number of // milliseconds elapsed. func MillisDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { enc.AppendInt64(d.Nanoseconds() / 1e6) } // StringDurationEncoder serializes a time.Duration using its built-in String // method. func StringDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { enc.AppendString(d.String()) } // UnmarshalText unmarshals text to a DurationEncoder. "string" is unmarshaled // to StringDurationEncoder, and anything else is unmarshaled to // NanosDurationEncoder. func (e *DurationEncoder) UnmarshalText(text []byte) error { switch string(text) { case "string": *e = StringDurationEncoder case "nanos": *e = NanosDurationEncoder case "ms": *e = MillisDurationEncoder default: *e = SecondsDurationEncoder } return nil } // A CallerEncoder serializes an EntryCaller to a primitive type. // // This function must make exactly one call // to a PrimitiveArrayEncoder's Append* method. type CallerEncoder func(EntryCaller, PrimitiveArrayEncoder) // FullCallerEncoder serializes a caller in /full/path/to/package/file:line // format. func FullCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder) { // TODO: consider using a byte-oriented API to save an allocation. enc.AppendString(caller.String()) } // ShortCallerEncoder serializes a caller in package/file:line format, trimming // all but the final directory from the full path. func ShortCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder) { // TODO: consider using a byte-oriented API to save an allocation. enc.AppendString(caller.TrimmedPath()) } // UnmarshalText unmarshals text to a CallerEncoder. "full" is unmarshaled to // FullCallerEncoder and anything else is unmarshaled to ShortCallerEncoder. func (e *CallerEncoder) UnmarshalText(text []byte) error { switch string(text) { case "full": *e = FullCallerEncoder default: *e = ShortCallerEncoder } return nil } // A NameEncoder serializes a period-separated logger name to a primitive // type. // // This function must make exactly one call // to a PrimitiveArrayEncoder's Append* method. type NameEncoder func(string, PrimitiveArrayEncoder) // FullNameEncoder serializes the logger name as-is. func FullNameEncoder(loggerName string, enc PrimitiveArrayEncoder) { enc.AppendString(loggerName) } // UnmarshalText unmarshals text to a NameEncoder. Currently, everything is // unmarshaled to FullNameEncoder. func (e *NameEncoder) UnmarshalText(text []byte) error { switch string(text) { case "full": *e = FullNameEncoder default: *e = FullNameEncoder } return nil } // An EncoderConfig allows users to configure the concrete encoders supplied by // zapcore. type EncoderConfig struct { // Set the keys used for each log entry. If any key is empty, that portion // of the entry is omitted. MessageKey string `json:"messageKey" yaml:"messageKey"` LevelKey string `json:"levelKey" yaml:"levelKey"` TimeKey string `json:"timeKey" yaml:"timeKey"` NameKey string `json:"nameKey" yaml:"nameKey"` CallerKey string `json:"callerKey" yaml:"callerKey"` FunctionKey string `json:"functionKey" yaml:"functionKey"` StacktraceKey string `json:"stacktraceKey" yaml:"stacktraceKey"` SkipLineEnding bool `json:"skipLineEnding" yaml:"skipLineEnding"` LineEnding string `json:"lineEnding" yaml:"lineEnding"` // Configure the primitive representations of common complex types. For // example, some users may want all time.Times serialized as floating-point // seconds since epoch, while others may prefer ISO8601 strings. EncodeLevel LevelEncoder `json:"levelEncoder" yaml:"levelEncoder"` EncodeTime TimeEncoder `json:"timeEncoder" yaml:"timeEncoder"` EncodeDuration DurationEncoder `json:"durationEncoder" yaml:"durationEncoder"` EncodeCaller CallerEncoder `json:"callerEncoder" yaml:"callerEncoder"` // Unlike the other primitive type encoders, EncodeName is optional. The // zero value falls back to FullNameEncoder. EncodeName NameEncoder `json:"nameEncoder" yaml:"nameEncoder"` // Configure the encoder for interface{} type objects. // If not provided, objects are encoded using json.Encoder NewReflectedEncoder func(io.Writer) ReflectedEncoder `json:"-" yaml:"-"` // Configures the field separator used by the console encoder. Defaults // to tab. ConsoleSeparator string `json:"consoleSeparator" yaml:"consoleSeparator"` } // ObjectEncoder is a strongly-typed, encoding-agnostic interface for adding a // map- or struct-like object to the logging context. Like maps, ObjectEncoders // aren't safe for concurrent use (though typical use shouldn't require locks). type ObjectEncoder interface { // Logging-specific marshalers. AddArray(key string, marshaler ArrayMarshaler) error AddObject(key string, marshaler ObjectMarshaler) error // Built-in types. AddBinary(key string, value []byte) // for arbitrary bytes AddByteString(key string, value []byte) // for UTF-8 encoded bytes AddBool(key string, value bool) AddComplex128(key string, value complex128) AddComplex64(key string, value complex64) AddDuration(key string, value time.Duration) AddFloat64(key string, value float64) AddFloat32(key string, value float32) AddInt(key string, value int) AddInt64(key string, value int64) AddInt32(key string, value int32) AddInt16(key string, value int16) AddInt8(key string, value int8) AddString(key, value string) AddTime(key string, value time.Time) AddUint(key string, value uint) AddUint64(key string, value uint64) AddUint32(key string, value uint32) AddUint16(key string, value uint16) AddUint8(key string, value uint8) AddUintptr(key string, value uintptr) // AddReflected uses reflection to serialize arbitrary objects, so it can be // slow and allocation-heavy. AddReflected(key string, value interface{}) error // OpenNamespace opens an isolated namespace where all subsequent fields will // be added. Applications can use namespaces to prevent key collisions when // injecting loggers into sub-components or third-party libraries. OpenNamespace(key string) } // ArrayEncoder is a strongly-typed, encoding-agnostic interface for adding // array-like objects to the logging context. Of note, it supports mixed-type // arrays even though they aren't typical in Go. Like slices, ArrayEncoders // aren't safe for concurrent use (though typical use shouldn't require locks). type ArrayEncoder interface { // Built-in types. PrimitiveArrayEncoder // Time-related types. AppendDuration(time.Duration) AppendTime(time.Time) // Logging-specific marshalers. AppendArray(ArrayMarshaler) error AppendObject(ObjectMarshaler) error // AppendReflected uses reflection to serialize arbitrary objects, so it's // slow and allocation-heavy. AppendReflected(value interface{}) error } // PrimitiveArrayEncoder is the subset of the ArrayEncoder interface that deals // only in Go's built-in types. It's included only so that Duration- and // TimeEncoders cannot trigger infinite recursion. type PrimitiveArrayEncoder interface { // Built-in types. AppendBool(bool) AppendByteString([]byte) // for UTF-8 encoded bytes AppendComplex128(complex128) AppendComplex64(complex64) AppendFloat64(float64) AppendFloat32(float32) AppendInt(int) AppendInt64(int64) AppendInt32(int32) AppendInt16(int16) AppendInt8(int8) AppendString(string) AppendUint(uint) AppendUint64(uint64) AppendUint32(uint32) AppendUint16(uint16) AppendUint8(uint8) AppendUintptr(uintptr) } // Encoder is a format-agnostic interface for all log entry marshalers. Since // log encoders don't need to support the same wide range of use cases as // general-purpose marshalers, it's possible to make them faster and // lower-allocation. // // Implementations of the ObjectEncoder interface's methods can, of course, // freely modify the receiver. However, the Clone and EncodeEntry methods will // be called concurrently and shouldn't modify the receiver. type Encoder interface { ObjectEncoder // Clone copies the encoder, ensuring that adding fields to the copy doesn't // affect the original. Clone() Encoder // EncodeEntry encodes an entry and fields, along with any accumulated // context, into a byte buffer and returns it. Any fields that are empty, // including fields on the `Entry` type, should be omitted. EncodeEntry(Entry, []Field) (*buffer.Buffer, error) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/zapcore/level_strings.go
vendor/go.uber.org/zap/zapcore/level_strings.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package zapcore import "go.uber.org/zap/internal/color" var ( _levelToColor = map[Level]color.Color{ DebugLevel: color.Magenta, InfoLevel: color.Blue, WarnLevel: color.Yellow, ErrorLevel: color.Red, DPanicLevel: color.Red, PanicLevel: color.Red, FatalLevel: color.Red, } _unknownLevelColor = color.Red _levelToLowercaseColorString = make(map[Level]string, len(_levelToColor)) _levelToCapitalColorString = make(map[Level]string, len(_levelToColor)) ) func init() { for level, color := range _levelToColor { _levelToLowercaseColorString[level] = color.Add(level.String()) _levelToCapitalColorString[level] = color.Add(level.CapitalString()) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/internal/level_enabler.go
vendor/go.uber.org/zap/internal/level_enabler.go
// Copyright (c) 2022 Uber Technologies, Inc. // // 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. // Package internal and its subpackages hold types and functionality // that are not part of Zap's public API. package internal import "go.uber.org/zap/zapcore" // LeveledEnabler is an interface satisfied by LevelEnablers that are able to // report their own level. // // This interface is defined to use more conveniently in tests and non-zapcore // packages. // This cannot be imported from zapcore because of the cyclic dependency. type LeveledEnabler interface { zapcore.LevelEnabler Level() zapcore.Level }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/internal/bufferpool/bufferpool.go
vendor/go.uber.org/zap/internal/bufferpool/bufferpool.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. // Package bufferpool houses zap's shared internal buffer pool. Third-party // packages can recreate the same functionality with buffers.NewPool. package bufferpool import "go.uber.org/zap/buffer" var ( _pool = buffer.NewPool() // Get retrieves a buffer from the pool, creating one if necessary. Get = _pool.Get )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/internal/exit/exit.go
vendor/go.uber.org/zap/internal/exit/exit.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. // Package exit provides stubs so that unit tests can exercise code that calls // os.Exit(1). package exit import "os" var _exit = os.Exit // With terminates the process by calling os.Exit(code). If the package is // stubbed, it instead records a call in the testing spy. func With(code int) { _exit(code) } // A StubbedExit is a testing fake for os.Exit. type StubbedExit struct { Exited bool Code int prev func(code int) } // Stub substitutes a fake for the call to os.Exit(1). func Stub() *StubbedExit { s := &StubbedExit{prev: _exit} _exit = s.exit return s } // WithStub runs the supplied function with Exit stubbed. It returns the stub // used, so that users can test whether the process would have crashed. func WithStub(f func()) *StubbedExit { s := Stub() defer s.Unstub() f() return s } // Unstub restores the previous exit function. func (se *StubbedExit) Unstub() { _exit = se.prev } func (se *StubbedExit) exit(code int) { se.Exited = true se.Code = code }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/internal/pool/pool.go
vendor/go.uber.org/zap/internal/pool/pool.go
// Copyright (c) 2023 Uber Technologies, Inc. // // 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. // Package pool provides internal pool utilities. package pool import ( "sync" ) // A Pool is a generic wrapper around [sync.Pool] to provide strongly-typed // object pooling. // // Note that SA6002 (ref: https://staticcheck.io/docs/checks/#SA6002) will // not be detected, so all internal pool use must take care to only store // pointer types. type Pool[T any] struct { pool sync.Pool } // New returns a new [Pool] for T, and will use fn to construct new Ts when // the pool is empty. func New[T any](fn func() T) *Pool[T] { return &Pool[T]{ pool: sync.Pool{ New: func() any { return fn() }, }, } } // Get gets a T from the pool, or creates a new one if the pool is empty. func (p *Pool[T]) Get() T { return p.pool.Get().(T) } // Put returns x into the pool. func (p *Pool[T]) Put(x T) { p.pool.Put(x) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/internal/stacktrace/stack.go
vendor/go.uber.org/zap/internal/stacktrace/stack.go
// Copyright (c) 2023 Uber Technologies, Inc. // // 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. // Package stacktrace provides support for gathering stack traces // efficiently. package stacktrace import ( "runtime" "go.uber.org/zap/buffer" "go.uber.org/zap/internal/bufferpool" "go.uber.org/zap/internal/pool" ) var _stackPool = pool.New(func() *Stack { return &Stack{ storage: make([]uintptr, 64), } }) // Stack is a captured stack trace. type Stack struct { pcs []uintptr // program counters; always a subslice of storage frames *runtime.Frames // The size of pcs varies depending on requirements: // it will be one if the only the first frame was requested, // and otherwise it will reflect the depth of the call stack. // // storage decouples the slice we need (pcs) from the slice we pool. // We will always allocate a reasonably large storage, but we'll use // only as much of it as we need. storage []uintptr } // Depth specifies how deep of a stack trace should be captured. type Depth int const ( // First captures only the first frame. First Depth = iota // Full captures the entire call stack, allocating more // storage for it if needed. Full ) // Capture captures a stack trace of the specified depth, skipping // the provided number of frames. skip=0 identifies the caller of // Capture. // // The caller must call Free on the returned stacktrace after using it. func Capture(skip int, depth Depth) *Stack { stack := _stackPool.Get() switch depth { case First: stack.pcs = stack.storage[:1] case Full: stack.pcs = stack.storage } // Unlike other "skip"-based APIs, skip=0 identifies runtime.Callers // itself. +2 to skip captureStacktrace and runtime.Callers. numFrames := runtime.Callers( skip+2, stack.pcs, ) // runtime.Callers truncates the recorded stacktrace if there is no // room in the provided slice. For the full stack trace, keep expanding // storage until there are fewer frames than there is room. if depth == Full { pcs := stack.pcs for numFrames == len(pcs) { pcs = make([]uintptr, len(pcs)*2) numFrames = runtime.Callers(skip+2, pcs) } // Discard old storage instead of returning it to the pool. // This will adjust the pool size over time if stack traces are // consistently very deep. stack.storage = pcs stack.pcs = pcs[:numFrames] } else { stack.pcs = stack.pcs[:numFrames] } stack.frames = runtime.CallersFrames(stack.pcs) return stack } // Free releases resources associated with this stacktrace // and returns it back to the pool. func (st *Stack) Free() { st.frames = nil st.pcs = nil _stackPool.Put(st) } // Count reports the total number of frames in this stacktrace. // Count DOES NOT change as Next is called. func (st *Stack) Count() int { return len(st.pcs) } // Next returns the next frame in the stack trace, // and a boolean indicating whether there are more after it. func (st *Stack) Next() (_ runtime.Frame, more bool) { return st.frames.Next() } // Take returns a string representation of the current stacktrace. // // skip is the number of frames to skip before recording the stack trace. // skip=0 identifies the caller of Take. func Take(skip int) string { stack := Capture(skip+1, Full) defer stack.Free() buffer := bufferpool.Get() defer buffer.Free() stackfmt := NewFormatter(buffer) stackfmt.FormatStack(stack) return buffer.String() } // Formatter formats a stack trace into a readable string representation. type Formatter struct { b *buffer.Buffer nonEmpty bool // whehther we've written at least one frame already } // NewFormatter builds a new Formatter. func NewFormatter(b *buffer.Buffer) Formatter { return Formatter{b: b} } // FormatStack formats all remaining frames in the provided stacktrace -- minus // the final runtime.main/runtime.goexit frame. func (sf *Formatter) FormatStack(stack *Stack) { // Note: On the last iteration, frames.Next() returns false, with a valid // frame, but we ignore this frame. The last frame is a runtime frame which // adds noise, since it's only either runtime.main or runtime.goexit. for frame, more := stack.Next(); more; frame, more = stack.Next() { sf.FormatFrame(frame) } } // FormatFrame formats the given frame. func (sf *Formatter) FormatFrame(frame runtime.Frame) { if sf.nonEmpty { sf.b.AppendByte('\n') } sf.nonEmpty = true sf.b.AppendString(frame.Function) sf.b.AppendByte('\n') sf.b.AppendByte('\t') sf.b.AppendString(frame.File) sf.b.AppendByte(':') sf.b.AppendInt(int64(frame.Line)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/internal/color/color.go
vendor/go.uber.org/zap/internal/color/color.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. // Package color adds coloring functionality for TTY output. package color import "fmt" // Foreground colors. const ( Black Color = iota + 30 Red Green Yellow Blue Magenta Cyan White ) // Color represents a text color. type Color uint8 // Add adds the coloring to the given string. func (c Color) Add(s string) string { return fmt.Sprintf("\x1b[%dm%s\x1b[0m", uint8(c), s) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/buffer/buffer.go
vendor/go.uber.org/zap/buffer/buffer.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. // Package buffer provides a thin wrapper around a byte slice. Unlike the // standard library's bytes.Buffer, it supports a portion of the strconv // package's zero-allocation formatters. package buffer // import "go.uber.org/zap/buffer" import ( "strconv" "time" ) const _size = 1024 // by default, create 1 KiB buffers // Buffer is a thin wrapper around a byte slice. It's intended to be pooled, so // the only way to construct one is via a Pool. type Buffer struct { bs []byte pool Pool } // AppendByte writes a single byte to the Buffer. func (b *Buffer) AppendByte(v byte) { b.bs = append(b.bs, v) } // AppendBytes writes the given slice of bytes to the Buffer. func (b *Buffer) AppendBytes(v []byte) { b.bs = append(b.bs, v...) } // AppendString writes a string to the Buffer. func (b *Buffer) AppendString(s string) { b.bs = append(b.bs, s...) } // AppendInt appends an integer to the underlying buffer (assuming base 10). func (b *Buffer) AppendInt(i int64) { b.bs = strconv.AppendInt(b.bs, i, 10) } // AppendTime appends the time formatted using the specified layout. func (b *Buffer) AppendTime(t time.Time, layout string) { b.bs = t.AppendFormat(b.bs, layout) } // AppendUint appends an unsigned integer to the underlying buffer (assuming // base 10). func (b *Buffer) AppendUint(i uint64) { b.bs = strconv.AppendUint(b.bs, i, 10) } // AppendBool appends a bool to the underlying buffer. func (b *Buffer) AppendBool(v bool) { b.bs = strconv.AppendBool(b.bs, v) } // AppendFloat appends a float to the underlying buffer. It doesn't quote NaN // or +/- Inf. func (b *Buffer) AppendFloat(f float64, bitSize int) { b.bs = strconv.AppendFloat(b.bs, f, 'f', -1, bitSize) } // Len returns the length of the underlying byte slice. func (b *Buffer) Len() int { return len(b.bs) } // Cap returns the capacity of the underlying byte slice. func (b *Buffer) Cap() int { return cap(b.bs) } // Bytes returns a mutable reference to the underlying byte slice. func (b *Buffer) Bytes() []byte { return b.bs } // String returns a string copy of the underlying byte slice. func (b *Buffer) String() string { return string(b.bs) } // Reset resets the underlying byte slice. Subsequent writes re-use the slice's // backing array. func (b *Buffer) Reset() { b.bs = b.bs[:0] } // Write implements io.Writer. func (b *Buffer) Write(bs []byte) (int, error) { b.bs = append(b.bs, bs...) return len(bs), nil } // WriteByte writes a single byte to the Buffer. // // Error returned is always nil, function signature is compatible // with bytes.Buffer and bufio.Writer func (b *Buffer) WriteByte(v byte) error { b.AppendByte(v) return nil } // WriteString writes a string to the Buffer. // // Error returned is always nil, function signature is compatible // with bytes.Buffer and bufio.Writer func (b *Buffer) WriteString(s string) (int, error) { b.AppendString(s) return len(s), nil } // TrimNewline trims any final "\n" byte from the end of the buffer. func (b *Buffer) TrimNewline() { if i := len(b.bs) - 1; i >= 0 { if b.bs[i] == '\n' { b.bs = b.bs[:i] } } } // Free returns the Buffer to its Pool. // // Callers must not retain references to the Buffer after calling Free. func (b *Buffer) Free() { b.pool.put(b) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.uber.org/zap/buffer/pool.go
vendor/go.uber.org/zap/buffer/pool.go
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package buffer import ( "go.uber.org/zap/internal/pool" ) // A Pool is a type-safe wrapper around a sync.Pool. type Pool struct { p *pool.Pool[*Buffer] } // NewPool constructs a new Pool. func NewPool() Pool { return Pool{ p: pool.New(func() *Buffer { return &Buffer{ bs: make([]byte, 0, _size), } }), } } // Get retrieves a Buffer from the pool, creating one if necessary. func (p Pool) Get() *Buffer { buf := p.p.Get() buf.Reset() buf.pool = p return buf } func (p Pool) put(buf *Buffer) { p.p.Put(buf) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/encoding/prototext/encode.go
vendor/google.golang.org/protobuf/encoding/prototext/encode.go
// Copyright 2018 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. package prototext import ( "fmt" "strconv" "unicode/utf8" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/encoding/text" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/flags" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/order" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ) const defaultIndent = " " // Format formats the message as a multiline string. // This function is only intended for human consumption and ignores errors. // Do not depend on the output being stable. Its output will change across // different builds of your program, even when using the same version of the // protobuf module. func Format(m proto.Message) string { return MarshalOptions{Multiline: true}.Format(m) } // Marshal writes the given [proto.Message] in textproto format using default // options. Do not depend on the output being stable. Its output will change // across different builds of your program, even when using the same version of // the protobuf module. func Marshal(m proto.Message) ([]byte, error) { return MarshalOptions{}.Marshal(m) } // MarshalOptions is a configurable text format marshaler. type MarshalOptions struct { pragma.NoUnkeyedLiterals // Multiline specifies whether the marshaler should format the output in // indented-form with every textual element on a new line. // If Indent is an empty string, then an arbitrary indent is chosen. Multiline bool // Indent specifies the set of indentation characters to use in a multiline // formatted output such that every entry is preceded by Indent and // terminated by a newline. If non-empty, then Multiline is treated as true. // Indent can only be composed of space or tab characters. Indent string // EmitASCII specifies whether to format strings and bytes as ASCII only // as opposed to using UTF-8 encoding when possible. EmitASCII bool // allowInvalidUTF8 specifies whether to permit the encoding of strings // with invalid UTF-8. This is unexported as it is intended to only // be specified by the Format method. allowInvalidUTF8 bool // AllowPartial allows messages that have missing required fields to marshal // without returning an error. If AllowPartial is false (the default), // Marshal will return error if there are any missing required fields. AllowPartial bool // EmitUnknown specifies whether to emit unknown fields in the output. // If specified, the unmarshaler may be unable to parse the output. // The default is to exclude unknown fields. EmitUnknown bool // Resolver is used for looking up types when expanding google.protobuf.Any // messages. If nil, this defaults to using protoregistry.GlobalTypes. Resolver interface { protoregistry.ExtensionTypeResolver protoregistry.MessageTypeResolver } } // Format formats the message as a string. // This method is only intended for human consumption and ignores errors. // Do not depend on the output being stable. Its output will change across // different builds of your program, even when using the same version of the // protobuf module. func (o MarshalOptions) Format(m proto.Message) string { if m == nil || !m.ProtoReflect().IsValid() { return "<nil>" // invalid syntax, but okay since this is for debugging } o.allowInvalidUTF8 = true o.AllowPartial = true o.EmitUnknown = true b, _ := o.Marshal(m) return string(b) } // Marshal writes the given [proto.Message] in textproto format using options in // MarshalOptions object. Do not depend on the output being stable. Its output // will change across different builds of your program, even when using the // same version of the protobuf module. func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) { return o.marshal(nil, m) } // MarshalAppend appends the textproto format encoding of m to b, // returning the result. func (o MarshalOptions) MarshalAppend(b []byte, m proto.Message) ([]byte, error) { return o.marshal(b, m) } // marshal is a centralized function that all marshal operations go through. // For profiling purposes, avoid changing the name of this function or // introducing other code paths for marshal that do not go through this. func (o MarshalOptions) marshal(b []byte, m proto.Message) ([]byte, error) { var delims = [2]byte{'{', '}'} if o.Multiline && o.Indent == "" { o.Indent = defaultIndent } if o.Resolver == nil { o.Resolver = protoregistry.GlobalTypes } internalEnc, err := text.NewEncoder(b, o.Indent, delims, o.EmitASCII) if err != nil { return nil, err } // Treat nil message interface as an empty message, // in which case there is nothing to output. if m == nil { return b, nil } enc := encoder{internalEnc, o} err = enc.marshalMessage(m.ProtoReflect(), false) if err != nil { return nil, err } out := enc.Bytes() if len(o.Indent) > 0 && len(out) > 0 { out = append(out, '\n') } if o.AllowPartial { return out, nil } return out, proto.CheckInitialized(m) } type encoder struct { *text.Encoder opts MarshalOptions } // marshalMessage marshals the given protoreflect.Message. func (e encoder) marshalMessage(m protoreflect.Message, inclDelims bool) error { messageDesc := m.Descriptor() if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) { return errors.New("no support for proto1 MessageSets") } if inclDelims { e.StartMessage() defer e.EndMessage() } // Handle Any expansion. if messageDesc.FullName() == genid.Any_message_fullname { if e.marshalAny(m) { return nil } // If unable to expand, continue on to marshal Any as a regular message. } // Marshal fields. var err error order.RangeFields(m, order.IndexNameFieldOrder, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { if err = e.marshalField(fd.TextName(), v, fd); err != nil { return false } return true }) if err != nil { return err } // Marshal unknown fields. if e.opts.EmitUnknown { e.marshalUnknown(m.GetUnknown()) } return nil } // marshalField marshals the given field with protoreflect.Value. func (e encoder) marshalField(name string, val protoreflect.Value, fd protoreflect.FieldDescriptor) error { switch { case fd.IsList(): return e.marshalList(name, val.List(), fd) case fd.IsMap(): return e.marshalMap(name, val.Map(), fd) default: e.WriteName(name) return e.marshalSingular(val, fd) } } // marshalSingular marshals the given non-repeated field value. This includes // all scalar types, enums, messages, and groups. func (e encoder) marshalSingular(val protoreflect.Value, fd protoreflect.FieldDescriptor) error { kind := fd.Kind() switch kind { case protoreflect.BoolKind: e.WriteBool(val.Bool()) case protoreflect.StringKind: s := val.String() if !e.opts.allowInvalidUTF8 && strs.EnforceUTF8(fd) && !utf8.ValidString(s) { return errors.InvalidUTF8(string(fd.FullName())) } e.WriteString(s) case protoreflect.Int32Kind, protoreflect.Int64Kind, protoreflect.Sint32Kind, protoreflect.Sint64Kind, protoreflect.Sfixed32Kind, protoreflect.Sfixed64Kind: e.WriteInt(val.Int()) case protoreflect.Uint32Kind, protoreflect.Uint64Kind, protoreflect.Fixed32Kind, protoreflect.Fixed64Kind: e.WriteUint(val.Uint()) case protoreflect.FloatKind: // Encoder.WriteFloat handles the special numbers NaN and infinites. e.WriteFloat(val.Float(), 32) case protoreflect.DoubleKind: // Encoder.WriteFloat handles the special numbers NaN and infinites. e.WriteFloat(val.Float(), 64) case protoreflect.BytesKind: e.WriteString(string(val.Bytes())) case protoreflect.EnumKind: num := val.Enum() if desc := fd.Enum().Values().ByNumber(num); desc != nil { e.WriteLiteral(string(desc.Name())) } else { // Use numeric value if there is no enum description. e.WriteInt(int64(num)) } case protoreflect.MessageKind, protoreflect.GroupKind: return e.marshalMessage(val.Message(), true) default: panic(fmt.Sprintf("%v has unknown kind: %v", fd.FullName(), kind)) } return nil } // marshalList marshals the given protoreflect.List as multiple name-value fields. func (e encoder) marshalList(name string, list protoreflect.List, fd protoreflect.FieldDescriptor) error { size := list.Len() for i := 0; i < size; i++ { e.WriteName(name) if err := e.marshalSingular(list.Get(i), fd); err != nil { return err } } return nil } // marshalMap marshals the given protoreflect.Map as multiple name-value fields. func (e encoder) marshalMap(name string, mmap protoreflect.Map, fd protoreflect.FieldDescriptor) error { var err error order.RangeEntries(mmap, order.GenericKeyOrder, func(key protoreflect.MapKey, val protoreflect.Value) bool { e.WriteName(name) e.StartMessage() defer e.EndMessage() e.WriteName(string(genid.MapEntry_Key_field_name)) err = e.marshalSingular(key.Value(), fd.MapKey()) if err != nil { return false } e.WriteName(string(genid.MapEntry_Value_field_name)) err = e.marshalSingular(val, fd.MapValue()) if err != nil { return false } return true }) return err } // marshalUnknown parses the given []byte and marshals fields out. // This function assumes proper encoding in the given []byte. func (e encoder) marshalUnknown(b []byte) { const dec = 10 const hex = 16 for len(b) > 0 { num, wtype, n := protowire.ConsumeTag(b) b = b[n:] e.WriteName(strconv.FormatInt(int64(num), dec)) switch wtype { case protowire.VarintType: var v uint64 v, n = protowire.ConsumeVarint(b) e.WriteUint(v) case protowire.Fixed32Type: var v uint32 v, n = protowire.ConsumeFixed32(b) e.WriteLiteral("0x" + strconv.FormatUint(uint64(v), hex)) case protowire.Fixed64Type: var v uint64 v, n = protowire.ConsumeFixed64(b) e.WriteLiteral("0x" + strconv.FormatUint(v, hex)) case protowire.BytesType: var v []byte v, n = protowire.ConsumeBytes(b) e.WriteString(string(v)) case protowire.StartGroupType: e.StartMessage() var v []byte v, n = protowire.ConsumeGroup(num, b) e.marshalUnknown(v) e.EndMessage() default: panic(fmt.Sprintf("prototext: error parsing unknown field wire type: %v", wtype)) } b = b[n:] } } // marshalAny marshals the given google.protobuf.Any message in expanded form. // It returns true if it was able to marshal, else false. func (e encoder) marshalAny(any protoreflect.Message) bool { // Construct the embedded message. fds := any.Descriptor().Fields() fdType := fds.ByNumber(genid.Any_TypeUrl_field_number) typeURL := any.Get(fdType).String() mt, err := e.opts.Resolver.FindMessageByURL(typeURL) if err != nil { return false } m := mt.New().Interface() // Unmarshal bytes into embedded message. fdValue := fds.ByNumber(genid.Any_Value_field_number) value := any.Get(fdValue) err = proto.UnmarshalOptions{ AllowPartial: true, Resolver: e.opts.Resolver, }.Unmarshal(value.Bytes(), m) if err != nil { return false } // Get current encoder position. If marshaling fails, reset encoder output // back to this position. pos := e.Snapshot() // Field name is the proto field name enclosed in []. e.WriteName("[" + typeURL + "]") err = e.marshalMessage(m.ProtoReflect(), true) if err != nil { e.Reset(pos) return false } return true }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/encoding/prototext/doc.go
vendor/google.golang.org/protobuf/encoding/prototext/doc.go
// Copyright 2019 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. // Package prototext marshals and unmarshals protocol buffer messages as the // textproto format. package prototext
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/encoding/prototext/decode.go
vendor/google.golang.org/protobuf/encoding/prototext/decode.go
// Copyright 2018 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. package prototext import ( "fmt" "unicode/utf8" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/encoding/text" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/flags" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/internal/set" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ) // Unmarshal reads the given []byte into the given [proto.Message]. // The provided message must be mutable (e.g., a non-nil pointer to a message). func Unmarshal(b []byte, m proto.Message) error { return UnmarshalOptions{}.Unmarshal(b, m) } // UnmarshalOptions is a configurable textproto format unmarshaler. type UnmarshalOptions struct { pragma.NoUnkeyedLiterals // AllowPartial accepts input for messages that will result in missing // required fields. If AllowPartial is false (the default), Unmarshal will // return error if there are any missing required fields. AllowPartial bool // DiscardUnknown specifies whether to ignore unknown fields when parsing. // An unknown field is any field whose field name or field number does not // resolve to any known or extension field in the message. // By default, unmarshal rejects unknown fields as an error. DiscardUnknown bool // Resolver is used for looking up types when unmarshaling // google.protobuf.Any messages or extension fields. // If nil, this defaults to using protoregistry.GlobalTypes. Resolver interface { protoregistry.MessageTypeResolver protoregistry.ExtensionTypeResolver } } // Unmarshal reads the given []byte and populates the given [proto.Message] // using options in the UnmarshalOptions object. // The provided message must be mutable (e.g., a non-nil pointer to a message). func (o UnmarshalOptions) Unmarshal(b []byte, m proto.Message) error { return o.unmarshal(b, m) } // unmarshal is a centralized function that all unmarshal operations go through. // For profiling purposes, avoid changing the name of this function or // introducing other code paths for unmarshal that do not go through this. func (o UnmarshalOptions) unmarshal(b []byte, m proto.Message) error { proto.Reset(m) if o.Resolver == nil { o.Resolver = protoregistry.GlobalTypes } dec := decoder{text.NewDecoder(b), o} if err := dec.unmarshalMessage(m.ProtoReflect(), false); err != nil { return err } if o.AllowPartial { return nil } return proto.CheckInitialized(m) } type decoder struct { *text.Decoder opts UnmarshalOptions } // newError returns an error object with position info. func (d decoder) newError(pos int, f string, x ...any) error { line, column := d.Position(pos) head := fmt.Sprintf("(line %d:%d): ", line, column) return errors.New(head+f, x...) } // unexpectedTokenError returns a syntax error for the given unexpected token. func (d decoder) unexpectedTokenError(tok text.Token) error { return d.syntaxError(tok.Pos(), "unexpected token: %s", tok.RawString()) } // syntaxError returns a syntax error for given position. func (d decoder) syntaxError(pos int, f string, x ...any) error { line, column := d.Position(pos) head := fmt.Sprintf("syntax error (line %d:%d): ", line, column) return errors.New(head+f, x...) } // unmarshalMessage unmarshals into the given protoreflect.Message. func (d decoder) unmarshalMessage(m protoreflect.Message, checkDelims bool) error { messageDesc := m.Descriptor() if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) { return errors.New("no support for proto1 MessageSets") } if messageDesc.FullName() == genid.Any_message_fullname { return d.unmarshalAny(m, checkDelims) } if checkDelims { tok, err := d.Read() if err != nil { return err } if tok.Kind() != text.MessageOpen { return d.unexpectedTokenError(tok) } } var seenNums set.Ints var seenOneofs set.Ints fieldDescs := messageDesc.Fields() for { // Read field name. tok, err := d.Read() if err != nil { return err } switch typ := tok.Kind(); typ { case text.Name: // Continue below. case text.EOF: if checkDelims { return text.ErrUnexpectedEOF } return nil default: if checkDelims && typ == text.MessageClose { return nil } return d.unexpectedTokenError(tok) } // Resolve the field descriptor. var name protoreflect.Name var fd protoreflect.FieldDescriptor var xt protoreflect.ExtensionType var xtErr error var isFieldNumberName bool switch tok.NameKind() { case text.IdentName: name = protoreflect.Name(tok.IdentName()) fd = fieldDescs.ByTextName(string(name)) case text.TypeName: // Handle extensions only. This code path is not for Any. xt, xtErr = d.opts.Resolver.FindExtensionByName(protoreflect.FullName(tok.TypeName())) case text.FieldNumber: isFieldNumberName = true num := protoreflect.FieldNumber(tok.FieldNumber()) if !num.IsValid() { return d.newError(tok.Pos(), "invalid field number: %d", num) } fd = fieldDescs.ByNumber(num) if fd == nil { xt, xtErr = d.opts.Resolver.FindExtensionByNumber(messageDesc.FullName(), num) } } if xt != nil { fd = xt.TypeDescriptor() if !messageDesc.ExtensionRanges().Has(fd.Number()) || fd.ContainingMessage().FullName() != messageDesc.FullName() { return d.newError(tok.Pos(), "message %v cannot be extended by %v", messageDesc.FullName(), fd.FullName()) } } else if xtErr != nil && xtErr != protoregistry.NotFound { return d.newError(tok.Pos(), "unable to resolve [%s]: %v", tok.RawString(), xtErr) } // Handle unknown fields. if fd == nil { if d.opts.DiscardUnknown || messageDesc.ReservedNames().Has(name) { d.skipValue() continue } return d.newError(tok.Pos(), "unknown field: %v", tok.RawString()) } // Handle fields identified by field number. if isFieldNumberName { // TODO: Add an option to permit parsing field numbers. // // This requires careful thought as the MarshalOptions.EmitUnknown // option allows formatting unknown fields as the field number and the // best-effort textual representation of the field value. In that case, // it may not be possible to unmarshal the value from a parser that does // have information about the unknown field. return d.newError(tok.Pos(), "cannot specify field by number: %v", tok.RawString()) } switch { case fd.IsList(): kind := fd.Kind() if kind != protoreflect.MessageKind && kind != protoreflect.GroupKind && !tok.HasSeparator() { return d.syntaxError(tok.Pos(), "missing field separator :") } list := m.Mutable(fd).List() if err := d.unmarshalList(fd, list); err != nil { return err } case fd.IsMap(): mmap := m.Mutable(fd).Map() if err := d.unmarshalMap(fd, mmap); err != nil { return err } default: kind := fd.Kind() if kind != protoreflect.MessageKind && kind != protoreflect.GroupKind && !tok.HasSeparator() { return d.syntaxError(tok.Pos(), "missing field separator :") } // If field is a oneof, check if it has already been set. if od := fd.ContainingOneof(); od != nil { idx := uint64(od.Index()) if seenOneofs.Has(idx) { return d.newError(tok.Pos(), "error parsing %q, oneof %v is already set", tok.RawString(), od.FullName()) } seenOneofs.Set(idx) } num := uint64(fd.Number()) if seenNums.Has(num) { return d.newError(tok.Pos(), "non-repeated field %q is repeated", tok.RawString()) } if err := d.unmarshalSingular(fd, m); err != nil { return err } seenNums.Set(num) } } return nil } // unmarshalSingular unmarshals a non-repeated field value specified by the // given FieldDescriptor. func (d decoder) unmarshalSingular(fd protoreflect.FieldDescriptor, m protoreflect.Message) error { var val protoreflect.Value var err error switch fd.Kind() { case protoreflect.MessageKind, protoreflect.GroupKind: val = m.NewField(fd) err = d.unmarshalMessage(val.Message(), true) default: val, err = d.unmarshalScalar(fd) } if err == nil { m.Set(fd, val) } return err } // unmarshalScalar unmarshals a scalar/enum protoreflect.Value specified by the // given FieldDescriptor. func (d decoder) unmarshalScalar(fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { tok, err := d.Read() if err != nil { return protoreflect.Value{}, err } if tok.Kind() != text.Scalar { return protoreflect.Value{}, d.unexpectedTokenError(tok) } kind := fd.Kind() switch kind { case protoreflect.BoolKind: if b, ok := tok.Bool(); ok { return protoreflect.ValueOfBool(b), nil } case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: if n, ok := tok.Int32(); ok { return protoreflect.ValueOfInt32(n), nil } case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: if n, ok := tok.Int64(); ok { return protoreflect.ValueOfInt64(n), nil } case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: if n, ok := tok.Uint32(); ok { return protoreflect.ValueOfUint32(n), nil } case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: if n, ok := tok.Uint64(); ok { return protoreflect.ValueOfUint64(n), nil } case protoreflect.FloatKind: if n, ok := tok.Float32(); ok { return protoreflect.ValueOfFloat32(n), nil } case protoreflect.DoubleKind: if n, ok := tok.Float64(); ok { return protoreflect.ValueOfFloat64(n), nil } case protoreflect.StringKind: if s, ok := tok.String(); ok { if strs.EnforceUTF8(fd) && !utf8.ValidString(s) { return protoreflect.Value{}, d.newError(tok.Pos(), "contains invalid UTF-8") } return protoreflect.ValueOfString(s), nil } case protoreflect.BytesKind: if b, ok := tok.String(); ok { return protoreflect.ValueOfBytes([]byte(b)), nil } case protoreflect.EnumKind: if lit, ok := tok.Enum(); ok { // Lookup EnumNumber based on name. if enumVal := fd.Enum().Values().ByName(protoreflect.Name(lit)); enumVal != nil { return protoreflect.ValueOfEnum(enumVal.Number()), nil } } if num, ok := tok.Int32(); ok { return protoreflect.ValueOfEnum(protoreflect.EnumNumber(num)), nil } default: panic(fmt.Sprintf("invalid scalar kind %v", kind)) } return protoreflect.Value{}, d.newError(tok.Pos(), "invalid value for %v type: %v", kind, tok.RawString()) } // unmarshalList unmarshals into given protoreflect.List. A list value can // either be in [] syntax or simply just a single scalar/message value. func (d decoder) unmarshalList(fd protoreflect.FieldDescriptor, list protoreflect.List) error { tok, err := d.Peek() if err != nil { return err } switch fd.Kind() { case protoreflect.MessageKind, protoreflect.GroupKind: switch tok.Kind() { case text.ListOpen: d.Read() for { tok, err := d.Peek() if err != nil { return err } switch tok.Kind() { case text.ListClose: d.Read() return nil case text.MessageOpen: pval := list.NewElement() if err := d.unmarshalMessage(pval.Message(), true); err != nil { return err } list.Append(pval) default: return d.unexpectedTokenError(tok) } } case text.MessageOpen: pval := list.NewElement() if err := d.unmarshalMessage(pval.Message(), true); err != nil { return err } list.Append(pval) return nil } default: switch tok.Kind() { case text.ListOpen: d.Read() for { tok, err := d.Peek() if err != nil { return err } switch tok.Kind() { case text.ListClose: d.Read() return nil case text.Scalar: pval, err := d.unmarshalScalar(fd) if err != nil { return err } list.Append(pval) default: return d.unexpectedTokenError(tok) } } case text.Scalar: pval, err := d.unmarshalScalar(fd) if err != nil { return err } list.Append(pval) return nil } } return d.unexpectedTokenError(tok) } // unmarshalMap unmarshals into given protoreflect.Map. A map value is a // textproto message containing {key: <kvalue>, value: <mvalue>}. func (d decoder) unmarshalMap(fd protoreflect.FieldDescriptor, mmap protoreflect.Map) error { // Determine ahead whether map entry is a scalar type or a message type in // order to call the appropriate unmarshalMapValue func inside // unmarshalMapEntry. var unmarshalMapValue func() (protoreflect.Value, error) switch fd.MapValue().Kind() { case protoreflect.MessageKind, protoreflect.GroupKind: unmarshalMapValue = func() (protoreflect.Value, error) { pval := mmap.NewValue() if err := d.unmarshalMessage(pval.Message(), true); err != nil { return protoreflect.Value{}, err } return pval, nil } default: unmarshalMapValue = func() (protoreflect.Value, error) { return d.unmarshalScalar(fd.MapValue()) } } tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case text.MessageOpen: return d.unmarshalMapEntry(fd, mmap, unmarshalMapValue) case text.ListOpen: for { tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case text.ListClose: return nil case text.MessageOpen: if err := d.unmarshalMapEntry(fd, mmap, unmarshalMapValue); err != nil { return err } default: return d.unexpectedTokenError(tok) } } default: return d.unexpectedTokenError(tok) } } // unmarshalMap unmarshals into given protoreflect.Map. A map value is a // textproto message containing {key: <kvalue>, value: <mvalue>}. func (d decoder) unmarshalMapEntry(fd protoreflect.FieldDescriptor, mmap protoreflect.Map, unmarshalMapValue func() (protoreflect.Value, error)) error { var key protoreflect.MapKey var pval protoreflect.Value Loop: for { // Read field name. tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case text.Name: if tok.NameKind() != text.IdentName { if !d.opts.DiscardUnknown { return d.newError(tok.Pos(), "unknown map entry field %q", tok.RawString()) } d.skipValue() continue Loop } // Continue below. case text.MessageClose: break Loop default: return d.unexpectedTokenError(tok) } switch name := protoreflect.Name(tok.IdentName()); name { case genid.MapEntry_Key_field_name: if !tok.HasSeparator() { return d.syntaxError(tok.Pos(), "missing field separator :") } if key.IsValid() { return d.newError(tok.Pos(), "map entry %q cannot be repeated", name) } val, err := d.unmarshalScalar(fd.MapKey()) if err != nil { return err } key = val.MapKey() case genid.MapEntry_Value_field_name: if kind := fd.MapValue().Kind(); (kind != protoreflect.MessageKind) && (kind != protoreflect.GroupKind) { if !tok.HasSeparator() { return d.syntaxError(tok.Pos(), "missing field separator :") } } if pval.IsValid() { return d.newError(tok.Pos(), "map entry %q cannot be repeated", name) } pval, err = unmarshalMapValue() if err != nil { return err } default: if !d.opts.DiscardUnknown { return d.newError(tok.Pos(), "unknown map entry field %q", name) } d.skipValue() } } if !key.IsValid() { key = fd.MapKey().Default().MapKey() } if !pval.IsValid() { switch fd.MapValue().Kind() { case protoreflect.MessageKind, protoreflect.GroupKind: // If value field is not set for message/group types, construct an // empty one as default. pval = mmap.NewValue() default: pval = fd.MapValue().Default() } } mmap.Set(key, pval) return nil } // unmarshalAny unmarshals an Any textproto. It can either be in expanded form // or non-expanded form. func (d decoder) unmarshalAny(m protoreflect.Message, checkDelims bool) error { var typeURL string var bValue []byte var seenTypeUrl bool var seenValue bool var isExpanded bool if checkDelims { tok, err := d.Read() if err != nil { return err } if tok.Kind() != text.MessageOpen { return d.unexpectedTokenError(tok) } } Loop: for { // Read field name. Can only have 3 possible field names, i.e. type_url, // value and type URL name inside []. tok, err := d.Read() if err != nil { return err } if typ := tok.Kind(); typ != text.Name { if checkDelims { if typ == text.MessageClose { break Loop } } else if typ == text.EOF { break Loop } return d.unexpectedTokenError(tok) } switch tok.NameKind() { case text.IdentName: // Both type_url and value fields require field separator :. if !tok.HasSeparator() { return d.syntaxError(tok.Pos(), "missing field separator :") } switch name := protoreflect.Name(tok.IdentName()); name { case genid.Any_TypeUrl_field_name: if seenTypeUrl { return d.newError(tok.Pos(), "duplicate %v field", genid.Any_TypeUrl_field_fullname) } if isExpanded { return d.newError(tok.Pos(), "conflict with [%s] field", typeURL) } tok, err := d.Read() if err != nil { return err } var ok bool typeURL, ok = tok.String() if !ok { return d.newError(tok.Pos(), "invalid %v field value: %v", genid.Any_TypeUrl_field_fullname, tok.RawString()) } seenTypeUrl = true case genid.Any_Value_field_name: if seenValue { return d.newError(tok.Pos(), "duplicate %v field", genid.Any_Value_field_fullname) } if isExpanded { return d.newError(tok.Pos(), "conflict with [%s] field", typeURL) } tok, err := d.Read() if err != nil { return err } s, ok := tok.String() if !ok { return d.newError(tok.Pos(), "invalid %v field value: %v", genid.Any_Value_field_fullname, tok.RawString()) } bValue = []byte(s) seenValue = true default: if !d.opts.DiscardUnknown { return d.newError(tok.Pos(), "invalid field name %q in %v message", tok.RawString(), genid.Any_message_fullname) } } case text.TypeName: if isExpanded { return d.newError(tok.Pos(), "cannot have more than one type") } if seenTypeUrl { return d.newError(tok.Pos(), "conflict with type_url field") } typeURL = tok.TypeName() var err error bValue, err = d.unmarshalExpandedAny(typeURL, tok.Pos()) if err != nil { return err } isExpanded = true default: if !d.opts.DiscardUnknown { return d.newError(tok.Pos(), "invalid field name %q in %v message", tok.RawString(), genid.Any_message_fullname) } } } fds := m.Descriptor().Fields() if len(typeURL) > 0 { m.Set(fds.ByNumber(genid.Any_TypeUrl_field_number), protoreflect.ValueOfString(typeURL)) } if len(bValue) > 0 { m.Set(fds.ByNumber(genid.Any_Value_field_number), protoreflect.ValueOfBytes(bValue)) } return nil } func (d decoder) unmarshalExpandedAny(typeURL string, pos int) ([]byte, error) { mt, err := d.opts.Resolver.FindMessageByURL(typeURL) if err != nil { return nil, d.newError(pos, "unable to resolve message [%v]: %v", typeURL, err) } // Create new message for the embedded message type and unmarshal the value // field into it. m := mt.New() if err := d.unmarshalMessage(m, true); err != nil { return nil, err } // Serialize the embedded message and return the resulting bytes. b, err := proto.MarshalOptions{ AllowPartial: true, // Never check required fields inside an Any. Deterministic: true, }.Marshal(m.Interface()) if err != nil { return nil, d.newError(pos, "error in marshaling message into Any.value: %v", err) } return b, nil } // skipValue makes the decoder parse a field value in order to advance the read // to the next field. It relies on Read returning an error if the types are not // in valid sequence. func (d decoder) skipValue() error { tok, err := d.Read() if err != nil { return err } // Only need to continue reading for messages and lists. switch tok.Kind() { case text.MessageOpen: return d.skipMessageValue() case text.ListOpen: for { tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case text.ListClose: return nil case text.MessageOpen: if err := d.skipMessageValue(); err != nil { return err } default: // Skip items. This will not validate whether skipped values are // of the same type or not, same behavior as C++ // TextFormat::Parser::AllowUnknownField(true) version 3.8.0. } } } return nil } // skipMessageValue makes the decoder parse and skip over all fields in a // message. It assumes that the previous read type is MessageOpen. func (d decoder) skipMessageValue() error { for { tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case text.MessageClose: return nil case text.Name: if err := d.skipValue(); err != nil { return err } } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/encoding/protodelim/protodelim.go
vendor/google.golang.org/protobuf/encoding/protodelim/protodelim.go
// 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. // Package protodelim marshals and unmarshals varint size-delimited messages. package protodelim import ( "bufio" "encoding/binary" "fmt" "io" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/proto" ) // MarshalOptions is a configurable varint size-delimited marshaler. type MarshalOptions struct{ proto.MarshalOptions } // MarshalTo writes a varint size-delimited wire-format message to w. // If w returns an error, MarshalTo returns it unchanged. func (o MarshalOptions) MarshalTo(w io.Writer, m proto.Message) (int, error) { msgBytes, err := o.MarshalOptions.Marshal(m) if err != nil { return 0, err } sizeBytes := protowire.AppendVarint(nil, uint64(len(msgBytes))) sizeWritten, err := w.Write(sizeBytes) if err != nil { return sizeWritten, err } msgWritten, err := w.Write(msgBytes) if err != nil { return sizeWritten + msgWritten, err } return sizeWritten + msgWritten, nil } // MarshalTo writes a varint size-delimited wire-format message to w // with the default options. // // See the documentation for [MarshalOptions.MarshalTo]. func MarshalTo(w io.Writer, m proto.Message) (int, error) { return MarshalOptions{}.MarshalTo(w, m) } // UnmarshalOptions is a configurable varint size-delimited unmarshaler. type UnmarshalOptions struct { proto.UnmarshalOptions // MaxSize is the maximum size in wire-format bytes of a single message. // Unmarshaling a message larger than MaxSize will return an error. // A zero MaxSize will default to 4 MiB. // Setting MaxSize to -1 disables the limit. MaxSize int64 } const defaultMaxSize = 4 << 20 // 4 MiB, corresponds to the default gRPC max request/response size // SizeTooLargeError is an error that is returned when the unmarshaler encounters a message size // that is larger than its configured [UnmarshalOptions.MaxSize]. type SizeTooLargeError struct { // Size is the varint size of the message encountered // that was larger than the provided MaxSize. Size uint64 // MaxSize is the MaxSize limit configured in UnmarshalOptions, which Size exceeded. MaxSize uint64 } func (e *SizeTooLargeError) Error() string { return fmt.Sprintf("message size %d exceeded unmarshaler's maximum configured size %d", e.Size, e.MaxSize) } // Reader is the interface expected by [UnmarshalFrom]. // It is implemented by *[bufio.Reader]. type Reader interface { io.Reader io.ByteReader } // UnmarshalFrom parses and consumes a varint size-delimited wire-format message // from r. // The provided message must be mutable (e.g., a non-nil pointer to a message). // // The error is [io.EOF] error only if no bytes are read. // If an EOF happens after reading some but not all the bytes, // UnmarshalFrom returns a non-io.EOF error. // In particular if r returns a non-io.EOF error, UnmarshalFrom returns it unchanged, // and if only a size is read with no subsequent message, [io.ErrUnexpectedEOF] is returned. func (o UnmarshalOptions) UnmarshalFrom(r Reader, m proto.Message) error { var sizeArr [binary.MaxVarintLen64]byte sizeBuf := sizeArr[:0] for i := range sizeArr { b, err := r.ReadByte() if err != nil { // Immediate EOF is unexpected. if err == io.EOF && i != 0 { break } return err } sizeBuf = append(sizeBuf, b) if b < 0x80 { break } } size, n := protowire.ConsumeVarint(sizeBuf) if n < 0 { return protowire.ParseError(n) } maxSize := o.MaxSize if maxSize == 0 { maxSize = defaultMaxSize } if maxSize != -1 && size > uint64(maxSize) { return errors.Wrap(&SizeTooLargeError{Size: size, MaxSize: uint64(maxSize)}, "") } var b []byte var err error if br, ok := r.(*bufio.Reader); ok { // Use the []byte from the bufio.Reader instead of having to allocate one. // This reduces CPU usage and allocated bytes. b, err = br.Peek(int(size)) if err == nil { defer br.Discard(int(size)) } else { b = nil } } if b == nil { b = make([]byte, size) _, err = io.ReadFull(r, b) } if err == io.EOF { return io.ErrUnexpectedEOF } if err != nil { return err } if err := o.Unmarshal(b, m); err != nil { return err } return nil } // UnmarshalFrom parses and consumes a varint size-delimited wire-format message // from r with the default options. // The provided message must be mutable (e.g., a non-nil pointer to a message). // // See the documentation for [UnmarshalOptions.UnmarshalFrom]. func UnmarshalFrom(r Reader, m proto.Message) error { return UnmarshalOptions{}.UnmarshalFrom(r, m) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/encoding/protowire/wire.go
vendor/google.golang.org/protobuf/encoding/protowire/wire.go
// Copyright 2018 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. // Package protowire parses and formats the raw wire encoding. // See https://protobuf.dev/programming-guides/encoding. // // For marshaling and unmarshaling entire protobuf messages, // use the [google.golang.org/protobuf/proto] package instead. package protowire import ( "io" "math" "math/bits" "google.golang.org/protobuf/internal/errors" ) // Number represents the field number. type Number int32 const ( MinValidNumber Number = 1 FirstReservedNumber Number = 19000 LastReservedNumber Number = 19999 MaxValidNumber Number = 1<<29 - 1 DefaultRecursionLimit = 10000 ) // IsValid reports whether the field number is semantically valid. func (n Number) IsValid() bool { return MinValidNumber <= n && n <= MaxValidNumber } // Type represents the wire type. type Type int8 const ( VarintType Type = 0 Fixed32Type Type = 5 Fixed64Type Type = 1 BytesType Type = 2 StartGroupType Type = 3 EndGroupType Type = 4 ) const ( _ = -iota errCodeTruncated errCodeFieldNumber errCodeOverflow errCodeReserved errCodeEndGroup errCodeRecursionDepth ) var ( errFieldNumber = errors.New("invalid field number") errOverflow = errors.New("variable length integer overflow") errReserved = errors.New("cannot parse reserved wire type") errEndGroup = errors.New("mismatching end group marker") errParse = errors.New("parse error") ) // ParseError converts an error code into an error value. // This returns nil if n is a non-negative number. func ParseError(n int) error { if n >= 0 { return nil } switch n { case errCodeTruncated: return io.ErrUnexpectedEOF case errCodeFieldNumber: return errFieldNumber case errCodeOverflow: return errOverflow case errCodeReserved: return errReserved case errCodeEndGroup: return errEndGroup default: return errParse } } // ConsumeField parses an entire field record (both tag and value) and returns // the field number, the wire type, and the total length. // This returns a negative length upon an error (see [ParseError]). // // The total length includes the tag header and the end group marker (if the // field is a group). func ConsumeField(b []byte) (Number, Type, int) { num, typ, n := ConsumeTag(b) if n < 0 { return 0, 0, n // forward error code } m := ConsumeFieldValue(num, typ, b[n:]) if m < 0 { return 0, 0, m // forward error code } return num, typ, n + m } // ConsumeFieldValue parses a field value and returns its length. // This assumes that the field [Number] and wire [Type] have already been parsed. // This returns a negative length upon an error (see [ParseError]). // // When parsing a group, the length includes the end group marker and // the end group is verified to match the starting field number. func ConsumeFieldValue(num Number, typ Type, b []byte) (n int) { return consumeFieldValueD(num, typ, b, DefaultRecursionLimit) } func consumeFieldValueD(num Number, typ Type, b []byte, depth int) (n int) { switch typ { case VarintType: _, n = ConsumeVarint(b) return n case Fixed32Type: _, n = ConsumeFixed32(b) return n case Fixed64Type: _, n = ConsumeFixed64(b) return n case BytesType: _, n = ConsumeBytes(b) return n case StartGroupType: if depth < 0 { return errCodeRecursionDepth } n0 := len(b) for { num2, typ2, n := ConsumeTag(b) if n < 0 { return n // forward error code } b = b[n:] if typ2 == EndGroupType { if num != num2 { return errCodeEndGroup } return n0 - len(b) } n = consumeFieldValueD(num2, typ2, b, depth-1) if n < 0 { return n // forward error code } b = b[n:] } case EndGroupType: return errCodeEndGroup default: return errCodeReserved } } // AppendTag encodes num and typ as a varint-encoded tag and appends it to b. func AppendTag(b []byte, num Number, typ Type) []byte { return AppendVarint(b, EncodeTag(num, typ)) } // ConsumeTag parses b as a varint-encoded tag, reporting its length. // This returns a negative length upon an error (see [ParseError]). func ConsumeTag(b []byte) (Number, Type, int) { v, n := ConsumeVarint(b) if n < 0 { return 0, 0, n // forward error code } num, typ := DecodeTag(v) if num < MinValidNumber { return 0, 0, errCodeFieldNumber } return num, typ, n } func SizeTag(num Number) int { return SizeVarint(EncodeTag(num, 0)) // wire type has no effect on size } // AppendVarint appends v to b as a varint-encoded uint64. func AppendVarint(b []byte, v uint64) []byte { switch { case v < 1<<7: b = append(b, byte(v)) case v < 1<<14: b = append(b, byte((v>>0)&0x7f|0x80), byte(v>>7)) case v < 1<<21: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte(v>>14)) case v < 1<<28: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte(v>>21)) case v < 1<<35: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte((v>>21)&0x7f|0x80), byte(v>>28)) case v < 1<<42: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte((v>>21)&0x7f|0x80), byte((v>>28)&0x7f|0x80), byte(v>>35)) case v < 1<<49: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte((v>>21)&0x7f|0x80), byte((v>>28)&0x7f|0x80), byte((v>>35)&0x7f|0x80), byte(v>>42)) case v < 1<<56: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte((v>>21)&0x7f|0x80), byte((v>>28)&0x7f|0x80), byte((v>>35)&0x7f|0x80), byte((v>>42)&0x7f|0x80), byte(v>>49)) case v < 1<<63: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte((v>>21)&0x7f|0x80), byte((v>>28)&0x7f|0x80), byte((v>>35)&0x7f|0x80), byte((v>>42)&0x7f|0x80), byte((v>>49)&0x7f|0x80), byte(v>>56)) default: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte((v>>21)&0x7f|0x80), byte((v>>28)&0x7f|0x80), byte((v>>35)&0x7f|0x80), byte((v>>42)&0x7f|0x80), byte((v>>49)&0x7f|0x80), byte((v>>56)&0x7f|0x80), 1) } return b } // ConsumeVarint parses b as a varint-encoded uint64, reporting its length. // This returns a negative length upon an error (see [ParseError]). func ConsumeVarint(b []byte) (v uint64, n int) { var y uint64 if len(b) <= 0 { return 0, errCodeTruncated } v = uint64(b[0]) if v < 0x80 { return v, 1 } v -= 0x80 if len(b) <= 1 { return 0, errCodeTruncated } y = uint64(b[1]) v += y << 7 if y < 0x80 { return v, 2 } v -= 0x80 << 7 if len(b) <= 2 { return 0, errCodeTruncated } y = uint64(b[2]) v += y << 14 if y < 0x80 { return v, 3 } v -= 0x80 << 14 if len(b) <= 3 { return 0, errCodeTruncated } y = uint64(b[3]) v += y << 21 if y < 0x80 { return v, 4 } v -= 0x80 << 21 if len(b) <= 4 { return 0, errCodeTruncated } y = uint64(b[4]) v += y << 28 if y < 0x80 { return v, 5 } v -= 0x80 << 28 if len(b) <= 5 { return 0, errCodeTruncated } y = uint64(b[5]) v += y << 35 if y < 0x80 { return v, 6 } v -= 0x80 << 35 if len(b) <= 6 { return 0, errCodeTruncated } y = uint64(b[6]) v += y << 42 if y < 0x80 { return v, 7 } v -= 0x80 << 42 if len(b) <= 7 { return 0, errCodeTruncated } y = uint64(b[7]) v += y << 49 if y < 0x80 { return v, 8 } v -= 0x80 << 49 if len(b) <= 8 { return 0, errCodeTruncated } y = uint64(b[8]) v += y << 56 if y < 0x80 { return v, 9 } v -= 0x80 << 56 if len(b) <= 9 { return 0, errCodeTruncated } y = uint64(b[9]) v += y << 63 if y < 2 { return v, 10 } return 0, errCodeOverflow } // SizeVarint returns the encoded size of a varint. // The size is guaranteed to be within 1 and 10, inclusive. func SizeVarint(v uint64) int { // This computes 1 + (bits.Len64(v)-1)/7. // 9/64 is a good enough approximation of 1/7 return int(9*uint32(bits.Len64(v))+64) / 64 } // AppendFixed32 appends v to b as a little-endian uint32. func AppendFixed32(b []byte, v uint32) []byte { return append(b, byte(v>>0), byte(v>>8), byte(v>>16), byte(v>>24)) } // ConsumeFixed32 parses b as a little-endian uint32, reporting its length. // This returns a negative length upon an error (see [ParseError]). func ConsumeFixed32(b []byte) (v uint32, n int) { if len(b) < 4 { return 0, errCodeTruncated } v = uint32(b[0])<<0 | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 return v, 4 } // SizeFixed32 returns the encoded size of a fixed32; which is always 4. func SizeFixed32() int { return 4 } // AppendFixed64 appends v to b as a little-endian uint64. func AppendFixed64(b []byte, v uint64) []byte { return append(b, byte(v>>0), byte(v>>8), byte(v>>16), byte(v>>24), byte(v>>32), byte(v>>40), byte(v>>48), byte(v>>56)) } // ConsumeFixed64 parses b as a little-endian uint64, reporting its length. // This returns a negative length upon an error (see [ParseError]). func ConsumeFixed64(b []byte) (v uint64, n int) { if len(b) < 8 { return 0, errCodeTruncated } v = uint64(b[0])<<0 | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 return v, 8 } // SizeFixed64 returns the encoded size of a fixed64; which is always 8. func SizeFixed64() int { return 8 } // AppendBytes appends v to b as a length-prefixed bytes value. func AppendBytes(b []byte, v []byte) []byte { return append(AppendVarint(b, uint64(len(v))), v...) } // ConsumeBytes parses b as a length-prefixed bytes value, reporting its length. // This returns a negative length upon an error (see [ParseError]). func ConsumeBytes(b []byte) (v []byte, n int) { m, n := ConsumeVarint(b) if n < 0 { return nil, n // forward error code } if m > uint64(len(b[n:])) { return nil, errCodeTruncated } return b[n:][:m], n + int(m) } // SizeBytes returns the encoded size of a length-prefixed bytes value, // given only the length. func SizeBytes(n int) int { return SizeVarint(uint64(n)) + n } // AppendString appends v to b as a length-prefixed bytes value. func AppendString(b []byte, v string) []byte { return append(AppendVarint(b, uint64(len(v))), v...) } // ConsumeString parses b as a length-prefixed bytes value, reporting its length. // This returns a negative length upon an error (see [ParseError]). func ConsumeString(b []byte) (v string, n int) { bb, n := ConsumeBytes(b) return string(bb), n } // AppendGroup appends v to b as group value, with a trailing end group marker. // The value v must not contain the end marker. func AppendGroup(b []byte, num Number, v []byte) []byte { return AppendVarint(append(b, v...), EncodeTag(num, EndGroupType)) } // ConsumeGroup parses b as a group value until the trailing end group marker, // and verifies that the end marker matches the provided num. The value v // does not contain the end marker, while the length does contain the end marker. // This returns a negative length upon an error (see [ParseError]). func ConsumeGroup(num Number, b []byte) (v []byte, n int) { n = ConsumeFieldValue(num, StartGroupType, b) if n < 0 { return nil, n // forward error code } b = b[:n] // Truncate off end group marker, but need to handle denormalized varints. // Assuming end marker is never 0 (which is always the case since // EndGroupType is non-zero), we can truncate all trailing bytes where the // lower 7 bits are all zero (implying that the varint is denormalized). for len(b) > 0 && b[len(b)-1]&0x7f == 0 { b = b[:len(b)-1] } b = b[:len(b)-SizeTag(num)] return b, n } // SizeGroup returns the encoded size of a group, given only the length. func SizeGroup(num Number, n int) int { return n + SizeTag(num) } // DecodeTag decodes the field [Number] and wire [Type] from its unified form. // The [Number] is -1 if the decoded field number overflows int32. // Other than overflow, this does not check for field number validity. func DecodeTag(x uint64) (Number, Type) { // NOTE: MessageSet allows for larger field numbers than normal. if x>>3 > uint64(math.MaxInt32) { return -1, 0 } return Number(x >> 3), Type(x & 7) } // EncodeTag encodes the field [Number] and wire [Type] into its unified form. func EncodeTag(num Number, typ Type) uint64 { return uint64(num)<<3 | uint64(typ&7) } // DecodeZigZag decodes a zig-zag-encoded uint64 as an int64. // // Input: {…, 5, 3, 1, 0, 2, 4, 6, …} // Output: {…, -3, -2, -1, 0, +1, +2, +3, …} func DecodeZigZag(x uint64) int64 { return int64(x>>1) ^ int64(x)<<63>>63 } // EncodeZigZag encodes an int64 as a zig-zag-encoded uint64. // // Input: {…, -3, -2, -1, 0, +1, +2, +3, …} // Output: {…, 5, 3, 1, 0, 2, 4, 6, …} func EncodeZigZag(x int64) uint64 { return uint64(x<<1) ^ uint64(x>>63) } // DecodeBool decodes a uint64 as a bool. // // Input: { 0, 1, 2, …} // Output: {false, true, true, …} func DecodeBool(x uint64) bool { return x != 0 } // EncodeBool encodes a bool as a uint64. // // Input: {false, true} // Output: { 0, 1} func EncodeBool(x bool) uint64 { if x { return 1 } return 0 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/merge.go
vendor/google.golang.org/protobuf/proto/merge.go
// Copyright 2019 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. package proto import ( "fmt" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // Merge merges src into dst, which must be a message with the same descriptor. // // Populated scalar fields in src are copied to dst, while populated // singular messages in src are merged into dst by recursively calling Merge. // The elements of every list field in src is appended to the corresponded // list fields in dst. The entries of every map field in src is copied into // the corresponding map field in dst, possibly replacing existing entries. // The unknown fields of src are appended to the unknown fields of dst. // // It is semantically equivalent to unmarshaling the encoded form of src // into dst with the [UnmarshalOptions.Merge] option specified. func Merge(dst, src Message) { // TODO: Should nil src be treated as semantically equivalent to a // untyped, read-only, empty message? What about a nil dst? dstMsg, srcMsg := dst.ProtoReflect(), src.ProtoReflect() if dstMsg.Descriptor() != srcMsg.Descriptor() { if got, want := dstMsg.Descriptor().FullName(), srcMsg.Descriptor().FullName(); got != want { panic(fmt.Sprintf("descriptor mismatch: %v != %v", got, want)) } panic("descriptor mismatch") } mergeOptions{}.mergeMessage(dstMsg, srcMsg) } // Clone returns a deep copy of m. // If the top-level message is invalid, it returns an invalid message as well. func Clone(m Message) Message { // NOTE: Most usages of Clone assume the following properties: // t := reflect.TypeOf(m) // t == reflect.TypeOf(m.ProtoReflect().New().Interface()) // t == reflect.TypeOf(m.ProtoReflect().Type().Zero().Interface()) // // Embedding protobuf messages breaks this since the parent type will have // a forwarded ProtoReflect method, but the Interface method will return // the underlying embedded message type. if m == nil { return nil } src := m.ProtoReflect() if !src.IsValid() { return src.Type().Zero().Interface() } dst := src.New() mergeOptions{}.mergeMessage(dst, src) return dst.Interface() } // CloneOf returns a deep copy of m. If the top-level message is invalid, // it returns an invalid message as well. func CloneOf[M Message](m M) M { return Clone(m).(M) } // mergeOptions provides a namespace for merge functions, and can be // exported in the future if we add user-visible merge options. type mergeOptions struct{} func (o mergeOptions) mergeMessage(dst, src protoreflect.Message) { methods := protoMethods(dst) if methods != nil && methods.Merge != nil { in := protoiface.MergeInput{ Destination: dst, Source: src, } out := methods.Merge(in) if out.Flags&protoiface.MergeComplete != 0 { return } } if !dst.IsValid() { panic(fmt.Sprintf("cannot merge into invalid %v message", dst.Descriptor().FullName())) } src.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { switch { case fd.IsList(): o.mergeList(dst.Mutable(fd).List(), v.List(), fd) case fd.IsMap(): o.mergeMap(dst.Mutable(fd).Map(), v.Map(), fd.MapValue()) case fd.Message() != nil: o.mergeMessage(dst.Mutable(fd).Message(), v.Message()) case fd.Kind() == protoreflect.BytesKind: dst.Set(fd, o.cloneBytes(v)) default: dst.Set(fd, v) } return true }) if len(src.GetUnknown()) > 0 { dst.SetUnknown(append(dst.GetUnknown(), src.GetUnknown()...)) } } func (o mergeOptions) mergeList(dst, src protoreflect.List, fd protoreflect.FieldDescriptor) { // Merge semantics appends to the end of the existing list. for i, n := 0, src.Len(); i < n; i++ { switch v := src.Get(i); { case fd.Message() != nil: dstv := dst.NewElement() o.mergeMessage(dstv.Message(), v.Message()) dst.Append(dstv) case fd.Kind() == protoreflect.BytesKind: dst.Append(o.cloneBytes(v)) default: dst.Append(v) } } } func (o mergeOptions) mergeMap(dst, src protoreflect.Map, fd protoreflect.FieldDescriptor) { // Merge semantics replaces, rather than merges into existing entries. src.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { switch { case fd.Message() != nil: dstv := dst.NewValue() o.mergeMessage(dstv.Message(), v.Message()) dst.Set(k, dstv) case fd.Kind() == protoreflect.BytesKind: dst.Set(k, o.cloneBytes(v)) default: dst.Set(k, v) } return true }) } func (o mergeOptions) cloneBytes(v protoreflect.Value) protoreflect.Value { return protoreflect.ValueOfBytes(append([]byte{}, v.Bytes()...)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/size.go
vendor/google.golang.org/protobuf/proto/size.go
// Copyright 2019 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. package proto import ( "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // Size returns the size in bytes of the wire-format encoding of m. // // Note that Size might return more bytes than Marshal will write in the case of // lazily decoded messages that arrive in non-minimal wire format: see // https://protobuf.dev/reference/go/size/ for more details. func Size(m Message) int { return MarshalOptions{}.Size(m) } // Size returns the size in bytes of the wire-format encoding of m. // // Note that Size might return more bytes than Marshal will write in the case of // lazily decoded messages that arrive in non-minimal wire format: see // https://protobuf.dev/reference/go/size/ for more details. func (o MarshalOptions) Size(m Message) int { // Treat a nil message interface as an empty message; nothing to output. if m == nil { return 0 } return o.size(m.ProtoReflect()) } // size is a centralized function that all size operations go through. // For profiling purposes, avoid changing the name of this function or // introducing other code paths for size that do not go through this. func (o MarshalOptions) size(m protoreflect.Message) (size int) { methods := protoMethods(m) if methods != nil && methods.Size != nil { out := methods.Size(protoiface.SizeInput{ Message: m, Flags: o.flags(), }) return out.Size } if methods != nil && methods.Marshal != nil { // This is not efficient, but we don't have any choice. // This case is mainly used for legacy types with a Marshal method. out, _ := methods.Marshal(protoiface.MarshalInput{ Message: m, Flags: o.flags(), }) return len(out.Buf) } return o.sizeMessageSlow(m) } func (o MarshalOptions) sizeMessageSlow(m protoreflect.Message) (size int) { if messageset.IsMessageSet(m.Descriptor()) { return o.sizeMessageSet(m) } m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { size += o.sizeField(fd, v) return true }) size += len(m.GetUnknown()) return size } func (o MarshalOptions) sizeField(fd protoreflect.FieldDescriptor, value protoreflect.Value) (size int) { num := fd.Number() switch { case fd.IsList(): return o.sizeList(num, fd, value.List()) case fd.IsMap(): return o.sizeMap(num, fd, value.Map()) default: return protowire.SizeTag(num) + o.sizeSingular(num, fd.Kind(), value) } } func (o MarshalOptions) sizeList(num protowire.Number, fd protoreflect.FieldDescriptor, list protoreflect.List) (size int) { sizeTag := protowire.SizeTag(num) if fd.IsPacked() && list.Len() > 0 { content := 0 for i, llen := 0, list.Len(); i < llen; i++ { content += o.sizeSingular(num, fd.Kind(), list.Get(i)) } return sizeTag + protowire.SizeBytes(content) } for i, llen := 0, list.Len(); i < llen; i++ { size += sizeTag + o.sizeSingular(num, fd.Kind(), list.Get(i)) } return size } func (o MarshalOptions) sizeMap(num protowire.Number, fd protoreflect.FieldDescriptor, mapv protoreflect.Map) (size int) { sizeTag := protowire.SizeTag(num) mapv.Range(func(key protoreflect.MapKey, value protoreflect.Value) bool { size += sizeTag size += protowire.SizeBytes(o.sizeField(fd.MapKey(), key.Value()) + o.sizeField(fd.MapValue(), value)) return true }) return size }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/checkinit.go
vendor/google.golang.org/protobuf/proto/checkinit.go
// Copyright 2019 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. package proto import ( "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // CheckInitialized returns an error if any required fields in m are not set. func CheckInitialized(m Message) error { // Treat a nil message interface as an "untyped" empty message, // which we assume to have no required fields. if m == nil { return nil } return checkInitialized(m.ProtoReflect()) } // CheckInitialized returns an error if any required fields in m are not set. func checkInitialized(m protoreflect.Message) error { if methods := protoMethods(m); methods != nil && methods.CheckInitialized != nil { _, err := methods.CheckInitialized(protoiface.CheckInitializedInput{ Message: m, }) return err } return checkInitializedSlow(m) } func checkInitializedSlow(m protoreflect.Message) error { md := m.Descriptor() fds := md.Fields() for i, nums := 0, md.RequiredNumbers(); i < nums.Len(); i++ { fd := fds.ByNumber(nums.Get(i)) if !m.Has(fd) { return errors.RequiredNotSet(string(fd.FullName())) } } var err error m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { switch { case fd.IsList(): if fd.Message() == nil { return true } for i, list := 0, v.List(); i < list.Len() && err == nil; i++ { err = checkInitialized(list.Get(i).Message()) } case fd.IsMap(): if fd.MapValue().Message() == nil { return true } v.Map().Range(func(key protoreflect.MapKey, v protoreflect.Value) bool { err = checkInitialized(v.Message()) return err == nil }) default: if fd.Message() == nil { return true } err = checkInitialized(v.Message()) } return err == nil }) return err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/messageset.go
vendor/google.golang.org/protobuf/proto/messageset.go
// Copyright 2019 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. package proto import ( "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/flags" "google.golang.org/protobuf/internal/order" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ) func (o MarshalOptions) sizeMessageSet(m protoreflect.Message) (size int) { m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { size += messageset.SizeField(fd.Number()) size += protowire.SizeTag(messageset.FieldMessage) size += protowire.SizeBytes(o.size(v.Message())) return true }) size += messageset.SizeUnknown(m.GetUnknown()) return size } func (o MarshalOptions) marshalMessageSet(b []byte, m protoreflect.Message) ([]byte, error) { if !flags.ProtoLegacy { return b, errors.New("no support for message_set_wire_format") } fieldOrder := order.AnyFieldOrder if o.Deterministic { fieldOrder = order.NumberFieldOrder } var err error order.RangeFields(m, fieldOrder, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { b, err = o.marshalMessageSetField(b, fd, v) return err == nil }) if err != nil { return b, err } return messageset.AppendUnknown(b, m.GetUnknown()) } func (o MarshalOptions) marshalMessageSetField(b []byte, fd protoreflect.FieldDescriptor, value protoreflect.Value) ([]byte, error) { b = messageset.AppendFieldStart(b, fd.Number()) b = protowire.AppendTag(b, messageset.FieldMessage, protowire.BytesType) calculatedSize := o.Size(value.Message().Interface()) b = protowire.AppendVarint(b, uint64(calculatedSize)) before := len(b) b, err := o.marshalMessage(b, value.Message()) if err != nil { return b, err } if measuredSize := len(b) - before; calculatedSize != measuredSize { return nil, errors.MismatchedSizeCalculation(calculatedSize, measuredSize) } b = messageset.AppendFieldEnd(b) return b, nil } func (o UnmarshalOptions) unmarshalMessageSet(b []byte, m protoreflect.Message) error { if !flags.ProtoLegacy { return errors.New("no support for message_set_wire_format") } return messageset.Unmarshal(b, false, func(num protowire.Number, v []byte) error { err := o.unmarshalMessageSetField(m, num, v) if err == errUnknown { unknown := m.GetUnknown() unknown = protowire.AppendTag(unknown, num, protowire.BytesType) unknown = protowire.AppendBytes(unknown, v) m.SetUnknown(unknown) return nil } return err }) } func (o UnmarshalOptions) unmarshalMessageSetField(m protoreflect.Message, num protowire.Number, v []byte) error { md := m.Descriptor() if !md.ExtensionRanges().Has(num) { return errUnknown } xt, err := o.Resolver.FindExtensionByNumber(md.FullName(), num) if err == protoregistry.NotFound { return errUnknown } if err != nil { return errors.New("%v: unable to resolve extension %v: %v", md.FullName(), num, err) } xd := xt.TypeDescriptor() if err := o.unmarshalMessage(v, m.Mutable(xd).Message()); err != nil { return err } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/reset.go
vendor/google.golang.org/protobuf/proto/reset.go
// Copyright 2019 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. package proto import ( "fmt" "google.golang.org/protobuf/reflect/protoreflect" ) // Reset clears every field in the message. // The resulting message shares no observable memory with its previous state // other than the memory for the message itself. func Reset(m Message) { if mr, ok := m.(interface{ Reset() }); ok && hasProtoMethods { mr.Reset() return } resetMessage(m.ProtoReflect()) } func resetMessage(m protoreflect.Message) { if !m.IsValid() { panic(fmt.Sprintf("cannot reset invalid %v message", m.Descriptor().FullName())) } // Clear all known fields. fds := m.Descriptor().Fields() for i := 0; i < fds.Len(); i++ { m.Clear(fds.Get(i)) } // Clear extension fields. m.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { m.Clear(fd) return true }) // Clear unknown fields. m.SetUnknown(nil) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/size_gen.go
vendor/google.golang.org/protobuf/proto/size_gen.go
// Copyright 2018 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. // Code generated by generate-types. DO NOT EDIT. package proto import ( "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/reflect/protoreflect" ) func (o MarshalOptions) sizeSingular(num protowire.Number, kind protoreflect.Kind, v protoreflect.Value) int { switch kind { case protoreflect.BoolKind: return protowire.SizeVarint(protowire.EncodeBool(v.Bool())) case protoreflect.EnumKind: return protowire.SizeVarint(uint64(v.Enum())) case protoreflect.Int32Kind: return protowire.SizeVarint(uint64(int32(v.Int()))) case protoreflect.Sint32Kind: return protowire.SizeVarint(protowire.EncodeZigZag(int64(int32(v.Int())))) case protoreflect.Uint32Kind: return protowire.SizeVarint(uint64(uint32(v.Uint()))) case protoreflect.Int64Kind: return protowire.SizeVarint(uint64(v.Int())) case protoreflect.Sint64Kind: return protowire.SizeVarint(protowire.EncodeZigZag(v.Int())) case protoreflect.Uint64Kind: return protowire.SizeVarint(v.Uint()) case protoreflect.Sfixed32Kind: return protowire.SizeFixed32() case protoreflect.Fixed32Kind: return protowire.SizeFixed32() case protoreflect.FloatKind: return protowire.SizeFixed32() case protoreflect.Sfixed64Kind: return protowire.SizeFixed64() case protoreflect.Fixed64Kind: return protowire.SizeFixed64() case protoreflect.DoubleKind: return protowire.SizeFixed64() case protoreflect.StringKind: return protowire.SizeBytes(len(v.String())) case protoreflect.BytesKind: return protowire.SizeBytes(len(v.Bytes())) case protoreflect.MessageKind: return protowire.SizeBytes(o.size(v.Message())) case protoreflect.GroupKind: return protowire.SizeGroup(num, o.size(v.Message())) default: return 0 } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/proto_reflect.go
vendor/google.golang.org/protobuf/proto/proto_reflect.go
// Copyright 2019 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. // The protoreflect build tag disables use of fast-path methods. //go:build protoreflect // +build protoreflect package proto import ( "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) const hasProtoMethods = false func protoMethods(m protoreflect.Message) *protoiface.Methods { return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/encode_gen.go
vendor/google.golang.org/protobuf/proto/encode_gen.go
// Copyright 2018 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. // Code generated by generate-types. DO NOT EDIT. package proto import ( "math" "unicode/utf8" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/reflect/protoreflect" ) var wireTypes = map[protoreflect.Kind]protowire.Type{ protoreflect.BoolKind: protowire.VarintType, protoreflect.EnumKind: protowire.VarintType, protoreflect.Int32Kind: protowire.VarintType, protoreflect.Sint32Kind: protowire.VarintType, protoreflect.Uint32Kind: protowire.VarintType, protoreflect.Int64Kind: protowire.VarintType, protoreflect.Sint64Kind: protowire.VarintType, protoreflect.Uint64Kind: protowire.VarintType, protoreflect.Sfixed32Kind: protowire.Fixed32Type, protoreflect.Fixed32Kind: protowire.Fixed32Type, protoreflect.FloatKind: protowire.Fixed32Type, protoreflect.Sfixed64Kind: protowire.Fixed64Type, protoreflect.Fixed64Kind: protowire.Fixed64Type, protoreflect.DoubleKind: protowire.Fixed64Type, protoreflect.StringKind: protowire.BytesType, protoreflect.BytesKind: protowire.BytesType, protoreflect.MessageKind: protowire.BytesType, protoreflect.GroupKind: protowire.StartGroupType, } func (o MarshalOptions) marshalSingular(b []byte, fd protoreflect.FieldDescriptor, v protoreflect.Value) ([]byte, error) { switch fd.Kind() { case protoreflect.BoolKind: b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) case protoreflect.EnumKind: b = protowire.AppendVarint(b, uint64(v.Enum())) case protoreflect.Int32Kind: b = protowire.AppendVarint(b, uint64(int32(v.Int()))) case protoreflect.Sint32Kind: b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(int32(v.Int())))) case protoreflect.Uint32Kind: b = protowire.AppendVarint(b, uint64(uint32(v.Uint()))) case protoreflect.Int64Kind: b = protowire.AppendVarint(b, uint64(v.Int())) case protoreflect.Sint64Kind: b = protowire.AppendVarint(b, protowire.EncodeZigZag(v.Int())) case protoreflect.Uint64Kind: b = protowire.AppendVarint(b, v.Uint()) case protoreflect.Sfixed32Kind: b = protowire.AppendFixed32(b, uint32(v.Int())) case protoreflect.Fixed32Kind: b = protowire.AppendFixed32(b, uint32(v.Uint())) case protoreflect.FloatKind: b = protowire.AppendFixed32(b, math.Float32bits(float32(v.Float()))) case protoreflect.Sfixed64Kind: b = protowire.AppendFixed64(b, uint64(v.Int())) case protoreflect.Fixed64Kind: b = protowire.AppendFixed64(b, v.Uint()) case protoreflect.DoubleKind: b = protowire.AppendFixed64(b, math.Float64bits(v.Float())) case protoreflect.StringKind: if strs.EnforceUTF8(fd) && !utf8.ValidString(v.String()) { return b, errors.InvalidUTF8(string(fd.FullName())) } b = protowire.AppendString(b, v.String()) case protoreflect.BytesKind: b = protowire.AppendBytes(b, v.Bytes()) case protoreflect.MessageKind: var pos int var err error b, pos = appendSpeculativeLength(b) b, err = o.marshalMessage(b, v.Message()) if err != nil { return b, err } b = finishSpeculativeLength(b, pos) case protoreflect.GroupKind: var err error b, err = o.marshalMessage(b, v.Message()) if err != nil { return b, err } b = protowire.AppendVarint(b, protowire.EncodeTag(fd.Number(), protowire.EndGroupType)) default: return b, errors.New("invalid kind %v", fd.Kind()) } return b, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/proto.go
vendor/google.golang.org/protobuf/proto/proto.go
// Copyright 2018 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. package proto import ( "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/reflect/protoreflect" ) // Message is the top-level interface that all messages must implement. // It provides access to a reflective view of a message. // Any implementation of this interface may be used with all functions in the // protobuf module that accept a Message, except where otherwise specified. // // This is the v2 interface definition for protobuf messages. // The v1 interface definition is [github.com/golang/protobuf/proto.Message]. // // - To convert a v1 message to a v2 message, // use [google.golang.org/protobuf/protoadapt.MessageV2Of]. // - To convert a v2 message to a v1 message, // use [google.golang.org/protobuf/protoadapt.MessageV1Of]. type Message = protoreflect.ProtoMessage // Error matches all errors produced by packages in the protobuf module // according to [errors.Is]. // // Example usage: // // if errors.Is(err, proto.Error) { ... } var Error error func init() { Error = errors.Error } // MessageName returns the full name of m. // If m is nil, it returns an empty string. func MessageName(m Message) protoreflect.FullName { if m == nil { return "" } return m.ProtoReflect().Descriptor().FullName() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/equal.go
vendor/google.golang.org/protobuf/proto/equal.go
// Copyright 2019 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. package proto import ( "reflect" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // Equal reports whether two messages are equal, // by recursively comparing the fields of the message. // // - Bytes fields are equal if they contain identical bytes. // Empty bytes (regardless of nil-ness) are considered equal. // // - Floating-point fields are equal if they contain the same value. // Unlike the == operator, a NaN is equal to another NaN. // // - Other scalar fields are equal if they contain the same value. // // - Message fields are equal if they have // the same set of populated known and extension field values, and // the same set of unknown fields values. // // - Lists are equal if they are the same length and // each corresponding element is equal. // // - Maps are equal if they have the same set of keys and // the corresponding value for each key is equal. // // An invalid message is not equal to a valid message. // An invalid message is only equal to another invalid message of the // same type. An invalid message often corresponds to a nil pointer // of the concrete message type. For example, (*pb.M)(nil) is not equal // to &pb.M{}. // If two valid messages marshal to the same bytes under deterministic // serialization, then Equal is guaranteed to report true. func Equal(x, y Message) bool { if x == nil || y == nil { return x == nil && y == nil } if reflect.TypeOf(x).Kind() == reflect.Ptr && x == y { // Avoid an expensive comparison if both inputs are identical pointers. return true } mx := x.ProtoReflect() my := y.ProtoReflect() if mx.IsValid() != my.IsValid() { return false } // Only one of the messages needs to implement the fast-path for it to work. pmx := protoMethods(mx) pmy := protoMethods(my) if pmx != nil && pmy != nil && pmx.Equal != nil && pmy.Equal != nil { return pmx.Equal(protoiface.EqualInput{MessageA: mx, MessageB: my}).Equal } vx := protoreflect.ValueOfMessage(mx) vy := protoreflect.ValueOfMessage(my) return vx.Equal(vy) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/decode_gen.go
vendor/google.golang.org/protobuf/proto/decode_gen.go
// Copyright 2018 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. // Code generated by generate-types. DO NOT EDIT. package proto import ( "math" "unicode/utf8" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/reflect/protoreflect" ) // unmarshalScalar decodes a value of the given kind. // // Message values are decoded into a []byte which aliases the input data. func (o UnmarshalOptions) unmarshalScalar(b []byte, wtyp protowire.Type, fd protoreflect.FieldDescriptor) (val protoreflect.Value, n int, err error) { switch fd.Kind() { case protoreflect.BoolKind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfBool(protowire.DecodeBool(v)), n, nil case protoreflect.EnumKind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfEnum(protoreflect.EnumNumber(v)), n, nil case protoreflect.Int32Kind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfInt32(int32(v)), n, nil case protoreflect.Sint32Kind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfInt32(int32(protowire.DecodeZigZag(v & math.MaxUint32))), n, nil case protoreflect.Uint32Kind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfUint32(uint32(v)), n, nil case protoreflect.Int64Kind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfInt64(int64(v)), n, nil case protoreflect.Sint64Kind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfInt64(protowire.DecodeZigZag(v)), n, nil case protoreflect.Uint64Kind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfUint64(v), n, nil case protoreflect.Sfixed32Kind: if wtyp != protowire.Fixed32Type { return val, 0, errUnknown } v, n := protowire.ConsumeFixed32(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfInt32(int32(v)), n, nil case protoreflect.Fixed32Kind: if wtyp != protowire.Fixed32Type { return val, 0, errUnknown } v, n := protowire.ConsumeFixed32(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfUint32(uint32(v)), n, nil case protoreflect.FloatKind: if wtyp != protowire.Fixed32Type { return val, 0, errUnknown } v, n := protowire.ConsumeFixed32(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfFloat32(math.Float32frombits(uint32(v))), n, nil case protoreflect.Sfixed64Kind: if wtyp != protowire.Fixed64Type { return val, 0, errUnknown } v, n := protowire.ConsumeFixed64(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfInt64(int64(v)), n, nil case protoreflect.Fixed64Kind: if wtyp != protowire.Fixed64Type { return val, 0, errUnknown } v, n := protowire.ConsumeFixed64(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfUint64(v), n, nil case protoreflect.DoubleKind: if wtyp != protowire.Fixed64Type { return val, 0, errUnknown } v, n := protowire.ConsumeFixed64(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfFloat64(math.Float64frombits(v)), n, nil case protoreflect.StringKind: if wtyp != protowire.BytesType { return val, 0, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return val, 0, errDecode } if strs.EnforceUTF8(fd) && !utf8.Valid(v) { return protoreflect.Value{}, 0, errors.InvalidUTF8(string(fd.FullName())) } return protoreflect.ValueOfString(string(v)), n, nil case protoreflect.BytesKind: if wtyp != protowire.BytesType { return val, 0, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfBytes(append(emptyBuf[:], v...)), n, nil case protoreflect.MessageKind: if wtyp != protowire.BytesType { return val, 0, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfBytes(v), n, nil case protoreflect.GroupKind: if wtyp != protowire.StartGroupType { return val, 0, errUnknown } v, n := protowire.ConsumeGroup(fd.Number(), b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfBytes(v), n, nil default: return val, 0, errUnknown } } func (o UnmarshalOptions) unmarshalList(b []byte, wtyp protowire.Type, list protoreflect.List, fd protoreflect.FieldDescriptor) (n int, err error) { switch fd.Kind() { case protoreflect.BoolKind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfBool(protowire.DecodeBool(v))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfBool(protowire.DecodeBool(v))) return n, nil case protoreflect.EnumKind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfEnum(protoreflect.EnumNumber(v))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfEnum(protoreflect.EnumNumber(v))) return n, nil case protoreflect.Int32Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfInt32(int32(v))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfInt32(int32(v))) return n, nil case protoreflect.Sint32Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfInt32(int32(protowire.DecodeZigZag(v & math.MaxUint32)))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfInt32(int32(protowire.DecodeZigZag(v & math.MaxUint32)))) return n, nil case protoreflect.Uint32Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfUint32(uint32(v))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfUint32(uint32(v))) return n, nil case protoreflect.Int64Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfInt64(int64(v))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfInt64(int64(v))) return n, nil case protoreflect.Sint64Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfInt64(protowire.DecodeZigZag(v))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfInt64(protowire.DecodeZigZag(v))) return n, nil case protoreflect.Uint64Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfUint64(v)) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfUint64(v)) return n, nil case protoreflect.Sfixed32Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeFixed32(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfInt32(int32(v))) } return n, nil } if wtyp != protowire.Fixed32Type { return 0, errUnknown } v, n := protowire.ConsumeFixed32(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfInt32(int32(v))) return n, nil case protoreflect.Fixed32Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeFixed32(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfUint32(uint32(v))) } return n, nil } if wtyp != protowire.Fixed32Type { return 0, errUnknown } v, n := protowire.ConsumeFixed32(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfUint32(uint32(v))) return n, nil case protoreflect.FloatKind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeFixed32(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfFloat32(math.Float32frombits(uint32(v)))) } return n, nil } if wtyp != protowire.Fixed32Type { return 0, errUnknown } v, n := protowire.ConsumeFixed32(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfFloat32(math.Float32frombits(uint32(v)))) return n, nil case protoreflect.Sfixed64Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeFixed64(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfInt64(int64(v))) } return n, nil } if wtyp != protowire.Fixed64Type { return 0, errUnknown } v, n := protowire.ConsumeFixed64(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfInt64(int64(v))) return n, nil case protoreflect.Fixed64Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeFixed64(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfUint64(v)) } return n, nil } if wtyp != protowire.Fixed64Type { return 0, errUnknown } v, n := protowire.ConsumeFixed64(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfUint64(v)) return n, nil case protoreflect.DoubleKind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeFixed64(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfFloat64(math.Float64frombits(v))) } return n, nil } if wtyp != protowire.Fixed64Type { return 0, errUnknown } v, n := protowire.ConsumeFixed64(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfFloat64(math.Float64frombits(v))) return n, nil case protoreflect.StringKind: if wtyp != protowire.BytesType { return 0, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } if strs.EnforceUTF8(fd) && !utf8.Valid(v) { return 0, errors.InvalidUTF8(string(fd.FullName())) } list.Append(protoreflect.ValueOfString(string(v))) return n, nil case protoreflect.BytesKind: if wtyp != protowire.BytesType { return 0, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfBytes(append(emptyBuf[:], v...))) return n, nil case protoreflect.MessageKind: if wtyp != protowire.BytesType { return 0, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } m := list.NewElement() if err := o.unmarshalMessage(v, m.Message()); err != nil { return 0, err } list.Append(m) return n, nil case protoreflect.GroupKind: if wtyp != protowire.StartGroupType { return 0, errUnknown } v, n := protowire.ConsumeGroup(fd.Number(), b) if n < 0 { return 0, errDecode } m := list.NewElement() if err := o.unmarshalMessage(v, m.Message()); err != nil { return 0, err } list.Append(m) return n, nil default: return 0, errUnknown } } // We append to an empty array rather than a nil []byte to get non-nil zero-length byte slices. var emptyBuf [0]byte
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/proto_methods.go
vendor/google.golang.org/protobuf/proto/proto_methods.go
// Copyright 2019 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. // The protoreflect build tag disables use of fast-path methods. //go:build !protoreflect // +build !protoreflect package proto import ( "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) const hasProtoMethods = true func protoMethods(m protoreflect.Message) *protoiface.Methods { return m.ProtoMethods() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/encode.go
vendor/google.golang.org/protobuf/proto/encode.go
// Copyright 2019 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. package proto import ( "errors" "fmt" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/order" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" protoerrors "google.golang.org/protobuf/internal/errors" ) // MarshalOptions configures the marshaler. // // Example usage: // // b, err := MarshalOptions{Deterministic: true}.Marshal(m) type MarshalOptions struct { pragma.NoUnkeyedLiterals // AllowPartial allows messages that have missing required fields to marshal // without returning an error. If AllowPartial is false (the default), // Marshal will return an error if there are any missing required fields. AllowPartial bool // Deterministic controls whether the same message will always be // serialized to the same bytes within the same binary. // // Setting this option guarantees that repeated serialization of // the same message will return the same bytes, and that different // processes of the same binary (which may be executing on different // machines) will serialize equal messages to the same bytes. // It has no effect on the resulting size of the encoded message compared // to a non-deterministic marshal. // // Note that the deterministic serialization is NOT canonical across // languages. It is not guaranteed to remain stable over time. It is // unstable across different builds with schema changes due to unknown // fields. Users who need canonical serialization (e.g., persistent // storage in a canonical form, fingerprinting, etc.) must define // their own canonicalization specification and implement their own // serializer rather than relying on this API. // // If deterministic serialization is requested, map entries will be // sorted by keys in lexographical order. This is an implementation // detail and subject to change. Deterministic bool // UseCachedSize indicates that the result of a previous Size call // may be reused. // // Setting this option asserts that: // // 1. Size has previously been called on this message with identical // options (except for UseCachedSize itself). // // 2. The message and all its submessages have not changed in any // way since the Size call. For lazily decoded messages, accessing // a message results in decoding the message, which is a change. // // If either of these invariants is violated, // the results are undefined and may include panics or corrupted output. // // Implementations MAY take this option into account to provide // better performance, but there is no guarantee that they will do so. // There is absolutely no guarantee that Size followed by Marshal with // UseCachedSize set will perform equivalently to Marshal alone. UseCachedSize bool } // flags turns the specified MarshalOptions (user-facing) into // protoiface.MarshalInputFlags (used internally by the marshaler). // // See impl.marshalOptions.Options for the inverse operation. func (o MarshalOptions) flags() protoiface.MarshalInputFlags { var flags protoiface.MarshalInputFlags // Note: o.AllowPartial is always forced to true by MarshalOptions.marshal, // which is why it is not a part of MarshalInputFlags. if o.Deterministic { flags |= protoiface.MarshalDeterministic } if o.UseCachedSize { flags |= protoiface.MarshalUseCachedSize } return flags } // Marshal returns the wire-format encoding of m. // // This is the most common entry point for encoding a Protobuf message. // // See the [MarshalOptions] type if you need more control. func Marshal(m Message) ([]byte, error) { // Treat nil message interface as an empty message; nothing to output. if m == nil { return nil, nil } out, err := MarshalOptions{}.marshal(nil, m.ProtoReflect()) if len(out.Buf) == 0 && err == nil { out.Buf = emptyBytesForMessage(m) } return out.Buf, err } // Marshal returns the wire-format encoding of m. func (o MarshalOptions) Marshal(m Message) ([]byte, error) { // Treat nil message interface as an empty message; nothing to output. if m == nil { return nil, nil } out, err := o.marshal(nil, m.ProtoReflect()) if len(out.Buf) == 0 && err == nil { out.Buf = emptyBytesForMessage(m) } return out.Buf, err } // emptyBytesForMessage returns a nil buffer if and only if m is invalid, // otherwise it returns a non-nil empty buffer. // // This is to assist the edge-case where user-code does the following: // // m1.OptionalBytes, _ = proto.Marshal(m2) // // where they expect the proto2 "optional_bytes" field to be populated // if any only if m2 is a valid message. func emptyBytesForMessage(m Message) []byte { if m == nil || !m.ProtoReflect().IsValid() { return nil } return emptyBuf[:] } // MarshalAppend appends the wire-format encoding of m to b, // returning the result. // // This is a less common entry point than [Marshal], which is only needed if you // need to supply your own buffers for performance reasons. func (o MarshalOptions) MarshalAppend(b []byte, m Message) ([]byte, error) { // Treat nil message interface as an empty message; nothing to append. if m == nil { return b, nil } out, err := o.marshal(b, m.ProtoReflect()) return out.Buf, err } // MarshalState returns the wire-format encoding of a message. // // This method permits fine-grained control over the marshaler. // Most users should use [Marshal] instead. func (o MarshalOptions) MarshalState(in protoiface.MarshalInput) (protoiface.MarshalOutput, error) { return o.marshal(in.Buf, in.Message) } // marshal is a centralized function that all marshal operations go through. // For profiling purposes, avoid changing the name of this function or // introducing other code paths for marshal that do not go through this. func (o MarshalOptions) marshal(b []byte, m protoreflect.Message) (out protoiface.MarshalOutput, err error) { allowPartial := o.AllowPartial o.AllowPartial = true if methods := protoMethods(m); methods != nil && methods.Marshal != nil && !(o.Deterministic && methods.Flags&protoiface.SupportMarshalDeterministic == 0) { in := protoiface.MarshalInput{ Message: m, Buf: b, Flags: o.flags(), } if methods.Size != nil { sout := methods.Size(protoiface.SizeInput{ Message: m, Flags: in.Flags, }) if cap(b) < len(b)+sout.Size { in.Buf = make([]byte, len(b), growcap(cap(b), len(b)+sout.Size)) copy(in.Buf, b) } in.Flags |= protoiface.MarshalUseCachedSize } out, err = methods.Marshal(in) } else { out.Buf, err = o.marshalMessageSlow(b, m) } if err != nil { var mismatch *protoerrors.SizeMismatchError if errors.As(err, &mismatch) { return out, fmt.Errorf("marshaling %s: %v", string(m.Descriptor().FullName()), err) } return out, err } if allowPartial { return out, nil } return out, checkInitialized(m) } func (o MarshalOptions) marshalMessage(b []byte, m protoreflect.Message) ([]byte, error) { out, err := o.marshal(b, m) return out.Buf, err } // growcap scales up the capacity of a slice. // // Given a slice with a current capacity of oldcap and a desired // capacity of wantcap, growcap returns a new capacity >= wantcap. // // The algorithm is mostly identical to the one used by append as of Go 1.14. func growcap(oldcap, wantcap int) (newcap int) { if wantcap > oldcap*2 { newcap = wantcap } else if oldcap < 1024 { // The Go 1.14 runtime takes this case when len(s) < 1024, // not when cap(s) < 1024. The difference doesn't seem // significant here. newcap = oldcap * 2 } else { newcap = oldcap for 0 < newcap && newcap < wantcap { newcap += newcap / 4 } if newcap <= 0 { newcap = wantcap } } return newcap } func (o MarshalOptions) marshalMessageSlow(b []byte, m protoreflect.Message) ([]byte, error) { if messageset.IsMessageSet(m.Descriptor()) { return o.marshalMessageSet(b, m) } fieldOrder := order.AnyFieldOrder if o.Deterministic { // TODO: This should use a more natural ordering like NumberFieldOrder, // but doing so breaks golden tests that make invalid assumption about // output stability of this implementation. fieldOrder = order.LegacyFieldOrder } var err error order.RangeFields(m, fieldOrder, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { b, err = o.marshalField(b, fd, v) return err == nil }) if err != nil { return b, err } b = append(b, m.GetUnknown()...) return b, nil } func (o MarshalOptions) marshalField(b []byte, fd protoreflect.FieldDescriptor, value protoreflect.Value) ([]byte, error) { switch { case fd.IsList(): return o.marshalList(b, fd, value.List()) case fd.IsMap(): return o.marshalMap(b, fd, value.Map()) default: b = protowire.AppendTag(b, fd.Number(), wireTypes[fd.Kind()]) return o.marshalSingular(b, fd, value) } } func (o MarshalOptions) marshalList(b []byte, fd protoreflect.FieldDescriptor, list protoreflect.List) ([]byte, error) { if fd.IsPacked() && list.Len() > 0 { b = protowire.AppendTag(b, fd.Number(), protowire.BytesType) b, pos := appendSpeculativeLength(b) for i, llen := 0, list.Len(); i < llen; i++ { var err error b, err = o.marshalSingular(b, fd, list.Get(i)) if err != nil { return b, err } } b = finishSpeculativeLength(b, pos) return b, nil } kind := fd.Kind() for i, llen := 0, list.Len(); i < llen; i++ { var err error b = protowire.AppendTag(b, fd.Number(), wireTypes[kind]) b, err = o.marshalSingular(b, fd, list.Get(i)) if err != nil { return b, err } } return b, nil } func (o MarshalOptions) marshalMap(b []byte, fd protoreflect.FieldDescriptor, mapv protoreflect.Map) ([]byte, error) { keyf := fd.MapKey() valf := fd.MapValue() keyOrder := order.AnyKeyOrder if o.Deterministic { keyOrder = order.GenericKeyOrder } var err error order.RangeEntries(mapv, keyOrder, func(key protoreflect.MapKey, value protoreflect.Value) bool { b = protowire.AppendTag(b, fd.Number(), protowire.BytesType) var pos int b, pos = appendSpeculativeLength(b) b, err = o.marshalField(b, keyf, key.Value()) if err != nil { return false } b, err = o.marshalField(b, valf, value) if err != nil { return false } b = finishSpeculativeLength(b, pos) return true }) return b, err } // When encoding length-prefixed fields, we speculatively set aside some number of bytes // for the length, encode the data, and then encode the length (shifting the data if necessary // to make room). const speculativeLength = 1 func appendSpeculativeLength(b []byte) ([]byte, int) { pos := len(b) b = append(b, "\x00\x00\x00\x00"[:speculativeLength]...) return b, pos } func finishSpeculativeLength(b []byte, pos int) []byte { mlen := len(b) - pos - speculativeLength msiz := protowire.SizeVarint(uint64(mlen)) if msiz != speculativeLength { for i := 0; i < msiz-speculativeLength; i++ { b = append(b, 0) } copy(b[pos+msiz:], b[pos+speculativeLength:]) b = b[:pos+msiz+mlen] } protowire.AppendVarint(b[:pos], uint64(mlen)) return b }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/wrapperopaque.go
vendor/google.golang.org/protobuf/proto/wrapperopaque.go
// Copyright 2024 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. package proto // ValueOrNil returns nil if has is false, or a pointer to a new variable // containing the value returned by the specified getter. // // This function is similar to the wrappers (proto.Int32(), proto.String(), // etc.), but is generic (works for any field type) and works with the hasser // and getter of a field, as opposed to a value. // // This is convenient when populating builder fields. // // Example: // // hop := attr.GetDirectHop() // injectedRoute := ripb.InjectedRoute_builder{ // Prefixes: route.GetPrefixes(), // NextHop: proto.ValueOrNil(hop.HasAddress(), hop.GetAddress), // } func ValueOrNil[T any](has bool, getter func() T) *T { if !has { return nil } v := getter() return &v } // ValueOrDefault returns the protobuf message val if val is not nil, otherwise // it returns a pointer to an empty val message. // // This function allows for translating code from the old Open Struct API to the // new Opaque API. // // The old Open Struct API represented oneof fields with a wrapper struct: // // var signedImg *accountpb.SignedImage // profile := &accountpb.Profile{ // // The Avatar oneof will be set, with an empty SignedImage. // Avatar: &accountpb.Profile_SignedImage{signedImg}, // } // // The new Opaque API treats oneof fields like regular fields, there are no more // wrapper structs: // // var signedImg *accountpb.SignedImage // profile := &accountpb.Profile{} // profile.SetSignedImage(signedImg) // // For convenience, the Opaque API also offers Builders, which allow for a // direct translation of struct initialization. However, because Builders use // nilness to represent field presence (but there is no non-nil wrapper struct // anymore), Builders cannot distinguish between an unset oneof and a set oneof // with nil message. The above code would need to be translated with help of the // ValueOrDefault function to retain the same behavior: // // var signedImg *accountpb.SignedImage // return &accountpb.Profile_builder{ // SignedImage: proto.ValueOrDefault(signedImg), // }.Build() func ValueOrDefault[T interface { *P Message }, P any](val T) T { if val == nil { return T(new(P)) } return val } // ValueOrDefaultBytes is like ValueOrDefault but for working with fields of // type []byte. func ValueOrDefaultBytes(val []byte) []byte { if val == nil { return []byte{} } return val }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/extension.go
vendor/google.golang.org/protobuf/proto/extension.go
// Copyright 2019 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. package proto import ( "google.golang.org/protobuf/reflect/protoreflect" ) // HasExtension reports whether an extension field is populated. // It returns false if m is invalid or if xt does not extend m. func HasExtension(m Message, xt protoreflect.ExtensionType) bool { // Treat nil message interface or descriptor as an empty message; no populated // fields. if m == nil || xt == nil { return false } // As a special-case, we reports invalid or mismatching descriptors // as always not being populated (since they aren't). mr := m.ProtoReflect() xd := xt.TypeDescriptor() if mr.Descriptor() != xd.ContainingMessage() { return false } return mr.Has(xd) } // ClearExtension clears an extension field such that subsequent // [HasExtension] calls return false. // It panics if m is invalid or if xt does not extend m. func ClearExtension(m Message, xt protoreflect.ExtensionType) { m.ProtoReflect().Clear(xt.TypeDescriptor()) } // GetExtension retrieves the value for an extension field. // If the field is unpopulated, it returns the default value for // scalars and an immutable, empty value for lists or messages. // It panics if xt does not extend m. // // The type of the value is dependent on the field type of the extension. // For extensions generated by protoc-gen-go, the Go type is as follows: // // ╔═══════════════════╤═════════════════════════╗ // ║ Go type │ Protobuf kind ║ // ╠═══════════════════╪═════════════════════════╣ // ║ bool │ bool ║ // ║ int32 │ int32, sint32, sfixed32 ║ // ║ int64 │ int64, sint64, sfixed64 ║ // ║ uint32 │ uint32, fixed32 ║ // ║ uint64 │ uint64, fixed64 ║ // ║ float32 │ float ║ // ║ float64 │ double ║ // ║ string │ string ║ // ║ []byte │ bytes ║ // ║ protoreflect.Enum │ enum ║ // ║ proto.Message │ message, group ║ // ╚═══════════════════╧═════════════════════════╝ // // The protoreflect.Enum and proto.Message types are the concrete Go type // associated with the named enum or message. Repeated fields are represented // using a Go slice of the base element type. // // If a generated extension descriptor variable is directly passed to // GetExtension, then the call should be followed immediately by a // type assertion to the expected output value. For example: // // mm := proto.GetExtension(m, foopb.E_MyExtension).(*foopb.MyMessage) // // This pattern enables static analysis tools to verify that the asserted type // matches the Go type associated with the extension field and // also enables a possible future migration to a type-safe extension API. // // Since singular messages are the most common extension type, the pattern of // calling HasExtension followed by GetExtension may be simplified to: // // if mm := proto.GetExtension(m, foopb.E_MyExtension).(*foopb.MyMessage); mm != nil { // ... // make use of mm // } // // The mm variable is non-nil if and only if HasExtension reports true. func GetExtension(m Message, xt protoreflect.ExtensionType) any { // Treat nil message interface as an empty message; return the default. if m == nil { return xt.InterfaceOf(xt.Zero()) } return xt.InterfaceOf(m.ProtoReflect().Get(xt.TypeDescriptor())) } // SetExtension stores the value of an extension field. // It panics if m is invalid, xt does not extend m, or if type of v // is invalid for the specified extension field. // // The type of the value is dependent on the field type of the extension. // For extensions generated by protoc-gen-go, the Go type is as follows: // // ╔═══════════════════╤═════════════════════════╗ // ║ Go type │ Protobuf kind ║ // ╠═══════════════════╪═════════════════════════╣ // ║ bool │ bool ║ // ║ int32 │ int32, sint32, sfixed32 ║ // ║ int64 │ int64, sint64, sfixed64 ║ // ║ uint32 │ uint32, fixed32 ║ // ║ uint64 │ uint64, fixed64 ║ // ║ float32 │ float ║ // ║ float64 │ double ║ // ║ string │ string ║ // ║ []byte │ bytes ║ // ║ protoreflect.Enum │ enum ║ // ║ proto.Message │ message, group ║ // ╚═══════════════════╧═════════════════════════╝ // // The protoreflect.Enum and proto.Message types are the concrete Go type // associated with the named enum or message. Repeated fields are represented // using a Go slice of the base element type. // // If a generated extension descriptor variable is directly passed to // SetExtension (e.g., foopb.E_MyExtension), then the value should be a // concrete type that matches the expected Go type for the extension descriptor // so that static analysis tools can verify type correctness. // This also enables a possible future migration to a type-safe extension API. func SetExtension(m Message, xt protoreflect.ExtensionType, v any) { xd := xt.TypeDescriptor() pv := xt.ValueOf(v) // Specially treat an invalid list, map, or message as clear. isValid := true switch { case xd.IsList(): isValid = pv.List().IsValid() case xd.IsMap(): isValid = pv.Map().IsValid() case xd.Message() != nil: isValid = pv.Message().IsValid() } if !isValid { m.ProtoReflect().Clear(xd) return } m.ProtoReflect().Set(xd, pv) } // RangeExtensions iterates over every populated extension field in m in an // undefined order, calling f for each extension type and value encountered. // It returns immediately if f returns false. // While iterating, mutating operations may only be performed // on the current extension field. func RangeExtensions(m Message, f func(protoreflect.ExtensionType, any) bool) { // Treat nil message interface as an empty message; nothing to range over. if m == nil { return } m.ProtoReflect().Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { if fd.IsExtension() { xt := fd.(protoreflect.ExtensionTypeDescriptor).Type() vi := xt.InterfaceOf(v) return f(xt, vi) } return true }) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/doc.go
vendor/google.golang.org/protobuf/proto/doc.go
// Copyright 2019 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. // Package proto provides functions operating on protocol buffer messages. // // For documentation on protocol buffers in general, see: // https://protobuf.dev. // // For a tutorial on using protocol buffers with Go, see: // https://protobuf.dev/getting-started/gotutorial. // // For a guide to generated Go protocol buffer code, see: // https://protobuf.dev/reference/go/go-generated. // // # Binary serialization // // This package contains functions to convert to and from the wire format, // an efficient binary serialization of protocol buffers. // // - [Size] reports the size of a message in the wire format. // // - [Marshal] converts a message to the wire format. // The [MarshalOptions] type provides more control over wire marshaling. // // - [Unmarshal] converts a message from the wire format. // The [UnmarshalOptions] type provides more control over wire unmarshaling. // // # Basic message operations // // - [Clone] makes a deep copy of a message. // // - [Merge] merges the content of a message into another. // // - [Equal] compares two messages. For more control over comparisons // and detailed reporting of differences, see package // [google.golang.org/protobuf/testing/protocmp]. // // - [Reset] clears the content of a message. // // - [CheckInitialized] reports whether all required fields in a message are set. // // # Optional scalar constructors // // The API for some generated messages represents optional scalar fields // as pointers to a value. For example, an optional string field has the // Go type *string. // // - [Bool], [Int32], [Int64], [Uint32], [Uint64], [Float32], [Float64], and [String] // take a value and return a pointer to a new instance of it, // to simplify construction of optional field values. // // Generated enum types usually have an Enum method which performs the // same operation. // // Optional scalar fields are only supported in proto2. // // # Extension accessors // // - [HasExtension], [GetExtension], [SetExtension], and [ClearExtension] // access extension field values in a protocol buffer message. // // Extension fields are only supported in proto2. // // # Related packages // // - Package [google.golang.org/protobuf/encoding/protojson] converts messages to // and from JSON. // // - Package [google.golang.org/protobuf/encoding/prototext] converts messages to // and from the text format. // // - Package [google.golang.org/protobuf/reflect/protoreflect] provides a // reflection interface for protocol buffer data types. // // - Package [google.golang.org/protobuf/testing/protocmp] provides features // to compare protocol buffer messages with the [github.com/google/go-cmp/cmp] // package. // // - Package [google.golang.org/protobuf/types/dynamicpb] provides a dynamic // message type, suitable for working with messages where the protocol buffer // type is only known at runtime. // // This module contains additional packages for more specialized use cases. // Consult the individual package documentation for details. package proto
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/decode.go
vendor/google.golang.org/protobuf/proto/decode.go
// Copyright 2018 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. package proto import ( "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/runtime/protoiface" ) // UnmarshalOptions configures the unmarshaler. // // Example usage: // // err := UnmarshalOptions{DiscardUnknown: true}.Unmarshal(b, m) type UnmarshalOptions struct { pragma.NoUnkeyedLiterals // Merge merges the input into the destination message. // The default behavior is to always reset the message before unmarshaling, // unless Merge is specified. Merge bool // AllowPartial accepts input for messages that will result in missing // required fields. If AllowPartial is false (the default), Unmarshal will // return an error if there are any missing required fields. AllowPartial bool // If DiscardUnknown is set, unknown fields are ignored. DiscardUnknown bool // Resolver is used for looking up types when unmarshaling extension fields. // If nil, this defaults to using protoregistry.GlobalTypes. Resolver interface { FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) } // RecursionLimit limits how deeply messages may be nested. // If zero, a default limit is applied. RecursionLimit int // // NoLazyDecoding turns off lazy decoding, which otherwise is enabled by // default. Lazy decoding only affects submessages (annotated with [lazy = // true] in the .proto file) within messages that use the Opaque API. NoLazyDecoding bool } // Unmarshal parses the wire-format message in b and places the result in m. // The provided message must be mutable (e.g., a non-nil pointer to a message). // // See the [UnmarshalOptions] type if you need more control. func Unmarshal(b []byte, m Message) error { _, err := UnmarshalOptions{RecursionLimit: protowire.DefaultRecursionLimit}.unmarshal(b, m.ProtoReflect()) return err } // Unmarshal parses the wire-format message in b and places the result in m. // The provided message must be mutable (e.g., a non-nil pointer to a message). func (o UnmarshalOptions) Unmarshal(b []byte, m Message) error { if o.RecursionLimit == 0 { o.RecursionLimit = protowire.DefaultRecursionLimit } _, err := o.unmarshal(b, m.ProtoReflect()) return err } // UnmarshalState parses a wire-format message and places the result in m. // // This method permits fine-grained control over the unmarshaler. // Most users should use [Unmarshal] instead. func (o UnmarshalOptions) UnmarshalState(in protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { if o.RecursionLimit == 0 { o.RecursionLimit = protowire.DefaultRecursionLimit } return o.unmarshal(in.Buf, in.Message) } // unmarshal is a centralized function that all unmarshal operations go through. // For profiling purposes, avoid changing the name of this function or // introducing other code paths for unmarshal that do not go through this. func (o UnmarshalOptions) unmarshal(b []byte, m protoreflect.Message) (out protoiface.UnmarshalOutput, err error) { if o.Resolver == nil { o.Resolver = protoregistry.GlobalTypes } if !o.Merge { Reset(m.Interface()) } allowPartial := o.AllowPartial o.Merge = true o.AllowPartial = true methods := protoMethods(m) if methods != nil && methods.Unmarshal != nil && !(o.DiscardUnknown && methods.Flags&protoiface.SupportUnmarshalDiscardUnknown == 0) { in := protoiface.UnmarshalInput{ Message: m, Buf: b, Resolver: o.Resolver, Depth: o.RecursionLimit, } if o.DiscardUnknown { in.Flags |= protoiface.UnmarshalDiscardUnknown } if !allowPartial { // This does not affect how current unmarshal functions work, it just allows them // to record this for lazy the decoding case. in.Flags |= protoiface.UnmarshalCheckRequired } if o.NoLazyDecoding { in.Flags |= protoiface.UnmarshalNoLazyDecoding } out, err = methods.Unmarshal(in) } else { o.RecursionLimit-- if o.RecursionLimit < 0 { return out, errors.New("exceeded max recursion depth") } err = o.unmarshalMessageSlow(b, m) } if err != nil { return out, err } if allowPartial || (out.Flags&protoiface.UnmarshalInitialized != 0) { return out, nil } return out, checkInitialized(m) } func (o UnmarshalOptions) unmarshalMessage(b []byte, m protoreflect.Message) error { _, err := o.unmarshal(b, m) return err } func (o UnmarshalOptions) unmarshalMessageSlow(b []byte, m protoreflect.Message) error { md := m.Descriptor() if messageset.IsMessageSet(md) { return o.unmarshalMessageSet(b, m) } fields := md.Fields() for len(b) > 0 { // Parse the tag (field number and wire type). num, wtyp, tagLen := protowire.ConsumeTag(b) if tagLen < 0 { return errDecode } if num > protowire.MaxValidNumber { return errDecode } // Find the field descriptor for this field number. fd := fields.ByNumber(num) if fd == nil && md.ExtensionRanges().Has(num) { extType, err := o.Resolver.FindExtensionByNumber(md.FullName(), num) if err != nil && err != protoregistry.NotFound { return errors.New("%v: unable to resolve extension %v: %v", md.FullName(), num, err) } if extType != nil { fd = extType.TypeDescriptor() } } var err error if fd == nil { err = errUnknown } // Parse the field value. var valLen int switch { case err != nil: case fd.IsList(): valLen, err = o.unmarshalList(b[tagLen:], wtyp, m.Mutable(fd).List(), fd) case fd.IsMap(): valLen, err = o.unmarshalMap(b[tagLen:], wtyp, m.Mutable(fd).Map(), fd) default: valLen, err = o.unmarshalSingular(b[tagLen:], wtyp, m, fd) } if err != nil { if err != errUnknown { return err } valLen = protowire.ConsumeFieldValue(num, wtyp, b[tagLen:]) if valLen < 0 { return errDecode } if !o.DiscardUnknown { m.SetUnknown(append(m.GetUnknown(), b[:tagLen+valLen]...)) } } b = b[tagLen+valLen:] } return nil } func (o UnmarshalOptions) unmarshalSingular(b []byte, wtyp protowire.Type, m protoreflect.Message, fd protoreflect.FieldDescriptor) (n int, err error) { v, n, err := o.unmarshalScalar(b, wtyp, fd) if err != nil { return 0, err } switch fd.Kind() { case protoreflect.GroupKind, protoreflect.MessageKind: m2 := m.Mutable(fd).Message() if err := o.unmarshalMessage(v.Bytes(), m2); err != nil { return n, err } default: // Non-message scalars replace the previous value. m.Set(fd, v) } return n, nil } func (o UnmarshalOptions) unmarshalMap(b []byte, wtyp protowire.Type, mapv protoreflect.Map, fd protoreflect.FieldDescriptor) (n int, err error) { if wtyp != protowire.BytesType { return 0, errUnknown } b, n = protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } var ( keyField = fd.MapKey() valField = fd.MapValue() key protoreflect.Value val protoreflect.Value haveKey bool haveVal bool ) switch valField.Kind() { case protoreflect.GroupKind, protoreflect.MessageKind: val = mapv.NewValue() } // Map entries are represented as a two-element message with fields // containing the key and value. for len(b) > 0 { num, wtyp, n := protowire.ConsumeTag(b) if n < 0 { return 0, errDecode } if num > protowire.MaxValidNumber { return 0, errDecode } b = b[n:] err = errUnknown switch num { case genid.MapEntry_Key_field_number: key, n, err = o.unmarshalScalar(b, wtyp, keyField) if err != nil { break } haveKey = true case genid.MapEntry_Value_field_number: var v protoreflect.Value v, n, err = o.unmarshalScalar(b, wtyp, valField) if err != nil { break } switch valField.Kind() { case protoreflect.GroupKind, protoreflect.MessageKind: if err := o.unmarshalMessage(v.Bytes(), val.Message()); err != nil { return 0, err } default: val = v } haveVal = true } if err == errUnknown { n = protowire.ConsumeFieldValue(num, wtyp, b) if n < 0 { return 0, errDecode } } else if err != nil { return 0, err } b = b[n:] } // Every map entry should have entries for key and value, but this is not strictly required. if !haveKey { key = keyField.Default() } if !haveVal { switch valField.Kind() { case protoreflect.GroupKind, protoreflect.MessageKind: default: val = valField.Default() } } mapv.Set(key.MapKey(), val) return n, nil } // errUnknown is used internally to indicate fields which should be added // to the unknown field set of a message. It is never returned from an exported // function. var errUnknown = errors.New("BUG: internal error (unknown)") var errDecode = errors.New("cannot parse invalid wire-format data")
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/proto/wrappers.go
vendor/google.golang.org/protobuf/proto/wrappers.go
// Copyright 2019 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. package proto // Bool stores v in a new bool value and returns a pointer to it. func Bool(v bool) *bool { return &v } // Int32 stores v in a new int32 value and returns a pointer to it. func Int32(v int32) *int32 { return &v } // Int64 stores v in a new int64 value and returns a pointer to it. func Int64(v int64) *int64 { return &v } // Float32 stores v in a new float32 value and returns a pointer to it. func Float32(v float32) *float32 { return &v } // Float64 stores v in a new float64 value and returns a pointer to it. func Float64(v float64) *float64 { return &v } // Uint32 stores v in a new uint32 value and returns a pointer to it. func Uint32(v uint32) *uint32 { return &v } // Uint64 stores v in a new uint64 value and returns a pointer to it. func Uint64(v uint64) *uint64 { return &v } // String stores v in a new string value and returns a pointer to it. func String(v string) *string { return &v }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/runtime/protoimpl/impl.go
vendor/google.golang.org/protobuf/runtime/protoimpl/impl.go
// Copyright 2018 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. // Package protoimpl contains the default implementation for messages // generated by protoc-gen-go. // // WARNING: This package should only ever be imported by generated messages. // The compatibility agreement covers nothing except for functionality needed // to keep existing generated messages operational. Breakages that occur due // to unauthorized usages of this package are not the author's responsibility. package protoimpl import ( "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/internal/filetype" "google.golang.org/protobuf/internal/impl" "google.golang.org/protobuf/internal/protolazy" ) // UnsafeEnabled specifies whether package unsafe can be used. const UnsafeEnabled = impl.UnsafeEnabled type ( // Types used by generated code in init functions. DescBuilder = filedesc.Builder TypeBuilder = filetype.Builder // Types used by generated code to implement EnumType, MessageType, and ExtensionType. EnumInfo = impl.EnumInfo MessageInfo = impl.MessageInfo ExtensionInfo = impl.ExtensionInfo // Types embedded in generated messages. MessageState = impl.MessageState SizeCache = impl.SizeCache WeakFields = impl.WeakFields UnknownFields = impl.UnknownFields ExtensionFields = impl.ExtensionFields ExtensionFieldV1 = impl.ExtensionField Pointer = impl.Pointer LazyUnmarshalInfo = *protolazy.XXX_lazyUnmarshalInfo RaceDetectHookData = impl.RaceDetectHookData ) var X impl.Export
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/runtime/protoimpl/version.go
vendor/google.golang.org/protobuf/runtime/protoimpl/version.go
// Copyright 2019 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. package protoimpl import ( "google.golang.org/protobuf/internal/version" ) const ( // MaxVersion is the maximum supported version for generated .pb.go files. // It is always the current version of the module. MaxVersion = version.Minor // GenVersion is the runtime version required by generated .pb.go files. // This is incremented when generated code relies on new functionality // in the runtime. GenVersion = 20 // MinVersion is the minimum supported version for generated .pb.go files. // This is incremented when the runtime drops support for old code. MinVersion = 0 ) // EnforceVersion is used by code generated by protoc-gen-go // to statically enforce minimum and maximum versions of this package. // A compilation failure implies either that: // - the runtime package is too old and needs to be updated OR // - the generated code is too old and needs to be regenerated. // // The runtime package can be upgraded by running: // // go get google.golang.org/protobuf // // The generated code can be regenerated by running: // // protoc --go_out=${PROTOC_GEN_GO_ARGS} ${PROTO_FILES} // // Example usage by generated code: // // const ( // // Verify that this generated code is sufficiently up-to-date. // _ = protoimpl.EnforceVersion(genVersion - protoimpl.MinVersion) // // Verify that runtime/protoimpl is sufficiently up-to-date. // _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - genVersion) // ) // // The genVersion is the current minor version used to generated the code. // This compile-time check relies on negative integer overflow of a uint // being a compilation failure (guaranteed by the Go specification). type EnforceVersion uint // This enforces the following invariant: // // MinVersion ≤ GenVersion ≤ MaxVersion const ( _ = EnforceVersion(GenVersion - MinVersion) _ = EnforceVersion(MaxVersion - GenVersion) )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/runtime/protoiface/methods.go
vendor/google.golang.org/protobuf/runtime/protoiface/methods.go
// Copyright 2019 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. // Package protoiface contains types referenced or implemented by messages. // // WARNING: This package should only be imported by message implementations. // The functionality found in this package should be accessed through // higher-level abstractions provided by the proto package. package protoiface import ( "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/reflect/protoreflect" ) // Methods is a set of optional fast-path implementations of various operations. type Methods = struct { pragma.NoUnkeyedLiterals // Flags indicate support for optional features. Flags SupportFlags // Size returns the size in bytes of the wire-format encoding of a message. // Marshal must be provided if a custom Size is provided. Size func(SizeInput) SizeOutput // Marshal formats a message in the wire-format encoding to the provided buffer. // Size should be provided if a custom Marshal is provided. // It must not return an error for a partial message. Marshal func(MarshalInput) (MarshalOutput, error) // Unmarshal parses the wire-format encoding and merges the result into a message. // It must not reset the target message or return an error for a partial message. Unmarshal func(UnmarshalInput) (UnmarshalOutput, error) // Merge merges the contents of a source message into a destination message. Merge func(MergeInput) MergeOutput // CheckInitialized returns an error if any required fields in the message are not set. CheckInitialized func(CheckInitializedInput) (CheckInitializedOutput, error) // Equal compares two messages and returns EqualOutput.Equal == true if they are equal. Equal func(EqualInput) EqualOutput } // SupportFlags indicate support for optional features. type SupportFlags = uint64 const ( // SupportMarshalDeterministic reports whether MarshalOptions.Deterministic is supported. SupportMarshalDeterministic SupportFlags = 1 << iota // SupportUnmarshalDiscardUnknown reports whether UnmarshalOptions.DiscardUnknown is supported. SupportUnmarshalDiscardUnknown ) // SizeInput is input to the Size method. type SizeInput = struct { pragma.NoUnkeyedLiterals Message protoreflect.Message Flags MarshalInputFlags } // SizeOutput is output from the Size method. type SizeOutput = struct { pragma.NoUnkeyedLiterals Size int } // MarshalInput is input to the Marshal method. type MarshalInput = struct { pragma.NoUnkeyedLiterals Message protoreflect.Message Buf []byte // output is appended to this buffer Flags MarshalInputFlags } // MarshalOutput is output from the Marshal method. type MarshalOutput = struct { pragma.NoUnkeyedLiterals Buf []byte // contains marshaled message } // MarshalInputFlags configure the marshaler. // Most flags correspond to fields in proto.MarshalOptions. type MarshalInputFlags = uint8 const ( MarshalDeterministic MarshalInputFlags = 1 << iota MarshalUseCachedSize ) // UnmarshalInput is input to the Unmarshal method. type UnmarshalInput = struct { pragma.NoUnkeyedLiterals Message protoreflect.Message Buf []byte // input buffer Flags UnmarshalInputFlags Resolver interface { FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) } Depth int } // UnmarshalOutput is output from the Unmarshal method. type UnmarshalOutput = struct { pragma.NoUnkeyedLiterals Flags UnmarshalOutputFlags } // UnmarshalInputFlags configure the unmarshaler. // Most flags correspond to fields in proto.UnmarshalOptions. type UnmarshalInputFlags = uint8 const ( UnmarshalDiscardUnknown UnmarshalInputFlags = 1 << iota // UnmarshalAliasBuffer permits unmarshal operations to alias the input buffer. // The unmarshaller must not modify the contents of the buffer. UnmarshalAliasBuffer // UnmarshalValidated indicates that validation has already been // performed on the input buffer. UnmarshalValidated // UnmarshalCheckRequired is set if this unmarshal operation ultimately will care if required fields are // initialized. UnmarshalCheckRequired // UnmarshalNoLazyDecoding is set if this unmarshal operation should not use // lazy decoding, even when otherwise available. UnmarshalNoLazyDecoding ) // UnmarshalOutputFlags are output from the Unmarshal method. type UnmarshalOutputFlags = uint8 const ( // UnmarshalInitialized may be set on return if all required fields are known to be set. // If unset, then it does not necessarily indicate that the message is uninitialized, // only that its status could not be confirmed. UnmarshalInitialized UnmarshalOutputFlags = 1 << iota ) // MergeInput is input to the Merge method. type MergeInput = struct { pragma.NoUnkeyedLiterals Source protoreflect.Message Destination protoreflect.Message } // MergeOutput is output from the Merge method. type MergeOutput = struct { pragma.NoUnkeyedLiterals Flags MergeOutputFlags } // MergeOutputFlags are output from the Merge method. type MergeOutputFlags = uint8 const ( // MergeComplete reports whether the merge was performed. // If unset, the merger must have made no changes to the destination. MergeComplete MergeOutputFlags = 1 << iota ) // CheckInitializedInput is input to the CheckInitialized method. type CheckInitializedInput = struct { pragma.NoUnkeyedLiterals Message protoreflect.Message } // CheckInitializedOutput is output from the CheckInitialized method. type CheckInitializedOutput = struct { pragma.NoUnkeyedLiterals } // EqualInput is input to the Equal method. type EqualInput = struct { pragma.NoUnkeyedLiterals MessageA protoreflect.Message MessageB protoreflect.Message } // EqualOutput is output from the Equal method. type EqualOutput = struct { pragma.NoUnkeyedLiterals Equal bool }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/runtime/protoiface/legacy.go
vendor/google.golang.org/protobuf/runtime/protoiface/legacy.go
// Copyright 2018 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. package protoiface type MessageV1 interface { Reset() String() string ProtoMessage() } type ExtensionRangeV1 struct { Start, End int32 // both inclusive }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/types/gofeaturespb/go_features.pb.go
vendor/google.golang.org/protobuf/types/gofeaturespb/go_features.pb.go
// Protocol Buffers - Google's data interchange format // Copyright 2023 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/go_features.proto package gofeaturespb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" descriptorpb "google.golang.org/protobuf/types/descriptorpb" reflect "reflect" sync "sync" unsafe "unsafe" ) type GoFeatures_APILevel int32 const ( // API_LEVEL_UNSPECIFIED results in selecting the OPEN API, // but needs to be a separate value to distinguish between // an explicitly set api level or a missing api level. GoFeatures_API_LEVEL_UNSPECIFIED GoFeatures_APILevel = 0 GoFeatures_API_OPEN GoFeatures_APILevel = 1 GoFeatures_API_HYBRID GoFeatures_APILevel = 2 GoFeatures_API_OPAQUE GoFeatures_APILevel = 3 ) // Enum value maps for GoFeatures_APILevel. var ( GoFeatures_APILevel_name = map[int32]string{ 0: "API_LEVEL_UNSPECIFIED", 1: "API_OPEN", 2: "API_HYBRID", 3: "API_OPAQUE", } GoFeatures_APILevel_value = map[string]int32{ "API_LEVEL_UNSPECIFIED": 0, "API_OPEN": 1, "API_HYBRID": 2, "API_OPAQUE": 3, } ) func (x GoFeatures_APILevel) Enum() *GoFeatures_APILevel { p := new(GoFeatures_APILevel) *p = x return p } func (x GoFeatures_APILevel) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (GoFeatures_APILevel) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_go_features_proto_enumTypes[0].Descriptor() } func (GoFeatures_APILevel) Type() protoreflect.EnumType { return &file_google_protobuf_go_features_proto_enumTypes[0] } func (x GoFeatures_APILevel) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *GoFeatures_APILevel) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = GoFeatures_APILevel(num) return nil } // Deprecated: Use GoFeatures_APILevel.Descriptor instead. func (GoFeatures_APILevel) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_go_features_proto_rawDescGZIP(), []int{0, 0} } type GoFeatures_StripEnumPrefix int32 const ( GoFeatures_STRIP_ENUM_PREFIX_UNSPECIFIED GoFeatures_StripEnumPrefix = 0 GoFeatures_STRIP_ENUM_PREFIX_KEEP GoFeatures_StripEnumPrefix = 1 GoFeatures_STRIP_ENUM_PREFIX_GENERATE_BOTH GoFeatures_StripEnumPrefix = 2 GoFeatures_STRIP_ENUM_PREFIX_STRIP GoFeatures_StripEnumPrefix = 3 ) // Enum value maps for GoFeatures_StripEnumPrefix. var ( GoFeatures_StripEnumPrefix_name = map[int32]string{ 0: "STRIP_ENUM_PREFIX_UNSPECIFIED", 1: "STRIP_ENUM_PREFIX_KEEP", 2: "STRIP_ENUM_PREFIX_GENERATE_BOTH", 3: "STRIP_ENUM_PREFIX_STRIP", } GoFeatures_StripEnumPrefix_value = map[string]int32{ "STRIP_ENUM_PREFIX_UNSPECIFIED": 0, "STRIP_ENUM_PREFIX_KEEP": 1, "STRIP_ENUM_PREFIX_GENERATE_BOTH": 2, "STRIP_ENUM_PREFIX_STRIP": 3, } ) func (x GoFeatures_StripEnumPrefix) Enum() *GoFeatures_StripEnumPrefix { p := new(GoFeatures_StripEnumPrefix) *p = x return p } func (x GoFeatures_StripEnumPrefix) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (GoFeatures_StripEnumPrefix) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_go_features_proto_enumTypes[1].Descriptor() } func (GoFeatures_StripEnumPrefix) Type() protoreflect.EnumType { return &file_google_protobuf_go_features_proto_enumTypes[1] } func (x GoFeatures_StripEnumPrefix) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *GoFeatures_StripEnumPrefix) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = GoFeatures_StripEnumPrefix(num) return nil } // Deprecated: Use GoFeatures_StripEnumPrefix.Descriptor instead. func (GoFeatures_StripEnumPrefix) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_go_features_proto_rawDescGZIP(), []int{0, 1} } type GoFeatures struct { state protoimpl.MessageState `protogen:"open.v1"` // Whether or not to generate the deprecated UnmarshalJSON method for enums. // Can only be true for proto using the Open Struct api. LegacyUnmarshalJsonEnum *bool `protobuf:"varint,1,opt,name=legacy_unmarshal_json_enum,json=legacyUnmarshalJsonEnum" json:"legacy_unmarshal_json_enum,omitempty"` // One of OPEN, HYBRID or OPAQUE. ApiLevel *GoFeatures_APILevel `protobuf:"varint,2,opt,name=api_level,json=apiLevel,enum=pb.GoFeatures_APILevel" json:"api_level,omitempty"` StripEnumPrefix *GoFeatures_StripEnumPrefix `protobuf:"varint,3,opt,name=strip_enum_prefix,json=stripEnumPrefix,enum=pb.GoFeatures_StripEnumPrefix" json:"strip_enum_prefix,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GoFeatures) Reset() { *x = GoFeatures{} mi := &file_google_protobuf_go_features_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GoFeatures) String() string { return protoimpl.X.MessageStringOf(x) } func (*GoFeatures) ProtoMessage() {} func (x *GoFeatures) ProtoReflect() protoreflect.Message { mi := &file_google_protobuf_go_features_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GoFeatures.ProtoReflect.Descriptor instead. func (*GoFeatures) Descriptor() ([]byte, []int) { return file_google_protobuf_go_features_proto_rawDescGZIP(), []int{0} } func (x *GoFeatures) GetLegacyUnmarshalJsonEnum() bool { if x != nil && x.LegacyUnmarshalJsonEnum != nil { return *x.LegacyUnmarshalJsonEnum } return false } func (x *GoFeatures) GetApiLevel() GoFeatures_APILevel { if x != nil && x.ApiLevel != nil { return *x.ApiLevel } return GoFeatures_API_LEVEL_UNSPECIFIED } func (x *GoFeatures) GetStripEnumPrefix() GoFeatures_StripEnumPrefix { if x != nil && x.StripEnumPrefix != nil { return *x.StripEnumPrefix } return GoFeatures_STRIP_ENUM_PREFIX_UNSPECIFIED } var file_google_protobuf_go_features_proto_extTypes = []protoimpl.ExtensionInfo{ { ExtendedType: (*descriptorpb.FeatureSet)(nil), ExtensionType: (*GoFeatures)(nil), Field: 1002, Name: "pb.go", Tag: "bytes,1002,opt,name=go", Filename: "google/protobuf/go_features.proto", }, } // Extension fields to descriptorpb.FeatureSet. var ( // optional pb.GoFeatures go = 1002; E_Go = &file_google_protobuf_go_features_proto_extTypes[0] ) var File_google_protobuf_go_features_proto protoreflect.FileDescriptor const file_google_protobuf_go_features_proto_rawDesc = "" + "\n" + "!google/protobuf/go_features.proto\x12\x02pb\x1a google/protobuf/descriptor.proto\"\xab\x05\n" + "\n" + "GoFeatures\x12\xbe\x01\n" + "\x1alegacy_unmarshal_json_enum\x18\x01 \x01(\bB\x80\x01\x88\x01\x01\x98\x01\x06\x98\x01\x01\xa2\x01\t\x12\x04true\x18\x84\a\xa2\x01\n" + "\x12\x05false\x18\xe7\a\xb2\x01[\b\xe8\a\x10\xe8\a\x1aSThe legacy UnmarshalJSON API is deprecated and will be removed in a future edition.R\x17legacyUnmarshalJsonEnum\x12t\n" + "\tapi_level\x18\x02 \x01(\x0e2\x17.pb.GoFeatures.APILevelB>\x88\x01\x01\x98\x01\x03\x98\x01\x01\xa2\x01\x1a\x12\x15API_LEVEL_UNSPECIFIED\x18\x84\a\xa2\x01\x0f\x12\n" + "API_OPAQUE\x18\xe9\a\xb2\x01\x03\b\xe8\aR\bapiLevel\x12|\n" + "\x11strip_enum_prefix\x18\x03 \x01(\x0e2\x1e.pb.GoFeatures.StripEnumPrefixB0\x88\x01\x01\x98\x01\x06\x98\x01\a\x98\x01\x01\xa2\x01\x1b\x12\x16STRIP_ENUM_PREFIX_KEEP\x18\x84\a\xb2\x01\x03\b\xe9\aR\x0fstripEnumPrefix\"S\n" + "\bAPILevel\x12\x19\n" + "\x15API_LEVEL_UNSPECIFIED\x10\x00\x12\f\n" + "\bAPI_OPEN\x10\x01\x12\x0e\n" + "\n" + "API_HYBRID\x10\x02\x12\x0e\n" + "\n" + "API_OPAQUE\x10\x03\"\x92\x01\n" + "\x0fStripEnumPrefix\x12!\n" + "\x1dSTRIP_ENUM_PREFIX_UNSPECIFIED\x10\x00\x12\x1a\n" + "\x16STRIP_ENUM_PREFIX_KEEP\x10\x01\x12#\n" + "\x1fSTRIP_ENUM_PREFIX_GENERATE_BOTH\x10\x02\x12\x1b\n" + "\x17STRIP_ENUM_PREFIX_STRIP\x10\x03:<\n" + "\x02go\x12\x1b.google.protobuf.FeatureSet\x18\xea\a \x01(\v2\x0e.pb.GoFeaturesR\x02goB/Z-google.golang.org/protobuf/types/gofeaturespb" var ( file_google_protobuf_go_features_proto_rawDescOnce sync.Once file_google_protobuf_go_features_proto_rawDescData []byte ) func file_google_protobuf_go_features_proto_rawDescGZIP() []byte { file_google_protobuf_go_features_proto_rawDescOnce.Do(func() { file_google_protobuf_go_features_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_google_protobuf_go_features_proto_rawDesc), len(file_google_protobuf_go_features_proto_rawDesc))) }) return file_google_protobuf_go_features_proto_rawDescData } var file_google_protobuf_go_features_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_google_protobuf_go_features_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_google_protobuf_go_features_proto_goTypes = []any{ (GoFeatures_APILevel)(0), // 0: pb.GoFeatures.APILevel (GoFeatures_StripEnumPrefix)(0), // 1: pb.GoFeatures.StripEnumPrefix (*GoFeatures)(nil), // 2: pb.GoFeatures (*descriptorpb.FeatureSet)(nil), // 3: google.protobuf.FeatureSet } var file_google_protobuf_go_features_proto_depIdxs = []int32{ 0, // 0: pb.GoFeatures.api_level:type_name -> pb.GoFeatures.APILevel 1, // 1: pb.GoFeatures.strip_enum_prefix:type_name -> pb.GoFeatures.StripEnumPrefix 3, // 2: pb.go:extendee -> google.protobuf.FeatureSet 2, // 3: pb.go:type_name -> pb.GoFeatures 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 3, // [3:4] is the sub-list for extension type_name 2, // [2:3] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_google_protobuf_go_features_proto_init() } func file_google_protobuf_go_features_proto_init() { if File_google_protobuf_go_features_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_google_protobuf_go_features_proto_rawDesc), len(file_google_protobuf_go_features_proto_rawDesc)), NumEnums: 2, NumMessages: 1, NumExtensions: 1, NumServices: 0, }, GoTypes: file_google_protobuf_go_features_proto_goTypes, DependencyIndexes: file_google_protobuf_go_features_proto_depIdxs, EnumInfos: file_google_protobuf_go_features_proto_enumTypes, MessageInfos: file_google_protobuf_go_features_proto_msgTypes, ExtensionInfos: file_google_protobuf_go_features_proto_extTypes, }.Build() File_google_protobuf_go_features_proto = out.File file_google_protobuf_go_features_proto_goTypes = nil file_google_protobuf_go_features_proto_depIdxs = nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/types/descriptorpb/descriptor.pb.go
vendor/google.golang.org/protobuf/types/descriptorpb/descriptor.pb.go
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // // The messages in this file describe the definitions found in .proto files. // A valid .proto file can be translated directly to a FileDescriptorProto // without any other information (e.g. without reading its imports). // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/descriptor.proto package descriptorpb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) // The full set of known editions. type Edition int32 const ( // A placeholder for an unknown edition value. Edition_EDITION_UNKNOWN Edition = 0 // A placeholder edition for specifying default behaviors *before* a feature // was first introduced. This is effectively an "infinite past". Edition_EDITION_LEGACY Edition = 900 // Legacy syntax "editions". These pre-date editions, but behave much like // distinct editions. These can't be used to specify the edition of proto // files, but feature definitions must supply proto2/proto3 defaults for // backwards compatibility. Edition_EDITION_PROTO2 Edition = 998 Edition_EDITION_PROTO3 Edition = 999 // Editions that have been released. The specific values are arbitrary and // should not be depended on, but they will always be time-ordered for easy // comparison. Edition_EDITION_2023 Edition = 1000 Edition_EDITION_2024 Edition = 1001 // Placeholder editions for testing feature resolution. These should not be // used or relied on outside of tests. Edition_EDITION_1_TEST_ONLY Edition = 1 Edition_EDITION_2_TEST_ONLY Edition = 2 Edition_EDITION_99997_TEST_ONLY Edition = 99997 Edition_EDITION_99998_TEST_ONLY Edition = 99998 Edition_EDITION_99999_TEST_ONLY Edition = 99999 // Placeholder for specifying unbounded edition support. This should only // ever be used by plugins that can expect to never require any changes to // support a new edition. Edition_EDITION_MAX Edition = 2147483647 ) // Enum value maps for Edition. var ( Edition_name = map[int32]string{ 0: "EDITION_UNKNOWN", 900: "EDITION_LEGACY", 998: "EDITION_PROTO2", 999: "EDITION_PROTO3", 1000: "EDITION_2023", 1001: "EDITION_2024", 1: "EDITION_1_TEST_ONLY", 2: "EDITION_2_TEST_ONLY", 99997: "EDITION_99997_TEST_ONLY", 99998: "EDITION_99998_TEST_ONLY", 99999: "EDITION_99999_TEST_ONLY", 2147483647: "EDITION_MAX", } Edition_value = map[string]int32{ "EDITION_UNKNOWN": 0, "EDITION_LEGACY": 900, "EDITION_PROTO2": 998, "EDITION_PROTO3": 999, "EDITION_2023": 1000, "EDITION_2024": 1001, "EDITION_1_TEST_ONLY": 1, "EDITION_2_TEST_ONLY": 2, "EDITION_99997_TEST_ONLY": 99997, "EDITION_99998_TEST_ONLY": 99998, "EDITION_99999_TEST_ONLY": 99999, "EDITION_MAX": 2147483647, } ) func (x Edition) Enum() *Edition { p := new(Edition) *p = x return p } func (x Edition) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Edition) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[0].Descriptor() } func (Edition) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[0] } func (x Edition) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *Edition) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = Edition(num) return nil } // Deprecated: Use Edition.Descriptor instead. func (Edition) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{0} } // The verification state of the extension range. type ExtensionRangeOptions_VerificationState int32 const ( // All the extensions of the range must be declared. ExtensionRangeOptions_DECLARATION ExtensionRangeOptions_VerificationState = 0 ExtensionRangeOptions_UNVERIFIED ExtensionRangeOptions_VerificationState = 1 ) // Enum value maps for ExtensionRangeOptions_VerificationState. var ( ExtensionRangeOptions_VerificationState_name = map[int32]string{ 0: "DECLARATION", 1: "UNVERIFIED", } ExtensionRangeOptions_VerificationState_value = map[string]int32{ "DECLARATION": 0, "UNVERIFIED": 1, } ) func (x ExtensionRangeOptions_VerificationState) Enum() *ExtensionRangeOptions_VerificationState { p := new(ExtensionRangeOptions_VerificationState) *p = x return p } func (x ExtensionRangeOptions_VerificationState) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ExtensionRangeOptions_VerificationState) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[1].Descriptor() } func (ExtensionRangeOptions_VerificationState) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[1] } func (x ExtensionRangeOptions_VerificationState) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *ExtensionRangeOptions_VerificationState) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = ExtensionRangeOptions_VerificationState(num) return nil } // Deprecated: Use ExtensionRangeOptions_VerificationState.Descriptor instead. func (ExtensionRangeOptions_VerificationState) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{3, 0} } type FieldDescriptorProto_Type int32 const ( // 0 is reserved for errors. // Order is weird for historical reasons. FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1 FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2 // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if // negative values are likely. FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3 FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4 // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if // negative values are likely. FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5 FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6 FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7 FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8 FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9 // Tag-delimited aggregate. // Group type is deprecated and not supported after google.protobuf. However, Proto3 // implementations should still be able to parse the group wire format and // treat group fields as unknown fields. In Editions, the group wire format // can be enabled via the `message_encoding` feature. FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10 FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11 // Length-delimited aggregate. // New in version 2. FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12 FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13 FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14 FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15 FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16 FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17 // Uses ZigZag encoding. FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18 // Uses ZigZag encoding. ) // Enum value maps for FieldDescriptorProto_Type. var ( FieldDescriptorProto_Type_name = map[int32]string{ 1: "TYPE_DOUBLE", 2: "TYPE_FLOAT", 3: "TYPE_INT64", 4: "TYPE_UINT64", 5: "TYPE_INT32", 6: "TYPE_FIXED64", 7: "TYPE_FIXED32", 8: "TYPE_BOOL", 9: "TYPE_STRING", 10: "TYPE_GROUP", 11: "TYPE_MESSAGE", 12: "TYPE_BYTES", 13: "TYPE_UINT32", 14: "TYPE_ENUM", 15: "TYPE_SFIXED32", 16: "TYPE_SFIXED64", 17: "TYPE_SINT32", 18: "TYPE_SINT64", } FieldDescriptorProto_Type_value = map[string]int32{ "TYPE_DOUBLE": 1, "TYPE_FLOAT": 2, "TYPE_INT64": 3, "TYPE_UINT64": 4, "TYPE_INT32": 5, "TYPE_FIXED64": 6, "TYPE_FIXED32": 7, "TYPE_BOOL": 8, "TYPE_STRING": 9, "TYPE_GROUP": 10, "TYPE_MESSAGE": 11, "TYPE_BYTES": 12, "TYPE_UINT32": 13, "TYPE_ENUM": 14, "TYPE_SFIXED32": 15, "TYPE_SFIXED64": 16, "TYPE_SINT32": 17, "TYPE_SINT64": 18, } ) func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type { p := new(FieldDescriptorProto_Type) *p = x return p } func (x FieldDescriptorProto_Type) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FieldDescriptorProto_Type) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[2].Descriptor() } func (FieldDescriptorProto_Type) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[2] } func (x FieldDescriptorProto_Type) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FieldDescriptorProto_Type) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FieldDescriptorProto_Type(num) return nil } // Deprecated: Use FieldDescriptorProto_Type.Descriptor instead. func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{4, 0} } type FieldDescriptorProto_Label int32 const ( // 0 is reserved for errors FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1 FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3 // The required label is only allowed in google.protobuf. In proto3 and Editions // it's explicitly prohibited. In Editions, the `field_presence` feature // can be used to get this behavior. FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2 ) // Enum value maps for FieldDescriptorProto_Label. var ( FieldDescriptorProto_Label_name = map[int32]string{ 1: "LABEL_OPTIONAL", 3: "LABEL_REPEATED", 2: "LABEL_REQUIRED", } FieldDescriptorProto_Label_value = map[string]int32{ "LABEL_OPTIONAL": 1, "LABEL_REPEATED": 3, "LABEL_REQUIRED": 2, } ) func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label { p := new(FieldDescriptorProto_Label) *p = x return p } func (x FieldDescriptorProto_Label) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FieldDescriptorProto_Label) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[3].Descriptor() } func (FieldDescriptorProto_Label) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[3] } func (x FieldDescriptorProto_Label) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FieldDescriptorProto_Label) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FieldDescriptorProto_Label(num) return nil } // Deprecated: Use FieldDescriptorProto_Label.Descriptor instead. func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{4, 1} } // Generated classes can be optimized for speed or code size. type FileOptions_OptimizeMode int32 const ( FileOptions_SPEED FileOptions_OptimizeMode = 1 // Generate complete code for parsing, serialization, // etc. FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2 // Use ReflectionOps to implement these methods. FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3 // Generate code using MessageLite and the lite runtime. ) // Enum value maps for FileOptions_OptimizeMode. var ( FileOptions_OptimizeMode_name = map[int32]string{ 1: "SPEED", 2: "CODE_SIZE", 3: "LITE_RUNTIME", } FileOptions_OptimizeMode_value = map[string]int32{ "SPEED": 1, "CODE_SIZE": 2, "LITE_RUNTIME": 3, } ) func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode { p := new(FileOptions_OptimizeMode) *p = x return p } func (x FileOptions_OptimizeMode) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FileOptions_OptimizeMode) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[4].Descriptor() } func (FileOptions_OptimizeMode) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[4] } func (x FileOptions_OptimizeMode) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FileOptions_OptimizeMode) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FileOptions_OptimizeMode(num) return nil } // Deprecated: Use FileOptions_OptimizeMode.Descriptor instead. func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{10, 0} } type FieldOptions_CType int32 const ( // Default mode. FieldOptions_STRING FieldOptions_CType = 0 // The option [ctype=CORD] may be applied to a non-repeated field of type // "bytes". It indicates that in C++, the data should be stored in a Cord // instead of a string. For very large strings, this may reduce memory // fragmentation. It may also allow better performance when parsing from a // Cord, or when parsing with aliasing enabled, as the parsed Cord may then // alias the original buffer. FieldOptions_CORD FieldOptions_CType = 1 FieldOptions_STRING_PIECE FieldOptions_CType = 2 ) // Enum value maps for FieldOptions_CType. var ( FieldOptions_CType_name = map[int32]string{ 0: "STRING", 1: "CORD", 2: "STRING_PIECE", } FieldOptions_CType_value = map[string]int32{ "STRING": 0, "CORD": 1, "STRING_PIECE": 2, } ) func (x FieldOptions_CType) Enum() *FieldOptions_CType { p := new(FieldOptions_CType) *p = x return p } func (x FieldOptions_CType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FieldOptions_CType) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[5].Descriptor() } func (FieldOptions_CType) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[5] } func (x FieldOptions_CType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FieldOptions_CType) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FieldOptions_CType(num) return nil } // Deprecated: Use FieldOptions_CType.Descriptor instead. func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{12, 0} } type FieldOptions_JSType int32 const ( // Use the default type. FieldOptions_JS_NORMAL FieldOptions_JSType = 0 // Use JavaScript strings. FieldOptions_JS_STRING FieldOptions_JSType = 1 // Use JavaScript numbers. FieldOptions_JS_NUMBER FieldOptions_JSType = 2 ) // Enum value maps for FieldOptions_JSType. var ( FieldOptions_JSType_name = map[int32]string{ 0: "JS_NORMAL", 1: "JS_STRING", 2: "JS_NUMBER", } FieldOptions_JSType_value = map[string]int32{ "JS_NORMAL": 0, "JS_STRING": 1, "JS_NUMBER": 2, } ) func (x FieldOptions_JSType) Enum() *FieldOptions_JSType { p := new(FieldOptions_JSType) *p = x return p } func (x FieldOptions_JSType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FieldOptions_JSType) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[6].Descriptor() } func (FieldOptions_JSType) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[6] } func (x FieldOptions_JSType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FieldOptions_JSType) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FieldOptions_JSType(num) return nil } // Deprecated: Use FieldOptions_JSType.Descriptor instead. func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{12, 1} } // If set to RETENTION_SOURCE, the option will be omitted from the binary. type FieldOptions_OptionRetention int32 const ( FieldOptions_RETENTION_UNKNOWN FieldOptions_OptionRetention = 0 FieldOptions_RETENTION_RUNTIME FieldOptions_OptionRetention = 1 FieldOptions_RETENTION_SOURCE FieldOptions_OptionRetention = 2 ) // Enum value maps for FieldOptions_OptionRetention. var ( FieldOptions_OptionRetention_name = map[int32]string{ 0: "RETENTION_UNKNOWN", 1: "RETENTION_RUNTIME", 2: "RETENTION_SOURCE", } FieldOptions_OptionRetention_value = map[string]int32{ "RETENTION_UNKNOWN": 0, "RETENTION_RUNTIME": 1, "RETENTION_SOURCE": 2, } ) func (x FieldOptions_OptionRetention) Enum() *FieldOptions_OptionRetention { p := new(FieldOptions_OptionRetention) *p = x return p } func (x FieldOptions_OptionRetention) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FieldOptions_OptionRetention) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[7].Descriptor() } func (FieldOptions_OptionRetention) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[7] } func (x FieldOptions_OptionRetention) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FieldOptions_OptionRetention) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FieldOptions_OptionRetention(num) return nil } // Deprecated: Use FieldOptions_OptionRetention.Descriptor instead. func (FieldOptions_OptionRetention) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{12, 2} } // This indicates the types of entities that the field may apply to when used // as an option. If it is unset, then the field may be freely used as an // option on any kind of entity. type FieldOptions_OptionTargetType int32 const ( FieldOptions_TARGET_TYPE_UNKNOWN FieldOptions_OptionTargetType = 0 FieldOptions_TARGET_TYPE_FILE FieldOptions_OptionTargetType = 1 FieldOptions_TARGET_TYPE_EXTENSION_RANGE FieldOptions_OptionTargetType = 2 FieldOptions_TARGET_TYPE_MESSAGE FieldOptions_OptionTargetType = 3 FieldOptions_TARGET_TYPE_FIELD FieldOptions_OptionTargetType = 4 FieldOptions_TARGET_TYPE_ONEOF FieldOptions_OptionTargetType = 5 FieldOptions_TARGET_TYPE_ENUM FieldOptions_OptionTargetType = 6 FieldOptions_TARGET_TYPE_ENUM_ENTRY FieldOptions_OptionTargetType = 7 FieldOptions_TARGET_TYPE_SERVICE FieldOptions_OptionTargetType = 8 FieldOptions_TARGET_TYPE_METHOD FieldOptions_OptionTargetType = 9 ) // Enum value maps for FieldOptions_OptionTargetType. var ( FieldOptions_OptionTargetType_name = map[int32]string{ 0: "TARGET_TYPE_UNKNOWN", 1: "TARGET_TYPE_FILE", 2: "TARGET_TYPE_EXTENSION_RANGE", 3: "TARGET_TYPE_MESSAGE", 4: "TARGET_TYPE_FIELD", 5: "TARGET_TYPE_ONEOF", 6: "TARGET_TYPE_ENUM", 7: "TARGET_TYPE_ENUM_ENTRY", 8: "TARGET_TYPE_SERVICE", 9: "TARGET_TYPE_METHOD", } FieldOptions_OptionTargetType_value = map[string]int32{ "TARGET_TYPE_UNKNOWN": 0, "TARGET_TYPE_FILE": 1, "TARGET_TYPE_EXTENSION_RANGE": 2, "TARGET_TYPE_MESSAGE": 3, "TARGET_TYPE_FIELD": 4, "TARGET_TYPE_ONEOF": 5, "TARGET_TYPE_ENUM": 6, "TARGET_TYPE_ENUM_ENTRY": 7, "TARGET_TYPE_SERVICE": 8, "TARGET_TYPE_METHOD": 9, } ) func (x FieldOptions_OptionTargetType) Enum() *FieldOptions_OptionTargetType { p := new(FieldOptions_OptionTargetType) *p = x return p } func (x FieldOptions_OptionTargetType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FieldOptions_OptionTargetType) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[8].Descriptor() } func (FieldOptions_OptionTargetType) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[8] } func (x FieldOptions_OptionTargetType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FieldOptions_OptionTargetType) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FieldOptions_OptionTargetType(num) return nil } // Deprecated: Use FieldOptions_OptionTargetType.Descriptor instead. func (FieldOptions_OptionTargetType) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{12, 3} } // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, // or neither? HTTP based RPC implementation may choose GET verb for safe // methods, and PUT verb for idempotent methods instead of the default POST. type MethodOptions_IdempotencyLevel int32 const ( MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0 MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1 // implies idempotent MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2 // idempotent, but may have side effects ) // Enum value maps for MethodOptions_IdempotencyLevel. var ( MethodOptions_IdempotencyLevel_name = map[int32]string{ 0: "IDEMPOTENCY_UNKNOWN", 1: "NO_SIDE_EFFECTS", 2: "IDEMPOTENT", } MethodOptions_IdempotencyLevel_value = map[string]int32{ "IDEMPOTENCY_UNKNOWN": 0, "NO_SIDE_EFFECTS": 1, "IDEMPOTENT": 2, } ) func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel { p := new(MethodOptions_IdempotencyLevel) *p = x return p } func (x MethodOptions_IdempotencyLevel) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (MethodOptions_IdempotencyLevel) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[9].Descriptor() } func (MethodOptions_IdempotencyLevel) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[9] } func (x MethodOptions_IdempotencyLevel) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = MethodOptions_IdempotencyLevel(num) return nil } // Deprecated: Use MethodOptions_IdempotencyLevel.Descriptor instead. func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{17, 0} } type FeatureSet_FieldPresence int32 const ( FeatureSet_FIELD_PRESENCE_UNKNOWN FeatureSet_FieldPresence = 0 FeatureSet_EXPLICIT FeatureSet_FieldPresence = 1 FeatureSet_IMPLICIT FeatureSet_FieldPresence = 2 FeatureSet_LEGACY_REQUIRED FeatureSet_FieldPresence = 3 ) // Enum value maps for FeatureSet_FieldPresence. var ( FeatureSet_FieldPresence_name = map[int32]string{ 0: "FIELD_PRESENCE_UNKNOWN", 1: "EXPLICIT", 2: "IMPLICIT", 3: "LEGACY_REQUIRED", } FeatureSet_FieldPresence_value = map[string]int32{ "FIELD_PRESENCE_UNKNOWN": 0, "EXPLICIT": 1, "IMPLICIT": 2, "LEGACY_REQUIRED": 3, } ) func (x FeatureSet_FieldPresence) Enum() *FeatureSet_FieldPresence { p := new(FeatureSet_FieldPresence) *p = x return p } func (x FeatureSet_FieldPresence) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FeatureSet_FieldPresence) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[10].Descriptor() } func (FeatureSet_FieldPresence) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[10] } func (x FeatureSet_FieldPresence) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FeatureSet_FieldPresence) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FeatureSet_FieldPresence(num) return nil } // Deprecated: Use FeatureSet_FieldPresence.Descriptor instead. func (FeatureSet_FieldPresence) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{19, 0} } type FeatureSet_EnumType int32 const ( FeatureSet_ENUM_TYPE_UNKNOWN FeatureSet_EnumType = 0 FeatureSet_OPEN FeatureSet_EnumType = 1 FeatureSet_CLOSED FeatureSet_EnumType = 2 ) // Enum value maps for FeatureSet_EnumType. var ( FeatureSet_EnumType_name = map[int32]string{ 0: "ENUM_TYPE_UNKNOWN", 1: "OPEN", 2: "CLOSED", } FeatureSet_EnumType_value = map[string]int32{ "ENUM_TYPE_UNKNOWN": 0, "OPEN": 1, "CLOSED": 2, } ) func (x FeatureSet_EnumType) Enum() *FeatureSet_EnumType { p := new(FeatureSet_EnumType) *p = x return p } func (x FeatureSet_EnumType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FeatureSet_EnumType) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[11].Descriptor() } func (FeatureSet_EnumType) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[11] } func (x FeatureSet_EnumType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FeatureSet_EnumType) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FeatureSet_EnumType(num) return nil } // Deprecated: Use FeatureSet_EnumType.Descriptor instead. func (FeatureSet_EnumType) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{19, 1} } type FeatureSet_RepeatedFieldEncoding int32 const ( FeatureSet_REPEATED_FIELD_ENCODING_UNKNOWN FeatureSet_RepeatedFieldEncoding = 0 FeatureSet_PACKED FeatureSet_RepeatedFieldEncoding = 1 FeatureSet_EXPANDED FeatureSet_RepeatedFieldEncoding = 2 ) // Enum value maps for FeatureSet_RepeatedFieldEncoding. var ( FeatureSet_RepeatedFieldEncoding_name = map[int32]string{ 0: "REPEATED_FIELD_ENCODING_UNKNOWN", 1: "PACKED", 2: "EXPANDED", } FeatureSet_RepeatedFieldEncoding_value = map[string]int32{ "REPEATED_FIELD_ENCODING_UNKNOWN": 0, "PACKED": 1, "EXPANDED": 2, } ) func (x FeatureSet_RepeatedFieldEncoding) Enum() *FeatureSet_RepeatedFieldEncoding { p := new(FeatureSet_RepeatedFieldEncoding) *p = x return p } func (x FeatureSet_RepeatedFieldEncoding) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FeatureSet_RepeatedFieldEncoding) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[12].Descriptor() } func (FeatureSet_RepeatedFieldEncoding) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[12] } func (x FeatureSet_RepeatedFieldEncoding) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FeatureSet_RepeatedFieldEncoding) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FeatureSet_RepeatedFieldEncoding(num) return nil } // Deprecated: Use FeatureSet_RepeatedFieldEncoding.Descriptor instead. func (FeatureSet_RepeatedFieldEncoding) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{19, 2} } type FeatureSet_Utf8Validation int32 const ( FeatureSet_UTF8_VALIDATION_UNKNOWN FeatureSet_Utf8Validation = 0 FeatureSet_VERIFY FeatureSet_Utf8Validation = 2 FeatureSet_NONE FeatureSet_Utf8Validation = 3 ) // Enum value maps for FeatureSet_Utf8Validation. var ( FeatureSet_Utf8Validation_name = map[int32]string{ 0: "UTF8_VALIDATION_UNKNOWN", 2: "VERIFY", 3: "NONE", } FeatureSet_Utf8Validation_value = map[string]int32{ "UTF8_VALIDATION_UNKNOWN": 0, "VERIFY": 2, "NONE": 3, } ) func (x FeatureSet_Utf8Validation) Enum() *FeatureSet_Utf8Validation { p := new(FeatureSet_Utf8Validation) *p = x return p } func (x FeatureSet_Utf8Validation) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FeatureSet_Utf8Validation) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[13].Descriptor() } func (FeatureSet_Utf8Validation) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[13] } func (x FeatureSet_Utf8Validation) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FeatureSet_Utf8Validation) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FeatureSet_Utf8Validation(num) return nil } // Deprecated: Use FeatureSet_Utf8Validation.Descriptor instead. func (FeatureSet_Utf8Validation) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{19, 3} } type FeatureSet_MessageEncoding int32 const ( FeatureSet_MESSAGE_ENCODING_UNKNOWN FeatureSet_MessageEncoding = 0 FeatureSet_LENGTH_PREFIXED FeatureSet_MessageEncoding = 1 FeatureSet_DELIMITED FeatureSet_MessageEncoding = 2 ) // Enum value maps for FeatureSet_MessageEncoding. var ( FeatureSet_MessageEncoding_name = map[int32]string{ 0: "MESSAGE_ENCODING_UNKNOWN", 1: "LENGTH_PREFIXED", 2: "DELIMITED", }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go
vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/timestamp.proto // Package timestamppb contains generated types for google/protobuf/timestamp.proto. // // The Timestamp message represents a timestamp, // an instant in time since the Unix epoch (January 1st, 1970). // // # Conversion to a Go Time // // The AsTime method can be used to convert a Timestamp message to a // standard Go time.Time value in UTC: // // t := ts.AsTime() // ... // make use of t as a time.Time // // Converting to a time.Time is a common operation so that the extensive // set of time-based operations provided by the time package can be leveraged. // See https://golang.org/pkg/time for more information. // // The AsTime method performs the conversion on a best-effort basis. Timestamps // with denormal values (e.g., nanoseconds beyond 0 and 99999999, inclusive) // are normalized during the conversion to a time.Time. To manually check for // invalid Timestamps per the documented limitations in timestamp.proto, // additionally call the CheckValid method: // // if err := ts.CheckValid(); err != nil { // ... // handle error // } // // # Conversion from a Go Time // // The timestamppb.New function can be used to construct a Timestamp message // from a standard Go time.Time value: // // ts := timestamppb.New(t) // ... // make use of ts as a *timestamppb.Timestamp // // In order to construct a Timestamp representing the current time, use Now: // // ts := timestamppb.Now() // ... // make use of ts as a *timestamppb.Timestamp package timestamppb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" time "time" unsafe "unsafe" ) // A Timestamp represents a point in time independent of any time zone or local // calendar, encoded as a count of seconds and fractions of seconds at // nanosecond resolution. The count is relative to an epoch at UTC midnight on // January 1, 1970, in the proleptic Gregorian calendar which extends the // Gregorian calendar backwards to year one. // // All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap // second table is needed for interpretation, using a [24-hour linear // smear](https://developers.google.com/time/smear). // // The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By // restricting to that range, we ensure that we can convert to and from [RFC // 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. // // # Examples // // Example 1: Compute Timestamp from POSIX `time()`. // // Timestamp timestamp; // timestamp.set_seconds(time(NULL)); // timestamp.set_nanos(0); // // Example 2: Compute Timestamp from POSIX `gettimeofday()`. // // struct timeval tv; // gettimeofday(&tv, NULL); // // Timestamp timestamp; // timestamp.set_seconds(tv.tv_sec); // timestamp.set_nanos(tv.tv_usec * 1000); // // Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. // // FILETIME ft; // GetSystemTimeAsFileTime(&ft); // UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; // // // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z // // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. // Timestamp timestamp; // timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); // timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); // // Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. // // long millis = System.currentTimeMillis(); // // Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) // .setNanos((int) ((millis % 1000) * 1000000)).build(); // // Example 5: Compute Timestamp from Java `Instant.now()`. // // Instant now = Instant.now(); // // Timestamp timestamp = // Timestamp.newBuilder().setSeconds(now.getEpochSecond()) // .setNanos(now.getNano()).build(); // // Example 6: Compute Timestamp from current time in Python. // // timestamp = Timestamp() // timestamp.GetCurrentTime() // // # JSON Mapping // // In JSON format, the Timestamp type is encoded as a string in the // [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the // format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" // where {year} is always expressed using four digits while {month}, {day}, // {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional // seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), // are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone // is required. A proto3 JSON serializer should always use UTC (as indicated by // "Z") when printing the Timestamp type and a proto3 JSON parser should be // able to accept both UTC and other timezones (as indicated by an offset). // // For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past // 01:30 UTC on January 15, 2017. // // In JavaScript, one can convert a Date object to this format using the // standard // [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) // method. In Python, a standard `datetime.datetime` object can be converted // to this format using // [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with // the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use // the Joda Time's [`ISODateTimeFormat.dateTime()`]( // http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime() // ) to obtain a formatter capable of generating timestamps in this format. type Timestamp struct { state protoimpl.MessageState `protogen:"open.v1"` // Represents seconds of UTC time since Unix epoch // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to // 9999-12-31T23:59:59Z inclusive. Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` // Non-negative fractions of a second at nanosecond resolution. Negative // second values with fractions must still have non-negative nanos values // that count forward in time. Must be from 0 to 999,999,999 // inclusive. Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } // Now constructs a new Timestamp from the current time. func Now() *Timestamp { return New(time.Now()) } // New constructs a new Timestamp from the provided time.Time. func New(t time.Time) *Timestamp { return &Timestamp{Seconds: int64(t.Unix()), Nanos: int32(t.Nanosecond())} } // AsTime converts x to a time.Time. func (x *Timestamp) AsTime() time.Time { return time.Unix(int64(x.GetSeconds()), int64(x.GetNanos())).UTC() } // IsValid reports whether the timestamp is valid. // It is equivalent to CheckValid == nil. func (x *Timestamp) IsValid() bool { return x.check() == 0 } // CheckValid returns an error if the timestamp is invalid. // In particular, it checks whether the value represents a date that is // in the range of 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive. // An error is reported for a nil Timestamp. func (x *Timestamp) CheckValid() error { switch x.check() { case invalidNil: return protoimpl.X.NewError("invalid nil Timestamp") case invalidUnderflow: return protoimpl.X.NewError("timestamp (%v) before 0001-01-01", x) case invalidOverflow: return protoimpl.X.NewError("timestamp (%v) after 9999-12-31", x) case invalidNanos: return protoimpl.X.NewError("timestamp (%v) has out-of-range nanos", x) default: return nil } } const ( _ = iota invalidNil invalidUnderflow invalidOverflow invalidNanos ) func (x *Timestamp) check() uint { const minTimestamp = -62135596800 // Seconds between 1970-01-01T00:00:00Z and 0001-01-01T00:00:00Z, inclusive const maxTimestamp = +253402300799 // Seconds between 1970-01-01T00:00:00Z and 9999-12-31T23:59:59Z, inclusive secs := x.GetSeconds() nanos := x.GetNanos() switch { case x == nil: return invalidNil case secs < minTimestamp: return invalidUnderflow case secs > maxTimestamp: return invalidOverflow case nanos < 0 || nanos >= 1e9: return invalidNanos default: return 0 } } func (x *Timestamp) Reset() { *x = Timestamp{} mi := &file_google_protobuf_timestamp_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Timestamp) String() string { return protoimpl.X.MessageStringOf(x) } func (*Timestamp) ProtoMessage() {} func (x *Timestamp) ProtoReflect() protoreflect.Message { mi := &file_google_protobuf_timestamp_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Timestamp.ProtoReflect.Descriptor instead. func (*Timestamp) Descriptor() ([]byte, []int) { return file_google_protobuf_timestamp_proto_rawDescGZIP(), []int{0} } func (x *Timestamp) GetSeconds() int64 { if x != nil { return x.Seconds } return 0 } func (x *Timestamp) GetNanos() int32 { if x != nil { return x.Nanos } return 0 } var File_google_protobuf_timestamp_proto protoreflect.FileDescriptor const file_google_protobuf_timestamp_proto_rawDesc = "" + "\n" + "\x1fgoogle/protobuf/timestamp.proto\x12\x0fgoogle.protobuf\";\n" + "\tTimestamp\x12\x18\n" + "\aseconds\x18\x01 \x01(\x03R\aseconds\x12\x14\n" + "\x05nanos\x18\x02 \x01(\x05R\x05nanosB\x85\x01\n" + "\x13com.google.protobufB\x0eTimestampProtoP\x01Z2google.golang.org/protobuf/types/known/timestamppb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3" var ( file_google_protobuf_timestamp_proto_rawDescOnce sync.Once file_google_protobuf_timestamp_proto_rawDescData []byte ) func file_google_protobuf_timestamp_proto_rawDescGZIP() []byte { file_google_protobuf_timestamp_proto_rawDescOnce.Do(func() { file_google_protobuf_timestamp_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_google_protobuf_timestamp_proto_rawDesc), len(file_google_protobuf_timestamp_proto_rawDesc))) }) return file_google_protobuf_timestamp_proto_rawDescData } var file_google_protobuf_timestamp_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_google_protobuf_timestamp_proto_goTypes = []any{ (*Timestamp)(nil), // 0: google.protobuf.Timestamp } var file_google_protobuf_timestamp_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_google_protobuf_timestamp_proto_init() } func file_google_protobuf_timestamp_proto_init() { if File_google_protobuf_timestamp_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_google_protobuf_timestamp_proto_rawDesc), len(file_google_protobuf_timestamp_proto_rawDesc)), NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_google_protobuf_timestamp_proto_goTypes, DependencyIndexes: file_google_protobuf_timestamp_proto_depIdxs, MessageInfos: file_google_protobuf_timestamp_proto_msgTypes, }.Build() File_google_protobuf_timestamp_proto = out.File file_google_protobuf_timestamp_proto_goTypes = nil file_google_protobuf_timestamp_proto_depIdxs = nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/types/known/durationpb/duration.pb.go
vendor/google.golang.org/protobuf/types/known/durationpb/duration.pb.go
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/duration.proto // Package durationpb contains generated types for google/protobuf/duration.proto. // // The Duration message represents a signed span of time. // // # Conversion to a Go Duration // // The AsDuration method can be used to convert a Duration message to a // standard Go time.Duration value: // // d := dur.AsDuration() // ... // make use of d as a time.Duration // // Converting to a time.Duration is a common operation so that the extensive // set of time-based operations provided by the time package can be leveraged. // See https://golang.org/pkg/time for more information. // // The AsDuration method performs the conversion on a best-effort basis. // Durations with denormal values (e.g., nanoseconds beyond -99999999 and // +99999999, inclusive; or seconds and nanoseconds with opposite signs) // are normalized during the conversion to a time.Duration. To manually check for // invalid Duration per the documented limitations in duration.proto, // additionally call the CheckValid method: // // if err := dur.CheckValid(); err != nil { // ... // handle error // } // // Note that the documented limitations in duration.proto does not protect a // Duration from overflowing the representable range of a time.Duration in Go. // The AsDuration method uses saturation arithmetic such that an overflow clamps // the resulting value to the closest representable value (e.g., math.MaxInt64 // for positive overflow and math.MinInt64 for negative overflow). // // # Conversion from a Go Duration // // The durationpb.New function can be used to construct a Duration message // from a standard Go time.Duration value: // // dur := durationpb.New(d) // ... // make use of d as a *durationpb.Duration package durationpb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" math "math" reflect "reflect" sync "sync" time "time" unsafe "unsafe" ) // A Duration represents a signed, fixed-length span of time represented // as a count of seconds and fractions of seconds at nanosecond // resolution. It is independent of any calendar and concepts like "day" // or "month". It is related to Timestamp in that the difference between // two Timestamp values is a Duration and it can be added or subtracted // from a Timestamp. Range is approximately +-10,000 years. // // # Examples // // Example 1: Compute Duration from two Timestamps in pseudo code. // // Timestamp start = ...; // Timestamp end = ...; // Duration duration = ...; // // duration.seconds = end.seconds - start.seconds; // duration.nanos = end.nanos - start.nanos; // // if (duration.seconds < 0 && duration.nanos > 0) { // duration.seconds += 1; // duration.nanos -= 1000000000; // } else if (duration.seconds > 0 && duration.nanos < 0) { // duration.seconds -= 1; // duration.nanos += 1000000000; // } // // Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. // // Timestamp start = ...; // Duration duration = ...; // Timestamp end = ...; // // end.seconds = start.seconds + duration.seconds; // end.nanos = start.nanos + duration.nanos; // // if (end.nanos < 0) { // end.seconds -= 1; // end.nanos += 1000000000; // } else if (end.nanos >= 1000000000) { // end.seconds += 1; // end.nanos -= 1000000000; // } // // Example 3: Compute Duration from datetime.timedelta in Python. // // td = datetime.timedelta(days=3, minutes=10) // duration = Duration() // duration.FromTimedelta(td) // // # JSON Mapping // // In JSON format, the Duration type is encoded as a string rather than an // object, where the string ends in the suffix "s" (indicating seconds) and // is preceded by the number of seconds, with nanoseconds expressed as // fractional seconds. For example, 3 seconds with 0 nanoseconds should be // encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should // be expressed in JSON format as "3.000000001s", and 3 seconds and 1 // microsecond should be expressed in JSON format as "3.000001s". type Duration struct { state protoimpl.MessageState `protogen:"open.v1"` // Signed seconds of the span of time. Must be from -315,576,000,000 // to +315,576,000,000 inclusive. Note: these bounds are computed from: // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` // Signed fractions of a second at nanosecond resolution of the span // of time. Durations less than one second are represented with a 0 // `seconds` field and a positive or negative `nanos` field. For durations // of one second or more, a non-zero value for the `nanos` field must be // of the same sign as the `seconds` field. Must be from -999,999,999 // to +999,999,999 inclusive. Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } // New constructs a new Duration from the provided time.Duration. func New(d time.Duration) *Duration { nanos := d.Nanoseconds() secs := nanos / 1e9 nanos -= secs * 1e9 return &Duration{Seconds: int64(secs), Nanos: int32(nanos)} } // AsDuration converts x to a time.Duration, // returning the closest duration value in the event of overflow. func (x *Duration) AsDuration() time.Duration { secs := x.GetSeconds() nanos := x.GetNanos() d := time.Duration(secs) * time.Second overflow := d/time.Second != time.Duration(secs) d += time.Duration(nanos) * time.Nanosecond overflow = overflow || (secs < 0 && nanos < 0 && d > 0) overflow = overflow || (secs > 0 && nanos > 0 && d < 0) if overflow { switch { case secs < 0: return time.Duration(math.MinInt64) case secs > 0: return time.Duration(math.MaxInt64) } } return d } // IsValid reports whether the duration is valid. // It is equivalent to CheckValid == nil. func (x *Duration) IsValid() bool { return x.check() == 0 } // CheckValid returns an error if the duration is invalid. // In particular, it checks whether the value is within the range of // -10000 years to +10000 years inclusive. // An error is reported for a nil Duration. func (x *Duration) CheckValid() error { switch x.check() { case invalidNil: return protoimpl.X.NewError("invalid nil Duration") case invalidUnderflow: return protoimpl.X.NewError("duration (%v) exceeds -10000 years", x) case invalidOverflow: return protoimpl.X.NewError("duration (%v) exceeds +10000 years", x) case invalidNanosRange: return protoimpl.X.NewError("duration (%v) has out-of-range nanos", x) case invalidNanosSign: return protoimpl.X.NewError("duration (%v) has seconds and nanos with different signs", x) default: return nil } } const ( _ = iota invalidNil invalidUnderflow invalidOverflow invalidNanosRange invalidNanosSign ) func (x *Duration) check() uint { const absDuration = 315576000000 // 10000yr * 365.25day/yr * 24hr/day * 60min/hr * 60sec/min secs := x.GetSeconds() nanos := x.GetNanos() switch { case x == nil: return invalidNil case secs < -absDuration: return invalidUnderflow case secs > +absDuration: return invalidOverflow case nanos <= -1e9 || nanos >= +1e9: return invalidNanosRange case (secs > 0 && nanos < 0) || (secs < 0 && nanos > 0): return invalidNanosSign default: return 0 } } func (x *Duration) Reset() { *x = Duration{} mi := &file_google_protobuf_duration_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Duration) String() string { return protoimpl.X.MessageStringOf(x) } func (*Duration) ProtoMessage() {} func (x *Duration) ProtoReflect() protoreflect.Message { mi := &file_google_protobuf_duration_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Duration.ProtoReflect.Descriptor instead. func (*Duration) Descriptor() ([]byte, []int) { return file_google_protobuf_duration_proto_rawDescGZIP(), []int{0} } func (x *Duration) GetSeconds() int64 { if x != nil { return x.Seconds } return 0 } func (x *Duration) GetNanos() int32 { if x != nil { return x.Nanos } return 0 } var File_google_protobuf_duration_proto protoreflect.FileDescriptor const file_google_protobuf_duration_proto_rawDesc = "" + "\n" + "\x1egoogle/protobuf/duration.proto\x12\x0fgoogle.protobuf\":\n" + "\bDuration\x12\x18\n" + "\aseconds\x18\x01 \x01(\x03R\aseconds\x12\x14\n" + "\x05nanos\x18\x02 \x01(\x05R\x05nanosB\x83\x01\n" + "\x13com.google.protobufB\rDurationProtoP\x01Z1google.golang.org/protobuf/types/known/durationpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3" var ( file_google_protobuf_duration_proto_rawDescOnce sync.Once file_google_protobuf_duration_proto_rawDescData []byte ) func file_google_protobuf_duration_proto_rawDescGZIP() []byte { file_google_protobuf_duration_proto_rawDescOnce.Do(func() { file_google_protobuf_duration_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_google_protobuf_duration_proto_rawDesc), len(file_google_protobuf_duration_proto_rawDesc))) }) return file_google_protobuf_duration_proto_rawDescData } var file_google_protobuf_duration_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_google_protobuf_duration_proto_goTypes = []any{ (*Duration)(nil), // 0: google.protobuf.Duration } var file_google_protobuf_duration_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_google_protobuf_duration_proto_init() } func file_google_protobuf_duration_proto_init() { if File_google_protobuf_duration_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_google_protobuf_duration_proto_rawDesc), len(file_google_protobuf_duration_proto_rawDesc)), NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_google_protobuf_duration_proto_goTypes, DependencyIndexes: file_google_protobuf_duration_proto_depIdxs, MessageInfos: file_google_protobuf_duration_proto_msgTypes, }.Build() File_google_protobuf_duration_proto = out.File file_google_protobuf_duration_proto_goTypes = nil file_google_protobuf_duration_proto_depIdxs = nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/types/known/anypb/any.pb.go
vendor/google.golang.org/protobuf/types/known/anypb/any.pb.go
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/any.proto // Package anypb contains generated types for google/protobuf/any.proto. // // The Any message is a dynamic representation of any other message value. // It is functionally a tuple of the full name of the remote message type and // the serialized bytes of the remote message value. // // # Constructing an Any // // An Any message containing another message value is constructed using New: // // any, err := anypb.New(m) // if err != nil { // ... // handle error // } // ... // make use of any // // # Unmarshaling an Any // // With a populated Any message, the underlying message can be serialized into // a remote concrete message value in a few ways. // // If the exact concrete type is known, then a new (or pre-existing) instance // of that message can be passed to the UnmarshalTo method: // // m := new(foopb.MyMessage) // if err := any.UnmarshalTo(m); err != nil { // ... // handle error // } // ... // make use of m // // If the exact concrete type is not known, then the UnmarshalNew method can be // used to unmarshal the contents into a new instance of the remote message type: // // m, err := any.UnmarshalNew() // if err != nil { // ... // handle error // } // ... // make use of m // // UnmarshalNew uses the global type registry to resolve the message type and // construct a new instance of that message to unmarshal into. In order for a // message type to appear in the global registry, the Go type representing that // protobuf message type must be linked into the Go binary. For messages // generated by protoc-gen-go, this is achieved through an import of the // generated Go package representing a .proto file. // // A common pattern with UnmarshalNew is to use a type switch with the resulting // proto.Message value: // // switch m := m.(type) { // case *foopb.MyMessage: // ... // make use of m as a *foopb.MyMessage // case *barpb.OtherMessage: // ... // make use of m as a *barpb.OtherMessage // case *bazpb.SomeMessage: // ... // make use of m as a *bazpb.SomeMessage // } // // This pattern ensures that the generated packages containing the message types // listed in the case clauses are linked into the Go binary and therefore also // registered in the global registry. // // # Type checking an Any // // In order to type check whether an Any message represents some other message, // then use the MessageIs method: // // if any.MessageIs((*foopb.MyMessage)(nil)) { // ... // make use of any, knowing that it contains a foopb.MyMessage // } // // The MessageIs method can also be used with an allocated instance of the target // message type if the intention is to unmarshal into it if the type matches: // // m := new(foopb.MyMessage) // if any.MessageIs(m) { // if err := any.UnmarshalTo(m); err != nil { // ... // handle error // } // ... // make use of m // } package anypb import ( proto "google.golang.org/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoregistry "google.golang.org/protobuf/reflect/protoregistry" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" strings "strings" sync "sync" unsafe "unsafe" ) // `Any` contains an arbitrary serialized protocol buffer message along with a // URL that describes the type of the serialized message. // // Protobuf library provides support to pack/unpack Any values in the form // of utility functions or additional generated methods of the Any type. // // Example 1: Pack and unpack a message in C++. // // Foo foo = ...; // Any any; // any.PackFrom(foo); // ... // if (any.UnpackTo(&foo)) { // ... // } // // Example 2: Pack and unpack a message in Java. // // Foo foo = ...; // Any any = Any.pack(foo); // ... // if (any.is(Foo.class)) { // foo = any.unpack(Foo.class); // } // // or ... // if (any.isSameTypeAs(Foo.getDefaultInstance())) { // foo = any.unpack(Foo.getDefaultInstance()); // } // // Example 3: Pack and unpack a message in Python. // // foo = Foo(...) // any = Any() // any.Pack(foo) // ... // if any.Is(Foo.DESCRIPTOR): // any.Unpack(foo) // ... // // Example 4: Pack and unpack a message in Go // // foo := &pb.Foo{...} // any, err := anypb.New(foo) // if err != nil { // ... // } // ... // foo := &pb.Foo{} // if err := any.UnmarshalTo(foo); err != nil { // ... // } // // The pack methods provided by protobuf library will by default use // 'type.googleapis.com/full.type.name' as the type URL and the unpack // methods only use the fully qualified type name after the last '/' // in the type URL, for example "foo.bar.com/x/y.z" will yield type // name "y.z". // // JSON // ==== // The JSON representation of an `Any` value uses the regular // representation of the deserialized, embedded message, with an // additional field `@type` which contains the type URL. Example: // // package google.profile; // message Person { // string first_name = 1; // string last_name = 2; // } // // { // "@type": "type.googleapis.com/google.profile.Person", // "firstName": <string>, // "lastName": <string> // } // // If the embedded message type is well-known and has a custom JSON // representation, that representation will be embedded adding a field // `value` which holds the custom JSON in addition to the `@type` // field. Example (for message [google.protobuf.Duration][]): // // { // "@type": "type.googleapis.com/google.protobuf.Duration", // "value": "1.212s" // } type Any struct { state protoimpl.MessageState `protogen:"open.v1"` // A URL/resource name that uniquely identifies the type of the serialized // protocol buffer message. This string must contain at least // one "/" character. The last segment of the URL's path must represent // the fully qualified name of the type (as in // `path/google.protobuf.Duration`). The name should be in a canonical form // (e.g., leading "." is not accepted). // // In practice, teams usually precompile into the binary all types that they // expect it to use in the context of Any. However, for URLs which use the // scheme `http`, `https`, or no scheme, one can optionally set up a type // server that maps type URLs to message definitions as follows: // // - If no scheme is provided, `https` is assumed. // - An HTTP GET on the URL must yield a [google.protobuf.Type][] // value in binary format, or produce an error. // - Applications are allowed to cache lookup results based on the // URL, or have them precompiled into a binary to avoid any // lookup. Therefore, binary compatibility needs to be preserved // on changes to types. (Use versioned type names to manage // breaking changes.) // // Note: this functionality is not currently available in the official // protobuf release, and it is not used for type URLs beginning with // type.googleapis.com. As of May 2023, there are no widely used type server // implementations and no plans to implement one. // // Schemes other than `http`, `https` (or the empty scheme) might be // used with implementation specific semantics. TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"` // Must be a valid serialized protocol buffer of the above specified type. Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } // New marshals src into a new Any instance. func New(src proto.Message) (*Any, error) { dst := new(Any) if err := dst.MarshalFrom(src); err != nil { return nil, err } return dst, nil } // MarshalFrom marshals src into dst as the underlying message // using the provided marshal options. // // If no options are specified, call dst.MarshalFrom instead. func MarshalFrom(dst *Any, src proto.Message, opts proto.MarshalOptions) error { const urlPrefix = "type.googleapis.com/" if src == nil { return protoimpl.X.NewError("invalid nil source message") } b, err := opts.Marshal(src) if err != nil { return err } dst.TypeUrl = urlPrefix + string(src.ProtoReflect().Descriptor().FullName()) dst.Value = b return nil } // UnmarshalTo unmarshals the underlying message from src into dst // using the provided unmarshal options. // It reports an error if dst is not of the right message type. // // If no options are specified, call src.UnmarshalTo instead. func UnmarshalTo(src *Any, dst proto.Message, opts proto.UnmarshalOptions) error { if src == nil { return protoimpl.X.NewError("invalid nil source message") } if !src.MessageIs(dst) { got := dst.ProtoReflect().Descriptor().FullName() want := src.MessageName() return protoimpl.X.NewError("mismatched message type: got %q, want %q", got, want) } return opts.Unmarshal(src.GetValue(), dst) } // UnmarshalNew unmarshals the underlying message from src into dst, // which is newly created message using a type resolved from the type URL. // The message type is resolved according to opt.Resolver, // which should implement protoregistry.MessageTypeResolver. // It reports an error if the underlying message type could not be resolved. // // If no options are specified, call src.UnmarshalNew instead. func UnmarshalNew(src *Any, opts proto.UnmarshalOptions) (dst proto.Message, err error) { if src.GetTypeUrl() == "" { return nil, protoimpl.X.NewError("invalid empty type URL") } if opts.Resolver == nil { opts.Resolver = protoregistry.GlobalTypes } r, ok := opts.Resolver.(protoregistry.MessageTypeResolver) if !ok { return nil, protoregistry.NotFound } mt, err := r.FindMessageByURL(src.GetTypeUrl()) if err != nil { if err == protoregistry.NotFound { return nil, err } return nil, protoimpl.X.NewError("could not resolve %q: %v", src.GetTypeUrl(), err) } dst = mt.New().Interface() return dst, opts.Unmarshal(src.GetValue(), dst) } // MessageIs reports whether the underlying message is of the same type as m. func (x *Any) MessageIs(m proto.Message) bool { if m == nil { return false } url := x.GetTypeUrl() name := string(m.ProtoReflect().Descriptor().FullName()) if !strings.HasSuffix(url, name) { return false } return len(url) == len(name) || url[len(url)-len(name)-1] == '/' } // MessageName reports the full name of the underlying message, // returning an empty string if invalid. func (x *Any) MessageName() protoreflect.FullName { url := x.GetTypeUrl() name := protoreflect.FullName(url) if i := strings.LastIndexByte(url, '/'); i >= 0 { name = name[i+len("/"):] } if !name.IsValid() { return "" } return name } // MarshalFrom marshals m into x as the underlying message. func (x *Any) MarshalFrom(m proto.Message) error { return MarshalFrom(x, m, proto.MarshalOptions{}) } // UnmarshalTo unmarshals the contents of the underlying message of x into m. // It resets m before performing the unmarshal operation. // It reports an error if m is not of the right message type. func (x *Any) UnmarshalTo(m proto.Message) error { return UnmarshalTo(x, m, proto.UnmarshalOptions{}) } // UnmarshalNew unmarshals the contents of the underlying message of x into // a newly allocated message of the specified type. // It reports an error if the underlying message type could not be resolved. func (x *Any) UnmarshalNew() (proto.Message, error) { return UnmarshalNew(x, proto.UnmarshalOptions{}) } func (x *Any) Reset() { *x = Any{} mi := &file_google_protobuf_any_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Any) String() string { return protoimpl.X.MessageStringOf(x) } func (*Any) ProtoMessage() {} func (x *Any) ProtoReflect() protoreflect.Message { mi := &file_google_protobuf_any_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Any.ProtoReflect.Descriptor instead. func (*Any) Descriptor() ([]byte, []int) { return file_google_protobuf_any_proto_rawDescGZIP(), []int{0} } func (x *Any) GetTypeUrl() string { if x != nil { return x.TypeUrl } return "" } func (x *Any) GetValue() []byte { if x != nil { return x.Value } return nil } var File_google_protobuf_any_proto protoreflect.FileDescriptor const file_google_protobuf_any_proto_rawDesc = "" + "\n" + "\x19google/protobuf/any.proto\x12\x0fgoogle.protobuf\"6\n" + "\x03Any\x12\x19\n" + "\btype_url\x18\x01 \x01(\tR\atypeUrl\x12\x14\n" + "\x05value\x18\x02 \x01(\fR\x05valueBv\n" + "\x13com.google.protobufB\bAnyProtoP\x01Z,google.golang.org/protobuf/types/known/anypb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3" var ( file_google_protobuf_any_proto_rawDescOnce sync.Once file_google_protobuf_any_proto_rawDescData []byte ) func file_google_protobuf_any_proto_rawDescGZIP() []byte { file_google_protobuf_any_proto_rawDescOnce.Do(func() { file_google_protobuf_any_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_google_protobuf_any_proto_rawDesc), len(file_google_protobuf_any_proto_rawDesc))) }) return file_google_protobuf_any_proto_rawDescData } var file_google_protobuf_any_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_google_protobuf_any_proto_goTypes = []any{ (*Any)(nil), // 0: google.protobuf.Any } var file_google_protobuf_any_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_google_protobuf_any_proto_init() } func file_google_protobuf_any_proto_init() { if File_google_protobuf_any_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_google_protobuf_any_proto_rawDesc), len(file_google_protobuf_any_proto_rawDesc)), NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_google_protobuf_any_proto_goTypes, DependencyIndexes: file_google_protobuf_any_proto_depIdxs, MessageInfos: file_google_protobuf_any_proto_msgTypes, }.Build() File_google_protobuf_any_proto = out.File file_google_protobuf_any_proto_goTypes = nil file_google_protobuf_any_proto_depIdxs = nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false