pack reestructurado terminado

master
DEV 2 years ago
parent e637d6752e
commit 410868b01b

@ -50,7 +50,7 @@ func NewPacker (options ...PackerFnc) *Packer {
} }
func (p Packer) Pack (value any) rsls.Bytes { func (p Packer) pack(value any) rsls.Bytes {
b := newBuilder(p.f) b := newBuilder(p.f)
defer b.release() defer b.release()

@ -1,7 +1,7 @@
package main package main
import ( import (
"apack/pkj" "apacks/pkjson"
"errs" "errs"
"fmt" "fmt"
"math/rand" "math/rand"
@ -11,13 +11,17 @@ import (
type ( type (
S struct { S struct {
A string A string `pack:"encrypted"`
F float32
} }
) )
func Una () S { func Una () S {
fmt.Println("Es llamado ") fmt.Println("Es llamado ")
return S { A : "Un valiue" } return S {
A : "sdsd",
F : 32.45,
}
} }
func randomInt(min, max int) int { func randomInt(min, max int) int {
@ -56,13 +60,13 @@ func main() {
"catorce": 15.16, "catorce": 15.16,
"dfate": time.Now(), "dfate": time.Now(),
time.Now(): "ff", time.Now(): "ff",
"SSSS" : S{A:"a"}, "SSSS" : S{A:"a",F: 32.2},
} }
r := p.Pack(myMap) r := p.pack(myMap)
if !r.Ok() { if !r.Ok() {
fmt.Printf("%s \n",string(errs.Format(r.Fail(), eftext.Formatter()))) fmt.Printf("%s \n",string(errs.Format(r.Fail(), eftext.Formatter())))
return return
@ -77,9 +81,8 @@ func main() {
*/ */
b := pkj.NewBuilder()
//r := b.Pack(S{ A : "SOOOOOO"}) r := pkjson.Pack(
r := b.Pack(
map[interface{}]interface{}{ map[interface{}]interface{}{
//1: "uno", //1: "uno",
"dos": 2, "dos": 2,
@ -98,7 +101,7 @@ func main() {
time.Now(): "ff", time.Now(): "ff",
"SSSS" : S{A:"a"}, "SSSS" : Una(),
}, },

@ -1,3 +0,0 @@
module apack
go 1.22

@ -0,0 +1,3 @@
module apacks
go 1.22

@ -0,0 +1,45 @@
// ------------------------------------------------------------------------
// 🚀 Project active3
// 🔗 Active Thing (activething.com) git.activething.com/go
//
// File name packer.go
// ✍️ Created by DEV
// 📅 Modified 12/06/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 apack
import "rsls"
type (
Packer interface {
pack(value any) rsls.Bytes
}
PackFnc func(value any) rsls.Bytes
)
func (f PackFnc) pack(value any) rsls.Bytes {
return f(value) }

@ -22,14 +22,15 @@
// limitations under the License. // limitations under the License.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
package pkj package pkjson
import ( import (
"apack" "apacks"
"blds" "blds"
"encoding" "encoding"
"encoding/json" "encoding/json"
"reflect" "reflect"
"rsls"
"time" "time"
) )
@ -87,3 +88,6 @@ var (
) )
func Pack (value any, flag...apack.Flags) rsls.Bytes {
return (NewBuilder(flag...)).Pack(value) }

@ -22,14 +22,15 @@
// limitations under the License. // limitations under the License.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
package pkj package pkjson
import ( import (
"apack" "apacks"
"apack/pstate" "apacks/pkstate"
"blds" "blds"
"cdcs/cjson" "cdcs/cjson"
"encoding/json" "encoding/json"
"fmt"
"reflect" "reflect"
"rsls" "rsls"
"time" "time"
@ -38,28 +39,75 @@ import (
type ( type (
Builder struct { Builder struct {
*pstate.State *pkstate.State
e *json.Encoder e *json.Encoder
f apack.Flags f apack.Flags
} }
) )
func NewBuilder () *Builder {
func NewBuilder(flag ...apack.Flags) *Builder {
f := apack.Flags(0)
if len(flag) == 1 {
f = flag[0]
} else if len(flag) > 1 {
for _,fl := range flag {
f|=fl
}
}
return &Builder{ return &Builder{
State : pstate.AcquireState(), State : pkstate.AcquireState(),
f : f,
} }
} }
func (b *Builder) Pack (value any) rsls.Bytes { func (b *Builder) release () {
pkstate.ReleaseState(b.State)
b.State = nil
}
func (b *Builder) Pack(value any) (rs rsls.Bytes) {
d := false
// Defer function to handle panic recovery and resource release
defer func(bl *Builder, dn *bool){
// If not done, recover from any panic
if !(*dn) {
if rc := recover(); rc != nil {
if er, is := rc.(error); is {
rs = rsls.MakeBytesError(er)
} else {
rs = rsls.MakeBytesError(fmt.Errorf("%#v", rc))
}
}
}
// Release resources
bl.release()
}(b, &d)
// Attempt to process the value
b.Any(value) b.Any(value)
d = true // Mark as done if no panic occurred
// Check for errors in the builder
if b.Err != nil { if b.Err != nil {
return rsls.MakeBytesError(b.Err) return rsls.MakeBytesError(b.Err)
} }
// Return success result with bytes
return rsls.MakeBytesSuccess(b.B.Bytes()) return rsls.MakeBytesSuccess(b.B.Bytes())
} }
func (b *Builder) Any (value any) { func (b *Builder) Any (value any) {
if value == nil { if value == nil {
@ -153,7 +201,7 @@ func (b *Builder) Any (value any) {
case []time.Duration: case []time.Duration:
packListG[time.Duration](b, v, b.Duration) packListG[time.Duration](b, v, b.Duration)
case []error: case []error:
b.buildLevel(pstate.ModeList, v == nil, len(v) == 0, func(bl *Builder) { b.buildLevel(pkstate.ModeList, v == nil, len(v) == 0, func(bl *Builder) {
for _, e := range v { for _, e := range v {
bl.Item() bl.Item()
if bl.Err == nil { if bl.Err == nil {
@ -196,7 +244,7 @@ func (b *Builder) Any (value any) {
case map[string]time.Duration: case map[string]time.Duration:
packMapG[time.Duration](b, v, b.Duration) packMapG[time.Duration](b, v, b.Duration)
case map[string]error: case map[string]error:
b.buildLevel(pstate.ModeMap, v == nil, len(v) == 0, func(bl *Builder) { b.buildLevel(pkstate.ModeMap, v == nil, len(v) == 0, func(bl *Builder) {
for k, v := range v { for k, v := range v {
bl.Field(k) bl.Field(k)
if bl.Err == nil { if bl.Err == nil {
@ -386,17 +434,17 @@ func (b *Builder) writeBinary (value []byte, flags apack.Flags) {
func (b *Builder) List (fnc func(builder blds.ListBuilder)) { func (b *Builder) List (fnc func(builder blds.ListBuilder)) {
b.buildLevel(pstate.ModeList,fnc==nil,false,func(bl *Builder){ b.buildLevel(pkstate.ModeList,fnc==nil,false,func(bl *Builder){
fnc(b) }) } fnc(b) }) }
func (b *Builder) Map (fnc func(builder blds.MapBuilder)) { func (b *Builder) Map (fnc func(builder blds.MapBuilder)) {
b.buildLevel(pstate.ModeMap,fnc == nil, false, func(bl *Builder){ b.buildLevel(pkstate.ModeMap,fnc == nil, false, func(bl *Builder){
fnc(b) }) } fnc(b) }) }
func (b *Builder) Object (fnc func(builder blds.ObjectBuilder)) { func (b *Builder) Object (fnc func(builder blds.ObjectBuilder)) {
b.buildLevel(pstate.ModeObject,fnc == nil, false, func(bl *Builder){ b.buildLevel(pkstate.ModeObject,fnc == nil, false, func(bl *Builder){
fnc(b) }) } fnc(b) }) }
@ -434,7 +482,7 @@ func (b *Builder) Field (name string) blds.ValueBuilder {
func (b *Builder) buildLevel (mode pstate.Mode, isNil, isEmpty bool, buildFnc func(builder *Builder)) { func (b *Builder) buildLevel (mode pkstate.Mode, isNil, isEmpty bool, buildFnc func(builder *Builder)) {
if !b.preValue() { if !b.preValue() {
return return
} }
@ -446,7 +494,7 @@ func (b *Builder) buildLevel (mode pstate.Mode, isNil, isEmpty bool, buildFnc fu
} }
if isEmpty { if isEmpty {
if mode == pstate.ModeList { if mode == pkstate.ModeList {
b.B.Write2Byte('[',']') b.B.Write2Byte('[',']')
} else { } else {
b.B.Write2Byte('{','}') b.B.Write2Byte('{','}')
@ -457,7 +505,7 @@ func (b *Builder) buildLevel (mode pstate.Mode, isNil, isEmpty bool, buildFnc fu
b.Open(mode) b.Open(mode)
be := byte('}') be := byte('}')
if mode == pstate.ModeList { if mode == pkstate.ModeList {
b.B.WriteByte('[') b.B.WriteByte('[')
be = ']' be = ']'
} else { } else {
@ -493,8 +541,8 @@ func (b *Builder) postValue () {
} }
b.Current.IsValue = false b.Current.IsValue = false
b.Current.Count++ b.Current.Count++
if b.Current.Mode == pstate.ModeValue { if b.Current.Mode == pkstate.ModeValue {
b.Current.Mode = pstate.ModeNone b.Current.Mode = pkstate.ModeNone
} }
} }
@ -533,7 +581,7 @@ func (b *Builder) encode (value any) error {
func packListG[T basicTypes](b *Builder, list []T, fncType func(vl T)) { func packListG[T basicTypes](b *Builder, list []T, fncType func(vl T)) {
b.buildLevel(pstate.ModeList,list == nil, len(list) == 0,func(bl *Builder){ b.buildLevel(pkstate.ModeList,list == nil, len(list) == 0,func(bl *Builder){
for _,v := range list { for _,v := range list {
b.Item() b.Item()
if b.Err == nil { if b.Err == nil {
@ -547,7 +595,7 @@ func packListG[T basicTypes](b *Builder, list []T, fncType func(vl T)) {
} }
func packMapG[T basicTypes](b *Builder, m map[string]T, fncType func(vl T)) { func packMapG[T basicTypes](b *Builder, m map[string]T, fncType func(vl T)) {
b.buildLevel(pstate.ModeMap, m == nil, len(m) == 0, func(bl *Builder){ b.buildLevel(pkstate.ModeMap, m == nil, len(m) == 0, func(bl *Builder){
for k,v := range m { for k,v := range m {
// Usamos b.Field y no b.Key porque sabemos que no es necesario // Usamos b.Field y no b.Key porque sabemos que no es necesario
// hacerle un stringify y el objeto como el map la codificación // hacerle un stringify y el objeto como el map la codificación

@ -22,11 +22,11 @@
// limitations under the License. // limitations under the License.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
package pkj package pkjson
import ( import (
"apack" "apacks"
"apack/pstate" "apacks/pkstate"
"blds" "blds"
"cdcs/cjson" "cdcs/cjson"
"core/tups" "core/tups"
@ -136,7 +136,7 @@ func newRPackers (options ...rpackersFnc) *rpackers {
if !v.IsNil() { if !v.IsNil() {
l = v.Interface().([]error) l = v.Interface().([]error)
} }
b.buildLevel(pstate.ModeList, l == nil, len(l) == 0, func(bl *Builder) { b.buildLevel(pkstate.ModeList, l == nil, len(l) == 0, func(bl *Builder) {
for _, e := range l { for _, e := range l {
bl.Item() bl.Item()
if bl.Err == nil { if bl.Err == nil {
@ -176,7 +176,7 @@ func newRPackers (options ...rpackersFnc) *rpackers {
if !v.IsNil() { if !v.IsNil() {
l = v.Interface().(map[string]error) l = v.Interface().(map[string]error)
} }
b.buildLevel(pstate.ModeMap, l == nil, len(l) == 0, func(bl *Builder) { b.buildLevel(pkstate.ModeMap, l == nil, len(l) == 0, func(bl *Builder) {
for k,v := range l { for k,v := range l {
bl.Field(k) bl.Field(k)
if bl.Err == nil { if bl.Err == nil {
@ -299,7 +299,7 @@ func (p *rpackers) buildRPacker (rtype reflect.Type) rPackFnc {
} }
} }
b.buildLevel(pstate.ModeList, false, v.Len() == 0, func(bl *Builder){ b.buildLevel(pkstate.ModeList, false, v.Len() == 0, func(bl *Builder){
for i:=0; i<v.Len();i++ { for i:=0; i<v.Len();i++ {
bl.Item() bl.Item()
eleFn(bl,v.Index(i)) eleFn(bl,v.Index(i))
@ -347,7 +347,7 @@ func (p *rpackers) buildRPacker (rtype reflect.Type) rPackFnc {
return ls[i].A < ls[j].A return ls[i].A < ls[j].A
}) })
b.buildLevel(pstate.ModeMap,v.IsNil(),v.Len() == 0,func(bl *Builder){ b.buildLevel(pkstate.ModeMap,v.IsNil(),v.Len() == 0,func(bl *Builder){
for i:=0; i<len(ls); i++ { for i:=0; i<len(ls); i++ {
bl.Field(ls[i].A) bl.Field(ls[i].A)
if b.Err == nil { if b.Err == nil {

@ -22,11 +22,11 @@
// limitations under the License. // limitations under the License.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
package pkj package pkjson
import ( import (
"apack" "apacks"
"reflect" "reflect"
) )

@ -22,7 +22,7 @@
// limitations under the License. // limitations under the License.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
package pkj package pkjson

@ -22,11 +22,13 @@
// limitations under the License. // limitations under the License.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
package pkj package pkjson
import ( import (
"apack" "apacks"
"apacks/pkstate"
"bfrs" "bfrs"
"fmt"
"reflect" "reflect"
"sort" "sort"
) )
@ -126,9 +128,7 @@ func newRObject (rtype reflect.Type) *rObject {
// BuildPack nameEscHTML and nameNonEsc ahead of time. // BuildPack nameEscHTML and nameNonEsc ahead of time.
nms.Reset() nms.Reset()
nms.WriteByte('"')
nms.WriteHTML(of.nameBin) nms.WriteHTML(of.nameBin)
nms.Write2Byte('"',':')
of.name = nms.String() of.name = nms.String()
of.nameUns = `"` + of.name + `":` of.nameUns = `"` + of.name + `":`
@ -143,14 +143,8 @@ func newRObject (rtype reflect.Type) *rObject {
if nxCnt[ft] == 1 { if nxCnt[ft] == 1 {
nxt = append(nxt,rField{ name: ft.Name(), index: index, rtype: ft}) nxt = append(nxt,rField{ name: ft.Name(), index: index, rtype: ft})
} }
} }
} }
} }
sort.Slice(fls,func(i,j int) bool { sort.Slice(fls,func(i,j int) bool {
@ -207,38 +201,30 @@ func newRObject (rtype reflect.Type) *rObject {
func (o rObject) pack (b *Builder, v reflect.Value) { func (o rObject) pack (b *Builder, v reflect.Value) {
nx := byte('{') b.buildLevel(pkstate.ModeObject,false,len(o.fields) == 0,func(bl *Builder){
FieldLoop: LOOP:
for i:= range o.fields { for i:= range o.fields {
fd := &o.fields[i] fd := &o.fields[i]
fv := v
fv := v for _,i := range fd.index {
for _,i := range fd.index { if fv.Kind() == reflect.Pointer {
if fv.Kind() == reflect.Pointer { if fv.IsNil() {
if fv.IsNil() { continue LOOP
continue FieldLoop }
fv = fv.Elem()
} }
fv = fv.Elem() fv = fv.Field(i)
} }
fv = fv.Field(i) if fd.flags.OmitEmpty() && isEmptyValue(v) {
} continue
if fd.flags.OmitEmpty() && isEmptyValue(v) { }
continue bl.Field(fd.name)
} if fd.flags.Encrypted() {
b.B.WriteByte(nx) fmt.Println(fd.name," Es encriptado\n")
nx = ',' }
if fd.flags.EscapeHTML() { fd.packFn(b,fv)
b.B.WriteString(fd.nameHtm)
} else {
b.B.WriteString(fd.nameUns)
} }
fd.packFn(b,fv) })
}
if nx == '{' {
b.B.Write2Byte('{','}')
} else {
b.B.WriteByte('}')
}
} }

@ -22,10 +22,10 @@
// limitations under the License. // limitations under the License.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
package pkj package pkjson
import ( import (
"apack" "apacks"
"cdcs/cjson" "cdcs/cjson"
"encoding" "encoding"
"encoding/json" "encoding/json"

@ -22,7 +22,7 @@
// limitations under the License. // limitations under the License.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
package pstate package pkstate
import "syns/pools" import "syns/pools"

@ -22,7 +22,7 @@
// limitations under the License. // limitations under the License.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
package pstate package pkstate
const ( const (

@ -22,7 +22,7 @@
// limitations under the License. // limitations under the License.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
package pstate package pkstate
const( const(

@ -22,10 +22,10 @@
// limitations under the License. // limitations under the License.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
package pstate package pkstate
import ( import (
"apack" "apacks"
"bfrs" "bfrs"
"crps" "crps"
) )

@ -22,7 +22,7 @@
// limitations under the License. // limitations under the License.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
package pstate package pkstate
type ( type (

@ -248,6 +248,29 @@ func (b *ABuffer) WOQ (add bool, quote byte, value []byte) {
func (b *ABuffer) WriteHTML(source []byte) { func (b *ABuffer) WriteHTML(source []byte) {
st := 0
for i, c := range source {
if c == '<' || c == '>' || c == '&' {
if st < i {
b.W(source[st:i])
}
b.WriteString(`\u00`)
b.WriteByte(chrs.G.HEX[c>>4])
b.WriteByte(chrs.G.HEX[c&0xF])
st = i + 1
} else if c == 0xE2 && i+2 < len(source) && source[i+1] == 0x80 && source[i+2]&^1 == 0xA8 {
if st < i {
b.W(source[st:i])
}
b.WriteString(`\u202`)
b.WriteByte(chrs.G.HEX[source[i+2]&0xF])
st = i + 3
}
}
if st < len(source) {
b.W(source[st:])
}
/*
st := 0 st := 0
for i,c := range source { for i,c := range source {
if c == '<' || c == '>' || c == '&' { if c == '<' || c == '>' || c == '&' {
@ -271,6 +294,8 @@ func (b *ABuffer) WriteHTML(source []byte) {
b.W(source[st:]) b.W(source[st:])
} }
} }
*/
} }

@ -25,7 +25,7 @@
package errs package errs
import ( import (
"errs/eftext" "errs/efjson"
"errs/stack" "errs/stack"
"errs/wrap" "errs/wrap"
"fmt" "fmt"
@ -61,7 +61,7 @@ var (
ErrParamNil : ErrCode(CodeParamNilError), ErrParamNil : ErrCode(CodeParamNilError),
ErrParamOutOfRange : ErrCode(CodeParamOutOfRangeError), ErrParamOutOfRange : ErrCode(CodeParamOutOfRangeError),
Formatter : eftext.Formatter(), Formatter : efjson.Formatter(),
} }
) )

@ -4,7 +4,7 @@ use (
./a ./a
./a/test ./a/test
./base/alogs ./base/alogs
./base/apack ./base/apacks
./core ./core
./core/aios ./core/aios
./core/bfrs ./core/bfrs

Loading…
Cancel
Save

Powered by TurnKey Linux.