mennanov / fieldmask-utils

Protobuf Field Mask Go utils
MIT License
229 stars 26 forks source link

feature: support control max copy size for slice/array field #24

Closed zhuliquan closed 2 years ago

zhuliquan commented 2 years ago

You can limit array/slice type of field to a maximum of maxCopySize elements by using option func WithMaxCopyListSize(maxCopySize).

Usage:

package main

import (
    fieldmask_utils "github.com/mennanov/fieldmask-utils"
)

func main() {
    type A struct {
        Field []int
    }
    const copySize int = 2

    src := &A{Field: []int{1, 2, 3}}
    dst := &A{}
    mask := fieldmask_utils.MaskFromString("Field1")
    // Limit Field to copy up to copySize elements
    // After copy, dst is A{Field: []int{1,2}}
    err := fieldmask_utils.StructToMap(mask, src, dst,
        fieldmask_utils.WithMaxCopyListSize(copySize))
    if err != nil {
        panic(err)
    }
}
codecov[bot] commented 2 years ago

Codecov Report

Merging #24 (1b754f4) into master (a076f18) will increase coverage by 2.28%. The diff coverage is 85.00%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master      #24      +/-   ##
==========================================
+ Coverage   88.85%   91.14%   +2.28%     
==========================================
  Files           2        2              
  Lines         341      350       +9     
==========================================
+ Hits          303      319      +16     
+ Misses         20       16       -4     
+ Partials       18       15       -3     
Impacted Files Coverage Δ
copy.go 88.79% <85.00%> (+3.59%) :arrow_up:

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update a076f18...1b754f4. Read the comment docs.

zhuliquan commented 2 years ago

I rewrite options with visitor function CopyListSize according to your advice.

New Usage:

package main

import (
    fieldmask_utils "github.com/mennanov/fieldmask-utils"
)

func main() {
    type A struct {
        Field []int
    }
    const copySize int = 2

    src := &A{Field: []int{1, 2, 3}}
    dst := &A{}
    mask := fieldmask_utils.MaskFromString("Field1")
    // Limit Field to copy up to copySize elements
    // After copy, dst is A{Field: []int{1,2}}
    err := fieldmask_utils.StructToStruct(mask, src, dst,
        fieldmask_utils.WithCopyListSize(func(src, dst *reflect.Value) int {
            return copySize
        }))
    if err != nil {
        panic(err)
    }
}
mennanov commented 2 years ago

Thanks a lot for contributing!