Terminado el error stringify necesario para normalizar la funcion String de los errores definidos

master
DEV 2 years ago
parent 7a621e5c17
commit 4e932c6e9e

@ -1,7 +1,7 @@
package main
import (
"errs/erstr"
"errs/erstfy"
"errs/wrap"
"fmt"
"math/rand"
@ -31,15 +31,21 @@ func main() {
a := wrap.ErrCode("UnError")
//a = nil
var e error
e = wrap.WhitTrace(*wrap.WithMessage(a,"mensage"),1)
e := wrap.WithCause(wrap.WithInfo(wrap.WithMessage(a,"Esto es un mensage")),wrap.WithMessage(wrap.ErrCode("cidd"),"El mensaje de la causa"))
erstr.WithTransformers(
//e = wrap.WithFieldNew(e,"MiCampo",334.33)
/*
erstfy.WithTransformers(
false,"unlabel","upper",
)(&erstr.G.StringifyError)
)(&erstfy.G.Stringify)
*/
fmt.Printf(erstfy.G.ErrorToString(e))
fmt.Printf(erstr.G.Stringify("",e))
}

@ -46,6 +46,6 @@ func (e ErrCode) Code () string {
func (e ErrCode) Build (builder blds.Builder){
builder.Object(func (ob blds.ObjectBuilder) {
ob.Field("Error").String(string(e))
ob.Field("AsError").String(string(e))
})
}

@ -24,6 +24,7 @@
package base64
import (
"bfrs"
"encoding/base64"
)

@ -23,6 +23,10 @@
package errs
import (
"errs/erstfy"
)
type (
ErrCode string
@ -39,3 +43,6 @@ func (e ErrCode) Code () string {
return string(e) }
func (e ErrCode) String () string {
return erstfy.G.LabelLine("code",string(e))
}

@ -22,7 +22,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package erstr
package erstfy
const (
@ -36,7 +36,6 @@ type (
stringer interface { String () string }
unwrapper interface { Unwrap () error }
)
const(
@ -47,9 +46,11 @@ const(
var (
G = struct {
StringifyError
Stringify
}{
StringifyError: *NewStringifyError(),
Stringify: *NewStringify(),
}
)

@ -0,0 +1,81 @@
// ------------------------------------------------------------------------
// 🚀 Project active3
// 🔗 Active Thing (activething.com) git.activething.com/go
//
// File name labels.go
// ✍️ Created by DEV
// 📅 Modified 06/05/2024
//
// 🔒 Copyright 2024 activething.com
//
// 📜 LICENSE --------------------------------------------------------------
// 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 erstfy
import (
"fmt"
"strings"
"typs/strs"
)
type (
Labels struct {
labelSep string
lineLabelFmt string
labelFmt string
labelTrans strs.Transformers
labels map[string]string
}
)
func newLabels() *Labels {
lb := &Labels {
labels : map[string]string{
"message":"message",
"info" : "info",
"date" : "date",
"desc" : "desc",
"time" : "time",
"help" : "help",
"link" : "link",
"cause" : "cause",
"trace:": "trace,",
"param:": "param,",
"source": "source",
"user" : "user",
},
labelSep: labelSep,
labelFmt: "\t%-12s" + labelSep,
}
lb.lineLabelFmt = lb.labelFmt + "%s\n"
return lb
}
func (l *Labels) GetLabel (label string) string {
ll := strings.ToLower(label)
if lb,hs := l.labels[ll]; hs {
return lb
}
l.labels[ll]=label
return label
}
func (l *Labels) FormatLabel (label string) string {
return fmt.Sprintf(l.labelFmt,l.labelTrans.Transform(l.GetLabel(label))) }

@ -0,0 +1,131 @@
// ------------------------------------------------------------------------
// 🚀 Project active3
// 🔗 Active Thing (activething.com) git.activething.com/go
//
// File name stringify.go
// ✍️ Created by DEV
// 📅 Modified 06/05/2024
//
// 🔒 Copyright 2024 activething.com
//
// 📜 LICENSE --------------------------------------------------------------
// 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 erstfy
import (
"bytes"
"fmt"
"strings"
"typs/strs"
)
type (
Stringify struct {
labels Labels
useLabels bool
lineErrorFmt string
lineTextFmt string
trans strs.Transformers
}
StringifyFnc func (stringify *Stringify)
)
func NewStringify(options ...StringifyFnc) *Stringify {
s := &Stringify{
labels : *newLabels(),
useLabels: true,
lineTextFmt : "\t%s\n",
lineErrorFmt: "ERROR %s\n",
}
for _,o := range options {
o(s)
}
return s
}
func (s *Stringify) ErrorToString(err error, lines ...string) string {
ls := append([]string { "" },lines...)
var nl string
ne := err
for ne != nil {
if st,is := ne.(stringer); is {
ls = append(ls,st.String())
}
if uw,is := ne.(unwrapper); is {
ne = uw.Unwrap()
} else {
ne = nil
if strings.Index(nl,labelError) != -1 {
ls[0]= nl
break
}
}
}
if len(ls[0]) == 0 {
ls[0]=s.ErrorLine(err.Error())
}
if len(ls) == 1 {
return ls[0]
}
b := bytes.Buffer{}
for _,l := range ls {
b.WriteString(l)
}
return b.String()
}
func (s *Stringify) ErrorLine(strErr string) string {
if len(s.lineErrorFmt) == 0 {
if s.useLabels {
return s.LabelLine("error", strErr)
}
return s.TextLine(strErr)
}
return fmt.Sprintf(s.lineErrorFmt,s.trans.Transform(strErr))
}
func (s *Stringify) TextLine (text string) string {
if len(s.lineTextFmt) == 0 {
return s.trans.Transform(text) + "\n"
}
return fmt.Sprintf(s.lineTextFmt,s.trans.Transform(text))
}
func (s *Stringify) LabelLine(label, text string) string {
if !s.useLabels || len(label) == 0 {
return s.TextLine(text)
}
return fmt.Sprintf("%s%s\n",s.labels.FormatLabel(label),s.trans.Transform(text))
}
func (s *Stringify) FormatLineAppender (label string, appendFn func(d []byte) []byte) []byte {
if !s.useLabels || len(label) == 0 {
return appendFn(nil)
}
return append(appendFn([]byte(s.labels.FormatLabel(label))),'\n')
}

@ -1,160 +0,0 @@
// ------------------------------------------------------------------------
// 🚀 Project active3
// 🔗 Active Thing (activething.com) git.activething.com/go
//
// File name stringify.go
// ✍️ Created by DEV
// 📅 Modified 06/05/2024
//
// 🔒 Copyright 2024 activething.com
//
// 📜 LICENSE --------------------------------------------------------------
// 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 erstr
import (
"bytes"
"fmt"
"strings"
"typs/strs"
)
type (
StringifyError struct {
labelSep string
lineLabelFmt string
lineErrorFmt string
trans strs.Transformers
}
StringifyErrorFnc func (stringify *StringifyError)
)
func NewStringifyError (options ...StringifyErrorFnc) *StringifyError {
s := &StringifyError{
labelSep: labelSep,
lineLabelFmt: "%s" + labelSep + "%s\n",
lineErrorFmt: labelError + labelSep + "%s\n",
}
for _,o := range options {
o(s)
}
return s
}
func (s *StringifyError) Stringify (text string, err error) string {
ln := []string { "", text }
var nl string
ne := err
for ne != nil {
if st,is := ne.(stringer); is {
nl = st.String()
}
if uw,is := ne.(unwrapper); is {
ne = uw.Unwrap()
} else {
ne = nil
if strings.Index(nl,labelError) != -1 {
ln[0]= s.trans.Transform(nl)
break
}
}
ln = append(ln, s.trans.Transform(nl))
}
if len(ln[0]) == 0 {
ln[0]=s.trans.Transform(err.Error())
}
if len(ln) == 0 {
return ln[0]
}
b := bytes.Buffer{}
for _,l := range ln {
b.WriteString(l)
}
return b.String()
}
func (s *StringifyError) FormatLineError(strErr string) string {
return fmt.Sprintf(s.lineErrorFmt,strErr) }
func (s *StringifyError) FormatLine (label, text string) string {
return fmt.Sprintf(s.lineLabelFmt,label,text) }
func (s *StringifyError) removeLabel (text string) string {
if strings.Index(text,s.labelSep) == -1 {
return text
}
l := strings.Split(text,"\n")
b := bytes.Buffer{}
for _,t := range l {
if p := strings.Index(t,s.labelSep); p != -1 {
b.WriteString(t[p+len(s.labelSep):])
b.WriteByte('\n')
} else {
b.WriteString(t)
}
}
return b.String()
}
func WithFormats (fmtLabelLn, fmtErrorLn, sep string) StringifyErrorFnc {
return func (s *StringifyError) {
s.labelSep = sep
s.lineLabelFmt = fmtLabelLn
s.lineErrorFmt = fmtErrorLn
}
}
func WithTransformers (add bool, transformers ...any) StringifyErrorFnc {
return func (s *StringifyError) {
if !add {
s.trans = s.trans[:0]
}
for _, tf := range transformers {
switch t:=tf.(type) {
case string:
if t == LabelRemover {
s.trans = append(s.trans,strs.TransformFnc(s.removeLabel))
} else {
tr, hs := strs.G.Transformers.Get(t)
if !hs {
panic(strs.G.ErrTransformerNotFound)
}
s.trans = append(s.trans, tr)
}
case strs.Transformer:
if t != nil {
s.trans = append(s.trans,t)
}
case func(string)string:
if t != nil {
s.trans = append(s.trans,strs.TransformFnc(t))
}
default:
panic(strs.G.ErrTransformerNotFound)
}
}
}
}

@ -24,13 +24,13 @@
package ertext
import (
"ansi"
"atypes/astrings"
"aios/ansi"
"errs/stack"
"fmt"
"reflect"
"strings"
"sync"
"typs/strs"
)
@ -52,10 +52,10 @@ func DefaultEncoder() *TextEncoder {
g.formatter = NewTextEncoder(
WithNameTransformers(
astrings.TransformFnc(func (s string) string {
return astrings.ToKebab(s) }),
astrings.TransformFnc(func (s string) string {
return astrings.Pad(s,12,' ',true) }),
strs.TransformFnc(func (s string) string {
return strs.ToKebab(s) }),
strs.TransformFnc(func (s string) string {
return strs.Pad(s,12,' ',true) }),
),
WithSectionsFormat(func(c *Sections) {

@ -34,11 +34,11 @@ type (
TextEncoder struct {
Option
layout Layout
sections Sections
layout Layout
sections Sections
nameTrans strs.Transformers
valueTrans strs.Transformers
nameTrans strs.Transformers
valueTrans strs.Transformers
onFormatError ErrorFallbackFnc
onTraceError ErrorFallbackFnc
@ -83,11 +83,6 @@ func (f *TextEncoder) EncodeError(err error) []byte {
}
func WithErrorFallbacks (format, cause, trace ErrorFallbackFnc) TextEncoderFnc {
return func(f *TextEncoder) {
if format == nil {

@ -24,7 +24,7 @@
package wrap
import (
"errs/erstr"
"errs/erstfy"
)
type (
@ -57,4 +57,4 @@ func (e Cause) Cause () error {
func (e Cause) String() string {
return erstr.G.FormatLine(labelCause,e.cause.Error()) }
return erstfy.G.LabelLine(labelCause,e.cause.Error()) }

@ -24,8 +24,6 @@
package wrap
import "errs/erstr"
type (
ErrCode string
@ -49,5 +47,3 @@ func (e ErrCode) WithMessageF(msgf string, params ...any) *Message {
return WithMessageF(e,msgf,params) }
func (e ErrCode) String () string {
return erstr.G.FormatLineError(e.Error()) }

@ -24,28 +24,35 @@
package wrap
import "flds"
import (
"errs/erstfy"
"flds"
)
type (
Field struct {
error
field flds.Field
flds.Field
}
)
func WithField (err error, field flds.Field) *Field {
if err == nil {}
if field == nil {}
if err == nil { panic(G.ErrNilWrap) }
if field == nil { panic(flds.G.ErrInvalidFieldNil) }
return &Field{
error: err,
field: field,
Field: field,
}
}
func WithFieldNew (err error, name string, value any, kind flds.Kind) *Field {
return WithField(err,flds.Create(name,value,kind)) }
func WithFieldNew (err error, name string, value any) *Field {
return WithField(err,flds.CreateFromValue(name,value)) }
func (e Field) String () string {
return erstfy.G.LabelLine(e.Name(),string(e.AppendAsString(nil))) }

@ -24,13 +24,15 @@
package wrap
import (
"bfrs"
"errs/erstfy"
"flds"
)
type (
ErrFields struct {
Fields struct {
error
*flds.FieldsObject
}
@ -38,15 +40,15 @@ type (
)
func WithFields (err error, options ...flds.FieldsObjectFnc) *ErrFields {
func WithFields (err error, fields ...flds.Field) *Fields {
if err == nil {
panic(G.ErrNilWrap.WithMessageF(errNilWrapMsg, "Fields"))
}
fo,er := flds.NewFieldsObject(options...)
fo,er := flds.NewFieldsObject(flds.FieldsObjectWithFields(fields...))
if er != nil {
panic(er)
}
return &ErrFields{
return &Fields{
error: err,
FieldsObject: fo,
}
@ -54,12 +56,21 @@ func WithFields (err error, options ...flds.FieldsObjectFnc) *ErrFields {
func (e ErrFields) Unwrap() error {
func (e Fields) Unwrap() error {
return e.error }
func (e ErrFields) UnwrapAll() []error {
return nil }
func (e Fields) String () string {
if e.FieldsObject.Len() > 0 {
b := bfrs.AcquireABuffer()
defer bfrs.ReleaseABuffer(b)
for _,f := range e.FieldsObject.List() {
_,_ = b.Write(erstfy.G.FormatLineAppender(f.Name(),f.AppendAsString))
}
return b.String()
}
return ""
}

@ -25,7 +25,7 @@ package wrap
import (
"bytes"
"errs/erstr"
"errs/erstfy"
"time"
)
@ -65,12 +65,12 @@ func (e Info) Unwrap () error {
func (e Info) String () string {
b := bytes.Buffer{}
if len(e.Message) > 0 { b.WriteString(erstr.G.FormatLine(labelMessage,e.Message)) }
if len(e.Info) > 0 { b.WriteString(erstr.G.FormatLine(labelInfo,e.Message)) }
if len(e.Desc) > 0 { b.WriteString(erstr.G.FormatLine(labelDesc,e.Desc)) }
if len(e.Link) > 0 { b.WriteString(erstr.G.FormatLine(labelLink,e.Link)) }
if len(e.Help) > 0 { b.WriteString(erstr.G.FormatLine(labelHelp,e.Help)) }
b.WriteString(erstr.G.FormatLine(labelDate,e.Date.String()))
if len(e.Message) > 0 { b.WriteString(erstfy.G.LabelLine(labelMessage,e.Message)) }
if len(e.Info) > 0 { b.WriteString(erstfy.G.LabelLine(labelInfo,e.Message)) }
if len(e.Desc) > 0 { b.WriteString(erstfy.G.LabelLine(labelDesc,e.Desc)) }
if len(e.Link) > 0 { b.WriteString(erstfy.G.LabelLine(labelLink,e.Link)) }
if len(e.Help) > 0 { b.WriteString(erstfy.G.LabelLine(labelHelp,e.Help)) }
b.WriteString(erstfy.G.LabelLine(labelDate,e.Date.String()))
return b.String()
}

@ -24,7 +24,7 @@
package wrap
import (
"errs/erstr"
"errs/erstfy"
"fmt"
)
@ -59,5 +59,5 @@ func (e Message) Message () string {
func (e Message) String () string {
return erstr.G.FormatLine(labelMessage,e.message)
return erstfy.G.LabelLine(labelMessage,e.message)
}

@ -24,7 +24,10 @@
package wrap
import (
"bfrs"
"errs/erstfy"
"errs/stack"
"fmt"
)
type (
@ -61,3 +64,15 @@ func (e Trace) Unwrap() error {
func (e Trace) StackTrace () stack.Trace {
return e.stack }
func (e Trace) String () string {
b := bfrs.AcquireABuffer()
defer bfrs.ReleaseABuffer(b)
b.WriteString(erstfy.G.TextLine("BEGIN TRACE-----------------------------------"))
for i,f := range e.stack.Frames() {
b.WriteString(erstfy.G.TextLine(
fmt.Sprintf("%d %s.%s \n\t %.90s:%d",i,f.Package, f.FuncName,f.File, f.LineNumber)))
}
b.WriteString(erstfy.G.TextLine("-------------------------------------TRACE END"))
return b.String()
}

@ -45,6 +45,7 @@ var (
ErrInvalidKind ErrCode
ErrInvalidName ErrCode
ErrInvalidFieldNil ErrCode
ErrInvalidDeferFunc ErrCode
ErrDeferNotAllowed ErrCode
ErrFieldsReadOnly ErrCode
@ -52,12 +53,13 @@ var (
ErrDistinctType ErrCode
}{
ErrInvalidKind : ErrCode("invalid-valuerKind"),
ErrInvalidName : ErrCode("invalid-field-name"),
ErrInvalidDeferFunc : ErrCode("invalid-defer-func"),
ErrInvalidName : ErrCode("invalid-field-name"),
ErrInvalidFieldNil : ErrCode("invalid-field-nil"),
ErrInvalidDeferFunc : ErrCode("invalid-defer-func"),
ErrDeferNotAllowed : ErrCode("defer-field-not-allow"),
ErrFieldsReadOnly : ErrCode("fields-read-only"),
ErrDuplicatedField : ErrCode("duplicate-field-name"),
ErrDistinctType : ErrCode("distinct-field-types"),
ErrFieldsReadOnly : ErrCode("fields-read-only"),
ErrDuplicatedField : ErrCode("duplicate-field-name"),
ErrDistinctType : ErrCode("distinct-field-types"),
}
@ -69,10 +71,6 @@ var (
kindDeferName string
kindOnceName string
/* 🚫 DEPRECATED
constructors map[reflect.Type]func(name string, valueFn any) Field
*/
}{
kindDeferName : "defer",
kindOnceName : "defer_once",
@ -91,65 +89,6 @@ var (
"reflect",
},
/* 🚫 DEPRECATED : Tiene mejor rendimiento con el type switch, se descarta
constructors: map[reflect.Type] func(name string, valueFn any) Field {
reflect.TypeOf(false) : func(n string, v any) Field { return NewFieldBool (n,v.(bool)) },
reflect.TypeOf([]byte{}) : func(n string, v any) Field { return NewFieldBinary(n,v.([]byte))} ,
reflect.TypeOf("") : func(n string, v any) Field { return NewFieldString(n,v.(string))},
reflect.TypeOf(int(0)) : func(n string, v any) Field { return NewFieldInt (n,v.(int))},
reflect.TypeOf(int8 (0)) : func(n string, v any) Field { return NewFieldInt (n,int(v.(int8)))},
reflect.TypeOf(int16(0)) : func(n string, v any) Field { return NewFieldInt (n,int(v.(int32)))},
reflect.TypeOf(int32(0)) : func(n string, v any) Field { return NewFieldInt (n,int(v.(int32)))},
reflect.TypeOf(int64(0)) : func(n string, v any) Field { return NewFieldInt (n,int(v.(int64)))},
reflect.TypeOf(uint (0)) : func(n string, v any) Field { return NewFieldUint (n,v.(uint))},
reflect.TypeOf(uint8 (0)) : func(n string, v any) Field { return NewFieldUint (n,uint(v.(uint8)))},
reflect.TypeOf(uint16(0)) : func(n string, v any) Field { return NewFieldUint (n,uint(v.(uint32)))},
reflect.TypeOf(uint32(0)) : func(n string, v any) Field { return NewFieldUint (n,uint(v.(uint32)))},
reflect.TypeOf(uint64(0)) : func(n string, v any) Field { return NewFieldUint (n,uint(v.(uint64)))},
reflect.TypeOf(float64(0)): func(n string, v any) Field { return NewFieldFloat(n,v.(float64))},
reflect.TypeOf(float32(0)): func(n string, v any) Field { return NewFieldFloat(n,float64(v.(float32)))},
reflect.TypeOf(time.Time{}) : func(n string, v any) Field { return NewFieldTime(n,v.(time.Time))},
reflect.TypeOf(time.Duration(0)): func(n string, v any) Field { return NewFieldDuration(n,v.(time.Duration))},
reflect.TypeOf(reflect.Value{}) : func(n string, v any) Field { return NewFieldReflect(n,v.(reflect.Value))},
reflect.TypeOf(func() any (nil)): func(n string, v any) Field { return NewDFieldAny (n,v.(func()any)) },
reflect.TypeOf(func() bool (nil)): func(n string, v any) Field { return NewDFieldBool (n,v.(func()bool))},
reflect.TypeOf(func() []byte(nil)): func(n string, v any) Field { return NewDFieldBinary(n,v.(func()[]byte))},
reflect.TypeOf(func() string(nil)): func(n string, v any) Field { return NewDFieldString(n,v.(func()string))},
reflect.TypeOf(func() int (nil)): func(n string, v any) Field { return NewDFieldInt(n,v.(func()int)) } ,
reflect.TypeOf(func() int8 (nil)): func(n string, v any) Field { return NewDFieldInt(n,func() int { return int(v.(func()int8)()) }) },
reflect.TypeOf(func() int16 (nil)): func(n string, v any) Field { return NewDFieldInt(n,func() int { return int(v.(func()int16)()) }) },
reflect.TypeOf(func() int32 (nil)): func(n string, v any) Field { return NewDFieldInt(n,func() int { return int(v.(func()int32)()) }) },
reflect.TypeOf(func() int64 (nil)): func(n string, v any) Field { return NewDFieldInt(n,func() int { return int(v.(func()int64)()) }) },
reflect.TypeOf(func() uint (nil)): func(n string, v any) Field { return NewDFieldUint(n,v.(func()uint)) },
reflect.TypeOf(func() uint8 (nil)): func(n string, v any) Field { return NewDFieldUint(n,func() uint { return uint(v.(func()uint8)()) }) },
reflect.TypeOf(func() uint16 (nil)): func(n string, v any) Field { return NewDFieldUint(n,func() uint { return uint(v.(func()uint16)()) }) },
reflect.TypeOf(func() uint32 (nil)): func(n string, v any) Field { return NewDFieldUint(n,func() uint { return uint(v.(func()uint32)()) }) },
reflect.TypeOf(func() uint64 (nil)): func(n string, v any) Field { return NewDFieldUint(n,func() uint { return uint(v.(func()uint64)()) }) },
reflect.TypeOf(func() uintptr(nil)): func(n string, v any) Field { return NewDFieldUint(n,func() uint { return uint(v.(func()uintptr)()) }) },
reflect.TypeOf(func() float64(nil)): func(n string, v any) Field { return NewDFieldFloat(n,v.(func()float64)) },
reflect.TypeOf(func() float32(nil)): func(n string, v any) Field { return NewDFieldFloat(n,func()float64{ return float64(v.(func()float32)()) }) },
reflect.TypeOf(func() error (nil)): func(n string, v any) Field { return NewDFieldError(n,v.(func()error)) },
reflect.TypeOf(func() time.Time (nil)): func(n string, v any) Field { return NewDFieldTime(n,v.(func()time.Time)) },
reflect.TypeOf(func() time.Duration(nil)): func(n string, v any) Field { return NewDFieldDuration(n,v.(func()time.Duration)) },
reflect.TypeOf(func() reflect.Value(nil)): func(n string, v any) Field { return NewDFieldReflect(n,v.(func()reflect.Value))},
},
*/
}
)

@ -43,6 +43,6 @@ func (e ErrCode) Code () string {
func (e ErrCode) Build (builder blds.Builder) {
builder.Object(func (ob blds.ObjectBuilder ) {
ob.Field("Error").String(string(e))
ob.Field("AsError").String(string(e))
})
}

@ -29,6 +29,7 @@ type (
Field interface {
typeResolver
StringAppender
Kind () Kind
Name () string
@ -54,16 +55,16 @@ func buildFieldAsField (field Field, obuilder blds.ObjectBuilder) {
vb := obuilder.Field(field.Name())
switch field.Kind() {
case KindAny : vb.Any (field.Value())
case KindBool : v,_ := field.Bool(); vb.Bool(v)
case KindBinary : v,_ := field.Binary(); vb.Binary(v)
case KindString : v,_ := field.String(); vb.String(v)
case KindInt : v,_ := field.Int(); vb.Int(v)
case KindUint : v,_ := field.Uint(); vb.Uint(v)
case KindFloat : v,_ := field.Float(); vb.Float64(v)
case KindTime : v,_ := field.Time(); vb.Time(v)
case KindDuration: v,_ := field.Duration(); vb.Duration(v)
case KindError : v,_ := field.Error(); vb.Error(v)
case KindReflect : v,_ := field.Reflect(); vb.Reflect(v)
case KindBool : v,_ := field.AsBool(); vb.Bool(v)
case KindBinary : v,_ := field.AsBinary(); vb.Binary(v)
case KindString : v,_ := field.AsString(); vb.String(v)
case KindInt : v,_ := field.AsInt(); vb.Int(v)
case KindUint : v,_ := field.AsUint(); vb.Uint(v)
case KindFloat : v,_ := field.AsFloat(); vb.Float64(v)
case KindTime : v,_ := field.AsTime(); vb.Time(v)
case KindDuration: v,_ := field.AsDuration(); vb.Duration(v)
case KindError : v,_ := field.AsError(); vb.Error(v)
case KindReflect : v,_ := field.AsReflect(); vb.Reflect(v)
default:
vb.Any(field.Value())
}

@ -52,22 +52,22 @@ func (f FieldAny) Kind() Kind {
return KindAny | f.valuerKind() }
func (f FieldAny) Bool () (bool,bool) {
func (f FieldAny) AsBool() (bool,bool) {
v,ok := f.Native().(bool)
return v,ok
}
func (f FieldAny) Binary () ([]byte,bool) {
func (f FieldAny) AsBinary() ([]byte,bool) {
v, ok := f.Native().([]byte)
return v, ok
}
func (f FieldAny) String () (string,bool) {
func (f FieldAny) AsString() (string,bool) {
v,ok := f.Native().(string)
return v,ok
}
func (f FieldAny) Int () (int,bool) {
func (f FieldAny) AsInt() (int,bool) {
switch t := f.Native().(type) {
case int : return t,true
case int8 : return int(t),true
@ -78,7 +78,7 @@ func (f FieldAny) Int () (int,bool) {
}
}
func (f FieldAny) Uint () (uint,bool) {
func (f FieldAny) AsUint() (uint,bool) {
switch t := f.Native().(type) {
case uint : return t,true
case uint8 : return uint(t),true
@ -89,7 +89,7 @@ func (f FieldAny) Uint () (uint,bool) {
}
}
func (f FieldAny) Float () (float64,bool) {
func (f FieldAny) AsFloat() (float64,bool) {
vl := f.Native()
v, ok := vl.(float64)
if !ok {
@ -107,25 +107,25 @@ func (f FieldAny) Date () (time.Time,bool) {
return v, ok
}
func (f FieldAny) Time () (time.Time,bool) {
func (f FieldAny) AsTime() (time.Time,bool) {
v, ok := f.Native().(time.Time)
return v, ok
}
func (f FieldAny) Duration () (time.Duration,bool) {
func (f FieldAny) AsDuration() (time.Duration,bool) {
v, ok := f.Native().(time.Duration)
return v, ok
}
func (f FieldAny) Error () (error,bool) {
func (f FieldAny) AsError() (error,bool) {
v, ok := f.Native().(error)
return v, ok
}
func (f FieldAny) Reflect () (reflect.Value,bool) {
func (f FieldAny) AsReflect() (reflect.Value,bool) {
v, ok := f.Native().(reflect.Value)
return v, ok
}

@ -23,7 +23,10 @@
package flds
import "blds"
import (
"blds"
"encoding/base64"
)
type (
@ -47,10 +50,13 @@ func (f FieldBinary) Kind () Kind {
return KindBinary | f.valuerKind() }
func (f FieldBinary) Binary() ([]byte,bool) {
func (f FieldBinary) AsBinary() ([]byte,bool) {
return f.Native(),true }
func (f FieldBinary) AppendAsString (dest []byte) []byte {
return append(dest,[]byte(base64.StdEncoding.EncodeToString(f.Native()))...) }
func (f FieldBinary) Build (builder blds.Builder) {
builder.Object(func(b blds.ObjectBuilder){

@ -23,7 +23,10 @@
package flds
import "blds"
import (
"blds"
"strconv"
)
type (
@ -48,10 +51,14 @@ func (f FieldBool) Kind () Kind {
return KindBool | f.valuerKind() }
func (f FieldBool) Bool() (bool,bool) {
func (f FieldBool) AsBool() (bool,bool) {
return f.Native(),true }
func (f FieldBool) AppendAsString (dest []byte) []byte {
return strconv.AppendBool(dest,f.Native()) }
func (f FieldBool) Build (builder blds.Builder) {
builder.Object(func(b blds.ObjectBuilder){
b.Field(f.name).Bool(f.Native()) }) }

@ -25,6 +25,7 @@ package flds
import (
"blds"
"strconv"
"time"
)
@ -51,9 +52,12 @@ func (f FieldDuration) Kind () Kind {
return KindDuration | f.valuerKind() }
func (f FieldDuration) Duration() (time.Duration,bool) {
func (f FieldDuration) AsDuration() (time.Duration,bool) {
return f.Native(),true }
func (f FieldDuration) AppendAsString(dest []byte) []byte {
return strconv.AppendUint(dest,uint64(f.Native()),10) }
func (f FieldDuration) Build (builder blds.Builder) {
builder.Object(func(b blds.ObjectBuilder){

@ -23,7 +23,10 @@
package flds
import "blds"
import (
"blds"
"typs/strs"
)
type (
@ -48,9 +51,19 @@ func (f FieldError) Kind () Kind {
return KindError | f.valuerKind() }
func (f FieldError) Error() (error,bool) {
func (f FieldError) AsError() (error,bool) {
return f.Native(),true }
func (f FieldError) AppendAsString (dest []byte) []byte {
e := f.Native()
if e == nil {
return dest
}
if st,is := e.(strs.Stringer); is {
return append(dest,[]byte(st.String())...)
}
return append(dest,[]byte(e.Error())...)
}
func (f FieldError) Build (builder blds.Builder) {

@ -23,7 +23,10 @@
package flds
import "blds"
import (
"blds"
"strconv"
)
type (
@ -47,10 +50,13 @@ func (f FieldFloat) Kind () Kind {
return KindFloat | f.valuerKind() }
func (f FieldFloat) Float() (float64,bool) {
func (f FieldFloat) AsFloat() (float64,bool) {
return f.Native(),true }
func (f FieldFloat) AppendAsString (dest []byte) []byte {
return strconv.AppendFloat(dest,f.Native(),'f',-1,64) }
func (f FieldFloat) Build (builder blds.Builder) {
builder.Object(func(b blds.ObjectBuilder){

@ -23,7 +23,10 @@
package flds
import "blds"
import (
"blds"
"strconv"
)
type (
@ -48,10 +51,14 @@ func (f FieldInt) Kind () Kind {
return KindInt | f.valuerKind() }
func (f FieldInt) Int() (int,bool) {
func (f FieldInt) AsInt() (int,bool) {
return f.Native(),true }
func (f FieldInt) AppendAsString (dest []byte) []byte {
return strconv.AppendInt(dest,int64(f.Native()),10) }
func (f FieldInt) Build (builder blds.Builder) {
builder.Object(func(b blds.ObjectBuilder){
b.Field(f.name).Int(f.Native()) }) }

@ -25,6 +25,7 @@ package flds
import (
"blds"
"fmt"
"reflect"
)
@ -50,9 +51,11 @@ func (f FieldReflect) Kind () Kind {
return KindReflect | f.valuerKind() }
func (f FieldReflect) Reflect() (reflect.Value,bool) {
func (f FieldReflect) AsReflect() (reflect.Value,bool) {
return f.Native(),true }
func (f FieldReflect) AppendAsString (dest []byte) []byte {
return append (dest,fmt.Sprintf("%#v",f.Native())...) }
func (f FieldReflect) Build (builder blds.Builder) {

@ -23,7 +23,9 @@
package flds
import "blds"
import (
"blds"
)
type (
@ -47,9 +49,12 @@ func NewDOFieldString (name string, valueFn func() string) *FieldString {
func (f FieldString) Kind () Kind {
return KindString | f.valuerKind() }
func (f FieldString) String() (string,bool) {
func (f FieldString) AsString() (string,bool) {
return f.Native(),true }
func (f FieldString) AppendAsString (dest []byte) []byte {
return append (dest,[]byte(f.Native())...)}
func (f FieldString) Build (builder blds.Builder) {
builder.Object(func(b blds.ObjectBuilder){

@ -51,9 +51,12 @@ func (f FieldTime) Kind () Kind {
return KindTime | f.valuerKind() }
func (f FieldTime) Time() (time.Time,bool) {
func (f FieldTime) AsTime() (time.Time,bool) {
return f.Native(),true }
func (f FieldTime) AppendAsString (dest []byte) []byte {
return append (dest,[]byte(f.Native().String())...)}
func (f FieldTime) Build (builder blds.Builder) {
builder.Object(func(b blds.ObjectBuilder){

@ -23,7 +23,10 @@
package flds
import "blds"
import (
"blds"
"strconv"
)
type (
@ -50,10 +53,13 @@ func (f FieldUint) Kind () Kind {
return KindUint | f.valuerKind() }
func (f FieldUint) Uint() (uint,bool) {
func (f FieldUint) AsUint() (uint,bool) {
return f.Native(),true }
func (f FieldUint) AppendAsString (dest []byte) []byte {
return strconv.AppendUint (dest,uint64(f.Native()),10) }
func (f FieldUint) Build (builder blds.Builder) {
builder.Object(func(b blds.ObjectBuilder){

@ -99,6 +99,9 @@ func (f *FieldsObject) Add(field Field) error {
if f.atts.IsReadOnly() {
return G.ErrFieldsReadOnly
}
if field == nil {
return G.ErrInvalidFieldNil
}
if p := f.fields.indexOf(field.Name()); p != -1 {
if f.atts.IsNotDuplicate() {
return G.ErrDuplicatedField
@ -126,6 +129,9 @@ func (f *FieldsObject) Set(field Field) error {
if f.atts.IsReadOnly() {
return G.ErrFieldsReadOnly
}
if field == nil {
return G.ErrInvalidFieldNil
}
if f.atts.IsNotDefer() && field.Kind().IsDefer() {
return G.ErrDeferNotAllowed
}
@ -204,9 +210,20 @@ func FieldsObjectWithAtts (set FieldsAtt) FieldsObjectFnc {
return nil } }
func FieldsObjectWithField(field Field) FieldsObjectFnc {
func FieldsObjectWithFields (field ...Field) FieldsObjectFnc {
return func(f *FieldsObject) error {
return f.Add(field) } }
for _, fl := range field {
if fl == nil {
continue
}
if e := f.Add(fl); e != nil {
return e
}
}
return nil
}
}
func FieldsObjectWithNew (name string, value any, kind Kind) FieldsObjectFnc {

@ -53,6 +53,8 @@ type (
Kind uint16
)
func (k Kind) JustType () Kind {
return k&typesMask }
func (k Kind) IsAny() bool {
return k&KindAny != 0 }

@ -53,33 +53,30 @@ func makePartialFieldLocal[T any] (name string, value T) partialField[T]{
func makePartialFieldDefer[T any] (name string, valueFn func() T) partialField[T] {
return partialField[T]{
name : name,
valuer: makeDeferValuer[T](valueFn),
}
}
valuer: makeDeferValuer[T](valueFn) }}
func makePartialFieldOnce [T any] (name string, valueFn func() T) partialField[T] {
return partialField[T]{
name : name,
valuer: newOnceValuer[T](valueFn),
}
}
valuer: newOnceValuer[T](valueFn) }}
func (f partialField[T]) Name() string {
return f.name }
func (f partialField[T]) AppendAsString (dest []byte) []byte { return dest }
func (f partialField[T]) AsBool() (bool, bool) { return false, false }
func (f partialField[T]) AsString() (string, bool) { return "", false }
func (_ partialField[T]) AsBinary() ([]byte, bool) { return nil, false }
func (_ partialField[T]) AsInt() (int, bool) { return 0, false }
func (_ partialField[T]) AsUint() (uint, bool) { return 0, false }
func (_ partialField[T]) AsFloat() (float64, bool) { return 0, false }
func (_ partialField[T]) AsTime() (time.Time, bool) { return g.timeZero, false }
func (_ partialField[T]) AsDuration() (time.Duration, bool) { return 0, false }
func (_ partialField[T]) AsError() (error, bool) { return nil, false }
func (_ partialField[T]) AsReflect() (reflect.Value, bool) { return g.reflectZero, false }
func (_ partialField[T]) Bool () (bool, bool) { return false, false }
func (_ partialField[T]) String () (string, bool) { return "", false }
func (_ partialField[T]) Binary () ([]byte, bool) { return nil, false }
func (_ partialField[T]) Int () (int, bool) { return 0, false }
func (_ partialField[T]) Uint () (uint, bool) { return 0, false }
func (_ partialField[T]) Float () (float64, bool) { return 0, false }
func (_ partialField[T]) Time () (time.Time, bool) { return g.timeZero, false }
func (_ partialField[T]) Duration() (time.Duration, bool) { return 0, false }
func (_ partialField[T]) Error () (error, bool) { return nil, false }
func (_ partialField[T]) Reflect () (reflect.Value, bool) { return g.reflectZero, false }

@ -0,0 +1,36 @@
// ------------------------------------------------------------------------
// 🚀 Project active3
// 🔗 Active Thing (activething.com) git.activething.com/go
//
// File name string_appender.go
// ✍️ Created by DEV
// 📅 Modified 06/05/2024
//
// 🔒 Copyright 2024 activething.com
//
// 📜 LICENSE --------------------------------------------------------------
// 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 flds
type (
StringAppender interface {
AppendAsString (dest []byte) []byte
}
)

@ -35,44 +35,47 @@ type (
// de éxito para indicar si la resolución fue exitosa o no.
typeResolver interface {
// Bool intenta resolver y devolver el valor como un booleano.
// AsBool intenta resolver y devolver el valor como un booleano.
// Retorna el valor booleano y un indicador de éxito.
Bool() (bool, bool)
AsBool() (bool, bool)
// Binary intenta resolver y devolver el valor como un slice de bytes.
// AsBinary intenta resolver y devolver el valor como un slice de bytes.
// Retorna el slice de bytes y un indicador de éxito.
Binary() ([]byte, bool)
AsBinary() ([]byte, bool)
// String intenta resolver y devolver el valor como una cadena de texto.
// AsString intenta resolver y devolver el valor como una cadena de texto.
// Retorna la cadena de texto y un indicador de éxito.
String() (string, bool)
AsString() (string, bool)
// Int intenta resolver y devolver el valor como un entero.
// AsInt intenta resolver y devolver el valor como un entero.
// Retorna el entero y un indicador de éxito.
Int() (int, bool)
AsInt() (int, bool)
// Uint intenta resolver y devolver el valor como un entero sin signo.
// AsUint intenta resolver y devolver el valor como un entero sin signo.
// Retorna el entero sin signo y un indicador de éxito.
Uint() (uint, bool)
AsUint() (uint, bool)
// Float intenta resolver y devolver el valor como un número flotante de punto flotante de 64 bits.
// AsFloat intenta resolver y devolver el valor como un número flotante de punto flotante de 64 bits.
// Retorna el número flotante y un indicador de éxito.
Float() (float64, bool)
AsFloat() (float64, bool)
// Time intenta resolver y devolver el valor como una marca de tiempo.
// AsTime intenta resolver y devolver el valor como una marca de tiempo.
// Retorna la marca de tiempo y un indicador de éxito.
Time() (time.Time, bool)
AsTime() (time.Time, bool)
// Duration intenta resolver y devolver el valor como una duración de tiempo
// AsDuration intenta resolver y devolver el valor como una duración de tiempo
// Retorna la duración y un indicador de éxito.
Duration() (time.Duration, bool)
AsDuration() (time.Duration, bool)
// Error intenta resolver y devolver el valor como un error.
// AsError intenta resolver y devolver el valor como un error.
// Retorna el error y un indicador de éxito.
Error() (error, bool)
AsError() (error, bool)
// Reflect intenta resolver y devolver el valor como un reflect.Value.
// AsReflect intenta resolver y devolver el valor como un reflect.Value.
// Retorna el reflect.Value y un indicador de éxito.
Reflect() (reflect.Value, bool)
AsReflect() (reflect.Value, bool)
}
)

@ -35,7 +35,7 @@ type (
// devolvera nil.
Success() any
// Fail Error; contiene el error del resultado
// Fail AsError; contiene el error del resultado
Fail() error

@ -35,8 +35,8 @@ type (
// ABool
// Type: Struct
// Desc: Atomic Bool, estructura para realizar operaciones atomicas
// sobre un valor de tipo Bool
// Desc: Atomic AsBool, estructura para realizar operaciones atomicas
// sobre un valor de tipo AsBool
//
ABool struct {

@ -2,7 +2,7 @@
// Project active2
// Active Thing (activething.com) git.activething.com/go
//
// File name err_astrings.go
// File name err_strs.go
// Created by DEV
// Modified 26/04/2024
//

@ -0,0 +1,43 @@
// ------------------------------------------------------------------------
// 🚀 Project active3
// 🔗 Active Thing (activething.com) git.activething.com/go
//
// File name stringer.go
// ✍️ Created by DEV
// 📅 Modified 06/05/2024
//
// 🔒 Copyright 2024 activething.com
//
// 📜 LICENSE --------------------------------------------------------------
// 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 strs
type (
Stringer interface {
String() string
}
StringFnc func () string
)
func (f StringFnc) String() string {
return f() }
Loading…
Cancel
Save

Powered by TurnKey Linux.