github.com/go-spring/spring-base@v1.1.3/util/value.go (about)

     1  /*
     2   * Copyright 2012-2019 the original author or authors.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *      https://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package util
    18  
    19  import (
    20  	"reflect"
    21  	"runtime"
    22  	"strings"
    23  	"unsafe"
    24  )
    25  
    26  const (
    27  	flagStickyRO = 1 << 5
    28  	flagEmbedRO  = 1 << 6
    29  	flagRO       = flagStickyRO | flagEmbedRO
    30  )
    31  
    32  // PatchValue makes an unexported field can be assignable.
    33  func PatchValue(v reflect.Value) reflect.Value {
    34  	rv := reflect.ValueOf(&v)
    35  	flag := rv.Elem().FieldByName("flag")
    36  	ptrFlag := (*uintptr)(unsafe.Pointer(flag.UnsafeAddr()))
    37  	*ptrFlag = *ptrFlag &^ flagRO
    38  	return v
    39  }
    40  
    41  // Indirect returns its element type when t is a pointer type.
    42  func Indirect(t reflect.Type) reflect.Type {
    43  	if t.Kind() != reflect.Ptr {
    44  		return t
    45  	}
    46  	return t.Elem()
    47  }
    48  
    49  // FileLine returns a function's name, file name and line number.
    50  func FileLine(fn interface{}) (file string, line int, fnName string) {
    51  
    52  	fnPtr := reflect.ValueOf(fn).Pointer()
    53  	fnInfo := runtime.FuncForPC(fnPtr)
    54  	file, line = fnInfo.FileLine(fnPtr)
    55  
    56  	s := fnInfo.Name()
    57  	if ss := strings.Split(s, "/"); len(ss) > 0 {
    58  		s = ss[len(ss)-1]
    59  		i := strings.Index(s, ".")
    60  		s = s[i+1:]
    61  	}
    62  
    63  	// method values are printed as "T.m-fm"
    64  	s = strings.TrimRight(s, "-fm")
    65  	return file, line, s
    66  }